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
|
---|---|---|---|---|---|---|---|---|---|
872e685698b4f179cc89401ff0c5234961e11db6
|
frameworks/projects/HTML/as/src/org/apache/flex/html/TextArea.as
|
frameworks/projects/HTML/as/src/org/apache/flex/html/TextArea.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html
{
import org.apache.flex.core.ITextModel;
import org.apache.flex.core.UIBase;
COMPILE::JS
{
import org.apache.flex.core.WrappedHTMLElement;
}
/**
* The TextArea class implements the basic control for
* multi-line text input.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class TextArea extends UIBase
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function TextArea()
{
super();
}
/**
* @copy org.apache.flex.html.Label#text
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get text():String
{
return ITextModel(model).text;
}
/**
* @private
*/
public function set text(value:String):void
{
ITextModel(model).text = value;
}
/**
* @copy org.apache.flex.html.Label#html
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get html():String
{
return ITextModel(model).html;
}
/**
* @private
*/
public function set html(value:String):void
{
ITextModel(model).html = value;
}
/**
* @flexjsignorecoercion org.apache.flex.core.WrappedHTMLElement
*/
COMPILE::JS
override protected function createElement():WrappedHTMLElement
{
element = document.createElement('textarea') as WrappedHTMLElement;
positioner = element;
positioner.style.position = 'relative';
element.flexjs_wrapper = this;
element.className = 'TextArea';
typeNames = 'TextArea';
return element;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html
{
import org.apache.flex.core.ITextModel;
import org.apache.flex.core.UIBase;
COMPILE::JS
{
import org.apache.flex.core.WrappedHTMLElement;
}
/**
* The TextArea class implements the basic control for
* multi-line text input.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class TextArea extends UIBase
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function TextArea()
{
super();
}
/**
* @copy org.apache.flex.html.Label#text
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
* @flexjsignorecoercion HTMLInputElement
*/
public function get text():String
{
COMPILE::AS3
{
return ITextModel(model).text;
}
COMPILE::JS
{
return (element as HTMLInputElement).value;
}
}
/**
* @private
* @flexjsignorecoercion HTMLInputElement
*/
public function set text(value:String):void
{
COMPILE::AS3
{
ITextModel(model).text = value;
}
COMPILE::JS
{
(element as HTMLInputElement).value = value;
}
}
/**
* @copy org.apache.flex.html.Label#html
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get html():String
{
return ITextModel(model).html;
}
/**
* @private
*/
public function set html(value:String):void
{
ITextModel(model).html = value;
}
/**
* @flexjsignorecoercion org.apache.flex.core.WrappedHTMLElement
*/
COMPILE::JS
override protected function createElement():WrappedHTMLElement
{
element = document.createElement('textarea') as WrappedHTMLElement;
positioner = element;
positioner.style.position = 'relative';
element.flexjs_wrapper = this;
element.className = 'TextArea';
typeNames = 'TextArea';
return element;
}
}
}
|
fix textarea
|
fix textarea
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
aacf5c0a38361911fd3abdd4b3bb899a752e6f52
|
src/ageofai/map/view/MapView.as
|
src/ageofai/map/view/MapView.as
|
/**
* Created by newkrok on 08/04/16.
*/
package ageofai.map.view
{
import ageofai.building.view.home.HomeView;
import ageofai.map.constant.CMap;
import ageofai.map.constant.CMapNodeType;
import ageofai.map.model.MapNode;
import common.mvc.view.base.ABaseView;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.geom.Matrix;
public class MapView extends ABaseView
{
private var _baseBackground:Bitmap;
private var _terrainHelper:TerrainHelper;
public function MapView()
{
var testMap:Vector.<Vector.<MapNode>> = new <Vector.<MapNode>>[];
for( var i:int = 0; i < CMap.ROW_COUNT; i++ )
{
testMap.push( new <MapNode>[] );
for( var j:int = 0; j < CMap.COLUMN_COUNT; j++ )
{
testMap[ i ].push( new MapNode() );
}
}
this.createLayers();
this.createMap( testMap );
this.createHome();
this.createHome();
this.createHome();
this.createHome();
}
private function createHome():void
{
var home:HomeView = this.addChild( new HomeView() ) as HomeView;
home.x = CMap.TILE_SIZE * Math.floor( Math.random() * CMap.COLUMN_COUNT );
home.y = CMap.TILE_SIZE * Math.floor( Math.random() * CMap.ROW_COUNT );
}
private function createLayers():void
{
this._terrainLayer = new Sprite();
this.addChild( this._terrainLayer );
this._unitLayer = new Sprite();
this.addChild( this._unitLayer );
}
public function createMap( mapMatrix:Vector.<Vector.<MapNode>> ):void
{
this._terrainHelper = new TerrainHelper();
this._terrainHelper.createBaseTerrainBitmapDatas();
var lineCount:int = mapMatrix.length;
var colCount:int = mapMatrix[ 0 ].length;
var backgroundBitmapData:BitmapData = new BitmapData( lineCount * 32, colCount * 32, false, 0 );
backgroundBitmapData.lock();
for( var i:int = 0; i < lineCount; i++ )
{
for( var j:int = 0; j < colCount; j++ )
{
this.drawTerrainToBitmapData( i, j, backgroundBitmapData, mapMatrix[i][j].type );
}
}
backgroundBitmapData.unlock();
this._baseBackground = new Bitmap( backgroundBitmapData );
addChild( this._baseBackground );
this._terrainHelper.dispose();
}
private function drawTerrainToBitmapData( col:uint, row:uint, backgroundBitmapData:BitmapData, type:int ):void
{
var positionMatrix:Matrix = new Matrix();
positionMatrix.tx = col * CMap.TILE_SIZE;
positionMatrix.ty = row * CMap.TILE_SIZE;
backgroundBitmapData.draw( type == CMapNodeType.GRASS ? this._terrainHelper.terrainGrassUI : this._terrainHelper.terrainDarkGrassUI, positionMatrix );
}
}
}
|
/**
* Created by newkrok on 08/04/16.
*/
package ageofai.map.view
{
import ageofai.building.view.home.HomeView;
import ageofai.map.constant.CMap;
import ageofai.map.constant.CMapNodeType;
import ageofai.map.model.MapNode;
import common.mvc.view.base.ABaseView;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.geom.Matrix;
public class MapView extends ABaseView
{
private var _terrainLayer:Sprite;
private var _unitLayer:Sprite;
private var _baseBackground:Bitmap;
private var _terrainHelper:TerrainHelper;
public function MapView()
{
var testMap:Vector.<Vector.<MapNode>> = new <Vector.<MapNode>>[];
for( var i:int = 0; i < CMap.ROW_COUNT; i++ )
{
testMap.push( new <MapNode>[] );
for( var j:int = 0; j < CMap.COLUMN_COUNT; j++ )
{
testMap[ i ].push( new MapNode( 1 ) );
}
}
this.createLayers();
this.createMap( testMap );
this.createHome();
this.createHome();
this.createHome();
this.createHome();
}
private function createHome():void
{
var home:HomeView = this.addChild( new HomeView() ) as HomeView;
home.x = CMap.TILE_SIZE * Math.floor( Math.random() * CMap.COLUMN_COUNT );
home.y = CMap.TILE_SIZE * Math.floor( Math.random() * CMap.ROW_COUNT );
}
private function createLayers():void
{
this._terrainLayer = new Sprite();
this.addChild( this._terrainLayer );
this._unitLayer = new Sprite();
this.addChild( this._unitLayer );
}
public function createMap( mapMatrix:Vector.<Vector.<MapNode>> ):void
{
this._terrainHelper = new TerrainHelper();
this._terrainHelper.createBaseTerrainBitmapDatas();
var lineCount:int = mapMatrix.length;
var colCount:int = mapMatrix[ 0 ].length;
var backgroundBitmapData:BitmapData = new BitmapData( lineCount * 32, colCount * 32, false, 0 );
backgroundBitmapData.lock();
for( var i:int = 0; i < lineCount; i++ )
{
for( var j:int = 0; j < colCount; j++ )
{
this.drawTerrainToBitmapData( i, j, backgroundBitmapData, mapMatrix[i][j].type );
}
}
backgroundBitmapData.unlock();
this._baseBackground = new Bitmap( backgroundBitmapData );
addChild( this._baseBackground );
this._terrainHelper.dispose();
}
private function drawTerrainToBitmapData( col:uint, row:uint, backgroundBitmapData:BitmapData, type:int ):void
{
var positionMatrix:Matrix = new Matrix();
positionMatrix.tx = col * CMap.TILE_SIZE;
positionMatrix.ty = row * CMap.TILE_SIZE;
backgroundBitmapData.draw( type == CMapNodeType.GRASS ? this._terrainHelper.terrainGrassUI : this._terrainHelper.terrainDarkGrassUI, positionMatrix );
}
}
}
|
Test Map generation fixed
|
Test Map generation fixed
Test Map generation fixed
|
ActionScript
|
apache-2.0
|
goc-flashplusplus/ageofai
|
29a599371d400f3e167314a9fddaa01b4ac4dd60
|
src/aerys/minko/scene/node/AbstractSceneNode.as
|
src/aerys/minko/scene/node/AbstractSceneNode.as
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.controller.IRebindableController;
import aerys.minko.scene.data.TransformDataProvider;
import aerys.minko.type.Signal;
import aerys.minko.type.clone.CloneOptions;
import aerys.minko.type.clone.ControllerCloneAction;
import aerys.minko.type.math.Matrix4x4;
import flash.utils.Dictionary;
import flash.utils.getQualifiedClassName;
use namespace minko_scene;
/**
* The base class to extend in order to create new scene node types.
*
* @author Jean-Marc Le Roux
*
*/
public class AbstractSceneNode implements ISceneNode
{
private static var _id : uint = 0;
private var _name : String = null;
private var _root : ISceneNode = null;
private var _parent : Group = null;
private var _transformData : TransformDataProvider = new TransformDataProvider();
private var _transform : Matrix4x4 = new Matrix4x4();
private var _privateControllers : Vector.<AbstractController> = new <AbstractController>[];
private var _publicControllers : Vector.<AbstractController> = new <AbstractController>[];
private var _added : Signal = new Signal('AbstractSceneNode.added');
private var _removed : Signal = new Signal('AbstractSceneNode.removed');
private var _addedToScene : Signal = new Signal('AbstractSceneNode.addedToScene');
private var _removedFromScene : Signal = new Signal('AbstractSceneNode.removedFromScene');
private var _controllerAdded : Signal = new Signal('AbstractSceneNode.controllerAdded');
private var _controllerRemoved : Signal = new Signal('AbstractSceneNode.controllerRemoved');
public function get name() : String
{
return _name;
}
public function set name(value : String) : void
{
_name = value;
}
public function get parent() : Group
{
return _parent;
}
public function set parent(value : Group) : void
{
if (value == _parent)
return ;
// remove child
if (_parent)
{
var oldParent : Group = _parent;
oldParent._children.splice(
oldParent.getChildIndex(this),
1
);
parent._numChildren--;
oldParent.descendantRemoved.execute(oldParent, this);
_parent = null;
_removed.execute(this, oldParent);
}
// set parent
_parent = value;
// add child
if (_parent)
{
_parent._children[_parent.numChildren] = this;
_parent._numChildren++;
_parent.descendantAdded.execute(_parent, this);
_added.execute(this, _parent);
}
}
public function get root() : ISceneNode
{
return _root;
}
public function get transform() : Matrix4x4
{
return _transform;
}
public function get localToWorld() : Matrix4x4
{
return _transformData.localToWorld;
}
public function get worldToLocal() : Matrix4x4
{
return _transformData.worldToLocal;
}
public function get added() : Signal
{
return _added;
}
public function get removed() : Signal
{
return _removed;
}
public function get addedToScene() : Signal
{
return _addedToScene;
}
public function get removedFromScene() : Signal
{
return _removedFromScene;
}
public function get numControllers() : uint
{
return _publicControllers.length;
}
public function get controllerAdded() : Signal
{
return _controllerAdded;
}
public function get controllerRemoved() : Signal
{
return _controllerRemoved;
}
protected function get transformData() : TransformDataProvider
{
return _transformData;
}
public function AbstractSceneNode()
{
initialize();
}
private function initialize() : void
{
_name = getDefaultSceneName(this);
_root = this;
_added.add(addedHandler);
_removed.add(removedHandler);
_addedToScene.add(addedToSceneHandler);
_removedFromScene.add(removedFromSceneHandler);
_transform.changed.add(transformChangedHandler);
}
protected function addedHandler(child : ISceneNode, parent : Group) : void
{
_root = _parent ? _parent.root : this;
if (_root is Scene)
_addedToScene.execute(this, _root);
if (child === this)
{
_parent.localToWorld.changed.add(transformChangedHandler);
transformChangedHandler(_parent.transform);
}
}
protected function removedHandler(child : ISceneNode, parent : Group) : void
{
// update root
var oldRoot : ISceneNode = _root;
_root = _parent ? _parent.root : this;
if (oldRoot is Scene)
_removedFromScene.execute(this, oldRoot);
if (child === this)
parent.localToWorld.changed.remove(transformChangedHandler);
}
protected function addedToSceneHandler(child : ISceneNode, scene : Scene) : void
{
// nothing
}
protected function removedFromSceneHandler(child : ISceneNode, scene : Scene) : void
{
// nothing
}
protected function transformChangedHandler(transform : Matrix4x4) : void
{
if (_parent)
{
localToWorld.lock()
.copyFrom(_transform)
.append(_parent.localToWorld)
.unlock();
}
else
localToWorld.copyFrom(_transform);
worldToLocal.lock()
.copyFrom(localToWorld)
.invert()
.unlock();
}
public function addController(controller : AbstractController) : ISceneNode
{
_publicControllers.push(controller);
controller.addTarget(this);
_controllerAdded.execute(this, controller);
return this;
}
public function removeController(controller : AbstractController) : ISceneNode
{
var numControllers : uint = _publicControllers.length - 1;
_publicControllers[_publicControllers.indexOf(controller)] = _publicControllers[numControllers];
_publicControllers.length = numControllers;
controller.removeTarget(this);
_controllerRemoved.execute(this, controller);
return this;
}
public function removeAllControllers() : ISceneNode
{
while (numControllers)
removeController(getController(0));
return this;
}
public function getController(index : uint) : AbstractController
{
return _publicControllers[index];
}
public function getControllersByType(type : Class,
controllers : Vector.<AbstractController> = null) : Vector.<AbstractController>
{
controllers ||= new Vector.<AbstractController>();
var nbControllers : uint = numControllers;
for (var i : int = 0; i < nbControllers; ++i)
{
var ctrl : AbstractController = getController(i);
if (ctrl is type)
controllers.push(ctrl);
}
return controllers;
}
public static function getDefaultSceneName(scene : ISceneNode) : String
{
var className : String = getQualifiedClassName(scene);
return className.substr(className.lastIndexOf(':') + 1)
+ '_' + (++_id);
}
minko_scene function cloneNode() : AbstractSceneNode
{
throw new Error('Must be overriden');
}
public final function clone(cloneOptions : CloneOptions = null) : ISceneNode
{
cloneOptions ||= CloneOptions.defaultOptions;
// fill up 2 dics with all nodes and controllers
var nodeMap : Dictionary = new Dictionary();
var controllerMap : Dictionary = new Dictionary();
listItems(cloneNode(), nodeMap, controllerMap);
// clone controllers with respect with instructions
cloneControllers(controllerMap, cloneOptions);
// rebind all controller dependencies.
rebindControllerDependencies(controllerMap, nodeMap, cloneOptions);
// add cloned/rebinded/original controllers to clones
for (var objNode : Object in nodeMap)
{
var node : AbstractSceneNode = AbstractSceneNode(objNode);
var numControllers : uint = node.numControllers;
for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId)
{
var controller : AbstractController = controllerMap[node.getController(controllerId)];
if (controller != null)
nodeMap[node].addController(controller);
}
}
return nodeMap[this];
}
private function listItems(clonedRoot : ISceneNode,
nodes : Dictionary,
controllers : Dictionary) : void
{
var numControllers : uint = this.numControllers;
for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId)
controllers[getController(controllerId)] = true;
nodes[this] = clonedRoot;
if (this is Group)
{
var group : Group = Group(this);
var clonedGroup : Group = Group(clonedRoot);
var numChildren : uint = group.numChildren;
for (var childId : uint = 0; childId < numChildren; ++childId)
{
var child : AbstractSceneNode = AbstractSceneNode(group.getChildAt(childId));
var clonedChild : AbstractSceneNode = AbstractSceneNode(clonedGroup.getChildAt(childId));
child.listItems(clonedChild, nodes, controllers);
}
}
}
private function cloneControllers(controllerMap : Dictionary, cloneOptions : CloneOptions) : void
{
for (var objController : Object in controllerMap)
{
var controller : AbstractController = AbstractController(objController);
var action : uint = cloneOptions.getActionForController(controller);
if (action == ControllerCloneAction.CLONE)
controllerMap[controller] = controller.clone();
else if (action == ControllerCloneAction.REASSIGN)
controllerMap[controller] = controller;
else if (action == ControllerCloneAction.IGNORE)
controllerMap[controller] = null;
}
}
private function rebindControllerDependencies(controllerMap : Dictionary,
nodeMap : Dictionary,
cloneOptions : CloneOptions) : void
{
for (var objController : Object in controllerMap)
{
var controller : AbstractController = AbstractController(objController);
var action : uint = cloneOptions.getActionForController(controller);
if (controller is IRebindableController && action == ControllerCloneAction.CLONE)
IRebindableController(controllerMap[controller]).rebindDependencies(nodeMap, controllerMap);
}
}
}
}
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.controller.IRebindableController;
import aerys.minko.scene.data.TransformDataProvider;
import aerys.minko.type.Signal;
import aerys.minko.type.clone.CloneOptions;
import aerys.minko.type.clone.ControllerCloneAction;
import aerys.minko.type.math.Matrix4x4;
import flash.utils.Dictionary;
import flash.utils.getQualifiedClassName;
use namespace minko_scene;
/**
* The base class to extend in order to create new scene node types.
*
* @author Jean-Marc Le Roux
*
*/
public class AbstractSceneNode implements ISceneNode
{
private static var _id : uint = 0;
private var _name : String = null;
private var _root : ISceneNode = null;
private var _parent : Group = null;
private var _transformData : TransformDataProvider = new TransformDataProvider();
private var _transform : Matrix4x4 = new Matrix4x4();
private var _controllers : Vector.<AbstractController> = new <AbstractController>[];
private var _added : Signal = new Signal('AbstractSceneNode.added');
private var _removed : Signal = new Signal('AbstractSceneNode.removed');
private var _addedToScene : Signal = new Signal('AbstractSceneNode.addedToScene');
private var _removedFromScene : Signal = new Signal('AbstractSceneNode.removedFromScene');
private var _controllerAdded : Signal = new Signal('AbstractSceneNode.controllerAdded');
private var _controllerRemoved : Signal = new Signal('AbstractSceneNode.controllerRemoved');
public function get name() : String
{
return _name;
}
public function set name(value : String) : void
{
_name = value;
}
public function get parent() : Group
{
return _parent;
}
public function set parent(value : Group) : void
{
if (value == _parent)
return ;
// remove child
if (_parent)
{
var oldParent : Group = _parent;
oldParent._children.splice(
oldParent.getChildIndex(this),
1
);
parent._numChildren--;
oldParent.descendantRemoved.execute(oldParent, this);
_parent = null;
_removed.execute(this, oldParent);
}
// set parent
_parent = value;
// add child
if (_parent)
{
_parent._children[_parent.numChildren] = this;
_parent._numChildren++;
_parent.descendantAdded.execute(_parent, this);
_added.execute(this, _parent);
}
}
public function get root() : ISceneNode
{
return _root;
}
public function get transform() : Matrix4x4
{
return _transform;
}
public function get localToWorld() : Matrix4x4
{
return _transformData.localToWorld;
}
public function get worldToLocal() : Matrix4x4
{
return _transformData.worldToLocal;
}
public function get added() : Signal
{
return _added;
}
public function get removed() : Signal
{
return _removed;
}
public function get addedToScene() : Signal
{
return _addedToScene;
}
public function get removedFromScene() : Signal
{
return _removedFromScene;
}
public function get numControllers() : uint
{
return _controllers.length;
}
public function get controllerAdded() : Signal
{
return _controllerAdded;
}
public function get controllerRemoved() : Signal
{
return _controllerRemoved;
}
protected function get transformData() : TransformDataProvider
{
return _transformData;
}
public function AbstractSceneNode()
{
initialize();
}
private function initialize() : void
{
_name = getDefaultSceneName(this);
_root = this;
_added.add(addedHandler);
_removed.add(removedHandler);
_addedToScene.add(addedToSceneHandler);
_removedFromScene.add(removedFromSceneHandler);
_transform.changed.add(transformChangedHandler);
}
protected function addedHandler(child : ISceneNode, parent : Group) : void
{
_root = _parent ? _parent.root : this;
if (_root is Scene)
_addedToScene.execute(this, _root);
if (child === this)
{
_parent.localToWorld.changed.add(transformChangedHandler);
transformChangedHandler(_parent.transform);
}
}
protected function removedHandler(child : ISceneNode, parent : Group) : void
{
// update root
var oldRoot : ISceneNode = _root;
_root = _parent ? _parent.root : this;
if (oldRoot is Scene)
_removedFromScene.execute(this, oldRoot);
if (child === this)
parent.localToWorld.changed.remove(transformChangedHandler);
}
protected function addedToSceneHandler(child : ISceneNode, scene : Scene) : void
{
// nothing
}
protected function removedFromSceneHandler(child : ISceneNode, scene : Scene) : void
{
// nothing
}
protected function transformChangedHandler(transform : Matrix4x4) : void
{
if (_parent)
{
localToWorld.lock()
.copyFrom(_transform)
.append(_parent.localToWorld)
.unlock();
}
else
localToWorld.copyFrom(_transform);
worldToLocal.lock()
.copyFrom(localToWorld)
.invert()
.unlock();
}
public function addController(controller : AbstractController) : ISceneNode
{
_controllers.push(controller);
controller.addTarget(this);
_controllerAdded.execute(this, controller);
return this;
}
public function removeController(controller : AbstractController) : ISceneNode
{
var numControllers : uint = _controllers.length - 1;
_controllers[_controllers.indexOf(controller)] = _controllers[numControllers];
_controllers.length = numControllers;
controller.removeTarget(this);
_controllerRemoved.execute(this, controller);
return this;
}
public function removeAllControllers() : ISceneNode
{
while (numControllers)
removeController(getController(0));
return this;
}
public function getController(index : uint) : AbstractController
{
return _controllers[index];
}
public function getControllersByType(type : Class,
controllers : Vector.<AbstractController> = null) : Vector.<AbstractController>
{
controllers ||= new Vector.<AbstractController>();
var nbControllers : uint = numControllers;
for (var i : int = 0; i < nbControllers; ++i)
{
var ctrl : AbstractController = getController(i);
if (ctrl is type)
controllers.push(ctrl);
}
return controllers;
}
public static function getDefaultSceneName(scene : ISceneNode) : String
{
var className : String = getQualifiedClassName(scene);
return className.substr(className.lastIndexOf(':') + 1)
+ '_' + (++_id);
}
minko_scene function cloneNode() : AbstractSceneNode
{
throw new Error('Must be overriden');
}
public final function clone(cloneOptions : CloneOptions = null) : ISceneNode
{
cloneOptions ||= CloneOptions.defaultOptions;
// fill up 2 dics with all nodes and controllers
var nodeMap : Dictionary = new Dictionary();
var controllerMap : Dictionary = new Dictionary();
listItems(cloneNode(), nodeMap, controllerMap);
// clone controllers with respect with instructions
cloneControllers(controllerMap, cloneOptions);
// rebind all controller dependencies.
rebindControllerDependencies(controllerMap, nodeMap, cloneOptions);
// add cloned/rebinded/original controllers to clones
for (var objNode : Object in nodeMap)
{
var node : AbstractSceneNode = AbstractSceneNode(objNode);
var numControllers : uint = node.numControllers;
for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId)
{
var controller : AbstractController = controllerMap[node.getController(controllerId)];
if (controller != null)
nodeMap[node].addController(controller);
}
}
return nodeMap[this];
}
private function listItems(clonedRoot : ISceneNode,
nodes : Dictionary,
controllers : Dictionary) : void
{
var numControllers : uint = this.numControllers;
for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId)
controllers[getController(controllerId)] = true;
nodes[this] = clonedRoot;
if (this is Group)
{
var group : Group = Group(this);
var clonedGroup : Group = Group(clonedRoot);
var numChildren : uint = group.numChildren;
for (var childId : uint = 0; childId < numChildren; ++childId)
{
var child : AbstractSceneNode = AbstractSceneNode(group.getChildAt(childId));
var clonedChild : AbstractSceneNode = AbstractSceneNode(clonedGroup.getChildAt(childId));
child.listItems(clonedChild, nodes, controllers);
}
}
}
private function cloneControllers(controllerMap : Dictionary, cloneOptions : CloneOptions) : void
{
for (var objController : Object in controllerMap)
{
var controller : AbstractController = AbstractController(objController);
var action : uint = cloneOptions.getActionForController(controller);
if (action == ControllerCloneAction.CLONE)
controllerMap[controller] = controller.clone();
else if (action == ControllerCloneAction.REASSIGN)
controllerMap[controller] = controller;
else if (action == ControllerCloneAction.IGNORE)
controllerMap[controller] = null;
}
}
private function rebindControllerDependencies(controllerMap : Dictionary,
nodeMap : Dictionary,
cloneOptions : CloneOptions) : void
{
for (var objController : Object in controllerMap)
{
var controller : AbstractController = AbstractController(objController);
var action : uint = cloneOptions.getActionForController(controller);
if (controller is IRebindableController && action == ControllerCloneAction.CLONE)
IRebindableController(controllerMap[controller]).rebindDependencies(nodeMap, controllerMap);
}
}
}
}
|
Revert useless change on AbstractSceneNode
|
Revert useless change on AbstractSceneNode
|
ActionScript
|
mit
|
aerys/minko-as3
|
0a35ac861eac1a6198706706c12eeabae79d9547
|
Impetus.as
|
Impetus.as
|
package
{
import flash.display.Sprite;
import flash.external.ExternalInterface;
public class Impetus extends Sprite
{
private var sounds:Vector.<ImpetusSound>;
public function Impetus():void
{
this.sounds = new Vector.<ImpetusSound>();
if(ExternalInterface.available)
{
ExternalInterface.addCallback('getSound', this.getSound);
ExternalInterface.addCallback('playNew', this.playNew);
ExternalInterface.call("console.log", "Impetus loaded. (https://github.com/JWhile/Impetus)");
}
}
public function getSound(url:String):ImpetusSound
{
var len:int = this.sounds.length;
for(var i:int = 0; i < len; i++)
{
if(this.sounds[i].getUrl() === url)
{
return this.sounds[i];
}
}
var s:ImpetusSound = new ImpetusSound(url);
this.sounds.push(s);
return s;
}
public function playNew(url:String):void
{
this.getSound(url).playNew();
}
}
}
|
package
{
import flash.display.Sprite;
import flash.external.ExternalInterface;
public class Impetus extends Sprite
{
private var sounds:Vector.<ImpetusSound>;
public function Impetus():void
{
this.sounds = new Vector.<ImpetusSound>();
if(ExternalInterface.available)
{
ExternalInterface.addCallback('playNew', this.playNew);
ExternalInterface.call("console.log", "Impetus loaded. (https://github.com/JWhile/Impetus)");
}
}
public function playNew(url:String):void
{
this.getSound(url).playNew();
}
private function getSound(url:String):ImpetusSound
{
var len:int = this.sounds.length;
for(var i:int = 0; i < len; i++)
{
if(this.sounds[i].getUrl() === url)
{
return this.sounds[i];
}
}
var s:ImpetusSound = new ImpetusSound(url);
this.sounds.push(s);
return s;
}
}
}
|
Make getSound() private
|
Make getSound() private
|
ActionScript
|
mit
|
Julow/Impetus
|
59ea2affbb21aeffde5de06748788f6ee05dd846
|
Impetus.as
|
Impetus.as
|
package
{
import flash.display.Sprite;
import flash.external.ExternalInterface;
public class Impetus extends Sprite
{
private var sounds:Vector.<ImpetusSound>;
public function Impetus():void
{
this.sounds = new Vector.<ImpetusSound>();
if(ExternalInterface.available)
{
ExternalInterface.addCallback('getSound', this.getSound);
ExternalInterface.call("console.log", "Impetus loaded. (https://github.com/JWhile/Impetus)");
}
}
public function getSound(url:String):ImpetusSound
{
var len:int = this.sounds.length;
for(var i:int = 0; i < len; i++)
{
if(this.sounds[i].getUrl() === url)
{
return this.sounds[i];
}
}
var s:ImpetusSound = new ImpetusSound(url);
this.sounds.push(s);
return s;
}
}
}
|
package
{
import flash.display.Sprite;
import flash.external.ExternalInterface;
public class Impetus extends Sprite
{
private var sounds:Vector.<ImpetusSound>;
public function Impetus():void
{
this.sounds = new Vector.<ImpetusSound>();
if(ExternalInterface.available)
{
ExternalInterface.addCallback('getSound', this.getSound);
ExternalInterface.addCallback('playNew', this.playNew);
ExternalInterface.call("console.log", "Impetus loaded. (https://github.com/JWhile/Impetus)");
}
}
public function getSound(url:String):ImpetusSound
{
var len:int = this.sounds.length;
for(var i:int = 0; i < len; i++)
{
if(this.sounds[i].getUrl() === url)
{
return this.sounds[i];
}
}
var s:ImpetusSound = new ImpetusSound(url);
this.sounds.push(s);
return s;
}
public function playNew(url:String):void
{
this.getSound(url).playNew();
}
}
}
|
Add playNew method to Impetus & ExternalInterface callbacks
|
Add playNew method to Impetus & ExternalInterface callbacks
|
ActionScript
|
mit
|
Julow/Impetus
|
7085cf6260b16266cf28cb8a1ff853b25eec218e
|
src/goplayer/ConfigurationParser.as
|
src/goplayer/ConfigurationParser.as
|
package goplayer
{
public class ConfigurationParser
{
private const result : Configuration = new Configuration
private var parameters : Object
public function ConfigurationParser(parameters : Object)
{ this.parameters = parameters }
public function execute() : void
{
// XXX: Clean up the host stuff.
result.host = parameters.host || "staging.streamio.se"
result.skinURL = parameters.skin
|| "http://" + result.host + "/swfs/goplayer-black-skin.swf"
result.movieID = parameters.movie
result.trackerID = parameters.tracker || "global"
result.bitratePolicy = getBitratePolicy("bitrate", BitratePolicy.BEST)
result.enableRTMP = getBoolean("enableRtmp", true)
result.enableAutoplay = getBoolean("enableAutoplay", false)
result.enableLooping = getBoolean("enableLooping", false)
result.enableChrome = getBoolean("enableChrome", true)
result.enableUpperPanel = getBoolean("enableUpperPanel", true)
}
public static function parse(parameters : Object) : Configuration
{
const parser : ConfigurationParser
= new ConfigurationParser(parameters)
parser.execute()
return parser.result
}
// -----------------------------------------------------
private function getBitratePolicy
(name : String, fallback : BitratePolicy) : BitratePolicy
{
if (name in parameters)
return $getBitratePolicy(name, parameters[name], fallback)
else
return fallback
}
private function $getBitratePolicy
(name : String, value : String,
fallback : BitratePolicy) : BitratePolicy
{
try
{ return $$getBitratePolicy(value) }
catch (error : Error)
{
reportInvalidParameter(name, value, BITRATE_POLICY_VALUES)
return fallback
}
throw new Error
}
private const BITRATE_POLICY_VALUES : Array =
["<number>kbps", "min", "max", "best"]
private function $$getBitratePolicy(value : String) : BitratePolicy
{
if (value == "max")
return BitratePolicy.MAX
else if (value == "min")
return BitratePolicy.MIN
else if (value == "best")
return BitratePolicy.BEST
else if (Bitrate.parse(value))
return BitratePolicy.specific(Bitrate.parse(value))
else
throw new Error
}
// -----------------------------------------------------
private function getBoolean
(name : String, fallback : Boolean) : Boolean
{
if (name in parameters)
return $getBoolean(name, parameters[name], fallback)
else
return fallback
}
private function $getBoolean
(name : String, value : String, fallback : Boolean) : Boolean
{
try
{ return $$getBoolean(value) }
catch (error : Error)
{
reportInvalidParameter(name, value, ["true", "false"])
return fallback
}
throw new Error
}
private function $$getBoolean(value : String) : Boolean
{
if (value == "true")
return true
else if (value == "false")
return false
else
throw new Error
}
// -----------------------------------------------------
private function reportInvalidParameter
(name : String, value : String, validValues : Array) : void
{
debug("Error: Invalid parameter: “" + name + "=" + value + "”; " +
getInvalidParameterHint(validValues) + ".")
}
private function getInvalidParameterHint(values : Array) : String
{ return $getInvalidParameterHint(getQuotedValues(values)) }
private function $getInvalidParameterHint(values : Array) : String
{
return "please use " +
"either " + values.slice(0, -1).join(", ") + " " +
"or " + values[values.length - 1]
}
private function getQuotedValues(values : Array) : Array
{
var result : Array = []
for each (var value : String in values)
result.push("“" + value + "”")
return result
}
}
}
|
package goplayer
{
public class ConfigurationParser
{
private const result : Configuration = new Configuration
private var parameters : Object
public function ConfigurationParser(parameters : Object)
{ this.parameters = parameters }
public function execute() : void
{
// XXX: Clean up the host stuff.
result.host = parameters.host || "staging.streamio.se"
result.skinURL = parameters.skin
result.movieID = parameters.movie
result.trackerID = parameters.tracker || "global"
result.bitratePolicy = getBitratePolicy("bitrate", BitratePolicy.BEST)
result.enableRTMP = getBoolean("enableRtmp", true)
result.enableAutoplay = getBoolean("enableAutoplay", false)
result.enableLooping = getBoolean("enableLooping", false)
result.enableChrome = getBoolean("enableChrome", true)
result.enableUpperPanel = getBoolean("enableUpperPanel", true)
}
public static function parse(parameters : Object) : Configuration
{
const parser : ConfigurationParser
= new ConfigurationParser(parameters)
parser.execute()
return parser.result
}
// -----------------------------------------------------
private function getBitratePolicy
(name : String, fallback : BitratePolicy) : BitratePolicy
{
if (name in parameters)
return $getBitratePolicy(name, parameters[name], fallback)
else
return fallback
}
private function $getBitratePolicy
(name : String, value : String,
fallback : BitratePolicy) : BitratePolicy
{
try
{ return $$getBitratePolicy(value) }
catch (error : Error)
{
reportInvalidParameter(name, value, BITRATE_POLICY_VALUES)
return fallback
}
throw new Error
}
private const BITRATE_POLICY_VALUES : Array =
["<number>kbps", "min", "max", "best"]
private function $$getBitratePolicy(value : String) : BitratePolicy
{
if (value == "max")
return BitratePolicy.MAX
else if (value == "min")
return BitratePolicy.MIN
else if (value == "best")
return BitratePolicy.BEST
else if (Bitrate.parse(value))
return BitratePolicy.specific(Bitrate.parse(value))
else
throw new Error
}
// -----------------------------------------------------
private function getBoolean
(name : String, fallback : Boolean) : Boolean
{
if (name in parameters)
return $getBoolean(name, parameters[name], fallback)
else
return fallback
}
private function $getBoolean
(name : String, value : String, fallback : Boolean) : Boolean
{
try
{ return $$getBoolean(value) }
catch (error : Error)
{
reportInvalidParameter(name, value, ["true", "false"])
return fallback
}
throw new Error
}
private function $$getBoolean(value : String) : Boolean
{
if (value == "true")
return true
else if (value == "false")
return false
else
throw new Error
}
// -----------------------------------------------------
private function reportInvalidParameter
(name : String, value : String, validValues : Array) : void
{
debug("Error: Invalid parameter: “" + name + "=" + value + "”; " +
getInvalidParameterHint(validValues) + ".")
}
private function getInvalidParameterHint(values : Array) : String
{ return $getInvalidParameterHint(getQuotedValues(values)) }
private function $getInvalidParameterHint(values : Array) : String
{
return "please use " +
"either " + values.slice(0, -1).join(", ") + " " +
"or " + values[values.length - 1]
}
private function getQuotedValues(values : Array) : Array
{
var result : Array = []
for each (var value : String in values)
result.push("“" + value + "”")
return result
}
}
}
|
Remove hard-coded default skinURL.
|
Remove hard-coded default skinURL.
|
ActionScript
|
mit
|
dbrock/goplayer,dbrock/goplayer
|
bb6d4e27a253e5452a234ea02c825d02f61f5200
|
dolly-framework/src/main/actionscript/dolly/Copier.as
|
dolly-framework/src/main/actionscript/dolly/Copier.as
|
package dolly {
import dolly.core.dolly_internal;
import dolly.core.metadata.MetadataName;
import org.as3commons.reflect.Accessor;
import org.as3commons.reflect.AccessorAccess;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.IMetadataContainer;
import org.as3commons.reflect.Type;
import org.as3commons.reflect.Variable;
use namespace dolly_internal;
public class Copier {
private static function getCopyableFieldsOfType(type:Type):Vector.<Field> {
const result:Vector.<Field> = new Vector.<Field>();
var variable:Variable;
var accessor:Accessor;
const isTypeCloneable:Boolean = type.hasMetadata(MetadataName.COPYABLE);
if (isTypeCloneable) {
for each(variable in type.variables) {
if (!variable.isStatic) {
result.push(variable);
}
}
for each(accessor in type.accessors) {
if (!accessor.isStatic && accessor.access == AccessorAccess.READ_WRITE) {
result.push(accessor);
}
}
} else {
const metadataContainers:Array = type.getMetadataContainers(MetadataName.COPYABLE);
for each(var metadataContainer:IMetadataContainer in metadataContainers) {
if (metadataContainer is Variable) {
variable = metadataContainer as Variable;
if (!variable.isStatic && variable.hasMetadata(MetadataName.COPYABLE)) {
result.push(variable);
}
} else if (metadataContainer is Accessor) {
accessor = metadataContainer as Accessor;
if (!accessor.isStatic
&& accessor.access == AccessorAccess.READ_WRITE
&& accessor.hasMetadata(MetadataName.COPYABLE)) {
result.push(accessor);
}
}
}
}
return result;
}
dolly_internal static function findCopyableFieldsForType(type:Type):Vector.<Field> {
var result:Vector.<Field> = getCopyableFieldsOfType(type);
var superType:Type;
var superTypeCopyableFields:Vector.<Field>;
for each(var superTypeName:String in type.extendsClasses) {
superType = Type.forName(superTypeName);
superTypeCopyableFields = getCopyableFieldsOfType(superType);
if (superTypeCopyableFields.length > 0) {
result = result.concat(superTypeCopyableFields);
}
}
return result;
}
public static function copy(source:*):* {
const type:Type = Type.forInstance(source);
const copy:* = new (type.clazz)();
const fieldsToCopy:Vector.<Field> = findCopyableFieldsForType(type);
var name:String;
for each(var field:Field in fieldsToCopy) {
name = field.name;
copy[name] = source[name];
}
return copy;
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import dolly.core.metadata.MetadataName;
import flash.utils.Dictionary;
import org.as3commons.reflect.Accessor;
import org.as3commons.reflect.AccessorAccess;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.IMetadataContainer;
import org.as3commons.reflect.Type;
import org.as3commons.reflect.Variable;
use namespace dolly_internal;
public class Copier {
private static function getCopyableFieldsOfType(type:Type, foundFieldsMap:Dictionary):Vector.<Field> {
const result:Vector.<Field> = new Vector.<Field>();
var variable:Variable;
var accessor:Accessor;
const isTypeCloneable:Boolean = type.hasMetadata(MetadataName.COPYABLE);
if (isTypeCloneable) {
for each(variable in type.variables) {
if (!foundFieldsMap[variable.name] && !variable.isStatic) {
foundFieldsMap[variable.name] = variable;
result.push(variable);
}
}
for each(accessor in type.accessors) {
if (!foundFieldsMap[accessor.name]
&& !accessor.isStatic
&& accessor.access == AccessorAccess.READ_WRITE) {
foundFieldsMap[accessor.name] = accessor;
result.push(accessor);
}
}
} else {
const metadataContainers:Array = type.getMetadataContainers(MetadataName.COPYABLE);
for each(var metadataContainer:IMetadataContainer in metadataContainers) {
if (metadataContainer is Variable) {
variable = metadataContainer as Variable;
if (!foundFieldsMap[variable.name]
&& !variable.isStatic
&& variable.hasMetadata(MetadataName.COPYABLE)) {
foundFieldsMap[variable.name] = variable;
result.push(variable);
}
} else if (metadataContainer is Accessor) {
accessor = metadataContainer as Accessor;
if (!foundFieldsMap[accessor.name]
&& !accessor.isStatic
&& accessor.access == AccessorAccess.READ_WRITE
&& accessor.hasMetadata(MetadataName.COPYABLE)) {
foundFieldsMap[accessor.name] = accessor;
result.push(accessor);
}
}
}
}
return result;
}
dolly_internal static function findCopyableFieldsForType(type:Type):Vector.<Field> {
var foundFields:Dictionary = new Dictionary();
var result:Vector.<Field> = getCopyableFieldsOfType(type, foundFields);
var superType:Type;
var superTypeCopyableFields:Vector.<Field>;
for each(var superTypeName:String in type.extendsClasses) {
superType = Type.forName(superTypeName);
superTypeCopyableFields = getCopyableFieldsOfType(superType, foundFields);
if (superTypeCopyableFields.length > 0) {
result = result.concat(superTypeCopyableFields);
}
}
return result;
}
public static function copy(source:*):* {
const type:Type = Type.forInstance(source);
const copy:* = new (type.clazz)();
const fieldsToCopy:Vector.<Field> = findCopyableFieldsForType(type);
var name:String;
for each(var field:Field in fieldsToCopy) {
name = field.name;
copy[name] = source[name];
}
return copy;
}
}
}
|
Remove duplications from founded copyable fields list.
|
Remove duplications from founded copyable fields list.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
1d853a9a6c0d09aea60a6579fa6f1baa5bb9b5ba
|
src/aerys/minko/scene/controller/ScriptController.as
|
src/aerys/minko/scene/controller/ScriptController.as
|
package aerys.minko.scene.controller
{
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.KeyboardManager;
import aerys.minko.type.MouseManager;
import flash.display.BitmapData;
import flash.utils.Dictionary;
public class ScriptController extends EnterFrameController
{
private var _scene : Scene;
private var _started : Dictionary;
private var _lastTime : Number;
private var _deltaTime : Number;
private var _currentTarget : ISceneNode;
private var _viewport : Viewport;
protected function get scene() : Scene
{
return _scene;
}
protected function get deltaTime() : Number
{
return _deltaTime;
}
protected function get keyboard() : KeyboardManager
{
return _viewport.keyboardManager;
}
protected function get mouse() : MouseManager
{
return _viewport.mouseManager;
}
protected function get viewport() : Viewport
{
return _viewport;
}
public function ScriptController(targetType : Class = null)
{
super(targetType);
}
override protected function targetAddedToSceneHandler(target : ISceneNode,
scene : Scene) : void
{
if (_scene && scene != _scene)
throw new Error(
'The same ScriptController instance can not be used in more than one scene ' +
'at a time.'
);
_scene = scene;
}
override protected function targetRemovedFromSceneHandler(target : ISceneNode,
scene : Scene) : void
{
if (numTargetsInScene == 0)
_scene = null;
}
override protected function sceneEnterFrameHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
_viewport = viewport;
_deltaTime = _lastTime - time;
_lastTime = time;
beforeUpdate();
var numTargets : uint = this.numTargets;
for (var i : uint = 0; i < numTargets; ++i)
{
var target : ISceneNode = getTarget(i);
if (target.scene)
{
if (!_started[target])
{
_started[target] = true;
start(target);
}
update(target);
}
else if (_started[target])
{
_started[target] = false;
stop(target);
}
}
afterUpdate();
}
/**
* The 'start' method is called on a script target at the first frame occuring after it
* has been added to the scene.
*
* @param target
*
*/
protected function start(target : ISceneNode) : void
{
// nothing
}
/**
* The 'beforeUpdate' method is called before each target is updated via the 'update'
* method.
*
*/
protected function beforeUpdate() : void
{
// nothing
}
protected function update(target : ISceneNode) : void
{
// nothing
}
/**
* The 'afterUpdate' method is called after each target has been updated via the 'update'
* method.
*
*/
protected function afterUpdate() : void
{
// nothing
}
/**
* The 'start' method is called on a script target at the first frame occuring after it
* has been removed from the scene.
*
* @param target
*
*/
protected function stop(target : ISceneNode) : void
{
// nothing
}
}
}
|
package aerys.minko.scene.controller
{
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.KeyboardManager;
import aerys.minko.type.MouseManager;
import flash.display.BitmapData;
import flash.utils.Dictionary;
public class ScriptController extends EnterFrameController
{
private var _scene : Scene;
private var _started : Dictionary;
private var _lastTime : Number;
private var _deltaTime : Number;
private var _currentTarget : ISceneNode;
private var _viewport : Viewport;
protected function get scene() : Scene
{
return _scene;
}
protected function get deltaTime() : Number
{
return _deltaTime;
}
protected function get keyboard() : KeyboardManager
{
return _viewport.keyboardManager;
}
protected function get mouse() : MouseManager
{
return _viewport.mouseManager;
}
protected function get viewport() : Viewport
{
return _viewport;
}
public function ScriptController(targetType : Class = null)
{
super(targetType);
}
protected function initialize() : void
{
_started = new Dictionary(true);
}
override protected function targetAddedToSceneHandler(target : ISceneNode,
scene : Scene) : void
{
if (_scene && scene != _scene)
throw new Error(
'The same ScriptController instance can not be used in more than one scene ' +
'at a time.'
);
_scene = scene;
}
override protected function targetRemovedFromSceneHandler(target : ISceneNode,
scene : Scene) : void
{
if (numTargetsInScene == 0)
_scene = null;
}
override protected function sceneEnterFrameHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
_viewport = viewport;
_deltaTime = _lastTime - time;
_lastTime = time;
beforeUpdate();
var numTargets : uint = this.numTargets;
for (var i : uint = 0; i < numTargets; ++i)
{
var target : ISceneNode = getTarget(i);
if (target.scene)
{
if (!_started[target])
{
_started[target] = true;
start(target);
}
update(target);
}
else if (_started[target])
{
_started[target] = false;
stop(target);
}
}
afterUpdate();
}
/**
* The 'start' method is called on a script target at the first frame occuring after it
* has been added to the scene.
*
* @param target
*
*/
protected function start(target : ISceneNode) : void
{
// nothing
}
/**
* The 'beforeUpdate' method is called before each target is updated via the 'update'
* method.
*
*/
protected function beforeUpdate() : void
{
// nothing
}
protected function update(target : ISceneNode) : void
{
// nothing
}
/**
* The 'afterUpdate' method is called after each target has been updated via the 'update'
* method.
*
*/
protected function afterUpdate() : void
{
// nothing
}
/**
* The 'start' method is called on a script target at the first frame occuring after it
* has been removed from the scene.
*
* @param target
*
*/
protected function stop(target : ISceneNode) : void
{
// nothing
}
}
}
|
fix missing init of ScriptController._started
|
fix missing init of ScriptController._started
|
ActionScript
|
mit
|
aerys/minko-as3
|
2842d3921d37d810cda6fb2908cdaad89a217e36
|
Arguments/src/logic/ModusTollens.as
|
Arguments/src/logic/ModusTollens.as
|
package logic
{
/**
AGORA - an interactive and web-based argument mapping tool that stimulates reasoning,
reflection, critique, deliberation, and creativity in individual argument construction
and in collaborative or adversarial settings.
Copyright (C) 2011 Georgia Institute of Technology
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import classes.ArgumentPanel;
import mx.controls.Alert;
public class ModusTollens extends ParentArg
{
public var andOr:String;
private var _isExp:Boolean;
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
myname = MOD_TOL;
_dbType = "MT";
}
override public function getOption(dbString:String):String{
if(dbString.indexOf("or") >= 0)
{
return "or";
}
else if(dbString.indexOf("and") >= 0)
{
return "and" ;
}
else
{
return "";
}
}
override public function get dbType():String
{
for(var i:int=0; i<_langTypes.length; i++)
{
if(inference.myschemeSel.selectedType == _langTypes[i]){
if(_langTypes[i] == "Only if" && inference.hasMultipleReasons){
return _dbType+dbLangTypeNames[i]+andOr;
}
else
{
return _dbType+dbLangTypeNames[i];
}
}
}
return "Unset";
}
override public function createLinks():void
{
//Negate the claim if it is the first claim of the argument
if(inference.claim.inference != null && !inference.claim.statementNegated)
{
Alert.show("Error: The claim should not have been a non-negative statement");
}
//change claim and reason from multistatement to normal
//statement type
if(inference.claim.multiStatement)
{
inference.claim.multiStatement = false;
}
for(var i:int=0; i < inference.reasons.length; i++)
{
if(inference.reasons[i].multiStatement)
{
inference.reasons[i].multiStatement = false;
}
}
if(inference.claim.userEntered == false && inference.claim.inference == null && inference.claim.rules.length < 2)
{
inference.claim.input1.text = "P";
inference.claim.makeUnEditable();
inference.reasons[0].input1.text = "Q";
inference.reasons[0].makeUnEditable();
}
if(!inference.claim.statementNegated)
{
inference.claim.statementNegated = true;
}
for(i = 0; i < inference.reasons.length; i++)
{
if(!inference.reasons[i].statementNegated)
{
inference.reasons[i].statementNegated = true;
}
}
inference.implies = true;
var claim:ArgumentPanel = inference.claim;
var reasons:Vector.<ArgumentPanel> = inference.reasons;
claim.input1.forwardList.push(inference.input[0]);
inference.input[0].forwardList.push(inference.inputs[1]);
for(i=0; i < reasons.length; i++)
{
reasons[i].input1.forwardList.push(inference.input[i+1]);
inference.input[i+1].forwardList.push(inference.inputs[0]);
}
inference.implies = true;
}
override public function correctUsage():String {
var output:String = "";
var reason:Vector.<ArgumentPanel> = inference.reasons;
var claim:ArgumentPanel = inference.claim;
var i:int;
//Negate the reason. The reason will not be supported by other
//arguments. If it were, the argument woud have had 'typed' true,
//and myArg would not be pointing to a Modus Tollens Object
switch(inference.myschemeSel.selectedType) {
//negate reason
case _langTypes[0]: //If-then. If both claim and reason negated
//output += "If " + claim.positiveStmt + ", then "+ reason[0].positiveStmt;
inference.inputs[0].text = reason[0].positiveStmt;
inference.inputs[1].text = claim.positiveStmt;
output = Language.lookup("ArgIfCap") + inference.inputs[1].text + ","
+ Language.lookup("ArgThen") + inference.inputs[0].text;
inference.inputs[0].forwardUpdate();
inference.inputs[1].forwardUpdate();
break;
case _langTypes[1]: // Implies
output += claim.positiveStmt + Language.lookup("ArgImplies") + reason[0].positiveStmt;
inference.inputs[0].text = reason[0].positiveStmt;
inference.inputs[1].text = claim.positiveStmt;
inference.inputs[0].forwardUpdate();
inference.inputs[1].forwardUpdate();
break;
case _langTypes[2]: //Whenever
output += Language.lookup("ArgWhenever") + claim.positiveStmt + ", " + reason[0].positiveStmt;
inference.inputs[0].text = reason[0].positiveStmt;
inference.inputs[1].text = claim.positiveStmt;
inference.inputs[0].forwardUpdate();
inference.inputs[1].forwardUpdate();
break;
case _langTypes[3]: // Only if
var reasonStr:String = "";
output += claim.positiveStmt + Language.lookup("ArgOnlyIf");
for(i=0;i<reason.length-1;i++)
{
output += reason[i].positiveStmt + " " + andOr + " ";
reasonStr = reasonStr + reason[i].positiveStmt + " " + andOr + " ";
}
reasonStr = reasonStr + reason[i].positiveStmt;
output += reason[reason.length-1].positiveStmt;
inference.inputs[0].text = reasonStr;
inference.inputs[1].text = claim.positiveStmt;
inference.inputs[0].forwardUpdate();
inference.inputs[1].forwardUpdate();
break;
case _langTypes[4]: // Provided that
output += reason[0].positiveStmt + Language.lookup("ArgProvidedThat") + claim.positiveStmt;
inference.inputs[0].text = reason[0].positiveStmt;
inference.inputs[1].text = claim.positiveStmt;
inference.inputs[0].forwardUpdate();
inference.inputs[1].forwardUpdate();
break;
case _langTypes[5]: // Sufficient condition
output += claim.positiveStmt + Language.lookup("ArgSufficientCond") + reason[0].positiveStmt;
inference.inputs[0].text = reason[0].positiveStmt;
inference.inputs[1].text = claim.positiveStmt;
inference.inputs[0].forwardUpdate();
inference.inputs[1].forwardUpdate();
break;
case _langTypes[6]: // Necessary condition
output += reason[0].positiveStmt + Language.lookup("ArgNecessaryCond") + claim.positiveStmt;
inference.inputs[0].text = reason[0].positiveStmt;
inference.inputs[1].text = claim.positiveStmt;
inference.inputs[0].forwardUpdate();
inference.inputs[1].forwardUpdate();
break;
}
return output;
}
}
}
|
package logic
{
/**
AGORA - an interactive and web-based argument mapping tool that stimulates reasoning,
reflection, critique, deliberation, and creativity in individual argument construction
and in collaborative or adversarial settings.
Copyright (C) 2011 Georgia Institute of Technology
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import classes.ArgumentPanel;
import classes.Language;
import mx.controls.Alert;
public class ModusTollens extends ParentArg
{
public var andOr:String;
private var _isExp:Boolean;
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
myname = MOD_TOL;
_dbType = "MT";
}
override public function getOption(dbString:String):String{
if(dbString.indexOf("or") >= 0)
{
return "or";
}
else if(dbString.indexOf("and") >= 0)
{
return "and" ;
}
else
{
return "";
}
}
override public function get dbType():String
{
for(var i:int=0; i<_langTypes.length; i++)
{
if(inference.myschemeSel.selectedType == _langTypes[i]){
if(_langTypes[i] == "Only if" && inference.hasMultipleReasons){
return _dbType+dbLangTypeNames[i]+andOr;
}
else
{
return _dbType+dbLangTypeNames[i];
}
}
}
return "Unset";
}
override public function createLinks():void
{
//Negate the claim if it is the first claim of the argument
if(inference.claim.inference != null && !inference.claim.statementNegated)
{
Alert.show("Error: The claim should not have been a non-negative statement");
}
//change claim and reason from multistatement to normal
//statement type
if(inference.claim.multiStatement)
{
inference.claim.multiStatement = false;
}
for(var i:int=0; i < inference.reasons.length; i++)
{
if(inference.reasons[i].multiStatement)
{
inference.reasons[i].multiStatement = false;
}
}
if(inference.claim.userEntered == false && inference.claim.inference == null && inference.claim.rules.length < 2)
{
inference.claim.input1.text = "P";
inference.claim.makeUnEditable();
inference.reasons[0].input1.text = "Q";
inference.reasons[0].makeUnEditable();
}
if(!inference.claim.statementNegated)
{
inference.claim.statementNegated = true;
}
for(i = 0; i < inference.reasons.length; i++)
{
if(!inference.reasons[i].statementNegated)
{
inference.reasons[i].statementNegated = true;
}
}
inference.implies = true;
var claim:ArgumentPanel = inference.claim;
var reasons:Vector.<ArgumentPanel> = inference.reasons;
claim.input1.forwardList.push(inference.input[0]);
inference.input[0].forwardList.push(inference.inputs[1]);
for(i=0; i < reasons.length; i++)
{
reasons[i].input1.forwardList.push(inference.input[i+1]);
inference.input[i+1].forwardList.push(inference.inputs[0]);
}
inference.implies = true;
}
override public function correctUsage():String {
var output:String = "";
var reason:Vector.<ArgumentPanel> = inference.reasons;
var claim:ArgumentPanel = inference.claim;
var i:int;
//Negate the reason. The reason will not be supported by other
//arguments. If it were, the argument woud have had 'typed' true,
//and myArg would not be pointing to a Modus Tollens Object
switch(inference.myschemeSel.selectedType) {
//negate reason
case _langTypes[0]: //If-then. If both claim and reason negated
//output += "If " + claim.positiveStmt + ", then "+ reason[0].positiveStmt;
inference.inputs[0].text = reason[0].positiveStmt;
inference.inputs[1].text = claim.positiveStmt;
output = Language.lookup("ArgIfCap") + inference.inputs[1].text + ","
+ Language.lookup("ArgThen") + inference.inputs[0].text;
inference.inputs[0].forwardUpdate();
inference.inputs[1].forwardUpdate();
break;
case _langTypes[1]: // Implies
output += claim.positiveStmt + Language.lookup("ArgImplies") + reason[0].positiveStmt;
inference.inputs[0].text = reason[0].positiveStmt;
inference.inputs[1].text = claim.positiveStmt;
inference.inputs[0].forwardUpdate();
inference.inputs[1].forwardUpdate();
break;
case _langTypes[2]: //Whenever
output += Language.lookup("ArgWhenever") + claim.positiveStmt + ", " + reason[0].positiveStmt;
inference.inputs[0].text = reason[0].positiveStmt;
inference.inputs[1].text = claim.positiveStmt;
inference.inputs[0].forwardUpdate();
inference.inputs[1].forwardUpdate();
break;
case _langTypes[3]: // Only if
var reasonStr:String = "";
output += claim.positiveStmt + Language.lookup("ArgOnlyIf");
for(i=0;i<reason.length-1;i++)
{
output += reason[i].positiveStmt + " " + andOr + " ";
reasonStr = reasonStr + reason[i].positiveStmt + " " + andOr + " ";
}
reasonStr = reasonStr + reason[i].positiveStmt;
output += reason[reason.length-1].positiveStmt;
inference.inputs[0].text = reasonStr;
inference.inputs[1].text = claim.positiveStmt;
inference.inputs[0].forwardUpdate();
inference.inputs[1].forwardUpdate();
break;
case _langTypes[4]: // Provided that
output += reason[0].positiveStmt + Language.lookup("ArgProvidedThat") + claim.positiveStmt;
inference.inputs[0].text = reason[0].positiveStmt;
inference.inputs[1].text = claim.positiveStmt;
inference.inputs[0].forwardUpdate();
inference.inputs[1].forwardUpdate();
break;
case _langTypes[5]: // Sufficient condition
output += claim.positiveStmt + Language.lookup("ArgSufficientCond") + reason[0].positiveStmt;
inference.inputs[0].text = reason[0].positiveStmt;
inference.inputs[1].text = claim.positiveStmt;
inference.inputs[0].forwardUpdate();
inference.inputs[1].forwardUpdate();
break;
case _langTypes[6]: // Necessary condition
output += reason[0].positiveStmt + Language.lookup("ArgNecessaryCond") + claim.positiveStmt;
inference.inputs[0].text = reason[0].positiveStmt;
inference.inputs[1].text = claim.positiveStmt;
inference.inputs[0].forwardUpdate();
inference.inputs[1].forwardUpdate();
break;
}
return output;
}
}
}
|
Fix missing import
|
Fix missing import
|
ActionScript
|
agpl-3.0
|
mbjornas3/AGORA,MichaelHoffmann/AGORA,MichaelHoffmann/AGORA,MichaelHoffmann/AGORA,mbjornas3/AGORA
|
075b03fcac4b7ea46a8ea4e7143450cf1fca3b80
|
src/org/mangui/hls/model/FragmentData.as
|
src/org/mangui/hls/model/FragmentData.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.model {
import org.mangui.hls.demux.ID3Tag;
import org.mangui.hls.flv.FLVTag;
import org.mangui.hls.utils.AES;
import org.mangui.hls.utils.PTS;
import flash.utils.ByteArray;
/** Fragment Data. **/
public class FragmentData {
/** valid fragment **/
public var valid : Boolean;
/** fragment byte array **/
public var bytes : ByteArray;
/** bytes Loaded **/
public var bytesLoaded : int;
/** AES decryption instance **/
public var decryptAES : AES;
/** Start PTS of this chunk. **/
public var pts_start : Number;
/** computed Start PTS of this chunk. **/
public var pts_start_computed : Number;
/** min/max audio/video PTS/DTS of this chunk. **/
public var pts_min_audio : Number;
public var pts_max_audio : Number;
public var pts_min_video : Number;
public var pts_max_video : Number;
public var dts_min : Number;
/** audio/video found ? */
public var audio_found : Boolean;
public var video_found : Boolean;
/** tag related stuff */
public var metadata_tag_injected : Boolean;
private var tags_pts_min_audio : Number;
private var tags_pts_max_audio : Number;
private var tags_pts_min_video : Number;
private var tags_pts_max_video : Number;
private var tags_audio_found : Boolean;
private var tags_video_found : Boolean;
public var tags : Vector.<FLVTag>;
/* video dimension */
public var video_width : int;
public var video_height : int;
/* is fragment loaded selected by autolevel algo */
public var auto_level : Boolean;
/* ID3 tags linked to this fragment */
public var id3_tags : Vector.<ID3Tag>;
/** tag duration */
private var audio_tag_duration : Number;
private var video_tag_duration : Number;
private var audio_tag_last_dts : Number;
private var video_tag_last_dts : Number;
/** Fragment metrics **/
public function FragmentData() {
this.pts_start = NaN;
this.pts_start_computed = NaN;
this.valid = true;
this.video_width = 0;
this.video_height = 0;
};
public function appendTags(tags : Vector.<FLVTag>) : void {
// Audio PTS/DTS normalization + min/max computation
for each (var tag : FLVTag in tags) {
tag.pts = PTS.normalize(pts_start_computed, tag.pts);
tag.dts = PTS.normalize(pts_start_computed, tag.dts);
dts_min = Math.min(dts_min, tag.dts);
switch( tag.type ) {
case FLVTag.AAC_RAW:
case FLVTag.AAC_HEADER:
case FLVTag.MP3_RAW:
audio_found = true;
tags_audio_found = true;
audio_tag_duration = tag.dts - audio_tag_last_dts;
audio_tag_last_dts = tag.dts;
tags_pts_min_audio = Math.min(tags_pts_min_audio, tag.pts);
tags_pts_max_audio = Math.max(tags_pts_max_audio, tag.pts);
pts_min_audio = Math.min(pts_min_audio, tag.pts);
pts_max_audio = Math.max(pts_max_audio, tag.pts);
break;
case FLVTag.AVC_HEADER:
case FLVTag.AVC_NALU:
video_found = true;
tags_video_found = true;
video_tag_duration = tag.dts - video_tag_last_dts;
video_tag_last_dts = tag.dts;
tags_pts_min_video = Math.min(tags_pts_min_video, tag.pts);
tags_pts_max_video = Math.max(tags_pts_max_video, tag.pts);
pts_min_video = Math.min(pts_min_video, tag.pts);
pts_max_video = Math.max(pts_max_video, tag.pts);
break;
case FLVTag.DISCONTINUITY:
case FLVTag.METADATA:
default:
break;
}
this.tags.push(tag);
}
}
public function flushTags() : void {
// clean-up tags
tags = new Vector.<FLVTag>();
tags_audio_found = tags_video_found = false;
metadata_tag_injected = false;
pts_min_audio = pts_min_video = dts_min = tags_pts_min_audio = tags_pts_min_video = Number.POSITIVE_INFINITY;
pts_max_audio = pts_max_video = tags_pts_max_audio = tags_pts_max_video = Number.NEGATIVE_INFINITY;
audio_found = video_found = tags_audio_found = tags_video_found = false;
}
public function shiftTags() : void {
tags = new Vector.<FLVTag>();
if (tags_audio_found) {
tags_pts_min_audio = tags_pts_max_audio;
tags_audio_found = false;
}
if (tags_video_found) {
tags_pts_min_video = tags_pts_max_video;
tags_video_found = false;
}
}
public function get pts_min() : Number {
if (audio_found) {
return pts_min_audio;
} else {
return pts_min_video;
}
}
public function get pts_max() : Number {
if (audio_found) {
return pts_max_audio;
} else {
return pts_max_video;
}
}
public function get tag_duration() : Number {
var duration : Number;
if (audio_found) {
duration = audio_tag_duration;
} else {
duration = video_tag_duration;
}
if(isNaN(duration)) {
duration = 0;
}
return duration;
}
public function get tag_pts_min() : Number {
if (audio_found) {
return tags_pts_min_audio;
} else {
return tags_pts_min_video;
}
}
public function get tag_pts_max() : Number {
if (audio_found) {
return tags_pts_max_audio;
} else {
return tags_pts_max_video;
}
}
public function get tag_pts_start_offset() : Number {
if (tags_audio_found) {
return tags_pts_min_audio - pts_min_audio;
} else {
return tags_pts_min_video - pts_min_video;
}
}
public function get tag_pts_end_offset() : Number {
if (tags_audio_found) {
return tags_pts_max_audio - pts_min_audio;
} else {
return tags_pts_max_video - pts_min_video;
}
}
}
}
|
/* 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.model {
import org.mangui.hls.demux.ID3Tag;
import org.mangui.hls.flv.FLVTag;
import org.mangui.hls.utils.AES;
import org.mangui.hls.utils.PTS;
import flash.utils.ByteArray;
/** Fragment Data. **/
public class FragmentData {
/** valid fragment **/
public var valid : Boolean;
/** fragment byte array **/
public var bytes : ByteArray;
/* Total bytes this Fragment _will_ have */
public var bytesTotal: int;
/** bytes Loaded **/
public var bytesLoaded : int;
/** AES decryption instance **/
public var decryptAES : AES;
/** Start PTS of this chunk. **/
public var pts_start : Number;
/** computed Start PTS of this chunk. **/
public var pts_start_computed : Number;
/** min/max audio/video PTS/DTS of this chunk. **/
public var pts_min_audio : Number;
public var pts_max_audio : Number;
public var pts_min_video : Number;
public var pts_max_video : Number;
public var dts_min : Number;
/** audio/video found ? */
public var audio_found : Boolean;
public var video_found : Boolean;
/** tag related stuff */
public var metadata_tag_injected : Boolean;
private var tags_pts_min_audio : Number;
private var tags_pts_max_audio : Number;
private var tags_pts_min_video : Number;
private var tags_pts_max_video : Number;
private var tags_audio_found : Boolean;
private var tags_video_found : Boolean;
public var tags : Vector.<FLVTag>;
/* video dimension */
public var video_width : int;
public var video_height : int;
/* is fragment loaded selected by autolevel algo */
public var auto_level : Boolean;
/* ID3 tags linked to this fragment */
public var id3_tags : Vector.<ID3Tag>;
/** tag duration */
private var audio_tag_duration : Number;
private var video_tag_duration : Number;
private var audio_tag_last_dts : Number;
private var video_tag_last_dts : Number;
/** Fragment metrics **/
public function FragmentData() {
this.pts_start = NaN;
this.pts_start_computed = NaN;
this.valid = true;
this.video_width = 0;
this.video_height = 0;
};
public function appendTags(tags : Vector.<FLVTag>) : void {
// Audio PTS/DTS normalization + min/max computation
for each (var tag : FLVTag in tags) {
tag.pts = PTS.normalize(pts_start_computed, tag.pts);
tag.dts = PTS.normalize(pts_start_computed, tag.dts);
dts_min = Math.min(dts_min, tag.dts);
switch( tag.type ) {
case FLVTag.AAC_RAW:
case FLVTag.AAC_HEADER:
case FLVTag.MP3_RAW:
audio_found = true;
tags_audio_found = true;
audio_tag_duration = tag.dts - audio_tag_last_dts;
audio_tag_last_dts = tag.dts;
tags_pts_min_audio = Math.min(tags_pts_min_audio, tag.pts);
tags_pts_max_audio = Math.max(tags_pts_max_audio, tag.pts);
pts_min_audio = Math.min(pts_min_audio, tag.pts);
pts_max_audio = Math.max(pts_max_audio, tag.pts);
break;
case FLVTag.AVC_HEADER:
case FLVTag.AVC_NALU:
video_found = true;
tags_video_found = true;
video_tag_duration = tag.dts - video_tag_last_dts;
video_tag_last_dts = tag.dts;
tags_pts_min_video = Math.min(tags_pts_min_video, tag.pts);
tags_pts_max_video = Math.max(tags_pts_max_video, tag.pts);
pts_min_video = Math.min(pts_min_video, tag.pts);
pts_max_video = Math.max(pts_max_video, tag.pts);
break;
case FLVTag.DISCONTINUITY:
case FLVTag.METADATA:
default:
break;
}
this.tags.push(tag);
}
}
public function flushTags() : void {
// clean-up tags
tags = new Vector.<FLVTag>();
tags_audio_found = tags_video_found = false;
metadata_tag_injected = false;
pts_min_audio = pts_min_video = dts_min = tags_pts_min_audio = tags_pts_min_video = Number.POSITIVE_INFINITY;
pts_max_audio = pts_max_video = tags_pts_max_audio = tags_pts_max_video = Number.NEGATIVE_INFINITY;
audio_found = video_found = tags_audio_found = tags_video_found = false;
}
public function shiftTags() : void {
tags = new Vector.<FLVTag>();
if (tags_audio_found) {
tags_pts_min_audio = tags_pts_max_audio;
tags_audio_found = false;
}
if (tags_video_found) {
tags_pts_min_video = tags_pts_max_video;
tags_video_found = false;
}
}
public function get pts_min() : Number {
if (audio_found) {
return pts_min_audio;
} else {
return pts_min_video;
}
}
public function get pts_max() : Number {
if (audio_found) {
return pts_max_audio;
} else {
return pts_max_video;
}
}
public function get tag_duration() : Number {
var duration : Number;
if (audio_found) {
duration = audio_tag_duration;
} else {
duration = video_tag_duration;
}
if(isNaN(duration)) {
duration = 0;
}
return duration;
}
public function get tag_pts_min() : Number {
if (audio_found) {
return tags_pts_min_audio;
} else {
return tags_pts_min_video;
}
}
public function get tag_pts_max() : Number {
if (audio_found) {
return tags_pts_max_audio;
} else {
return tags_pts_max_video;
}
}
public function get tag_pts_start_offset() : Number {
if (tags_audio_found) {
return tags_pts_min_audio - pts_min_audio;
} else {
return tags_pts_min_video - pts_min_video;
}
}
public function get tag_pts_end_offset() : Number {
if (tags_audio_found) {
return tags_pts_max_audio - pts_min_audio;
} else {
return tags_pts_max_video - pts_min_video;
}
}
}
}
|
Add bytesTotal
|
[Mangui.FragmentData] Add bytesTotal
Parallel of ProgressEvent.bytesTotal. Used by FragmentStream.
|
ActionScript
|
mpl-2.0
|
codex-corp/flashls,codex-corp/flashls
|
165af193b98df393361f3ba50cf3e3c98e08b15b
|
frameworks/projects/framework/src/mx/utils/UIDUtil.as
|
frameworks/projects/framework/src/mx/utils/UIDUtil.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package mx.utils
{
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import mx.core.IPropertyChangeNotifier;
import mx.core.IUIComponent;
import mx.core.IUID;
import mx.core.mx_internal;
use namespace mx_internal;
/**
* The UIDUtil class is an all-static class
* with methods for working with UIDs (unique identifiers) within Flex.
* You do not create instances of UIDUtil;
* instead you simply call static methods such as the
* <code>UIDUtil.createUID()</code> method.
*
* <p><b>Note</b>: If you have a dynamic object that has no [Bindable] properties
* (which force the object to implement the IUID interface), Flex adds an
* <code>mx_internal_uid</code> property that contains a UID to the object.
* To avoid having this field
* in your dynamic object, make it [Bindable], implement the IUID interface
* in the object class, or set a <coded>uid</coded> property with a value.</p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public class UIDUtil
{
include "../core/Version.as";
//--------------------------------------------------------------------------
//
// Class constants
//
//--------------------------------------------------------------------------
/**
* @private
* Char codes for 0123456789ABCDEF
*/
private static const ALPHA_CHAR_CODES:Array = [48, 49, 50, 51, 52, 53, 54,
55, 56, 57, 65, 66, 67, 68, 69, 70];
private static const DASH:int = 45; // dash ascii
private static const UIDBuffer:ByteArray = new ByteArray(); // static ByteArray used for UID generation to save memory allocation cost
//--------------------------------------------------------------------------
//
// Class variables
//
//--------------------------------------------------------------------------
/**
* This Dictionary records all generated uids for all existing items.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
private static var uidDictionary:Dictionary = new Dictionary(true);
//--------------------------------------------------------------------------
//
// Class methods
//
//--------------------------------------------------------------------------
/**
* Generates a UID (unique identifier) based on ActionScript's
* pseudo-random number generator and the current time.
*
* <p>The UID has the form
* <code>"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"</code>
* where X is a hexadecimal digit (0-9, A-F).</p>
*
* <p>This UID will not be truly globally unique; but it is the best
* we can do without player support for UID generation.</p>
*
* @return The newly-generated UID.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static function createUID():String
{
UIDBuffer.position = 0;
var i:int;
var j:int;
for (i = 0; i < 8; i++)
{
UIDBuffer.writeByte(ALPHA_CHAR_CODES[int(Math.random() * 16)]);
}
for (i = 0; i < 3; i++)
{
UIDBuffer.writeByte(DASH);
for (j = 0; j < 4; j++)
{
UIDBuffer.writeByte(ALPHA_CHAR_CODES[int(Math.random() * 16)]);
}
}
UIDBuffer.writeByte(DASH);
var time:uint = new Date().getTime(); // extract last 8 digits
var timeString:String = time.toString(16).toUpperCase();
// 0xFFFFFFFF milliseconds ~= 3 days, so timeString may have between 1 and 8 digits, hence we need to pad with 0s to 8 digits
for (i = 8; i > timeString.length; --i)
UIDBuffer.writeByte(48);
UIDBuffer.writeUTFBytes(timeString);
for (i = 0; i < 4; i++)
{
UIDBuffer.writeByte(ALPHA_CHAR_CODES[int(Math.random() * 16)]);
}
return UIDBuffer.toString();
}
/**
* Converts a 128-bit UID encoded as a ByteArray to a String representation.
* The format matches that generated by createUID. If a suitable ByteArray
* is not provided, null is returned.
*
* @param ba ByteArray 16 bytes in length representing a 128-bit UID.
*
* @return String representation of the UID, or null if an invalid
* ByteArray is provided.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static function fromByteArray(ba:ByteArray):String
{
if (ba != null && ba.length >= 16 && ba.bytesAvailable >= 16)
{
var chars:Array = new Array(36);
var index:uint = 0;
for (var i:uint = 0; i < 16; i++)
{
if (i == 4 || i == 6 || i == 8 || i == 10)
chars[index++] = DASH; // Hyphen char code
var b:int = ba.readByte();
chars[index++] = ALPHA_CHAR_CODES[(b & 0xF0) >>> 4];
chars[index++] = ALPHA_CHAR_CODES[(b & 0x0F)];
}
return String.fromCharCode.apply(null, chars);
}
return null;
}
/**
* A utility method to check whether a String value represents a
* correctly formatted UID value. UID values are expected to be
* in the format generated by createUID(), implying that only
* capitalized A-F characters in addition to 0-9 digits are
* supported.
*
* @param uid The value to test whether it is formatted as a UID.
*
* @return Returns true if the value is formatted as a UID.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static function isUID(uid:String):Boolean
{
if (uid != null && uid.length == 36)
{
for (var i:uint = 0; i < 36; i++)
{
var c:Number = uid.charCodeAt(i);
// Check for correctly placed hyphens
if (i == 8 || i == 13 || i == 18 || i == 23)
{
if (c != DASH)
{
return false;
}
}
// We allow capital alpha-numeric hex digits only
else if (c < 48 || c > 70 || (c > 57 && c < 65))
{
return false;
}
}
return true;
}
return false;
}
/**
* Converts a UID formatted String to a ByteArray. The UID must be in the
* format generated by createUID, otherwise null is returned.
*
* @param String representing a 128-bit UID
*
* @return ByteArray 16 bytes in length representing the 128-bits of the
* UID or null if the uid could not be converted.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static function toByteArray(uid:String):ByteArray
{
if (isUID(uid))
{
var result:ByteArray = new ByteArray();
for (var i:uint = 0; i < uid.length; i++)
{
var c:String = uid.charAt(i);
if (c == "-")
continue;
var h1:uint = getDigit(c);
i++;
var h2:uint = getDigit(uid.charAt(i));
result.writeByte(((h1 << 4) | h2) & 0xFF);
}
result.position = 0;
return result;
}
return null;
}
/**
* Returns the UID (unique identifier) for the specified object.
* If the specified object doesn't have an UID
* then the method assigns one to it.
* If a map is specified this method will use the map
* to construct the UID.
* As a special case, if the item passed in is null,
* this method returns a null UID.
*
* @param item Object that we need to find the UID for.
*
* @return The UID that was either found or generated.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static function getUID(item:Object):String
{
var result:String = null;
if (item == null)
return result;
if (item is IUID)
{
result = IUID(item).uid;
if (result == null || result.length == 0)
{
result = createUID();
IUID(item).uid = result;
}
}
else if ((item is IPropertyChangeNotifier) &&
!(item is IUIComponent))
{
result = IPropertyChangeNotifier(item).uid;
if (result == null || result.length == 0)
{
result = createUID();
IPropertyChangeNotifier(item).uid = result;
}
}
else if (item is String)
{
return item as String;
}
else
{
try
{
// We don't create uids for XMLLists, but if
// there's only a single XML node, we'll extract it.
if (item is XMLList && item.length == 1)
item = item[0];
if (item is XML)
{
// XML nodes carry their UID on the
// function-that-is-a-hashtable they can carry around.
// To decorate an XML node with a UID,
// we need to first initialize it for notification.
// There is a potential performance issue here,
// since notification does have a cost,
// but most use cases for needing a UID on an XML node also
// require listening for change notifications on the node.
var xitem:XML = XML(item);
var nodeKind:String = xitem.nodeKind();
if (nodeKind == "text" || nodeKind == "attribute")
return xitem.toString();
var notificationFunction:Function = xitem.notification();
if (!(notificationFunction is Function))
{
// The xml node hasn't already been initialized
// for notification, so do so now.
notificationFunction =
XMLNotifier.initializeXMLForNotification();
xitem.setNotification(notificationFunction);
}
// Generate a new uid for the node if necessary.
if (notificationFunction["uid"] == undefined)
result = notificationFunction["uid"] = createUID();
result = notificationFunction["uid"];
}
else
{
if ("mx_internal_uid" in item)
return item.mx_internal_uid;
if ("uid" in item)
return item.uid;
result = uidDictionary[item];
if (!result)
{
result = createUID();
try
{
item.mx_internal_uid = result;
}
catch(e:Error)
{
uidDictionary[item] = result;
}
}
}
}
catch(e:Error)
{
result = item.toString();
}
}
return result;
}
/**
* Returns the decimal representation of a hex digit.
* @private
*/
private static function getDigit(hex:String):uint
{
switch (hex)
{
case "A":
case "a":
return 10;
case "B":
case "b":
return 11;
case "C":
case "c":
return 12;
case "D":
case "d":
return 13;
case "E":
case "e":
return 14;
case "F":
case "f":
return 15;
default:
return new uint(hex);
}
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package mx.utils
{
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import mx.core.IPropertyChangeNotifier;
import mx.core.IUIComponent;
import mx.core.IUID;
import mx.core.mx_internal;
use namespace mx_internal;
/**
* The UIDUtil class is an all-static class
* with methods for working with UIDs (unique identifiers) within Flex.
* You do not create instances of UIDUtil;
* instead you simply call static methods such as the
* <code>UIDUtil.createUID()</code> method.
*
* <p><b>Note</b>: If you have a dynamic object that has no [Bindable] properties
* (which force the object to implement the IUID interface), Flex adds an
* <code>mx_internal_uid</code> property that contains a UID to the object.
* To avoid having this field
* in your dynamic object, make it [Bindable], implement the IUID interface
* in the object class, or set a <coded>uid</coded> property with a value.</p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public class UIDUtil
{
include "../core/Version.as";
//--------------------------------------------------------------------------
//
// Class constants
//
//--------------------------------------------------------------------------
/**
* @private
* Char codes for 0123456789ABCDEF
*/
private static const ALPHA_CHAR_CODES:Array = [48, 49, 50, 51, 52, 53, 54,
55, 56, 57, 65, 66, 67, 68, 69, 70];
private static const DASH:int = 45; // dash ascii
private static const UIDBuffer:ByteArray = new ByteArray(); // static ByteArray used for UID generation to save memory allocation cost
//--------------------------------------------------------------------------
//
// Class variables
//
//--------------------------------------------------------------------------
/**
* This Dictionary records all generated uids for all existing items.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
private static var uidDictionary:Dictionary = new Dictionary(true);
//--------------------------------------------------------------------------
//
// Class methods
//
//--------------------------------------------------------------------------
/**
* Generates a UID (unique identifier) based on ActionScript's
* pseudo-random number generator and the current time.
*
* <p>The UID has the form
* <code>"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"</code>
* where X is a hexadecimal digit (0-9, A-F).</p>
*
* <p>This UID will not be truly globally unique; but it is the best
* we can do without player support for UID generation.</p>
*
* @return The newly-generated UID.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static function createUID():String
{
UIDBuffer.position = 0;
var i:int;
var j:int;
for (i = 0; i < 8; i++)
{
UIDBuffer.writeByte(ALPHA_CHAR_CODES[int(Math.random() * 16)]);
}
for (i = 0; i < 3; i++)
{
UIDBuffer.writeByte(DASH);
for (j = 0; j < 4; j++)
{
UIDBuffer.writeByte(ALPHA_CHAR_CODES[int(Math.random() * 16)]);
}
}
UIDBuffer.writeByte(DASH);
var time:uint = new Date().getTime(); // extract last 8 digits
var timeString:String = time.toString(16).toUpperCase();
// 0xFFFFFFFF milliseconds ~= 3 days, so timeString may have between 1 and 8 digits, hence we need to pad with 0s to 8 digits
for (i = 8; i > timeString.length; i--)
UIDBuffer.writeByte(48);
UIDBuffer.writeUTFBytes(timeString);
for (i = 0; i < 4; i++)
{
UIDBuffer.writeByte(ALPHA_CHAR_CODES[int(Math.random() * 16)]);
}
return UIDBuffer.toString();
}
/**
* Converts a 128-bit UID encoded as a ByteArray to a String representation.
* The format matches that generated by createUID. If a suitable ByteArray
* is not provided, null is returned.
*
* @param ba ByteArray 16 bytes in length representing a 128-bit UID.
*
* @return String representation of the UID, or null if an invalid
* ByteArray is provided.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static function fromByteArray(ba:ByteArray):String
{
if (ba != null && ba.length >= 16 && ba.bytesAvailable >= 16)
{
var chars:Array = new Array(36);
var index:uint = 0;
for (var i:uint = 0; i < 16; i++)
{
if (i == 4 || i == 6 || i == 8 || i == 10)
chars[index++] = DASH; // Hyphen char code
var b:int = ba.readByte();
chars[index++] = ALPHA_CHAR_CODES[(b & 0xF0) >>> 4];
chars[index++] = ALPHA_CHAR_CODES[(b & 0x0F)];
}
return String.fromCharCode.apply(null, chars);
}
return null;
}
/**
* A utility method to check whether a String value represents a
* correctly formatted UID value. UID values are expected to be
* in the format generated by createUID(), implying that only
* capitalized A-F characters in addition to 0-9 digits are
* supported.
*
* @param uid The value to test whether it is formatted as a UID.
*
* @return Returns true if the value is formatted as a UID.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static function isUID(uid:String):Boolean
{
if (uid != null && uid.length == 36)
{
for (var i:uint = 0; i < 36; i++)
{
var c:Number = uid.charCodeAt(i);
// Check for correctly placed hyphens
if (i == 8 || i == 13 || i == 18 || i == 23)
{
if (c != DASH)
{
return false;
}
}
// We allow capital alpha-numeric hex digits only
else if (c < 48 || c > 70 || (c > 57 && c < 65))
{
return false;
}
}
return true;
}
return false;
}
/**
* Converts a UID formatted String to a ByteArray. The UID must be in the
* format generated by createUID, otherwise null is returned.
*
* @param String representing a 128-bit UID
*
* @return ByteArray 16 bytes in length representing the 128-bits of the
* UID or null if the uid could not be converted.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static function toByteArray(uid:String):ByteArray
{
if (isUID(uid))
{
var result:ByteArray = new ByteArray();
for (var i:uint = 0; i < uid.length; i++)
{
var c:String = uid.charAt(i);
if (c == "-")
continue;
var h1:uint = getDigit(c);
i++;
var h2:uint = getDigit(uid.charAt(i));
result.writeByte(((h1 << 4) | h2) & 0xFF);
}
result.position = 0;
return result;
}
return null;
}
/**
* Returns the UID (unique identifier) for the specified object.
* If the specified object doesn't have an UID
* then the method assigns one to it.
* If a map is specified this method will use the map
* to construct the UID.
* As a special case, if the item passed in is null,
* this method returns a null UID.
*
* @param item Object that we need to find the UID for.
*
* @return The UID that was either found or generated.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static function getUID(item:Object):String
{
var result:String = null;
if (item == null)
return result;
if (item is IUID)
{
result = IUID(item).uid;
if (result == null || result.length == 0)
{
result = createUID();
IUID(item).uid = result;
}
}
else if ((item is IPropertyChangeNotifier) &&
!(item is IUIComponent))
{
result = IPropertyChangeNotifier(item).uid;
if (result == null || result.length == 0)
{
result = createUID();
IPropertyChangeNotifier(item).uid = result;
}
}
else if (item is String)
{
return item as String;
}
else
{
try
{
// We don't create uids for XMLLists, but if
// there's only a single XML node, we'll extract it.
if (item is XMLList && item.length == 1)
item = item[0];
if (item is XML)
{
// XML nodes carry their UID on the
// function-that-is-a-hashtable they can carry around.
// To decorate an XML node with a UID,
// we need to first initialize it for notification.
// There is a potential performance issue here,
// since notification does have a cost,
// but most use cases for needing a UID on an XML node also
// require listening for change notifications on the node.
var xitem:XML = XML(item);
var nodeKind:String = xitem.nodeKind();
if (nodeKind == "text" || nodeKind == "attribute")
return xitem.toString();
var notificationFunction:Function = xitem.notification();
if (!(notificationFunction is Function))
{
// The xml node hasn't already been initialized
// for notification, so do so now.
notificationFunction =
XMLNotifier.initializeXMLForNotification();
xitem.setNotification(notificationFunction);
}
// Generate a new uid for the node if necessary.
if (notificationFunction["uid"] == undefined)
result = notificationFunction["uid"] = createUID();
result = notificationFunction["uid"];
}
else
{
if ("mx_internal_uid" in item)
return item.mx_internal_uid;
if ("uid" in item)
return item.uid;
result = uidDictionary[item];
if (!result)
{
result = createUID();
try
{
item.mx_internal_uid = result;
}
catch(e:Error)
{
uidDictionary[item] = result;
}
}
}
}
catch(e:Error)
{
result = item.toString();
}
}
return result;
}
/**
* Returns the decimal representation of a hex digit.
* @private
*/
private static function getDigit(hex:String):uint
{
switch (hex)
{
case "A":
case "a":
return 10;
case "B":
case "b":
return 11;
case "C":
case "c":
return 12;
case "D":
case "d":
return 13;
case "E":
case "e":
return 14;
case "F":
case "f":
return 15;
default:
return new uint(hex);
}
}
}
}
|
UPDATE FLEX-33829 improve create UID performance and use fix minor issue
|
UPDATE FLEX-33829 improve create UID performance and use
fix minor issue
|
ActionScript
|
apache-2.0
|
adufilie/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk
|
2981af0cf0c570be1e60bccd0ccbc215de8993dc
|
swfcat.as
|
swfcat.as
|
package
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.net.XMLSocket;
public class swfcat extends Sprite
{
private var output_text:TextField;
private function puts(s:String):void
{
output_text.appendText(s + "\n");
}
public function swfcat()
{
output_text = new TextField();
output_text.width = 400;
output_text.height = 300;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44CC44;
addChild(output_text);
}
}
}
|
package
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.net.Socket;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
public class swfcat extends Sprite
{
private var output_text:TextField;
private function puts(s:String):void
{
output_text.appendText(s + "\n");
}
public function swfcat()
{
output_text = new TextField();
output_text.width = 400;
output_text.height = 300;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44CC44;
addChild(output_text);
var s:Socket = new Socket();
s.addEventListener(Event.CONNECT, function (e:Event):void {
puts("Connected.");
});
s.addEventListener(Event.CLOSE, function (e:Event):void {
puts("Closed.");
});
s.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("IO error: " + e.text + ".");
});
s.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Security error: " + e.text + ".");
});
puts("Requesting connection.");
s.connect("192.168.0.2", 9999);
puts("Connection requested.");
}
}
}
|
Add socket connection.
|
Add socket connection.
|
ActionScript
|
mit
|
infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,infinity0/flashproxy,glamrock/flashproxy,infinity0/flashproxy,infinity0/flashproxy,infinity0/flashproxy,infinity0/flashproxy,glamrock/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,glamrock/flashproxy
|
05f5806ac6a8f60caaa0dff403554e36aeba728d
|
HLSPlugin/src/org/denivip/osmf/plugins/HLSPluginInfo.as
|
HLSPlugin/src/org/denivip/osmf/plugins/HLSPluginInfo.as
|
package org.denivip.osmf.plugins
{
import org.denivip.osmf.elements.M3U8Element;
import org.denivip.osmf.logging.GALogHandler;
import org.denivip.osmf.logging.HLSLoggerFactory;
import org.denivip.osmf.logging.LogHandler;
import org.denivip.osmf.logging.TraceLogHandler;
import org.osmf.logging.Log;
import org.osmf.media.MediaElement;
import org.osmf.media.MediaFactoryItem;
import org.osmf.media.MediaFactoryItemType;
import org.osmf.media.MediaResourceBase;
import org.osmf.media.PluginInfo;
import org.osmf.media.URLResource;
public class HLSPluginInfo extends PluginInfo
{
public function HLSPluginInfo(items:Vector.<MediaFactoryItem>=null, elementCreationNotifFunc:Function=null){
items = new Vector.<MediaFactoryItem>();
items.push(
new MediaFactoryItem(
'org.denivip.osmf.plugins.HLSPlugin',
canHandleResource,
createMediaElement,
MediaFactoryItemType.STANDARD
)
);
super(items, elementCreationNotifFunc);
CONFIG::LOGGING
{
var handlers:Vector.<LogHandler> = new Vector.<LogHandler>();
// add handlers
handlers.push(new TraceLogHandler());
//handlers.push(new GALogHandler());
Log.loggerFactory = new HLSLoggerFactory(handlers);
}
}
private function canHandleResource(resource:MediaResourceBase):Boolean{
if(resource == null)
return false;
if(!(resource is URLResource))
return false;
var urlResource:URLResource = resource as URLResource;
if (urlResource.url.search(/(https?|file)\:\/\/.*?\.m3u8(\?.*)?/i) !== -1) {
return true;
}
var contentType:Object = urlResource.getMetadataValue("content-type");
if (contentType && contentType is String) {
if ((contentType as String).search(/(application\/x-mpegURL|vnd.apple.mpegURL)/i) !== -1) {
return true;
}
}
return false;
}
private function createMediaElement():MediaElement{
return new M3U8Element();
}
}
}
|
package org.denivip.osmf.plugins
{
import org.denivip.osmf.elements.M3U8Element;
//import org.denivip.osmf.logging.GALogHandler;
import org.denivip.osmf.logging.HLSLoggerFactory;
import org.denivip.osmf.logging.LogHandler;
import org.denivip.osmf.logging.TraceLogHandler;
import org.osmf.logging.Log;
import org.osmf.media.MediaElement;
import org.osmf.media.MediaFactoryItem;
import org.osmf.media.MediaFactoryItemType;
import org.osmf.media.MediaResourceBase;
import org.osmf.media.PluginInfo;
import org.osmf.media.URLResource;
public class HLSPluginInfo extends PluginInfo
{
public function HLSPluginInfo(items:Vector.<MediaFactoryItem>=null, elementCreationNotifFunc:Function=null){
items = new Vector.<MediaFactoryItem>();
items.push(
new MediaFactoryItem(
'org.denivip.osmf.plugins.HLSPlugin',
canHandleResource,
createMediaElement,
MediaFactoryItemType.STANDARD
)
);
super(items, elementCreationNotifFunc);
CONFIG::LOGGING
{
var handlers:Vector.<LogHandler> = new Vector.<LogHandler>();
// add handlers
handlers.push(new TraceLogHandler());
//handlers.push(new GALogHandler());
Log.loggerFactory = new HLSLoggerFactory(handlers);
}
}
private function canHandleResource(resource:MediaResourceBase):Boolean{
if(resource == null)
return false;
if(!(resource is URLResource))
return false;
var urlResource:URLResource = resource as URLResource;
if (urlResource.url.search(/(https?|file)\:\/\/.*?\.m3u8(\?.*)?/i) !== -1) {
return true;
}
var contentType:Object = urlResource.getMetadataValue("content-type");
if (contentType && contentType is String) {
if ((contentType as String).search(/(application\/x-mpegURL|vnd.apple.mpegURL)/i) !== -1) {
return true;
}
}
return false;
}
private function createMediaElement():MediaElement{
return new M3U8Element();
}
}
}
|
Comment unnecessary import
|
Comment unnecessary import
|
ActionScript
|
isc
|
denivip/osmf-hls-plugin,denivip/osmf-hls-plugin,mruse/osmf-hls-plugin,mruse/osmf-hls-plugin
|
f3aa02f61db68dd6a11b7edba6d30b5542eae294
|
Makefile.as
|
Makefile.as
|
# Makefile to rebuild SM64 split image
################ Target Executable and Sources ###############
# TARGET is used to specify prefix in all build artifacts including
# output ROM is $(TARGET).z64
TARGET = sm64
# BUILD_DIR is location where all build artifacts are placed
BUILD_DIR = build
##################### Compiler Options #######################
CROSS = mips64-elf-
AS = $(CROSS)as
LD = $(CROSS)ld
OBJDUMP = $(CROSS)objdump
OBJCOPY = $(CROSS)objcopy
ASFLAGS = -mtune=vr4300 -march=vr4300
LDFLAGS = -T $(LD_SCRIPT) -Map $(BUILD_DIR)/sm64.map
####################### Other Tools #########################
# N64 tools
TOOLS_DIR = .
MIO0TOOL = $(TOOLS_DIR)/mio0
N64CKSUM = $(TOOLS_DIR)/n64cksum
N64GRAPHICS = $(TOOLS_DIR)/n64graphics
EMULATOR = mupen64plus
EMU_FLAGS = --noosd
######################## Targets #############################
default: all
# file dependencies generated by splitter
MAKEFILE_GEN = gen/Makefile.gen
include $(MAKEFILE_GEN)
all: $(TARGET).gen.z64
clean:
rm -f $(BUILD_DIR)/$(TARGET).elf $(BUILD_DIR)/$(TARGET).o $(BUILD_DIR)/$(TARGET).bin $(TARGET).v64
$(MIO0_DIR)/%.mio0: $(MIO0_DIR)/%.bin
$(MIO0TOOL) $< $@
$(BUILD_DIR):
mkdir -p $(BUILD_DIR)
$(BUILD_DIR)/$(TARGET).o: gen/$(TARGET).s Makefile.as $(MAKEFILE_GEN) $(MIO0_FILES) $(LEVEL_FILES) | $(BUILD_DIR)
$(AS) $(ASFLAGS) -o $@ $<
$(BUILD_DIR)/$(TARGET).elf: $(BUILD_DIR)/$(TARGET).o $(LD_SCRIPT)
$(LD) $(LDFLAGS) -o $@ $< $(LIBS)
$(BUILD_DIR)/$(TARGET).bin: $(BUILD_DIR)/$(TARGET).elf
$(OBJCOPY) $< $@ -O binary
# final z64 updates checksum
$(TARGET).gen.z64: $(BUILD_DIR)/$(TARGET).bin
$(N64CKSUM) $< $@
$(BUILD_DIR)/$(TARGET).gen.hex: $(TARGET).gen.z64
xxd $< > $@
$(BUILD_DIR)/$(TARGET).objdump: $(BUILD_DIR)/$(TARGET).elf
$(OBJDUMP) -D $< > $@
diff: $(BUILD_DIR)/$(TARGET).gen.hex
diff sm64.hex $< | wc -l
test: $(TARGET).gen.z64
$(EMULATOR) $(EMU_FLAGS) $<
.PHONY: all clean default diff test
|
# Makefile to rebuild SM64 split image
################ Target Executable and Sources ###############
# TARGET is used to specify prefix in all build artifacts including
# output ROM is $(TARGET).z64
TARGET = sm64
# BUILD_DIR is location where all build artifacts are placed
BUILD_DIR = build
##################### Compiler Options #######################
CROSS = mips64-elf-
AS = $(CROSS)as
LD = $(CROSS)ld
OBJDUMP = $(CROSS)objdump
OBJCOPY = $(CROSS)objcopy
ASFLAGS = -mtune=vr4300 -march=vr4300
LDFLAGS = -T $(LD_SCRIPT) -Map $(BUILD_DIR)/sm64.map
####################### Other Tools #########################
# N64 tools
TOOLS_DIR = .
MIO0TOOL = $(TOOLS_DIR)/mio0
N64CKSUM = $(TOOLS_DIR)/n64cksum
N64GRAPHICS = $(TOOLS_DIR)/n64graphics
EMULATOR = mupen64plus
EMU_FLAGS = --noosd
LOADER = loader64
LOADER_FLAGS = -vwf
######################## Targets #############################
default: all
# file dependencies generated by splitter
MAKEFILE_GEN = gen/Makefile.gen
include $(MAKEFILE_GEN)
all: $(TARGET).gen.z64
clean:
rm -f $(BUILD_DIR)/$(TARGET).elf $(BUILD_DIR)/$(TARGET).o $(BUILD_DIR)/$(TARGET).bin $(TARGET).v64
$(MIO0_DIR)/%.mio0: $(MIO0_DIR)/%.bin
$(MIO0TOOL) $< $@
$(BUILD_DIR):
mkdir -p $(BUILD_DIR)
$(BUILD_DIR)/$(TARGET).o: gen/$(TARGET).s Makefile.as $(MAKEFILE_GEN) $(MIO0_FILES) $(LEVEL_FILES) | $(BUILD_DIR)
$(AS) $(ASFLAGS) -o $@ $<
$(BUILD_DIR)/$(TARGET).elf: $(BUILD_DIR)/$(TARGET).o $(LD_SCRIPT)
$(LD) $(LDFLAGS) -o $@ $< $(LIBS)
$(BUILD_DIR)/$(TARGET).bin: $(BUILD_DIR)/$(TARGET).elf
$(OBJCOPY) $< $@ -O binary
# final z64 updates checksum
$(TARGET).gen.z64: $(BUILD_DIR)/$(TARGET).bin
$(N64CKSUM) $< $@
$(BUILD_DIR)/$(TARGET).gen.hex: $(TARGET).gen.z64
xxd $< > $@
$(BUILD_DIR)/$(TARGET).objdump: $(BUILD_DIR)/$(TARGET).elf
$(OBJDUMP) -D $< > $@
diff: $(BUILD_DIR)/$(TARGET).gen.hex
diff sm64.hex $< | wc -l
test: $(TARGET).gen.z64
$(EMULATOR) $(EMU_FLAGS) $<
load: $(TARGET).gen.z64
$(LOADER) $(LOADER_FLAGS) $<
.PHONY: all clean default diff test
|
Add target to load ROM to EverDrive using loader64
|
Add target to load ROM to EverDrive using loader64
|
ActionScript
|
mit
|
queueRAM/sm64tools,queueRAM/sm64tools
|
ea6fb6bcc5760f60bb24ff34cef8df36a5608445
|
src/aerys/minko/render/geometry/stream/IndexStream.as
|
src/aerys/minko/render/geometry/stream/IndexStream.as
|
package aerys.minko.render.geometry.stream
{
import aerys.minko.ns.minko_stream;
import aerys.minko.render.resource.IndexBuffer3DResource;
import aerys.minko.type.Signal;
import flash.utils.ByteArray;
import flash.utils.Endian;
public final class IndexStream
{
use namespace minko_stream;
minko_stream var _data : ByteArray;
minko_stream var _localDispose : Boolean;
private var _usage : uint;
private var _resource : IndexBuffer3DResource;
private var _length : uint;
private var _locked : Boolean;
private var _changed : Signal;
public function get usage() : uint
{
return _usage;
}
public function get resource() : IndexBuffer3DResource
{
return _resource;
}
public function get length() : uint
{
return _length;
}
public function set length(value : uint) : void
{
_data.length = value << 1;
invalidate();
}
public function get changed() : Signal
{
return _changed;
}
public function IndexStream(usage : uint,
data : ByteArray = null,
offset : uint = 0,
length : uint = 0)
{
super();
initialize(data, offset, length, usage);
}
minko_stream function invalidate() : void
{
_data.position = 0;
_length = _data.length >>> 1;
if (!_locked)
_changed.execute(this);
}
private function initialize(data : ByteArray,
offset : uint,
length : uint,
usage : uint) : void
{
_changed = new Signal('IndexStream.changed');
_usage = usage;
_resource = new IndexBuffer3DResource(this);
_data = new ByteArray();
_data.endian = Endian.LITTLE_ENDIAN;
if (data)
{
if (data.endian != Endian.LITTLE_ENDIAN)
throw new Error('Endianness must be Endian.LITTLE_ENDIAN.');
if (length == 0)
length = data.bytesAvailable;
if (length % 6 != 0)
throw new Error();
_data.writeBytes(data, offset, length);
}
else
{
_data = dummyData(length);
}
_data.position = 0;
invalidate();
}
public function get(index : uint) : uint
{
var value : uint = 0;
checkReadUsage(this);
_data.position = index << 1;
value = _data.readShort();
_data.position = 0;
return value;
}
public function set(index : uint, value : uint) : void
{
checkWriteUsage(this);
_data.position = index << 1;
_data.writeShort(value);
_data.position = 0;
invalidate();
}
public function deleteTriangleByIndex(index : uint) : void
{
checkWriteUsage(this);
_data.position = 0;
_data.writeBytes(_data, index * 12, 12);
_data.position = 0;
invalidate();
}
public function clone(usage : uint = 0) : IndexStream
{
return new IndexStream(usage || _usage, _data, length);
}
public function toString() : String
{
return _data.toString();
}
public function concat(indexStream : IndexStream,
firstIndex : uint = 0,
count : uint = 0,
offset : uint = 0) : IndexStream
{
checkReadUsage(indexStream);
checkWriteUsage(this);
_data.position = _data.length;
_data.writeBytes(indexStream._data);
_data.position = 0;
invalidate();
return this;
}
public function push(indices : Vector.<uint>,
firstIndex : uint = 0,
count : uint = 0,
offset : uint = 0) : void
{
checkWriteUsage(this);
var numIndices : int = _data.length;
count ||= indices.length;
_data.position = _data.length;
for (var i : int = 0; i < count; ++i)
_data.writeShort(indices[int(firstIndex + i)] + offset);
_data.position = 0;
invalidate();
}
public function disposeLocalData(waitForUpload : Boolean = true) : void
{
if (waitForUpload && _length != resource.numIndices)
_localDispose = true;
else
{
_data = null;
_usage = StreamUsage.STATIC;
}
}
public function dispose() : void
{
_resource.dispose();
}
public function lock() : ByteArray
{
checkReadUsage(this);
_data.position = 0;
_locked = true;
return _data;
}
public function unlock(hasChanged : Boolean = true) : void
{
_data.position = 0;
if (hasChanged)
_changed.execute(this);
}
private static function checkReadUsage(stream : IndexStream) : void
{
if (!(stream._usage & StreamUsage.READ))
throw new Error(
'Unable to read from vertex stream: stream usage is not set to StreamUsage.READ.'
);
}
private static function checkWriteUsage(stream : IndexStream) : void
{
if (!(stream._usage & StreamUsage.WRITE))
throw new Error(
'Unable to write in vertex stream: stream usage is not set to StreamUsage.WRITE.'
);
}
public static function dummyData(size : uint,
offset : uint = 0) : ByteArray
{
var indices : ByteArray = new ByteArray();
indices.endian = Endian.LITTLE_ENDIAN;
for (var i : int = 0; i < size; ++i)
indices.writeShort(i + offset);
indices.position = 0;
return indices;
}
public static function fromVector(usage : uint, data : Vector.<uint>) : IndexStream
{
var stream : IndexStream = new IndexStream(usage);
var numIndices : uint = data.length;
for (var i : uint = 0; i < numIndices; ++i)
stream._data.writeShort(data[i]);
stream._data.position = 0;
stream._length = numIndices;
return stream;
}
}
}
|
package aerys.minko.render.geometry.stream
{
import aerys.minko.ns.minko_stream;
import aerys.minko.render.resource.IndexBuffer3DResource;
import aerys.minko.type.Signal;
import flash.utils.ByteArray;
import flash.utils.Endian;
public final class IndexStream
{
use namespace minko_stream;
minko_stream var _data : ByteArray;
minko_stream var _localDispose : Boolean;
private var _usage : uint;
private var _resource : IndexBuffer3DResource;
private var _length : uint;
private var _locked : Boolean;
private var _changed : Signal;
public function get usage() : uint
{
return _usage;
}
public function get resource() : IndexBuffer3DResource
{
return _resource;
}
public function get length() : uint
{
return _length;
}
public function set length(value : uint) : void
{
_data.length = value << 1;
invalidate();
}
public function get changed() : Signal
{
return _changed;
}
public function IndexStream(usage : uint,
data : ByteArray = null,
length : uint = 0)
{
super();
initialize(data, length, usage);
}
minko_stream function invalidate() : void
{
_data.position = 0;
_length = _data.length >>> 1;
if (!_locked)
_changed.execute(this);
}
private function initialize(data : ByteArray,
length : uint,
usage : uint) : void
{
_changed = new Signal('IndexStream.changed');
_usage = usage;
_resource = new IndexBuffer3DResource(this);
_data = new ByteArray();
_data.endian = Endian.LITTLE_ENDIAN;
if (data)
{
if (data.endian != Endian.LITTLE_ENDIAN)
throw new Error('Endianness must be Endian.LITTLE_ENDIAN.');
if (length == 0)
length = data.bytesAvailable;
if (length % 6 != 0)
throw new Error();
data.readBytes(_data, 0, length);
}
else
{
_data = dummyData(length);
}
_data.position = 0;
invalidate();
}
public function get(index : uint) : uint
{
var value : uint = 0;
checkReadUsage(this);
_data.position = index << 1;
value = _data.readUnsignedShort();
_data.position = 0;
return value;
}
public function set(index : uint, value : uint) : void
{
checkWriteUsage(this);
_data.position = index << 1;
_data.writeShort(value);
_data.position = 0;
invalidate();
}
public function deleteTriangle(triangleIndex : uint) : void
{
checkWriteUsage(this);
_data.position = 0;
_data.writeBytes(_data, triangleIndex * 12, 12);
_data.length -= 12;
_data.position = 0;
invalidate();
}
public function clone(usage : uint = 0) : IndexStream
{
return new IndexStream(usage || _usage, _data);
}
public function toString() : String
{
return _data.toString();
}
public function concat(indexStream : IndexStream,
firstIndex : uint = 0,
count : uint = 0,
indexOffset : uint = 0) : IndexStream
{
checkReadUsage(indexStream);
checkWriteUsage(this);
pushBytes(indexStream._data, firstIndex, count, indexOffset);
indexStream._data.position = 0;
return this;
}
public function pushBytes(bytes : ByteArray,
firstIndex : uint = 0,
count : uint = 0,
indexOffset : uint = 0) : IndexStream
{
count ||= bytes.length >>> 1;
_data.position = _data.length;
if (indexOffset == 0)
_data.writeBytes(bytes, firstIndex << 1, count << 1);
else
{
bytes.position = firstIndex << 1;
for (var i : uint = 0; i < count; ++i)
_data.writeShort(bytes.readUnsignedShort() + indexOffset);
}
_data.position = 0;
bytes.position = (firstIndex + count) << 1;
invalidate();
return this;
}
public function pushVector(indices : Vector.<uint>,
firstIndex : uint = 0,
count : uint = 0,
offset : uint = 0) : IndexStream
{
checkWriteUsage(this);
var numIndices : int = _data.length;
count ||= indices.length;
_data.position = _data.length;
for (var i : int = 0; i < count; ++i)
_data.writeShort(indices[int(firstIndex + i)] + offset);
_data.position = 0;
invalidate();
return this;
}
public function pushTriangle(index1 : uint, index2 : uint, index3 : uint) : IndexStream
{
return setTriangle(length * 3, index1, index2, index3);
}
public function setTriangle(triangleIndex : uint,
index1 : uint,
index2 : uint,
index3 : uint) : IndexStream
{
_data.position = triangleIndex << 1;
_data.writeShort(index1);
_data.writeShort(index2);
_data.writeShort(index3);
_data.position = 0;
invalidate();
return this;
}
public function disposeLocalData(waitForUpload : Boolean = true) : void
{
if (waitForUpload && _length != resource.numIndices)
_localDispose = true;
else
{
_data = null;
_usage = StreamUsage.STATIC;
}
}
public function dispose() : void
{
_resource.dispose();
}
public function lock() : ByteArray
{
checkReadUsage(this);
_data.position = 0;
_locked = true;
return _data;
}
public function unlock(hasChanged : Boolean = true) : void
{
_data.position = 0;
if (hasChanged)
_changed.execute(this);
}
private static function checkReadUsage(stream : IndexStream) : void
{
if (!(stream._usage & StreamUsage.READ))
throw new Error(
'Unable to read from vertex stream: stream usage is not set to StreamUsage.READ.'
);
}
private static function checkWriteUsage(stream : IndexStream) : void
{
if (!(stream._usage & StreamUsage.WRITE))
throw new Error(
'Unable to write in vertex stream: stream usage is not set to StreamUsage.WRITE.'
);
}
public static function dummyData(size : uint,
offset : uint = 0) : ByteArray
{
var indices : ByteArray = new ByteArray();
indices.endian = Endian.LITTLE_ENDIAN;
for (var i : int = 0; i < size; ++i)
indices.writeShort(i + offset);
indices.position = 0;
return indices;
}
public static function fromVector(usage : uint, data : Vector.<uint>) : IndexStream
{
var stream : IndexStream = new IndexStream(usage);
var numIndices : uint = data.length;
for (var i : uint = 0; i < numIndices; ++i)
stream._data.writeShort(data[i]);
stream._data.position = 0;
stream._length = numIndices;
return stream;
}
}
}
|
remove useless offset argument from the IndexStream constructor and add IndexStream.pushBytes(), IndexStream.pushTriangle() and IndexStream.setTriangle()
|
remove useless offset argument from the IndexStream constructor and add IndexStream.pushBytes(), IndexStream.pushTriangle() and IndexStream.setTriangle()
|
ActionScript
|
mit
|
aerys/minko-as3
|
ec96f80864b89970953eba9aff0fe16adb5f452e
|
frameworks/projects/Core/src/main/flex/org/apache/flex/utils/Timer.as
|
frameworks/projects/Core/src/main/flex/org/apache/flex/utils/Timer.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.utils
{
COMPILE::SWF
{
import flash.events.TimerEvent;
import flash.utils.Timer;
}
import org.apache.flex.events.Event;
COMPILE::JS
{
import org.apache.flex.events.EventDispatcher;
}
//--------------------------------------
// Events
//--------------------------------------
/**
* Dispatched as requested via the delay and
* repeat count parameters in the constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="timer", type="org.apache.flex.events.Event")]
/**
* The Timer class dispatches events based on a delay
* and repeat count.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
COMPILE::SWF
public class Timer extends flash.utils.Timer
{
/**
* Constructor.
*
* @param delay The number of milliseconds
* to wait before dispatching the event.
* @param repeatCount The number of times to dispatch
* the event. If 0, keep dispatching forever.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function Timer(delay:Number, repeatCount:int = 0)
{
super(delay, repeatCount);
addEventListener("timer", interceptor, false, 9999);
}
private function interceptor(event:flash.events.Event):void
{
if (event is TimerEvent)
{
event.stopImmediatePropagation();
dispatchEvent(new Event("timer"));
}
}
}
COMPILE::JS
public class Timer extends EventDispatcher
{
/**
* Constructor.
*
* @param delay The number of milliseconds
* to wait before dispatching the event.
* @param repeatCount The number of times to dispatch
* the event. If 0, keep dispatching forever.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function Timer(delay:Number, repeatCount:int = 0)
{
this.delay = delay;
this.repeatCount = repeatCount;
}
public var delay:Number;
public var repeatCount:int;
private var currentCount:int = 0;
private var timerInterval:int = -1;
public function reset():void
{
stop();
currentCount = 0;
}
public function stop():void
{
clearInterval(timerInterval);
timerInterval = -1;
}
public function start():void
{
timerInterval =
setInterval(timerHandler, delay);
}
private function timerHandler():void
{
currentCount++;
if (repeatCount > 0 && currentCount >= repeatCount) {
stop();
}
dispatchEvent(new Event('timer'));
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.utils
{
COMPILE::SWF
{
import flash.events.TimerEvent;
import flash.utils.Timer;
}
import org.apache.flex.events.Event;
COMPILE::JS
{
import org.apache.flex.events.EventDispatcher;
}
//--------------------------------------
// Events
//--------------------------------------
/**
* Dispatched as requested via the delay and
* repeat count parameters in the constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="timer", type="org.apache.flex.events.Event")]
/**
* The Timer class dispatches events based on a delay
* and repeat count.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
COMPILE::SWF
public class Timer extends flash.utils.Timer
{
/**
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static const TIMER:String = "timer";
/**
* Constructor.
*
* @param delay The number of milliseconds
* to wait before dispatching the event.
* @param repeatCount The number of times to dispatch
* the event. If 0, keep dispatching forever.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function Timer(delay:Number, repeatCount:int = 0)
{
super(delay, repeatCount);
addEventListener("timer", interceptor, false, 9999);
}
private function interceptor(event:flash.events.Event):void
{
if (event is TimerEvent)
{
event.stopImmediatePropagation();
dispatchEvent(new Event("timer"));
}
}
}
COMPILE::JS
public class Timer extends EventDispatcher
{
/**
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static const TIMER:String = "timer";
/**
* Constructor.
*
* @param delay The number of milliseconds
* to wait before dispatching the event.
* @param repeatCount The number of times to dispatch
* the event. If 0, keep dispatching forever.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function Timer(delay:Number, repeatCount:int = 0)
{
this.delay = delay;
this.repeatCount = repeatCount;
}
public var delay:Number;
public var repeatCount:int;
private var currentCount:int = 0;
private var timerInterval:int = -1;
public function reset():void
{
stop();
currentCount = 0;
}
public function stop():void
{
clearInterval(timerInterval);
timerInterval = -1;
}
public function start():void
{
timerInterval =
setInterval(timerHandler, delay);
}
private function timerHandler():void
{
currentCount++;
if (repeatCount > 0 && currentCount >= repeatCount) {
stop();
}
dispatchEvent(new Event('timer'));
}
}
}
|
Add a TIMER constant for events.
|
Add a TIMER constant for events.
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
23fb282a12d0232556ebfc47f0781eb6b2ca35fd
|
flexEditor/src/org/arisgames/editor/util/AppConstants.as
|
flexEditor/src/org/arisgames/editor/util/AppConstants.as
|
package org.arisgames.editor.util
{
public class AppConstants
{
//Server URL
//public static const APPLICATION_ENVIRONMENT_ROOT_URL:String = "http://arisgames.org/stagingserver1"; //For other URL's to append to- Staging
public static const APPLICATION_ENVIRONMENT_ROOT_URL:String = "http://atsosxdev.doit.wisc.edu/aris/server"; //For other URL's to append to- Dev
public static const APPLICATION_ENVIRONMENT_SERVICES_URL:String = APPLICATION_ENVIRONMENT_ROOT_URL+"/services/aris_1_4/"; //staging
public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = APPLICATION_ENVIRONMENT_ROOT_URL+"/services/aris_1_4/uploadhandler.php";
public static const APPLICATION_ENVIRONMENT_GATEWAY_URL:String = APPLICATION_ENVIRONMENT_ROOT_URL+"/gateway.php"; //services-config.xml
//Google API
//public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBRloMOfjiI7F4SM41AgXh_4cb6l9xTHRyPNO3mgDcJkTIE742EL8ZoQ_Q"; //staging
//public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAArdp0t4v0pcA_JogLZhjrjBTf4EykMftsP7dwAfDsLsFl_zB7rBTq5-3Hy0k3tU1tgyomozB1YmIfNg"; //davembp
public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBQsvlSBtAWfm4N2P3iTGfWOp-UrmRRTU3pFPQwMJB92SZ3plLjvRpMIIw"; //dev
// Dynamic Events
public static const APPLICATIONDYNAMICEVENT_CURRENTSTATECHANGED:String = "ApplicationDynamicEventCurrentStateChanged";
public static const APPLICATIONDYNAMICEVENT_REDRAWOBJECTPALETTE:String = "ApplicationDynamicEventRedrawObjectPalette";
public static const APPLICATIONDYNAMICEVENT_GAMEPLACEMARKSLOADED:String = "ApplicationDynamicEventGamePlacemarksLoaded";
public static const DYNAMICEVENT_GEOSEARCH:String = "DynamicEventGeoSearch";
public static const DYNAMICEVENT_PLACEMARKSELECTED:String = "DynamicEventPlaceMarkSelected";
public static const DYNAMICEVENT_PLACEMARKREQUESTSDELETION:String = "DynamicEventPlaceMarkRequestsDeletion";
public static const DYNAMICEVENT_EDITOBJECTPALETTEITEM:String = "EditObjectPaletteItem";
public static const DYNAMICEVENT_HIGHLIGHTOBJECTPALETTEITEM:String = "HighlightObjectPaletteItem";
public static const DYNAMICEVENT_CLOSEOBJECTPALETTEITEMEDITOR:String = "CloseObjectPaletteItemEditor";
public static const DYNAMICEVENT_CLOSEMEDIAPICKER:String = "CloseMediaPicker";
public static const DYNAMICEVENT_CLOSEMEDIAUPLOADER:String = "CloseMediaUploader";
public static const DYNAMICEVENT_CLOSEREQUIREMENTSEDITOR:String = "CloseRequirementsEditor";
public static const DYNAMICEVENT_REFRESHDATAINREQUIREMENTSEDITOR:String = "RefreshDataInRequirementsEditor";
public static const DYNAMICEVENT_OPENREQUIREMENTSEDITORMAP:String = "OpenRequirementsEditorMap";
public static const DYNAMICEVENT_CLOSEREQUIREMENTSEDITORMAP:String = "CloseRequirementsEditorMap";
public static const DYNAMICEVENT_SAVEREQUIREMENTDUETOMAPDATACHANGE:String = "SaveRequirementDueToMapDataChange";
public static const DYNAMICEVENT_OPENQUESTSMAP:String = "OpenQuestsMap";
public static const DYNAMICEVENT_CLOSEQUESTSMAP:String = "CloseQuestsMap";
public static const DYNAMICEVENT_REFRESHDATAINQUESTSEDITOR:String = "RefreshDataInQuestsEditor";
public static const DYNAMICEVENT_OPENQUESTSEDITOR:String = "OpenQuestsEditor";
public static const DYNAMICEVENT_CLOSEQUESTSEDITOR:String = "CloseQuestsEditor";
public static const DYNAMICEVENT_REFRESHDATAINPLAYERSTATECHANGESEDITOR:String = "DYNAMICEVENT_REFRESHDATAINPLAYERSTATECHANGESEDITOR";
public static const DYNAMICEVENT_CLOSEPLAYERSTATECHANGEEDITOR:String = "DYNAMICEVENT_CLOSEPLAYERSTATECHANGEEDITOR";
public static const DYNAMICEVENT_REFRESHDATAINCONVERSATIONS:String = "DYNAMICEVENT_DYNAMICEVENT_REFRESHDATAINCONVERSATIONS";
// Placemark Content
public static const CONTENTTYPE_PAGE:String = "Plaque";
public static const CONTENTTYPE_CHARACTER:String = "Character";
public static const CONTENTTYPE_ITEM:String = "Item";
public static const CONTENTTYPE_WEBPAGE:String = "WebPage";
public static const CONTENTTYPE_AUGBUBBLE:String = "AugBubble";
public static const CONTENTTYPE_QRCODEGROUP:String = "QR Code Group";
public static const CONTENTTYPE_PAGE_VAL:Number = 0;
public static const CONTENTTYPE_CHARACTER_VAL:Number = 1;
public static const CONTENTTYPE_ITEM_VAL:Number = 2;
public static const CONTENTTYPE_QRCODEGROUP_VAL:Number = 3;
public static const CONTENTTYPE_WEBPAGE_VAL:Number = 4;
public static const CONTENTTYPE_AUGBUBBLE_VAL:Number = 5;
public static const CONTENTTYPE_PAGE_DATABASE:String = "Node";
public static const CONTENTTYPE_CHARACTER_DATABASE:String = "Npc";
public static const CONTENTTYPE_ITEM_DATABASE:String = "Item";
public static const CONTENTTYPE_WEBPAGE_DATABASE:String = "WebPage";
public static const CONTENTTYPE_AUGBUBBLE_DATABASE:String = "AugBubble";
public static const PLACEMARK_DEFAULT_ERROR_RANGE:Number = 30;
// Label Constants
public static const BUTTON_LOGIN:String = "Login!";
public static const BUTTON_REGISTER:String = "Register!";
public static const RADIO_FORGOTPASSWORD:String = "Forgot Password";
public static const RADIO_FORGOTUSERNAME:String = "Forgot Username";
// Max allowed upload size for media.........MB....KB....Bytes
public static const MAX_UPLOAD_SIZE:Number = 10 * 1024 * 1024 //In bytes
// Media Types
public static const MEDIATYPE:String = "Media Types";
public static const MEDIATYPE_IMAGE:String = "Image";
public static const MEDIATYPE_AUDIO:String = "Audio";
public static const MEDIATYPE_VIDEO:String = "Video";
public static const MEDIATYPE_ICON:String = "Icon";
public static const MEDIATYPE_SEPARATOR:String = " ";
public static const MEDIATYPE_UPLOADNEW:String = " ";
// Media-tree-icon Types
public static const MEDIATREEICON_SEPARATOR:String = "separatorIcon";
public static const MEDIATREEICON_UPLOAD:String = "uploadIcon";
//Player State Changes
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_ITEM:String = "VIEW_ITEM";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_WEBPAGE:String = "VIEW_WEBPAGE";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_AUGBUBBLE:String = "VIEW_AUGBUBBLE";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_NODE:String = "VIEW_NODE";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_NPC:String = "VIEW_NPC";
public static const PLAYERSTATECHANGE_ACTION_GIVEITEM:String = "GIVE_ITEM";
public static const PLAYERSTATECHANGE_ACTION_GIVEITEM_HUMAN:String = "Give Item";
public static const PLAYERSTATECHANGE_ACTION_TAKEITEM:String = "TAKE_ITEM";
public static const PLAYERSTATECHANGE_ACTION_TAKEITEM_HUMAN:String = "Take Item";
// Requirement Types
public static const REQUIREMENTTYPE_LOCATION:String = "Location";
public static const REQUIREMENTTYPE_QUESTDISPLAY:String = "QuestDisplay";
public static const REQUIREMENTTYPE_QUESTCOMPLETE:String = "QuestComplete";
public static const REQUIREMENTTYPE_NODE:String = "Node";
// Requirement Options
public static const REQUIREMENT_PLAYER_HAS_ITEM_DATABASE:String = "PLAYER_HAS_ITEM";
public static const REQUIREMENT_PLAYER_HAS_ITEM_HUMAN:String = "Player Has At Least Qty of an Item";
public static const REQUIREMENT_PLAYER_DOES_NOT_HAVE_ITEM_DATABASE:String = "PLAYER_DOES_NOT_HAVE_ITEM";
public static const REQUIREMENT_PLAYER_DOES_NOT_HAVE_ITEM_HUMAN:String = "Player Has Less Than Qty of an Item";
public static const REQUIREMENT_PLAYER_VIEWED_ITEM_DATABASE:String = "PLAYER_VIEWED_ITEM";
public static const REQUIREMENT_PLAYER_VIEWED_ITEM_HUMAN:String = "Player Viewed Item";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_ITEM_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_ITEM";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_ITEM_HUMAN:String = "Player Never Viewed Item";
public static const REQUIREMENT_PLAYER_VIEWED_WEBPAGE_DATABASE:String = "PLAYER_VIEWED_WEBPAGE";
public static const REQUIREMENT_PLAYER_VIEWED_WEBPAGE_HUMAN:String = "Player Viewed Web Page";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_WEBPAGE_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_WEBPAGE";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_WEBPAGE_HUMAN:String = "Player Never Viewed Web Page";
public static const REQUIREMENT_PLAYER_VIEWED_AUGBUBBLE_DATABASE:String = "PLAYER_VIEWED_AUGBUBBLE";
public static const REQUIREMENT_PLAYER_VIEWED_AUGBUBBLE_HUMAN:String = "Player Viewed Aug Bubble";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_AUGBUBBLE_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_AUGBUBBLE";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_AUGBUBBLE_HUMAN:String = "Player Never Viewed Aug Bubble";
public static const REQUIREMENT_PLAYER_VIEWED_NODE_DATABASE:String = "PLAYER_VIEWED_NODE";
public static const REQUIREMENT_PLAYER_VIEWED_NODE_HUMAN:String = "Player Viewed Plaque/Script";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NODE_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_NODE";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NODE_HUMAN:String = "Player Never Viewed Plaque/Script";
public static const REQUIREMENT_PLAYER_VIEWED_NPC_DATABASE:String = "PLAYER_VIEWED_NPC";
public static const REQUIREMENT_PLAYER_VIEWED_NPC_HUMAN:String = "Player Greeted By Character";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NPC_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_NPC";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NPC_HUMAN:String = "Player Never Greeted By Character";
public static const REQUIREMENT_PLAYER_HAS_UPLOADED_MEDIA_ITEM_DATABASE:String = "PLAYER_HAS_UPLOADED_MEDIA_ITEM";
public static const REQUIREMENT_PLAYER_HAS_UPLOADED_MEDIA_ITEM_HUMAN:String = "Player Has Uploaded Media Item";
public static const REQUIREMENT_PLAYER_HAS_COMPLETED_QUEST_DATABASE:String = "PLAYER_HAS_COMPLETED_QUEST";
public static const REQUIREMENT_PLAYER_HAS_COMPLETED_QUEST_HUMAN:String = "Player Has Completed Quest";
public static const REQUIREMENT_BOOLEAN_AND_DATABASE:String = "AND";
public static const REQUIREMENT_BOOLEAN_AND_HUMAN:String = "All";
public static const REQUIREMENT_BOOLEAN_OR_DATABASE:String = "OR";
public static const REQUIREMENT_BOOLEAN_OR_HUMAN:String = "Only this one";
// Defaults
public static const DEFAULT_ICON_MEDIA_ID_NPC:Number = 1;
public static const DEFAULT_ICON_MEDIA_ID_ITEM:Number = 2;
public static const DEFAULT_ICON_MEDIA_ID_PLAQUE:Number = 3;
public static const DEFAULT_ICON_MEDIA_ID_WEBPAGE:Number = 4;
public static const DEFAULT_ICON_MEDIA_ID_AUGBUBBLE:Number = 2;
// Palette Tree Stuff
public static const PALETTE_TREE_SELF_FOLDER_ID:Number = 0;
public static const PLAYER_GENERATED_MEDIA_FOLDER_ID:Number = -1;
public static const PLAYER_GENERATED_MEDIA_FOLDER_NAME:String = "New Player Created Items";
// Media Picker Stuff
public static const MEDIA_PICKER:Number = 0;
public static const ICON_PICKER:Number = 1;
public static const ALIGNMENT_PICKER:Number = 2;
/**
* Constructor
*/
public function AppConstants()
{
super();
}
}
}
|
package org.arisgames.editor.util
{
public class AppConstants
{
//Server URL
//public static const APPLICATION_ENVIRONMENT_ROOT_URL:String = "http://arisgames.org/stagingserver1"; //For other URL's to append to- Staging
public static const APPLICATION_ENVIRONMENT_ROOT_URL:String = "http://atsosxdev.doit.wisc.edu/aris/server"; //For other URL's to append to- Dev
public static const APPLICATION_ENVIRONMENT_SERVICES_URL:String = APPLICATION_ENVIRONMENT_ROOT_URL+"/services/aris_1_4/"; //staging
public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = APPLICATION_ENVIRONMENT_ROOT_URL+"/services/aris_1_4/uploadhandler.php";
public static const APPLICATION_ENVIRONMENT_GATEWAY_URL:String = APPLICATION_ENVIRONMENT_ROOT_URL+"/gateway.php"; //services-config.xml
//Google API
//public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBRloMOfjiI7F4SM41AgXh_4cb6l9xTHRyPNO3mgDcJkTIE742EL8ZoQ_Q"; //staging
//public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAArdp0t4v0pcA_JogLZhjrjBTf4EykMftsP7dwAfDsLsFl_zB7rBTq5-3Hy0k3tU1tgyomozB1YmIfNg"; //davembp
public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBQsvlSBtAWfm4N2P3iTGfWOp-UrmRRTU3pFPQwMJB92SZ3plLjvRpMIIw"; //dev
// Dynamic Events
public static const APPLICATIONDYNAMICEVENT_CURRENTSTATECHANGED:String = "ApplicationDynamicEventCurrentStateChanged";
public static const APPLICATIONDYNAMICEVENT_REDRAWOBJECTPALETTE:String = "ApplicationDynamicEventRedrawObjectPalette";
public static const APPLICATIONDYNAMICEVENT_GAMEPLACEMARKSLOADED:String = "ApplicationDynamicEventGamePlacemarksLoaded";
public static const DYNAMICEVENT_GEOSEARCH:String = "DynamicEventGeoSearch";
public static const DYNAMICEVENT_PLACEMARKSELECTED:String = "DynamicEventPlaceMarkSelected";
public static const DYNAMICEVENT_PLACEMARKREQUESTSDELETION:String = "DynamicEventPlaceMarkRequestsDeletion";
public static const DYNAMICEVENT_EDITOBJECTPALETTEITEM:String = "EditObjectPaletteItem";
public static const DYNAMICEVENT_HIGHLIGHTOBJECTPALETTEITEM:String = "HighlightObjectPaletteItem";
public static const DYNAMICEVENT_CLOSEOBJECTPALETTEITEMEDITOR:String = "CloseObjectPaletteItemEditor";
public static const DYNAMICEVENT_CLOSEMEDIAPICKER:String = "CloseMediaPicker";
public static const DYNAMICEVENT_CLOSEMEDIAUPLOADER:String = "CloseMediaUploader";
public static const DYNAMICEVENT_CLOSEREQUIREMENTSEDITOR:String = "CloseRequirementsEditor";
public static const DYNAMICEVENT_REFRESHDATAINREQUIREMENTSEDITOR:String = "RefreshDataInRequirementsEditor";
public static const DYNAMICEVENT_OPENREQUIREMENTSEDITORMAP:String = "OpenRequirementsEditorMap";
public static const DYNAMICEVENT_CLOSEREQUIREMENTSEDITORMAP:String = "CloseRequirementsEditorMap";
public static const DYNAMICEVENT_SAVEREQUIREMENTDUETOMAPDATACHANGE:String = "SaveRequirementDueToMapDataChange";
public static const DYNAMICEVENT_OPENQUESTSMAP:String = "OpenQuestsMap";
public static const DYNAMICEVENT_CLOSEQUESTSMAP:String = "CloseQuestsMap";
public static const DYNAMICEVENT_REFRESHDATAINQUESTSEDITOR:String = "RefreshDataInQuestsEditor";
public static const DYNAMICEVENT_OPENQUESTSEDITOR:String = "OpenQuestsEditor";
public static const DYNAMICEVENT_CLOSEQUESTSEDITOR:String = "CloseQuestsEditor";
public static const DYNAMICEVENT_REFRESHDATAINPLAYERSTATECHANGESEDITOR:String = "DYNAMICEVENT_REFRESHDATAINPLAYERSTATECHANGESEDITOR";
public static const DYNAMICEVENT_CLOSEPLAYERSTATECHANGEEDITOR:String = "DYNAMICEVENT_CLOSEPLAYERSTATECHANGEEDITOR";
public static const DYNAMICEVENT_REFRESHDATAINCONVERSATIONS:String = "DYNAMICEVENT_DYNAMICEVENT_REFRESHDATAINCONVERSATIONS";
// Placemark Content
public static const CONTENTTYPE_PAGE:String = "Plaque";
public static const CONTENTTYPE_CHARACTER:String = "Character";
public static const CONTENTTYPE_ITEM:String = "Item";
public static const CONTENTTYPE_WEBPAGE:String = "WebPage";
public static const CONTENTTYPE_AUGBUBBLE:String = "AugBubble";
public static const CONTENTTYPE_QRCODEGROUP:String = "QR Code Group";
public static const CONTENTTYPE_PAGE_VAL:Number = 0;
public static const CONTENTTYPE_CHARACTER_VAL:Number = 1;
public static const CONTENTTYPE_ITEM_VAL:Number = 2;
public static const CONTENTTYPE_QRCODEGROUP_VAL:Number = 3;
public static const CONTENTTYPE_WEBPAGE_VAL:Number = 4;
public static const CONTENTTYPE_AUGBUBBLE_VAL:Number = 5;
public static const CONTENTTYPE_PAGE_DATABASE:String = "Node";
public static const CONTENTTYPE_CHARACTER_DATABASE:String = "Npc";
public static const CONTENTTYPE_ITEM_DATABASE:String = "Item";
public static const CONTENTTYPE_WEBPAGE_DATABASE:String = "WebPage";
public static const CONTENTTYPE_AUGBUBBLE_DATABASE:String = "AugBubble";
public static const PLACEMARK_DEFAULT_ERROR_RANGE:Number = 30;
// Label Constants
public static const BUTTON_LOGIN:String = "Login!";
public static const BUTTON_REGISTER:String = "Register!";
public static const RADIO_FORGOTPASSWORD:String = "Forgot Password";
public static const RADIO_FORGOTUSERNAME:String = "Forgot Username";
// Max allowed upload size for media.........MB....KB....Bytes
public static const MAX_UPLOAD_SIZE:Number = 10 * 1024 * 1024 //In bytes
// Media Types
public static const MEDIATYPE:String = "Media Types";
public static const MEDIATYPE_IMAGE:String = "Image";
public static const MEDIATYPE_AUDIO:String = "Audio";
public static const MEDIATYPE_VIDEO:String = "Video";
public static const MEDIATYPE_ICON:String = "Icon";
public static const MEDIATYPE_SEPARATOR:String = " ";
public static const MEDIATYPE_UPLOADNEW:String = " ";
// Media-tree-icon Types
public static const MEDIATREEICON_SEPARATOR:String = "separatorIcon";
public static const MEDIATREEICON_UPLOAD:String = "uploadIcon";
//Player State Changes
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_ITEM:String = "VIEW_ITEM";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_WEBPAGE:String = "VIEW_WEBPAGE";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_AUGBUBBLE:String = "VIEW_AUGBUBBLE";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_NODE:String = "VIEW_NODE";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_NPC:String = "VIEW_NPC";
public static const PLAYERSTATECHANGE_ACTION_GIVEITEM:String = "GIVE_ITEM";
public static const PLAYERSTATECHANGE_ACTION_GIVEITEM_HUMAN:String = "Give Item";
public static const PLAYERSTATECHANGE_ACTION_TAKEITEM:String = "TAKE_ITEM";
public static const PLAYERSTATECHANGE_ACTION_TAKEITEM_HUMAN:String = "Take Item";
// Requirement Types
public static const REQUIREMENTTYPE_LOCATION:String = "Location";
public static const REQUIREMENTTYPE_QUESTDISPLAY:String = "QuestDisplay";
public static const REQUIREMENTTYPE_QUESTCOMPLETE:String = "QuestComplete";
public static const REQUIREMENTTYPE_NODE:String = "Node";
// Requirement Options
public static const REQUIREMENT_PLAYER_HAS_ITEM_DATABASE:String = "PLAYER_HAS_ITEM";
public static const REQUIREMENT_PLAYER_HAS_ITEM_HUMAN:String = "Player Has At Least Qty of an Item";
public static const REQUIREMENT_PLAYER_DOES_NOT_HAVE_ITEM_DATABASE:String = "PLAYER_DOES_NOT_HAVE_ITEM";
public static const REQUIREMENT_PLAYER_DOES_NOT_HAVE_ITEM_HUMAN:String = "Player Has Less Than Qty of an Item";
public static const REQUIREMENT_PLAYER_VIEWED_ITEM_DATABASE:String = "PLAYER_VIEWED_ITEM";
public static const REQUIREMENT_PLAYER_VIEWED_ITEM_HUMAN:String = "Player Viewed Item";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_ITEM_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_ITEM";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_ITEM_HUMAN:String = "Player Never Viewed Item";
public static const REQUIREMENT_PLAYER_VIEWED_WEBPAGE_DATABASE:String = "PLAYER_VIEWED_WEBPAGE";
public static const REQUIREMENT_PLAYER_VIEWED_WEBPAGE_HUMAN:String = "Player Viewed Web Page";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_WEBPAGE_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_WEBPAGE";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_WEBPAGE_HUMAN:String = "Player Never Viewed Web Page";
public static const REQUIREMENT_PLAYER_VIEWED_AUGBUBBLE_DATABASE:String = "PLAYER_VIEWED_AUGBUBBLE";
public static const REQUIREMENT_PLAYER_VIEWED_AUGBUBBLE_HUMAN:String = "Player Viewed Aug Bubble";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_AUGBUBBLE_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_AUGBUBBLE";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_AUGBUBBLE_HUMAN:String = "Player Never Viewed Aug Bubble";
public static const REQUIREMENT_PLAYER_VIEWED_NODE_DATABASE:String = "PLAYER_VIEWED_NODE";
public static const REQUIREMENT_PLAYER_VIEWED_NODE_HUMAN:String = "Player Viewed Plaque/Script";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NODE_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_NODE";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NODE_HUMAN:String = "Player Never Viewed Plaque/Script";
public static const REQUIREMENT_PLAYER_VIEWED_NPC_DATABASE:String = "PLAYER_VIEWED_NPC";
public static const REQUIREMENT_PLAYER_VIEWED_NPC_HUMAN:String = "Player Greeted By Character";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NPC_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_NPC";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NPC_HUMAN:String = "Player Never Greeted By Character";
public static const REQUIREMENT_PLAYER_HAS_UPLOADED_MEDIA_ITEM_DATABASE:String = "PLAYER_HAS_UPLOADED_MEDIA_ITEM";
public static const REQUIREMENT_PLAYER_HAS_UPLOADED_MEDIA_ITEM_HUMAN:String = "Player Has Uploaded Media Item";
public static const REQUIREMENT_PLAYER_HAS_COMPLETED_QUEST_DATABASE:String = "PLAYER_HAS_COMPLETED_QUEST";
public static const REQUIREMENT_PLAYER_HAS_COMPLETED_QUEST_HUMAN:String = "Player Has Completed Quest";
public static const REQUIREMENT_BOOLEAN_AND_DATABASE:String = "AND";
public static const REQUIREMENT_BOOLEAN_AND_HUMAN:String = "All";
public static const REQUIREMENT_BOOLEAN_OR_DATABASE:String = "OR";
public static const REQUIREMENT_BOOLEAN_OR_HUMAN:String = "Only this one";
// Defaults
public static const DEFAULT_ICON_MEDIA_ID_NPC:Number = 1;
public static const DEFAULT_ICON_MEDIA_ID_ITEM:Number = 2;
public static const DEFAULT_ICON_MEDIA_ID_PLAQUE:Number = 3;
public static const DEFAULT_ICON_MEDIA_ID_WEBPAGE:Number = 4;
public static const DEFAULT_ICON_MEDIA_ID_AUGBUBBLE:Number = 5;
// Palette Tree Stuff
public static const PALETTE_TREE_SELF_FOLDER_ID:Number = 0;
public static const PLAYER_GENERATED_MEDIA_FOLDER_ID:Number = -1;
public static const PLAYER_GENERATED_MEDIA_FOLDER_NAME:String = "New Player Created Items";
// Media Picker Stuff
public static const MEDIA_PICKER:Number = 0;
public static const ICON_PICKER:Number = 1;
public static const ALIGNMENT_PICKER:Number = 2;
/**
* Constructor
*/
public function AppConstants()
{
super();
}
}
}
|
update default augbubble icon
|
update default augbubble icon
|
ActionScript
|
mit
|
fielddaylab/sifter-ios,fielddaylab/sifter-ios
|
7f476b91e00821d74c0d1f589ce6aed45e7010ab
|
src/com/kemsky/impl/filters/mapped.as
|
src/com/kemsky/impl/filters/mapped.as
|
package com.kemsky.impl.filters
{
public function mapped(val1:*, map:Object):Function
{
return function (item:*):Boolean
{
var key:* = toValue(item, val1);
return map.hasOwnProperty(key);
};
}
}
|
package com.kemsky.impl.filters
{
public function mapped(val1:*, map:*):Function
{
return function (item:*):Boolean
{
var key:* = toValue(item, val1);
if(map is Function)
{
return map(key);
}
else
{
return map.hasOwnProperty(key);
}
};
}
}
|
remove flex dependencies
|
remove flex dependencies
|
ActionScript
|
mit
|
kemsky/stream
|
2797a2c3233ee08f5345719559e7cb40ee100db2
|
frameworks/projects/framework/src/mx/collections/ComplexSortField.as
|
frameworks/projects/framework/src/mx/collections/ComplexSortField.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package mx.collections {
import mx.utils.ObjectUtil;
[Alternative(replacement="spark.collections.ComplexSortField", since="4.15")]
public class ComplexSortField extends SortField implements IComplexSortField
{
private var _nameParts:Array;
public function ComplexSortField(name:String = null,
caseInsensitive:Boolean = false,
descending:Boolean = false,
numeric:Object = null)
{
super(name, caseInsensitive, descending, numeric);
_nameParts = name ? name.split(".") : [];
}
public function get nameParts():Array
{
return _nameParts;
}
override public function objectHasSortField(object:Object):Boolean
{
return object && nameParts && nameParts.length && object.hasOwnProperty(nameParts[0]);
}
override protected function getSortFieldValue(obj:Object):*
{
return ObjectUtil.getValue(obj, _nameParts);
}
override public function get arraySortOnOptions():int
{
return -1;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package mx.collections {
import mx.utils.ObjectUtil;
public class ComplexSortField extends SortField implements IComplexSortField
{
private var _nameParts:Array;
public function ComplexSortField(name:String = null,
caseInsensitive:Boolean = false,
descending:Boolean = false,
numeric:Object = null)
{
super(name, caseInsensitive, descending, numeric);
_nameParts = name ? name.split(".") : [];
}
public function get nameParts():Array
{
return _nameParts;
}
override public function objectHasSortField(object:Object):Boolean
{
return object && nameParts && nameParts.length && object.hasOwnProperty(nameParts[0]);
}
override protected function getSortFieldValue(obj:Object):*
{
return ObjectUtil.getValue(obj, _nameParts);
}
override public function get arraySortOnOptions():int
{
return -1;
}
}
}
|
Revert "TFC-12136"
|
Revert "TFC-12136"
This reverts commit 45e61644e6a3543937a0fa3db11c3b98b228ae2d.
|
ActionScript
|
apache-2.0
|
apache/flex-sdk,apache/flex-sdk,apache/flex-sdk,apache/flex-sdk,apache/flex-sdk,apache/flex-sdk
|
953559745cde7e54ffec0d070d3aaa92776d950f
|
as3/com/netease/protobuf/SimpleWebRPC.as
|
as3/com/netease/protobuf/SimpleWebRPC.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.net.*;
import flash.utils.*;
import flash.events.*;
public final class SimpleWebRPC {
private var urlPrefix:String
public function SimpleWebRPC(urlPrefix:String) {
this.urlPrefix = urlPrefix;
}
private static const REF:Dictionary = new Dictionary();
public function send(qualifiedMethodName:String,
input:IExternalizable,
rpcResult:Function,
outputType:Class):void {
const loader:URLLoader = new URLLoader
REF[loader] = true;
loader.dataFormat = URLLoaderDataFormat.BINARY
loader.addEventListener(Event.COMPLETE, function(event:Event):void {
delete REF[loader]
const output:IExternalizable = new outputType
output.readExternal(loader.data)
rpcResult(output)
})
function errorEventHandler(event:Event):void {
delete REF[loader]
rpcResult(event)
}
loader.addEventListener(IOErrorEvent.IO_ERROR, errorEventHandler)
loader.addEventListener(
SecurityErrorEvent.SECURITY_ERROR, errorEventHandler)
const request:URLRequest = new URLRequest(
urlPrefix + qualifiedMethodName.replace(/\./, "/"))
request.method = URLRequestMethod.POST
const requestContent:ByteArray = new ByteArray
input.writeExternal(requestContent)
request.data = requestContent
request.contentType = "application/x-protobuf"
loader.load(request)
}
}
}
|
// 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.net.*;
import flash.utils.*;
import flash.events.*;
public final class SimpleWebRPC {
private var urlPrefix:String
public function SimpleWebRPC(urlPrefix:String) {
this.urlPrefix = urlPrefix;
}
private static const REF:Dictionary = new Dictionary();
public function send(qualifiedMethodName:String,
input:IExternalizable,
rpcResult:Function,
outputType:Class):void {
const loader:URLLoader = new URLLoader
REF[loader] = true;
loader.dataFormat = URLLoaderDataFormat.BINARY
loader.addEventListener(Event.COMPLETE, function(event:Event):void {
delete REF[loader]
const output:IExternalizable = new outputType
output.readExternal(loader.data)
rpcResult(output)
})
function errorEventHandler(event:Event):void {
delete REF[loader]
rpcResult(event)
}
loader.addEventListener(IOErrorEvent.IO_ERROR, errorEventHandler)
loader.addEventListener(
SecurityErrorEvent.SECURITY_ERROR, errorEventHandler)
const request:URLRequest = new URLRequest(
urlPrefix + qualifiedMethodName.replace(/\./g, "/"))
request.method = URLRequestMethod.POST
const requestContent:ByteArray = new ByteArray
input.writeExternal(requestContent)
request.data = requestContent
request.contentType = "application/x-protobuf"
loader.load(request)
}
}
}
|
替换掉所有的 \.
|
替换掉所有的 \.
|
ActionScript
|
bsd-2-clause
|
tconkling/protoc-gen-as3
|
426678cf6b3320f33f0e6fe4ca99a7b8c1c69d22
|
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 flash.desktop.NativeApplication;
import flash.display.SimpleButton;
import flash.display.Sprite;
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;
public function FRESteamWorksTest()
{
tf = new TextField();
tf.width = stage.stageWidth;
tf.height = stage.stageHeight;
addChild(tf);
tf.addEventListener(MouseEvent.MOUSE_DOWN, onClick);
Steamworks.addEventListener(SteamEvent.STEAM_RESPONSE, onSteamResponse);
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 available\n");
log("User ID: " + Steamworks.getUserID());
log("Persona name: " + Steamworks.getPersonaName());
//comment.. current stats and achievement ids are from steam example app which is provided with their SDK
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'));
log("setCloudEnabledForApp(false) == "+Steamworks.setCloudEnabledForApp(false) );
log("setCloudEnabledForApp(true) == "+Steamworks.setCloudEnabledForApp(true) );
log("isCloudEnabledForApp() == "+Steamworks.isCloudEnabledForApp() );
log("getFileCount() == "+Steamworks.getFileCount() );
log("fileExists('test.txt') == "+Steamworks.fileExists('test.txt') );
//comment.. writing to app with id 480 is somehow not working, but works with our real appId
log("writeFileToCloud('test.txt','hello steam') == "+writeFileToCloud('test.txt','hello steam'));
log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') );
//-----------
//Steamworks.requestStats();
Steamworks.resetAllStats(true);
}else {
tf.appendText("STEAMWORKS API is NOT available\n");
}
} catch(e:Error) {
tf.appendText("*** ERROR ***");
tf.appendText(e.message + "\n");
tf.appendText(e.getStackTrace() + "\n");
}
}
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;
}
public function onClick(e:MouseEvent):void{
log("--click--");
if(Steamworks.isReady){
if(!Steamworks.isAchievement("ACH_WIN_ONE_GAME")) {
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"));
}
if(Steamworks.fileExists('test.txt')){
log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') );
log("Steamworks.fileDelete('test.txt') == "+Steamworks.fileDelete('test.txt'));
} else {
log("writeFileToCloud('test.txt','click') == "+writeFileToCloud('test.txt','click'));
}
//Steamworks.storeStats();
} else {
log("not able to set achievement\n");
}
}
public function onSteamResponse(e:SteamEvent):void{
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;
default:
log("STEAMresponse type:"+e.req_type+" response:"+e.response);
}
}
public function onExit(e:Event):void{
log("Exiting application, cleaning up");
Steamworks.dispose();
}
}
}
|
/*
* 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 flash.desktop.NativeApplication;
import flash.display.SimpleButton;
import flash.display.Sprite;
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;
public function FRESteamWorksTest()
{
tf = new TextField();
tf.width = stage.stageWidth;
tf.height = stage.stageHeight;
addChild(tf);
tf.addEventListener(MouseEvent.MOUSE_DOWN, onClick);
Steamworks.addEventListener(SteamEvent.STEAM_RESPONSE, onSteamResponse);
NativeApplication.nativeApplication.addEventListener(Event.EXITING, onExit);
try {
Steamworks.useCrashHandler(480, "1.0", "Feb 20 2013", "21:42:20");
if(!Steamworks.init()){
tf.appendText("STEAMWORKS API is NOT available\n");
return;
}
log("STEAMWORKS API is available\n");
log("User ID: " + Steamworks.getUserID());
log("Persona name: " + Steamworks.getPersonaName());
//comment.. current stats and achievement ids are from steam example app which is provided with their SDK
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'));
log("setCloudEnabledForApp(false) == "+Steamworks.setCloudEnabledForApp(false) );
log("setCloudEnabledForApp(true) == "+Steamworks.setCloudEnabledForApp(true) );
log("isCloudEnabledForApp() == "+Steamworks.isCloudEnabledForApp() );
log("getFileCount() == "+Steamworks.getFileCount() );
log("fileExists('test.txt') == "+Steamworks.fileExists('test.txt') );
//comment.. writing to app with id 480 is somehow not working, but works with our real appId
log("writeFileToCloud('test.txt','hello steam') == "+writeFileToCloud('test.txt','hello steam'));
log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') );
//-----------
//Steamworks.requestStats();
Steamworks.resetAllStats(true);
} catch(e:Error) {
tf.appendText("*** ERROR ***");
tf.appendText(e.message + "\n");
tf.appendText(e.getStackTrace() + "\n");
}
}
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;
}
public function onClick(e:MouseEvent):void{
log("--click--");
if(!Steamworks.isReady){
log("not able to set achievement\n");
return;
}
if(!Steamworks.isAchievement("ACH_WIN_ONE_GAME")) {
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"));
}
if(Steamworks.fileExists('test.txt')){
log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') );
log("Steamworks.fileDelete('test.txt') == "+Steamworks.fileDelete('test.txt'));
} else {
log("writeFileToCloud('test.txt','click') == "+writeFileToCloud('test.txt','click'));
}
//Steamworks.storeStats();
}
public function onSteamResponse(e:SteamEvent):void{
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;
default:
log("STEAMresponse type:"+e.req_type+" response:"+e.response);
}
}
public function onExit(e:Event):void{
log("Exiting application, cleaning up");
Steamworks.dispose();
}
}
}
|
Use guard style
|
[test] Use guard style
|
ActionScript
|
bsd-2-clause
|
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
|
8e6e94e3b25f1e4e3e92729a9bd6139aa36dadd8
|
exporter/src/main/as/flump/SwfTexture.as
|
exporter/src/main/as/flump/SwfTexture.as
|
//
// Flump - Copyright 2012 Three Rings Design
package flump {
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.IBitmapDrawable;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.Rectangle;
import flump.executor.load.LoadedSwf;
import flump.mold.MovieMold;
import flump.xfl.XflLibrary;
import flump.xfl.XflTexture;
public class SwfTexture
{
public var symbol :String;
public var offset :Point;
public var w :int, h :int, a :int;
public var scale :Number;
// The MD5 of the symbol XML in the library, or null if there is no associated symbol
public var md5 :String;
public static function renderToBitmapData (target :IBitmapDrawable, width :int,
height :int, scale :Number = 1) :BitmapData {
const bd :BitmapData = new BitmapData(width, height, true, 0x00);
const m :Matrix = new Matrix();
m.scale(scale, scale);
bd.draw(target, m, null, null, null, true);
return bd;
}
public static function fromFlipbook (lib :XflLibrary, movie :MovieMold, frame :int,
scale :Number = 1) :SwfTexture {
const klass :Class = Class(lib.swf.getSymbol(movie.id));
const clip :MovieClip = MovieClip(new klass());
clip.gotoAndStop(frame + 1);
const name :String = movie.id + "_flipbook_" + frame;
return new SwfTexture(null, name, clip, scale);
}
public static function fromTexture (swf :LoadedSwf, tex :XflTexture,
scale :Number = 1) :SwfTexture {
const klass :Class = Class(swf.getSymbol(tex.symbol));
const instance :Object = new klass();
const disp :DisplayObject = (instance is BitmapData) ?
new Bitmap(BitmapData(instance)) : DisplayObject(instance);
return new SwfTexture(tex.md5, tex.symbol, disp, scale);
}
public function SwfTexture (md5 :String, symbol :String, disp :DisplayObject, scale :Number) {
this.md5 = md5;
this.symbol = symbol;
this.scale = scale;
_disp = disp;
offset = getOffset(_disp, scale);
const size :Point = getSize(_disp, scale);
w = size.x;
h = size.y;
a = w * h;
}
public function toBitmapData () :BitmapData {
const holder :Sprite = new Sprite();
if (scale < 1) {
// for downlscaling, render at normal size first, then scale to get the
// benefit of bitmap smoothing. BitmapData.draw smoothing only works
// when the source is itself a BitmapData object.
const fullsizeOffset :Point = getOffset(_disp, 1);
const fullSize :Point = getSize(_disp, 1);
_disp.x = -fullsizeOffset.x;
_disp.y = -fullsizeOffset.y;
holder.addChild(_disp);
const bmd :BitmapData = renderToBitmapData(holder, fullSize.x, fullSize.y, 1);
return renderToBitmapData(bmd, w, h, scale);
} else {
_disp.x = -getOffset(_disp, scale).x;
_disp.y = -getOffset(_disp, scale).y;
holder.addChild(_disp);
return renderToBitmapData(holder, w, h, scale);
}
}
public function toString () :String { return "a " + a + " w " + w + " h " + h; }
protected static function getSize (disp :DisplayObject, scale :Number) :Point {
const bounds :Rectangle = getBounds(disp, scale);
return new Point(Math.ceil(bounds.width), Math.ceil(bounds.height));
}
protected static function getOffset (disp :DisplayObject, scale :Number) :Point {
const bounds :Rectangle = getBounds(disp, scale);
return new Point(bounds.x, bounds.y);
}
protected static function getBounds (disp :DisplayObject, scale :Number) :Rectangle {
const oldScale :Number = disp.scaleX;
disp.scaleX = disp.scaleY = scale;
const holder :Sprite = new Sprite();
holder.addChild(disp);
const bounds :Rectangle = disp.getBounds(holder);
disp.scaleX = disp.scaleY = oldScale;
return bounds;
}
protected var _disp :DisplayObject;
}
}
|
//
// Flump - Copyright 2012 Three Rings Design
package flump {
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.IBitmapDrawable;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.Rectangle;
import flump.executor.load.LoadedSwf;
import flump.mold.MovieMold;
import flump.xfl.XflLibrary;
import flump.xfl.XflTexture;
public class SwfTexture
{
public var symbol :String;
public var offset :Point;
public var w :int, h :int, a :int;
public var scale :Number;
// The MD5 of the symbol XML in the library, or null if there is no associated symbol
public var md5 :String;
public static function renderToBitmapData (target :IBitmapDrawable, width :int,
height :int, scale :Number = 1) :BitmapData {
const bd :BitmapData = new BitmapData(width, height, true, 0x00);
const m :Matrix = new Matrix();
m.scale(scale, scale);
bd.draw(target, m, null, null, null, true);
return bd;
}
public static function fromFlipbook (lib :XflLibrary, movie :MovieMold, frame :int,
scale :Number = 1) :SwfTexture {
const klass :Class = Class(lib.swf.getSymbol(movie.id));
const clip :MovieClip = MovieClip(new klass());
clip.gotoAndStop(frame + 1);
const name :String = movie.id + "_flipbook_" + frame;
return new SwfTexture(null, name, clip, scale);
}
public static function fromTexture (swf :LoadedSwf, tex :XflTexture,
scale :Number = 1) :SwfTexture {
const klass :Class = Class(swf.getSymbol(tex.symbol));
const instance :Object = new klass();
const disp :DisplayObject = (instance is BitmapData) ?
new Bitmap(BitmapData(instance)) : DisplayObject(instance);
return new SwfTexture(tex.md5, tex.symbol, disp, scale);
}
public function SwfTexture (md5 :String, symbol :String, disp :DisplayObject, scale :Number) {
this.md5 = md5;
this.symbol = symbol;
this.scale = scale;
_disp = disp;
offset = getOffset(_disp, scale);
const size :Point = getSize(_disp, scale);
w = size.x;
h = size.y;
a = w * h;
}
public function toBitmapData () :BitmapData {
const holder :Sprite = new Sprite();
if (scale != 1) {
// for down or up-scaling, render at normal size first, then scale to get the
// benefit of bitmap smoothing. BitmapData.draw smoothing only works
// when the source is itself a BitmapData object.
const fullsizeOffset :Point = getOffset(_disp, 1);
const fullSize :Point = getSize(_disp, 1);
_disp.x = -fullsizeOffset.x;
_disp.y = -fullsizeOffset.y;
holder.addChild(_disp);
const bmd :BitmapData = renderToBitmapData(holder, fullSize.x, fullSize.y, 1);
return renderToBitmapData(bmd, w, h, scale);
} else {
_disp.x = -getOffset(_disp, scale).x;
_disp.y = -getOffset(_disp, scale).y;
holder.addChild(_disp);
return renderToBitmapData(holder, w, h, scale);
}
}
public function toString () :String { return "a " + a + " w " + w + " h " + h; }
protected static function getSize (disp :DisplayObject, scale :Number) :Point {
const bounds :Rectangle = getBounds(disp, scale);
return new Point(Math.ceil(bounds.width), Math.ceil(bounds.height));
}
protected static function getOffset (disp :DisplayObject, scale :Number) :Point {
const bounds :Rectangle = getBounds(disp, scale);
return new Point(bounds.x, bounds.y);
}
protected static function getBounds (disp :DisplayObject, scale :Number) :Rectangle {
const oldScale :Number = disp.scaleX;
disp.scaleX = disp.scaleY = scale;
const holder :Sprite = new Sprite();
holder.addChild(disp);
const bounds :Rectangle = disp.getBounds(holder);
disp.scaleX = disp.scaleY = oldScale;
return bounds;
}
protected var _disp :DisplayObject;
}
}
|
Fix texture exporting for scales > 1
|
Fix texture exporting for scales > 1
Though really, we should never be scaling beyond 1...
|
ActionScript
|
mit
|
funkypandagame/flump,funkypandagame/flump,mathieuanthoine/flump,mathieuanthoine/flump,mathieuanthoine/flump,tconkling/flump,tconkling/flump
|
528dfa19ba16f202bfc2f23eece64afae6bb615d
|
src/aerys/minko/render/shader/compiler/graph/ShaderGraph.as
|
src/aerys/minko/render/shader/compiler/graph/ShaderGraph.as
|
package aerys.minko.render.shader.compiler.graph
{
import aerys.minko.Minko;
import aerys.minko.render.geometry.stream.format.VertexComponent;
import aerys.minko.render.resource.Program3DResource;
import aerys.minko.render.resource.texture.ITextureResource;
import aerys.minko.render.shader.Signature;
import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode;
import aerys.minko.render.shader.compiler.graph.visitors.*;
import aerys.minko.render.shader.compiler.register.Components;
import aerys.minko.render.shader.compiler.sequence.AgalInstruction;
import aerys.minko.type.log.DebugLevel;
import flash.utils.ByteArray;
import flash.utils.Endian;
/**
* @private
* @author Romain Gilliotte
*
*/
public class ShaderGraph
{
private static const SPLITTER : SplitterVisitor = new SplitterVisitor();
private static const REMOVE_EXTRACT : RemoveExtractsVisitor = new RemoveExtractsVisitor();
private static const MERGER : MergeVisitor = new MergeVisitor();
private static const OVERWRITER_CLEANER : OverwriterCleanerVisitor = new OverwriterCleanerVisitor();
private static const RESOLVE_CONSTANT : ResolveConstantComputationVisitor = new ResolveConstantComputationVisitor();
private static const CONSTANT_PACKER : ConstantPackerVisitor = new ConstantPackerVisitor();
private static const CONSTANT_GROUPER : ConstantGrouperVisitor = new ConstantGrouperVisitor();
private static const RESOLVE_PARAMETRIZED : ResolveParametrizedComputationVisitor = new ResolveParametrizedComputationVisitor();
private static const REMOVE_USELESS : RemoveUselessComputation = new RemoveUselessComputation();
private static const COPY_INSERTER : CopyInserterVisitor = new CopyInserterVisitor();
private static const ALLOCATOR : AllocationVisitor = new AllocationVisitor();
private static const INTERPOLATE_FINDER : InterpolateFinder = new InterpolateFinder();
private static const WRITE_DOT : WriteDot = new WriteDot();
private static const MATRIX_TRANSFORMATION : MatrixTransformationGrouper = new MatrixTransformationGrouper();
private var _position : AbstractNode;
private var _positionComponents : uint;
private var _interpolates : Vector.<AbstractNode>;
private var _color : AbstractNode;
private var _colorComponents : uint;
private var _kills : Vector.<AbstractNode>;
private var _killComponents : Vector.<uint>;
private var _computableConstants : Object;
private var _isCompiled : Boolean;
private var _vertexSequence : Vector.<AgalInstruction>;
private var _fragmentSequence : Vector.<AgalInstruction>;
private var _bindings : Object;
private var _vertexComponents : Vector.<VertexComponent>;
private var _vertexIndices : Vector.<uint>;
private var _vsConstants : Vector.<Number>;
private var _fsConstants : Vector.<Number>;
private var _textures : Vector.<ITextureResource>;
public function get position() : AbstractNode
{
return _position;
}
public function set position(v : AbstractNode) : void
{
_position = v;
}
public function get interpolates() : Vector.<AbstractNode>
{
return _interpolates;
}
public function get color() : AbstractNode
{
return _color;
}
public function set color(v : AbstractNode) : void
{
_color = v;
}
public function get kills() : Vector.<AbstractNode>
{
return _kills;
}
public function get positionComponents() : uint
{
return _positionComponents;
}
public function set positionComponents(v : uint) : void
{
_positionComponents = v;
}
public function get colorComponents() : uint
{
return _colorComponents;
}
public function set colorComponents(v : uint) : void
{
_colorComponents = v;
}
public function get killComponents() : Vector.<uint>
{
return _killComponents;
}
public function get computableConstants() : Object
{
return _computableConstants;
}
public function ShaderGraph(position : AbstractNode,
color : AbstractNode,
kills : Vector.<AbstractNode>)
{
_isCompiled = false;
_position = position;
_positionComponents = Components.createContinuous(0, 0, 4, position.size);
_interpolates = new Vector.<AbstractNode>();
_color = color;
_colorComponents = Components.createContinuous(0, 0, 4, color.size);
_kills = kills;
_killComponents = new Vector.<uint>();
_computableConstants = new Object();
var numKills : uint = kills.length;
for (var killId : uint = 0; killId < numKills; ++killId)
_killComponents[killId] = Components.createContinuous(0, 0, 1, 1);
}
public function generateProgram(name : String, signature : Signature) : Program3DResource
{
if (!_isCompiled)
compile();
if (Minko.debugLevel & DebugLevel.SHADER_AGAL)
Minko.log(DebugLevel.SHADER_AGAL, generateAGAL(name));
var vsProgram : ByteArray = computeBinaryProgram(_vertexSequence, true);
var fsProgram : ByteArray = computeBinaryProgram(_fragmentSequence, false);
var program : Program3DResource = new Program3DResource(
name,
signature,
vsProgram,
fsProgram,
_vertexComponents,
_vertexIndices,
_vsConstants,
_fsConstants,
_textures,
_bindings
);
return program;
}
public function generateAGAL(name : String) : String
{
var instruction : AgalInstruction;
var shader : String = name + "\n";
if (!_isCompiled)
compile();
shader += "- vertex shader\n";
for each (instruction in _vertexSequence)
shader += instruction.getAgal(true);
shader += "- fragment shader\n";
for each (instruction in _fragmentSequence)
shader += instruction.getAgal(false);
return shader;
}
private function compile() : void
{
// execute consecutive visitors to optimize the shader graph.
// Warning: the order matters, do not swap lines.
MERGER .process(this); // merge duplicate nodes
REMOVE_EXTRACT .process(this); // remove all extract nodes
OVERWRITER_CLEANER .process(this); // remove nested overwriters
RESOLVE_CONSTANT .process(this); // resolve constant computation
CONSTANT_PACKER .process(this); // pack constants [0,0,0,1] => [0,1].xxxy
REMOVE_USELESS .process(this); // remove some useless operations (add 0, mul 0, mul 1...)
RESOLVE_PARAMETRIZED .process(this); // replace computations that depend on parameters by evalexp parameters
// MATRIX_TRANSFORMATION .process(this); // replace ((vector * matrix1) * matrix2) by vector * (matrix1 * matrix2) to save registers on GPU
COPY_INSERTER .process(this); // ensure there are no operations between constants
SPLITTER .process(this); // clone nodes that are shared between vertex and fragment shader
CONSTANT_GROUPER .process(this); // group constants [0,1] & [0,2] => [0, 1, 2]
if (Minko.debugLevel & DebugLevel.SHADER_DOTTY)
{
WRITE_DOT.process(this);
Minko.log(DebugLevel.SHADER_DOTTY, WRITE_DOT.result);
WRITE_DOT.clear();
}
// generate final program
INTERPOLATE_FINDER .process(this); // find interpolate nodes. We may skip that in the future.
ALLOCATOR .process(this); // allocate memory and generate final code.
// retrieve program
_vertexSequence = ALLOCATOR.vertexSequence;
_fragmentSequence = ALLOCATOR.fragmentSequence;
_bindings = ALLOCATOR.parameterBindings;
_vertexComponents = ALLOCATOR.vertexComponents;
_vertexIndices = ALLOCATOR.vertexIndices;
_vsConstants = ALLOCATOR.vertexConstants;
_fsConstants = ALLOCATOR.fragmentConstants;
_textures = ALLOCATOR.textures;
ALLOCATOR.clear();
_isCompiled = true;
}
private function computeBinaryProgram(sequence : Vector.<AgalInstruction>,
isVertexShader : Boolean) : ByteArray
{
var program : ByteArray = new ByteArray();
program.endian = Endian.LITTLE_ENDIAN;
program.writeByte(0xa0); // tag version
program.writeUnsignedInt(1); // AGAL version, big endian, bit pattern will be 0x01000000
program.writeByte(0xa1); // tag program id
program.writeByte(isVertexShader ? 0 : 1); // vertex or fragment
for each (var instruction : AgalInstruction in sequence)
instruction.getBytecode(program);
return program;
}
}
}
|
package aerys.minko.render.shader.compiler.graph
{
import aerys.minko.Minko;
import aerys.minko.render.geometry.stream.format.VertexComponent;
import aerys.minko.render.resource.Program3DResource;
import aerys.minko.render.resource.texture.ITextureResource;
import aerys.minko.render.shader.Signature;
import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode;
import aerys.minko.render.shader.compiler.graph.visitors.*;
import aerys.minko.render.shader.compiler.register.Components;
import aerys.minko.render.shader.compiler.sequence.AgalInstruction;
import aerys.minko.type.log.DebugLevel;
import flash.utils.ByteArray;
import flash.utils.Endian;
/**
* @private
* @author Romain Gilliotte
*
*/
public class ShaderGraph
{
private static const SPLITTER : SplitterVisitor = new SplitterVisitor();
private static const REMOVE_EXTRACT : RemoveExtractsVisitor = new RemoveExtractsVisitor();
private static const MERGER : MergeVisitor = new MergeVisitor();
private static const OVERWRITER_CLEANER : OverwriterCleanerVisitor = new OverwriterCleanerVisitor();
private static const RESOLVE_CONSTANT : ResolveConstantComputationVisitor = new ResolveConstantComputationVisitor();
private static const CONSTANT_PACKER : ConstantPackerVisitor = new ConstantPackerVisitor();
private static const CONSTANT_GROUPER : ConstantGrouperVisitor = new ConstantGrouperVisitor();
private static const RESOLVE_PARAMETRIZED : ResolveParametrizedComputationVisitor = new ResolveParametrizedComputationVisitor();
private static const REMOVE_USELESS : RemoveUselessComputation = new RemoveUselessComputation();
private static const COPY_INSERTER : CopyInserterVisitor = new CopyInserterVisitor();
private static const ALLOCATOR : AllocationVisitor = new AllocationVisitor();
private static const INTERPOLATE_FINDER : InterpolateFinder = new InterpolateFinder();
private static const WRITE_DOT : WriteDot = new WriteDot();
private static const MATRIX_TRANSFORMATION : MatrixTransformationGrouper = new MatrixTransformationGrouper();
private var _position : AbstractNode;
private var _positionComponents : uint;
private var _interpolates : Vector.<AbstractNode>;
private var _color : AbstractNode;
private var _colorComponents : uint;
private var _kills : Vector.<AbstractNode>;
private var _killComponents : Vector.<uint>;
private var _computableConstants : Object;
private var _isCompiled : Boolean;
private var _vertexSequence : Vector.<AgalInstruction>;
private var _fragmentSequence : Vector.<AgalInstruction>;
private var _bindings : Object;
private var _vertexComponents : Vector.<VertexComponent>;
private var _vertexIndices : Vector.<uint>;
private var _vsConstants : Vector.<Number>;
private var _fsConstants : Vector.<Number>;
private var _textures : Vector.<ITextureResource>;
public function get position() : AbstractNode
{
return _position;
}
public function set position(v : AbstractNode) : void
{
_position = v;
}
public function get interpolates() : Vector.<AbstractNode>
{
return _interpolates;
}
public function get color() : AbstractNode
{
return _color;
}
public function set color(v : AbstractNode) : void
{
_color = v;
}
public function get kills() : Vector.<AbstractNode>
{
return _kills;
}
public function get positionComponents() : uint
{
return _positionComponents;
}
public function set positionComponents(v : uint) : void
{
_positionComponents = v;
}
public function get colorComponents() : uint
{
return _colorComponents;
}
public function set colorComponents(v : uint) : void
{
_colorComponents = v;
}
public function get killComponents() : Vector.<uint>
{
return _killComponents;
}
public function get computableConstants() : Object
{
return _computableConstants;
}
public function ShaderGraph(position : AbstractNode,
color : AbstractNode,
kills : Vector.<AbstractNode>)
{
_isCompiled = false;
_position = position;
_positionComponents = Components.createContinuous(0, 0, 4, position.size);
_interpolates = new Vector.<AbstractNode>();
_color = color;
_colorComponents = Components.createContinuous(0, 0, 4, color.size);
_kills = kills;
_killComponents = new Vector.<uint>();
_computableConstants = new Object();
var numKills : uint = kills.length;
for (var killId : uint = 0; killId < numKills; ++killId)
_killComponents[killId] = Components.createContinuous(0, 0, 1, 1);
}
public function generateProgram(name : String, signature : Signature) : Program3DResource
{
if (!_isCompiled)
compile();
if (Minko.debugLevel & DebugLevel.SHADER_AGAL)
Minko.log(DebugLevel.SHADER_AGAL, generateAGAL(name));
var vsProgram : ByteArray = computeBinaryProgram(_vertexSequence, true);
var fsProgram : ByteArray = computeBinaryProgram(_fragmentSequence, false);
var program : Program3DResource = new Program3DResource(
name,
signature,
vsProgram,
fsProgram,
_vertexComponents,
_vertexIndices,
_vsConstants,
_fsConstants,
_textures,
_bindings
);
return program;
}
public function generateAGAL(name : String) : String
{
var instruction : AgalInstruction;
var shader : String = name + "\n";
if (!_isCompiled)
compile();
shader += "- vertex shader\n";
for each (instruction in _vertexSequence)
shader += instruction.getAgal(true);
shader += "- fragment shader\n";
for each (instruction in _fragmentSequence)
shader += instruction.getAgal(false);
return shader;
}
private function compile() : void
{
// execute consecutive visitors to optimize the shader graph.
// Warning: the order matters, do not swap lines.
MERGER .process(this); // merge duplicate nodes
REMOVE_EXTRACT .process(this); // remove all extract nodes
OVERWRITER_CLEANER .process(this); // remove nested overwriters
RESOLVE_CONSTANT .process(this); // resolve constant computation
CONSTANT_PACKER .process(this); // pack constants [0,0,0,1] => [0,1].xxxy
REMOVE_USELESS .process(this); // remove some useless operations (add 0, mul 0, mul 1...)
// RESOLVE_PARAMETRIZED .process(this); // replace computations that depend on parameters by evalexp parameters
// MATRIX_TRANSFORMATION .process(this); // replace ((vector * matrix1) * matrix2) by vector * (matrix1 * matrix2) to save registers on GPU
COPY_INSERTER .process(this); // ensure there are no operations between constants
SPLITTER .process(this); // clone nodes that are shared between vertex and fragment shader
CONSTANT_GROUPER .process(this); // group constants [0,1] & [0,2] => [0, 1, 2]
if (Minko.debugLevel & DebugLevel.SHADER_DOTTY)
{
WRITE_DOT.process(this);
Minko.log(DebugLevel.SHADER_DOTTY, WRITE_DOT.result);
WRITE_DOT.clear();
}
// generate final program
INTERPOLATE_FINDER .process(this); // find interpolate nodes. We may skip that in the future.
ALLOCATOR .process(this); // allocate memory and generate final code.
// retrieve program
_vertexSequence = ALLOCATOR.vertexSequence;
_fragmentSequence = ALLOCATOR.fragmentSequence;
_bindings = ALLOCATOR.parameterBindings;
_vertexComponents = ALLOCATOR.vertexComponents;
_vertexIndices = ALLOCATOR.vertexIndices;
_vsConstants = ALLOCATOR.vertexConstants;
_fsConstants = ALLOCATOR.fragmentConstants;
_textures = ALLOCATOR.textures;
ALLOCATOR.clear();
_isCompiled = true;
}
private function computeBinaryProgram(sequence : Vector.<AgalInstruction>,
isVertexShader : Boolean) : ByteArray
{
var program : ByteArray = new ByteArray();
program.endian = Endian.LITTLE_ENDIAN;
program.writeByte(0xa0); // tag version
program.writeUnsignedInt(1); // AGAL version, big endian, bit pattern will be 0x01000000
program.writeByte(0xa1); // tag program id
program.writeByte(isVertexShader ? 0 : 1); // vertex or fragment
for each (var instruction : AgalInstruction in sequence)
instruction.getBytecode(program);
return program;
}
}
}
|
comment visitor responsible for automated CPU/GPU balancing in ShaderGraph because of poor performnaces of evalexp on the CPU
|
comment visitor responsible for automated CPU/GPU balancing in ShaderGraph because of poor performnaces of evalexp on the CPU
|
ActionScript
|
mit
|
aerys/minko-as3
|
51d604ffbaf28c27a83ad478bbe7a9ecb2a9c5d7
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/Application.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/Application.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.core
{
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageQuality;
import flash.display.StageScaleMode;
import flash.events.IOErrorEvent;
import flash.system.ApplicationDomain;
import flash.utils.getQualifiedClassName;
import org.apache.flex.events.Event;
import org.apache.flex.utils.MXMLDataInterpreter;
//--------------------------------------
// Events
//--------------------------------------
/**
* Dispatched at startup. Attributes and sub-instances of
* the MXML document have been created and assigned.
* The component lifecycle is different
* than the Flex SDK. There is no creationComplete event.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="initialize", type="org.apache.flex.events.Event")]
/**
* Dispatched at startup after the initial view has been
* put on the display list.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="viewChanged", type="org.apache.flex.events.Event")]
/**
* Dispatched at startup after the initial view has been
* put on the display list.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="applicationComplete", type="org.apache.flex.events.Event")]
/**
* The Application class is the main class and entry point for a FlexJS
* application. This Application class is different than the
* Flex SDK's mx:Application or spark:Application in that it does not contain
* user interface elements. Those UI elements go in the views. This
* Application class expects there to be a main model, a controller, and
* an initial view.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class Application extends Sprite implements IStrand, IFlexInfo, IParent
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function Application()
{
super();
if (stage)
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.quality = StageQuality.HIGH_16X16_LINEAR;
trace("working");
}
loaderInfo.addEventListener(flash.events.Event.INIT, initHandler);
}
/**
* The document property is used to provide
* a property lookup context for non-display objects.
* For Application, it points to itself.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var document:Object = this;
private function initHandler(event:flash.events.Event):void
{
ValuesManager.valuesImpl = valuesImpl;
ValuesManager.valuesImpl.init(this);
dispatchEvent(new Event("initialize"));
if (initialView)
{
initialView.applicationModel = model;
this.addElement(initialView);
dispatchEvent(new Event("viewChanged"));
}
dispatchEvent(new Event("applicationComplete"));
}
/**
* The org.apache.flex.core.IValuesImpl that will
* determine the default values and other values
* for the application. The most common choice
* is org.apache.flex.core.SimpleCSSValuesImpl.
*
* @see org.apache.flex.core.SimpleCSSValuesImpl
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var valuesImpl:IValuesImpl;
/**
* The initial view.
*
* @see org.apache.flex.core.ViewBase
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var initialView:ViewBase;
/**
* The data model (for the initial view).
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var model:Object;
/**
* The controller. The controller typically watches
* the UI for events and updates the model accordingly.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var controller:Object;
/**
* An array of data that describes the MXML attributes
* and tags in an MXML document. This data is usually
* decoded by an MXMLDataInterpreter
*
* @see org.apache.flex.utils.MXMLDataInterpreter
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get MXMLDescriptor():Array
{
return null;
}
/**
* An method called by the compiler's generated
* code to kick off the setting of MXML attribute
* values and instantiation of child tags.
*
* The call has to be made in the generated code
* in order to ensure that the constructors have
* completed first.
*
* @param data The encoded data representing the
* MXML attributes.
*
* @see org.apache.flex.utils.MXMLDataInterpreter
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function generateMXMLAttributes(data:Array):void
{
MXMLDataInterpreter.generateMXMLProperties(this, data);
}
/**
* The array property that is used to add additional
* beads to an MXML tag. From ActionScript, just
* call addBead directly.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var beads:Array;
private var _beads:Vector.<IBead>;
/**
* @copy org.apache.flex.core.IStrand#addBead()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function addBead(bead:IBead):void
{
if (!_beads)
_beads = new Vector.<IBead>;
_beads.push(bead);
bead.strand = this;
}
/**
* @copy org.apache.flex.core.IStrand#getBeadByType()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function getBeadByType(classOrInterface:Class):IBead
{
for each (var bead:IBead in _beads)
{
if (bead is classOrInterface)
return bead;
}
return null;
}
/**
* @copy org.apache.flex.core.IStrand#removeBead()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function removeBead(value:IBead):IBead
{
var n:int = _beads.length;
for (var i:int = 0; i < n; i++)
{
var bead:IBead = _beads[i];
if (bead == value)
{
_beads.splice(i, 1);
return bead;
}
}
return null;
}
private var _info:Object;
/**
* An Object containing information generated
* by the compiler that is useful at startup time.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function info():Object
{
if (!_info)
{
var mainClassName:String = getQualifiedClassName(this);
var initClassName:String = "_" + mainClassName + "_FlexInit";
var c:Class = ApplicationDomain.currentDomain.getDefinition(initClassName) as Class;
_info = c.info();
}
return _info;
}
/**
* @copy org.apache.flex.core.IParent#addElement()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function addElement(c:Object):void
{
if (c is IUIBase)
{
addChild(IUIBase(c).element as DisplayObject);
IUIBase(c).addedToParent();
}
else
addChild(c as DisplayObject);
}
/**
* @copy org.apache.flex.core.IParent#addElementAt()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function addElementAt(c:Object, index:int):void
{
if (c is IUIBase)
{
addChildAt(IUIBase(c).element as DisplayObject, index);
IUIBase(c).addedToParent();
}
else
addChildAt(c as DisplayObject, index);
}
/**
* @copy org.apache.flex.core.IParent#getElementIndex()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function getElementIndex(c:Object):int
{
if (c is IUIBase)
return getChildIndex(IUIBase(c).element as DisplayObject);
return getChildIndex(c as DisplayObject);
}
/**
* @copy org.apache.flex.core.IParent#removeElement()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function removeElement(c:Object):void
{
if (c is IUIBase)
{
removeChild(IUIBase(c).element as DisplayObject);
}
else
removeChild(c as DisplayObject);
}
/**
* @copy org.apache.flex.core.IParent#numElements
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get numElements():int
{
return numChildren;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.core
{
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageQuality;
import flash.display.StageScaleMode;
import flash.events.IOErrorEvent;
import flash.system.ApplicationDomain;
import flash.utils.getQualifiedClassName;
import org.apache.flex.events.Event;
import org.apache.flex.utils.MXMLDataInterpreter;
//--------------------------------------
// Events
//--------------------------------------
/**
* Dispatched at startup. Attributes and sub-instances of
* the MXML document have been created and assigned.
* The component lifecycle is different
* than the Flex SDK. There is no creationComplete event.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="initialize", type="org.apache.flex.events.Event")]
/**
* Dispatched at startup after the initial view has been
* put on the display list.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="viewChanged", type="org.apache.flex.events.Event")]
/**
* Dispatched at startup after the initial view has been
* put on the display list.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="applicationComplete", type="org.apache.flex.events.Event")]
/**
* The Application class is the main class and entry point for a FlexJS
* application. This Application class is different than the
* Flex SDK's mx:Application or spark:Application in that it does not contain
* user interface elements. Those UI elements go in the views. This
* Application class expects there to be a main model, a controller, and
* an initial view.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class Application extends Sprite implements IStrand, IFlexInfo, IParent
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function Application()
{
super();
if (stage)
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.quality = StageQuality.HIGH_16X16_LINEAR;
}
loaderInfo.addEventListener(flash.events.Event.INIT, initHandler);
}
/**
* The document property is used to provide
* a property lookup context for non-display objects.
* For Application, it points to itself.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var document:Object = this;
private function initHandler(event:flash.events.Event):void
{
ValuesManager.valuesImpl = valuesImpl;
ValuesManager.valuesImpl.init(this);
dispatchEvent(new Event("initialize"));
if (initialView)
{
initialView.applicationModel = model;
this.addElement(initialView);
dispatchEvent(new Event("viewChanged"));
}
dispatchEvent(new Event("applicationComplete"));
}
/**
* The org.apache.flex.core.IValuesImpl that will
* determine the default values and other values
* for the application. The most common choice
* is org.apache.flex.core.SimpleCSSValuesImpl.
*
* @see org.apache.flex.core.SimpleCSSValuesImpl
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var valuesImpl:IValuesImpl;
/**
* The initial view.
*
* @see org.apache.flex.core.ViewBase
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var initialView:ViewBase;
/**
* The data model (for the initial view).
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var model:Object;
/**
* The controller. The controller typically watches
* the UI for events and updates the model accordingly.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var controller:Object;
/**
* An array of data that describes the MXML attributes
* and tags in an MXML document. This data is usually
* decoded by an MXMLDataInterpreter
*
* @see org.apache.flex.utils.MXMLDataInterpreter
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get MXMLDescriptor():Array
{
return null;
}
/**
* An method called by the compiler's generated
* code to kick off the setting of MXML attribute
* values and instantiation of child tags.
*
* The call has to be made in the generated code
* in order to ensure that the constructors have
* completed first.
*
* @param data The encoded data representing the
* MXML attributes.
*
* @see org.apache.flex.utils.MXMLDataInterpreter
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function generateMXMLAttributes(data:Array):void
{
MXMLDataInterpreter.generateMXMLProperties(this, data);
}
/**
* The array property that is used to add additional
* beads to an MXML tag. From ActionScript, just
* call addBead directly.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var beads:Array;
private var _beads:Vector.<IBead>;
/**
* @copy org.apache.flex.core.IStrand#addBead()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function addBead(bead:IBead):void
{
if (!_beads)
_beads = new Vector.<IBead>;
_beads.push(bead);
bead.strand = this;
}
/**
* @copy org.apache.flex.core.IStrand#getBeadByType()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function getBeadByType(classOrInterface:Class):IBead
{
for each (var bead:IBead in _beads)
{
if (bead is classOrInterface)
return bead;
}
return null;
}
/**
* @copy org.apache.flex.core.IStrand#removeBead()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function removeBead(value:IBead):IBead
{
var n:int = _beads.length;
for (var i:int = 0; i < n; i++)
{
var bead:IBead = _beads[i];
if (bead == value)
{
_beads.splice(i, 1);
return bead;
}
}
return null;
}
private var _info:Object;
/**
* An Object containing information generated
* by the compiler that is useful at startup time.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function info():Object
{
if (!_info)
{
var mainClassName:String = getQualifiedClassName(this);
var initClassName:String = "_" + mainClassName + "_FlexInit";
var c:Class = ApplicationDomain.currentDomain.getDefinition(initClassName) as Class;
_info = c.info();
}
return _info;
}
/**
* @copy org.apache.flex.core.IParent#addElement()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function addElement(c:Object):void
{
if (c is IUIBase)
{
addChild(IUIBase(c).element as DisplayObject);
IUIBase(c).addedToParent();
}
else
addChild(c as DisplayObject);
}
/**
* @copy org.apache.flex.core.IParent#addElementAt()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function addElementAt(c:Object, index:int):void
{
if (c is IUIBase)
{
addChildAt(IUIBase(c).element as DisplayObject, index);
IUIBase(c).addedToParent();
}
else
addChildAt(c as DisplayObject, index);
}
/**
* @copy org.apache.flex.core.IParent#getElementIndex()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function getElementIndex(c:Object):int
{
if (c is IUIBase)
return getChildIndex(IUIBase(c).element as DisplayObject);
return getChildIndex(c as DisplayObject);
}
/**
* @copy org.apache.flex.core.IParent#removeElement()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function removeElement(c:Object):void
{
if (c is IUIBase)
{
removeChild(IUIBase(c).element as DisplayObject);
}
else
removeChild(c as DisplayObject);
}
/**
* @copy org.apache.flex.core.IParent#numElements
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get numElements():int
{
return numChildren;
}
}
}
|
Remove unnecessary trace
|
Remove unnecessary trace
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
9705549935493d55f661c8978f5ce29ac625a63c
|
frameworks/projects/HTML/as/src/org/apache/flex/html/beads/ImageView.as
|
frameworks/projects/HTML/as/src/org/apache/flex/html/beads/ImageView.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
{
COMPILE::AS3
{
import flash.display.Bitmap;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.events.IOErrorEvent;
import flash.net.URLRequest;
}
COMPILE::JS
{
import goog.events;
}
import org.apache.flex.core.BeadViewBase;
import org.apache.flex.core.IBeadView;
import org.apache.flex.core.IImageModel;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.UIBase;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
/**
* The ImageView class creates the visual elements of the org.apache.flex.html.Image component.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class ImageView extends BeadViewBase implements IBeadView
{
/**
* constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function ImageView()
{
}
COMPILE::AS3
private var bitmap:Bitmap;
COMPILE::AS3
private var loader:Loader;
private var _model:IImageModel;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
override public function set strand(value:IStrand):void
{
super.strand = value;
COMPILE::AS3
{
IEventDispatcher(_strand).addEventListener("widthChanged",handleSizeChange);
IEventDispatcher(_strand).addEventListener("heightChanged",handleSizeChange);
}
_model = value.getBeadByType(IImageModel) as IImageModel;
_model.addEventListener("urlChanged",handleUrlChange);
// handleUrlChange(null);
}
/**
* @private
*/
private function handleUrlChange(event:Event):void
{
COMPILE::AS3
{
if (_model.source) {
loader = new Loader();
loader.contentLoaderInfo.addEventListener("complete",onComplete);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
trace(e);
e.preventDefault();
});
loader.load(new URLRequest(_model.source));
}
}
COMPILE::JS
{
if (_model.source) {
var host:IUIBase = _strand as IUIBase;
host.element.addEventListener('load',
loadHandler, false);
host.addEventListener('sizeChanged',
sizeChangedHandler);
(host.element as HTMLImageElement).src = _model.source;
}
}
}
/**
* @private
*/
COMPILE::AS3
private function onComplete(event:Object):void
{
var host:UIBase = UIBase(_strand);
if (bitmap) {
host.removeChild(bitmap);
}
bitmap = Bitmap(LoaderInfo(event.target).content);
host.addChild(bitmap);
if (host.isWidthSizedToContent())
{
host.dispatchEvent(new Event("widthChanged"));
if (host.parent)
host.parent.dispatchEvent(new Event("layoutNeeded"));
}
else
bitmap.width = UIBase(_strand).width;
if (host.isHeightSizedToContent())
{
host.dispatchEvent(new Event("heightChanged"));
if (host.parent)
host.parent.dispatchEvent(new Event("layoutNeeded"));
}
else
bitmap.height = UIBase(_strand).height;
}
/**
* @private
*/
COMPILE::AS3
private function handleSizeChange(event:Object):void
{
var host:UIBase = UIBase(_strand);
if (bitmap) {
if (!isNaN(host.explicitWidth) || !isNaN(host.percentWidth))
bitmap.width = UIBase(_strand).width;
if (!isNaN(host.explicitHeight) || !isNaN(host.percentHeight))
bitmap.height = UIBase(_strand).height;
}
}
COMPILE::JS
private function loadHandler(event:Object):void
{
var host:UIBase = UIBase(_strand);
host.parent.dispatchEvent(new Event("layoutNeeded"));
}
/**
* @flexjsignorecoercion HTMLElement
*/
COMPILE::JS
private function sizeChangedHandler(event:Object):void
{
var host:UIBase = _strand as UIBase;
var s:Object = host.positioner.style;
var l:Number = NaN;
var ls:String = s.left;
if (typeof(ls) === 'string' && ls.length > 0)
l = parseFloat(ls.substring(0, ls.length - 2));
var r:Number = NaN;
var rs:String = s.right;
if (typeof(rs) === 'string' && rs.length > 0)
r = parseFloat(rs.substring(0, rs.length - 2));
if (!isNaN(l) &&
!isNaN(r)) {
// if just using size constraints and image will not shrink or grow
var computedWidth:Number = (host.positioner.offsetParent as HTMLElement).offsetWidth -
l - r;
s.width = computedWidth.toString() + 'px';
}
var t:Number = NaN;
var ts:String = s.top;
if (typeof(ts) === 'string' && ts.length > 0)
t = parseFloat(ts.substring(0, ts.length - 2));
var b:Number = NaN;
var bs:String = s.right;
if (typeof(bs) === 'string' && bs.length > 0)
b = parseFloat(bs.substring(0, bs.length - 2));
if (!isNaN(t) &&
!isNaN(b)) {
// if just using size constraints and image will not shrink or grow
var computedHeight:Number = (host.positioner.offsetParent as HTMLElement).offsetHeight -
t - b;
s.height = computedHeight.toString() + 'px';
}
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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
{
COMPILE::AS3
{
import flash.display.Bitmap;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.events.IOErrorEvent;
import flash.net.URLRequest;
}
COMPILE::JS
{
import goog.events;
}
import org.apache.flex.core.BeadViewBase;
import org.apache.flex.core.IBeadView;
import org.apache.flex.core.IImageModel;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.UIBase;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
/**
* The ImageView class creates the visual elements of the org.apache.flex.html.Image component.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class ImageView extends BeadViewBase implements IBeadView
{
/**
* constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function ImageView()
{
}
COMPILE::AS3
private var bitmap:Bitmap;
COMPILE::AS3
private var loader:Loader;
private var _model:IImageModel;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
override public function set strand(value:IStrand):void
{
super.strand = value;
COMPILE::AS3
{
IEventDispatcher(_strand).addEventListener("widthChanged",handleSizeChange);
IEventDispatcher(_strand).addEventListener("heightChanged",handleSizeChange);
}
_model = value.getBeadByType(IImageModel) as IImageModel;
_model.addEventListener("urlChanged",handleUrlChange);
handleUrlChange(null);
}
/**
* @private
*/
private function handleUrlChange(event:Event):void
{
COMPILE::AS3
{
if (_model.source) {
loader = new Loader();
loader.contentLoaderInfo.addEventListener("complete",onComplete);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
trace(e);
e.preventDefault();
});
loader.load(new URLRequest(_model.source));
}
}
COMPILE::JS
{
if (_model.source) {
var host:IUIBase = _strand as IUIBase;
host.element.addEventListener('load',
loadHandler, false);
host.addEventListener('sizeChanged',
sizeChangedHandler);
(host.element as HTMLImageElement).src = _model.source;
}
}
}
/**
* @private
*/
COMPILE::AS3
private function onComplete(event:Object):void
{
var host:UIBase = UIBase(_strand);
if (bitmap) {
host.removeChild(bitmap);
}
bitmap = Bitmap(LoaderInfo(event.target).content);
host.addChild(bitmap);
if (host.isWidthSizedToContent())
{
host.dispatchEvent(new Event("widthChanged"));
if (host.parent)
host.parent.dispatchEvent(new Event("layoutNeeded"));
}
else
bitmap.width = UIBase(_strand).width;
if (host.isHeightSizedToContent())
{
host.dispatchEvent(new Event("heightChanged"));
if (host.parent)
host.parent.dispatchEvent(new Event("layoutNeeded"));
}
else
bitmap.height = UIBase(_strand).height;
}
/**
* @private
*/
COMPILE::AS3
private function handleSizeChange(event:Object):void
{
var host:UIBase = UIBase(_strand);
if (bitmap) {
if (!isNaN(host.explicitWidth) || !isNaN(host.percentWidth))
bitmap.width = UIBase(_strand).width;
if (!isNaN(host.explicitHeight) || !isNaN(host.percentHeight))
bitmap.height = UIBase(_strand).height;
}
}
COMPILE::JS
private function loadHandler(event:Object):void
{
var host:UIBase = UIBase(_strand);
host.parent.dispatchEvent(new Event("layoutNeeded"));
}
/**
* @flexjsignorecoercion HTMLElement
*/
COMPILE::JS
private function sizeChangedHandler(event:Object):void
{
var host:UIBase = _strand as UIBase;
var s:Object = host.positioner.style;
var l:Number = NaN;
var ls:String = s.left;
if (typeof(ls) === 'string' && ls.length > 0)
l = parseFloat(ls.substring(0, ls.length - 2));
var r:Number = NaN;
var rs:String = s.right;
if (typeof(rs) === 'string' && rs.length > 0)
r = parseFloat(rs.substring(0, rs.length - 2));
if (!isNaN(l) &&
!isNaN(r)) {
// if just using size constraints and image will not shrink or grow
var computedWidth:Number = (host.positioner.offsetParent as HTMLElement).offsetWidth -
l - r;
s.width = computedWidth.toString() + 'px';
}
var t:Number = NaN;
var ts:String = s.top;
if (typeof(ts) === 'string' && ts.length > 0)
t = parseFloat(ts.substring(0, ts.length - 2));
var b:Number = NaN;
var bs:String = s.right;
if (typeof(bs) === 'string' && bs.length > 0)
b = parseFloat(bs.substring(0, bs.length - 2));
if (!isNaN(t) &&
!isNaN(b)) {
// if just using size constraints and image will not shrink or grow
var computedHeight:Number = (host.positioner.offsetParent as HTMLElement).offsetHeight -
t - b;
s.height = computedHeight.toString() + 'px';
}
}
}
}
|
fix image loading on the SWF side
|
fix image loading on the SWF side
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
a87b0dbd8f88c3777691f99afb34e080217ff72a
|
src/org/mangui/osmf/plugins/traits/HLSDynamicStreamTrait.as
|
src/org/mangui/osmf/plugins/traits/HLSDynamicStreamTrait.as
|
package org.mangui.osmf.plugins.traits {
import org.mangui.hls.HLS;
import org.mangui.hls.event.HLSEvent;
import org.osmf.traits.DynamicStreamTrait;
import org.osmf.utils.OSMFStrings;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
public class HLSDynamicStreamTrait extends DynamicStreamTrait {
private var _hls : HLS;
public function HLSDynamicStreamTrait(hls : HLS) {
CONFIG::LOGGING {
Log.debug("HLSDynamicStreamTrait()");
}
_hls = hls;
_hls.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler);
super(true, _hls.startlevel, hls.levels.length);
}
override public function dispose() : void {
CONFIG::LOGGING {
Log.debug("HLSDynamicStreamTrait:dispose");
}
_hls.removeEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler);
super.dispose();
}
override public function getBitrateForIndex(index : int) : Number {
if (index > numDynamicStreams - 1 || index < 0) {
throw new RangeError(OSMFStrings.getString(OSMFStrings.STREAMSWITCH_INVALID_INDEX));
}
var bitrate : Number = _hls.levels[index].bitrate / 1024;
CONFIG::LOGGING {
Log.debug("HLSDynamicStreamTrait:getBitrateForIndex(" + index + ")=" + bitrate);
}
return bitrate;
}
override public function switchTo(index : int) : void {
CONFIG::LOGGING {
Log.debug("HLSDynamicStreamTrait:switchTo(" + index + ")/max:" + maxAllowedIndex);
}
if (index < 0 || index > maxAllowedIndex) {
throw new RangeError(OSMFStrings.getString(OSMFStrings.STREAMSWITCH_INVALID_INDEX));
}
autoSwitch = false;
if (!switching) {
setSwitching(true, index);
}
}
override protected function autoSwitchChangeStart(value : Boolean) : void {
CONFIG::LOGGING {
Log.debug("HLSDynamicStreamTrait:autoSwitchChangeStart:" + value);
}
if (value == true && _hls.autolevel == false) {
_hls.level = -1;
// only seek if position is set
if (!isNaN(_hls.position)) {
_hls.stream.seek(_hls.position);
}
}
}
override protected function switchingChangeStart(newSwitching : Boolean, index : int) : void {
CONFIG::LOGGING {
Log.debug("HLSDynamicStreamTrait:switchingChangeStart(newSwitching/index):" + newSwitching + "/" + index);
}
if (newSwitching) {
_hls.level = index;
}
}
/** Update playback position/duration **/
private function _levelSwitchHandler(event : HLSEvent) : void {
var newLevel : int = event.level;
CONFIG::LOGGING {
Log.debug("HLSDynamicStreamTrait:_qualitySwitchHandler:" + newLevel);
}
setCurrentIndex(newLevel);
setSwitching(false, newLevel);
};
}
}
|
package org.mangui.osmf.plugins.traits {
import org.mangui.hls.HLS;
import org.mangui.hls.event.HLSEvent;
import org.osmf.traits.DynamicStreamTrait;
import org.osmf.utils.OSMFStrings;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
public class HLSDynamicStreamTrait extends DynamicStreamTrait {
private var _hls : HLS;
public function HLSDynamicStreamTrait(hls : HLS) {
CONFIG::LOGGING {
Log.debug("HLSDynamicStreamTrait()");
}
_hls = hls;
_hls.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler);
super(true, _hls.startlevel, hls.levels.length);
}
override public function dispose() : void {
CONFIG::LOGGING {
Log.debug("HLSDynamicStreamTrait:dispose");
}
_hls.removeEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler);
super.dispose();
}
override public function getBitrateForIndex(index : int) : Number {
if (index > numDynamicStreams - 1 || index < 0) {
throw new RangeError(OSMFStrings.getString(OSMFStrings.STREAMSWITCH_INVALID_INDEX));
}
var bitrate : Number = _hls.levels[index].bitrate / 1000;
CONFIG::LOGGING {
Log.debug("HLSDynamicStreamTrait:getBitrateForIndex(" + index + ")=" + bitrate);
}
return bitrate;
}
override public function switchTo(index : int) : void {
CONFIG::LOGGING {
Log.debug("HLSDynamicStreamTrait:switchTo(" + index + ")/max:" + maxAllowedIndex);
}
if (index < 0 || index > maxAllowedIndex) {
throw new RangeError(OSMFStrings.getString(OSMFStrings.STREAMSWITCH_INVALID_INDEX));
}
autoSwitch = false;
if (!switching) {
setSwitching(true, index);
}
}
override protected function autoSwitchChangeStart(value : Boolean) : void {
CONFIG::LOGGING {
Log.debug("HLSDynamicStreamTrait:autoSwitchChangeStart:" + value);
}
if (value == true && _hls.autolevel == false) {
_hls.level = -1;
// only seek if position is set
if (!isNaN(_hls.position)) {
_hls.stream.seek(_hls.position);
}
}
}
override protected function switchingChangeStart(newSwitching : Boolean, index : int) : void {
CONFIG::LOGGING {
Log.debug("HLSDynamicStreamTrait:switchingChangeStart(newSwitching/index):" + newSwitching + "/" + index);
}
if (newSwitching) {
_hls.level = index;
}
}
/** Update playback position/duration **/
private function _levelSwitchHandler(event : HLSEvent) : void {
var newLevel : int = event.level;
CONFIG::LOGGING {
Log.debug("HLSDynamicStreamTrait:_qualitySwitchHandler:" + newLevel);
}
setCurrentIndex(newLevel);
setSwitching(false, newLevel);
};
}
}
|
fix bitrate computation related to #97
|
flashlsOSMF.swf: fix bitrate computation
related to #97
|
ActionScript
|
mpl-2.0
|
fixedmachine/flashls,ryanhefner/flashls,mangui/flashls,fixedmachine/flashls,Peer5/flashls,JulianPena/flashls,stevemayhew/flashls,aevange/flashls,Corey600/flashls,hola/flashls,School-Improvement-Network/flashls,Boxie5/flashls,ryanhefner/flashls,suuhas/flashls,dighan/flashls,clappr/flashls,loungelogic/flashls,stevemayhew/flashls,clappr/flashls,stevemayhew/flashls,viktorot/flashls,School-Improvement-Network/flashls,Corey600/flashls,tedconf/flashls,NicolasSiver/flashls,neilrackett/flashls,neilrackett/flashls,codex-corp/flashls,viktorot/flashls,suuhas/flashls,vidible/vdb-flashls,Peer5/flashls,viktorot/flashls,School-Improvement-Network/flashls,aevange/flashls,jlacivita/flashls,thdtjsdn/flashls,NicolasSiver/flashls,loungelogic/flashls,mangui/flashls,Peer5/flashls,ryanhefner/flashls,thdtjsdn/flashls,dighan/flashls,Peer5/flashls,JulianPena/flashls,ryanhefner/flashls,suuhas/flashls,stevemayhew/flashls,tedconf/flashls,aevange/flashls,Boxie5/flashls,codex-corp/flashls,suuhas/flashls,jlacivita/flashls,hola/flashls,vidible/vdb-flashls,aevange/flashls
|
77bc817f4949cb2d269f5c3f1fda24fd8b2aa6b1
|
src/as/com/threerings/parlor/client/DefaultFlexTableConfigurator.as
|
src/as/com/threerings/parlor/client/DefaultFlexTableConfigurator.as
|
//
// $Id$
//
// Vilya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/vilya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.parlor.client {
import mx.binding.utils.BindingUtils;
import mx.containers.Grid;
import mx.controls.CheckBox;
import mx.controls.HSlider;
import mx.controls.Label;
import com.threerings.flex.GridUtil;
import com.threerings.parlor.data.TableConfig;
import com.threerings.parlor.util.ParlorContext;
import com.threerings.parlor.game.client.FlexGameConfigurator;
import com.threerings.parlor.game.data.GameConfig;
/**
* Provides a default implementation of a TableConfigurator for
* a Swing interface.
*/
public class DefaultFlexTableConfigurator extends TableConfigurator
{
/**
* Create a TableConfigurator that allows for the specified configuration
* parameters.
*/
public function DefaultFlexTableConfigurator (
desiredPlayers :int, minPlayers :int = -1, maxPlayers :int = -1,
allowPrivate :Boolean = false)
{
if (minPlayers < 0) {
minPlayers = desiredPlayers;
}
if (maxPlayers < 0) {
maxPlayers = desiredPlayers;
}
_config.minimumPlayerCount = minPlayers;
// create a slider for players, if applicable
if (minPlayers != maxPlayers) {
_playerSlider = new HSlider();
_playerSlider.value = desiredPlayers;
_playerSlider.minimum = minPlayers;
_playerSlider.maximum = maxPlayers;
_playerSlider.liveDragging = true;
_playerSlider.snapInterval = 1;
_playerSlider.showDataTip = false;
} else {
_config.desiredPlayerCount = desiredPlayers;
}
// create up the checkbox for private games, if applicable
if (allowPrivate) {
_privateCheck = new CheckBox();
}
}
// documentation inherited
override protected function createConfigInterface () :void
{
super.createConfigInterface();
var gconf :FlexGameConfigurator =
(_gameConfigurator as FlexGameConfigurator);
if (_playerSlider != null) {
// TODO: proper translation
var playerLabel :Label = new Label();
playerLabel.text = "Players:";
var countLabel :Label = new Label();
BindingUtils.bindProperty(countLabel, "text",
_playerSlider, "value");
var grid :Grid = new Grid();
GridUtil.addRow(grid, countLabel, _playerSlider);
gconf.addControl(playerLabel, grid);
}
if (_privateCheck != null) {
// TODO: proper translation
var privateLabel :Label = new Label();
privateLabel.text = "Private:";
gconf.addControl(privateLabel, _privateCheck);
}
}
// documentation inherited
override public function isEmpty () :Boolean
{
return (_playerSlider == null) && (_privateCheck == null);
}
// documentation inherited
override protected function flushTableConfig() :void
{
super.flushTableConfig();
if (_playerSlider != null) {
_config.desiredPlayerCount = _playerSlider.value;
}
if (_privateCheck != null) {
_config.privateTable = _privateCheck.selected;
}
}
/** A slider for configuring the number of players at the table. */
protected var _playerSlider :HSlider;
/** A checkbox to allow the table creator to specify if the table is
* private. */
protected var _privateCheck :CheckBox;
}
}
|
//
// $Id$
//
// Vilya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/vilya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.parlor.client {
import mx.containers.Grid;
import mx.controls.CheckBox;
import mx.controls.HSlider;
import mx.controls.Label;
import com.threerings.flex.GridUtil;
import com.threerings.flex.LabeledSlider;
import com.threerings.parlor.data.TableConfig;
import com.threerings.parlor.util.ParlorContext;
import com.threerings.parlor.game.client.FlexGameConfigurator;
import com.threerings.parlor.game.data.GameConfig;
/**
* Provides a default implementation of a TableConfigurator for
* a Swing interface.
*/
public class DefaultFlexTableConfigurator extends TableConfigurator
{
/**
* Create a TableConfigurator that allows for the specified configuration
* parameters.
*/
public function DefaultFlexTableConfigurator (
desiredPlayers :int, minPlayers :int = -1, maxPlayers :int = -1,
allowPrivate :Boolean = false)
{
if (minPlayers < 0) {
minPlayers = desiredPlayers;
}
if (maxPlayers < 0) {
maxPlayers = desiredPlayers;
}
_config.minimumPlayerCount = minPlayers;
// create a slider for players, if applicable
if (minPlayers != maxPlayers) {
_playerSlider = new HSlider();
_playerSlider.value = desiredPlayers;
_playerSlider.minimum = minPlayers;
_playerSlider.maximum = maxPlayers;
_playerSlider.liveDragging = true;
_playerSlider.snapInterval = 1;
} else {
_config.desiredPlayerCount = desiredPlayers;
}
// create up the checkbox for private games, if applicable
if (allowPrivate) {
_privateCheck = new CheckBox();
}
}
// documentation inherited
override protected function createConfigInterface () :void
{
super.createConfigInterface();
var gconf :FlexGameConfigurator =
(_gameConfigurator as FlexGameConfigurator);
if (_playerSlider != null) {
// TODO: proper translation
var playerLabel :Label = new Label();
playerLabel.text = "Players:";
gconf.addControl(playerLabel, new LabeledSlider(_playerSlider));
}
if (_privateCheck != null) {
// TODO: proper translation
var privateLabel :Label = new Label();
privateLabel.text = "Private:";
gconf.addControl(privateLabel, _privateCheck);
}
}
// documentation inherited
override public function isEmpty () :Boolean
{
return (_playerSlider == null) && (_privateCheck == null);
}
// documentation inherited
override protected function flushTableConfig() :void
{
super.flushTableConfig();
if (_playerSlider != null) {
_config.desiredPlayerCount = _playerSlider.value;
}
if (_privateCheck != null) {
_config.privateTable = _privateCheck.selected;
}
}
/** A slider for configuring the number of players at the table. */
protected var _playerSlider :HSlider;
/** A checkbox to allow the table creator to specify if the table is
* private. */
protected var _privateCheck :CheckBox;
}
}
|
Use the new LabeledSlider instead of rolling our own.
|
Use the new LabeledSlider instead of rolling our own.
git-svn-id: a3e1eb16dde062992de22c830ed8045c8013209a@241 c613c5cb-e716-0410-b11b-feb51c14d237
|
ActionScript
|
lgpl-2.1
|
threerings/vilya,threerings/vilya
|
07db69261e9b05a78139e178b0b91ed9c06fc15a
|
src/asfac.tests/src/com/thedevstop/asfac/FluentRegistrationTests.as
|
src/asfac.tests/src/com/thedevstop/asfac/FluentRegistrationTests.as
|
package com.thedevstop.asfac
{
import asunit.framework.TestCase;
import flash.errors.IllegalOperationError;
import flash.utils.Dictionary;
/**
* ...
* @author
*/
public class FluentRegistrationTests extends TestCase
{
public function FluentRegistrationTests(testMethod:String = null)
{
super(testMethod);
}
public function test_should_allow_register_concrete_instance():void
{
var factory:FluentAsFactory = new FluentAsFactory();
var instance:Object = { foo:"bar" };
factory.register(instance).asType(Object);
var result:Object = factory.resolve(Object);
assertSame(instance, result);
}
public function test_should_allow_register_type():void
{
var factory:FluentAsFactory = new FluentAsFactory();
factory.register(Dictionary).asType(Dictionary);
var result:Object = factory.resolve(Dictionary);
assertTrue(result.constructor == Dictionary);
}
public function test_should_allow_register_callback():void
{
var factory:FluentAsFactory = new FluentAsFactory();
var source:Array = [1, 2, 3];
factory.register(function():Array { return source; }).asType(Array);
var result:Array = factory.resolve(Array);
assertSame(source, result);
}
public function test_should_error_when_registering_callback_with_arguments():void
{
var factory:FluentAsFactory = new FluentAsFactory();
var registerFunc:Function = function():void
{
factory.register(function(name:String):Array { return [1, 2, 3]; }).asType(Array);
};
assertThrows(IllegalOperationError, registerFunc);
}
public function test_should_allow_register_callback_as_singleton():void
{
var factory:FluentAsFactory = new FluentAsFactory();
factory.register(function():Dictionary { return new Dictionary(); } ).asType(Dictionary).asSingleton();
var result1:Object = factory.resolve(Dictionary);
var result2:Object = factory.resolve(Dictionary);
assertSame(result1, result2);
}
public function test_should_allow_register_type_as_singleton():void
{
var factory:FluentAsFactory = new FluentAsFactory();
factory.register(Dictionary).asType(Dictionary).asSingleton();
var result1:Object = factory.resolve(Dictionary);
var result2:Object = factory.resolve(Dictionary);
assertSame(result1, result2);
}
public function test_should_error_when_registering_type_is_null():void
{
var factory:FluentAsFactory = new FluentAsFactory();
var registerFunc:Function = function():void
{
factory.register(Dictionary).asType(null);
};
assertThrows(IllegalOperationError, registerFunc);
}
}
}
|
package com.thedevstop.asfac
{
import asunit.framework.TestCase;
import flash.errors.IllegalOperationError;
import flash.utils.Dictionary;
/**
* ...
* @author
*/
public class FluentRegistrationTests extends TestCase
{
public function FluentRegistrationTests(testMethod:String = null)
{
super(testMethod);
}
public function test_should_allow_register_concrete_instance():void
{
var factory:FluentAsFactory = new FluentAsFactory();
var instance:Object = { foo:"bar" };
factory.register(instance).asType(Object);
var result:Object = factory.resolve(Object);
assertSame(instance, result);
}
public function test_should_allow_register_type():void
{
var factory:FluentAsFactory = new FluentAsFactory();
factory.register(Dictionary).asType(Dictionary);
var result:Object = factory.resolve(Dictionary);
assertTrue(result.constructor == Dictionary);
}
public function test_should_allow_register_callback():void
{
var factory:FluentAsFactory = new FluentAsFactory();
var source:Array = [1, 2, 3];
factory.register(function():Array { return source; }).asType(Array);
var result:Array = factory.resolve(Array);
assertSame(source, result);
}
public function test_should_error_when_registering_callback_with_arguments():void
{
var factory:FluentAsFactory = new FluentAsFactory();
var registerFunc:Function = function():void
{
factory.register(function(name:String):Array { return [1, 2, 3]; }).asType(Array);
};
assertThrows(IllegalOperationError, registerFunc);
}
public function test_should_allow_register_callback_as_singleton():void
{
var factory:FluentAsFactory = new FluentAsFactory();
factory.register(function():Dictionary { return new Dictionary(); } ).asType(Dictionary).asSingleton();
var result1:Object = factory.resolve(Dictionary);
var result2:Object = factory.resolve(Dictionary);
assertSame(result1, result2);
}
public function test_should_allow_register_type_as_singleton():void
{
var factory:FluentAsFactory = new FluentAsFactory();
factory.register(Dictionary).asType(Dictionary).asSingleton();
var result1:Object = factory.resolve(Dictionary);
var result2:Object = factory.resolve(Dictionary);
assertSame(result1, result2);
}
public function test_should_retun_new_instances_when_not_registered_as_singleton():void
{
var factory:FluentAsFactory = new FluentAsFactory();
factory.register(Dictionary).asType(Dictionary);
var result1:Object = factory.resolve(Dictionary);
var result2:Object = factory.resolve(Dictionary);
assertNotSame(result1, result2);
}
public function test_should_error_when_registering_type_is_null():void
{
var factory:FluentAsFactory = new FluentAsFactory();
var registerFunc:Function = function():void
{
factory.register(Dictionary).asType(null);
};
assertThrows(IllegalOperationError, registerFunc);
}
}
}
|
Add fluent test that new instances are returned when registering not as singleton
|
Add fluent test that new instances are returned when registering not as singleton
|
ActionScript
|
mit
|
thedevstop/asfac
|
f9c6a9328f553c52c03f371dcb0c57a83545b8de
|
Agent.as
|
Agent.as
|
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.DataEvent;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.net.XMLSocket;
public class Agent extends Sprite {
private static const HOST:String = "localhost";
private static const PORT:int = 42624;
private static const PREFIX:String = "[AGENT]";
private var _host:String;
private var _port:int;
private var _socket:XMLSocket;
private var _connected:Boolean;
public function Agent() {
trace(PREFIX, "Loaded");
/*trace(loaderInfo.loaderURL, loaderInfo.url);*/
_host = loaderInfo.parameters["host"] || HOST;
_port = loaderInfo.parameters["port"] || PORT;
_socket = new XMLSocket();
_socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, fail);
_socket.addEventListener(IOErrorEvent.IO_ERROR, fail);
_socket.addEventListener(DataEvent.DATA, dataReceived);
_socket.addEventListener(Event.CONNECT, connected);
_socket.addEventListener(Event.CLOSE, close);
connect();
}
private function dataReceived(e:DataEvent):void {
trace(PREFIX, "Received command", e.data);
}
private function connect():void {
trace(PREFIX, "Trying to connect to", _host, ":", _port);
try {
_socket.connect(_host, _port);
} catch (e:Error) {
trace(PREFIX, "Unable to connect ", e);
}
}
private function connected(e:Event):void {
_connected = true;
trace(PREFIX, "Connected");
}
private function close(e:Event):void {
_connected = false;
trace(PREFIX, "Disconnected, will try to reconnect");
connect();
}
private function fail(e:Event):void {
trace(PREFIX, "Communication failure", e);
}
}
}
|
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.DataEvent;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.net.XMLSocket;
public class Agent extends Sprite {
private static const HOST:String = "localhost";
private static const PORT:int = 42624;
private static const PREFIX:String = "[AGENT]";
private var _host:String;
private var _port:int;
private var _socket:XMLSocket;
private var _connected:Boolean;
public function Agent() {
trace(PREFIX, "Loaded");
_host = loaderInfo.parameters["host"] || HOST;
_port = loaderInfo.parameters["port"] || PORT;
_socket = new XMLSocket();
_socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, fail);
_socket.addEventListener(IOErrorEvent.IO_ERROR, fail);
_socket.addEventListener(DataEvent.DATA, dataReceived);
_socket.addEventListener(Event.CONNECT, connected);
_socket.addEventListener(Event.CLOSE, close);
connect();
}
private function dataReceived(e:DataEvent):void {
trace(PREFIX, "Received command", e.data);
}
private function connect():void {
trace(PREFIX, "Trying to connect to", _host, ":", _port);
try {
_socket.connect(_host, _port);
} catch (e:Error) {
trace(PREFIX, "Unable to connect ", e);
}
}
private function connected(e:Event):void {
_connected = true;
trace(PREFIX, "Connected");
}
private function close(e:Event):void {
_connected = false;
trace(PREFIX, "Disconnected, will try to reconnect");
connect();
}
private function fail(e:Event):void {
trace(PREFIX, "Communication failure", e);
}
}
}
|
remove debug line
|
remove debug line
|
ActionScript
|
apache-2.0
|
osi/flash-profiler
|
ab5b573d6a5baf12bd034e3ed937c622dbd37422
|
frameworks/projects/mobiletheme/src/spark/skins/ios7/ButtonBarSkin.as
|
frameworks/projects/mobiletheme/src/spark/skins/ios7/ButtonBarSkin.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.ios7
{
import spark.components.ButtonBar;
import spark.components.ButtonBarButton;
import spark.components.DataGroup;
import spark.components.supportClasses.ButtonBarHorizontalLayout;
import spark.skins.mobile.supportClasses.ButtonBarButtonClassFactory;
import spark.skins.mobile.supportClasses.MobileSkin;
/**
* iOS7+ specific skin class for the Spark ButtonBar component.
*
* @see spark.components.ButtonBar
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public class ButtonBarSkin extends MobileSkin
{
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*
*/
public function ButtonBarSkin()
{
super();
}
//--------------------------------------------------------------------------
//
// Skin parts
//
//--------------------------------------------------------------------------
/**
* @copy spark.skins.spark.ApplicationSkin#hostComponent
*/
public var hostComponent:ButtonBar;
/**
* @copy spark.components.ButtonBar#firstButton
*/
public var firstButton:ButtonBarButtonClassFactory;
/**
* @copy spark.components.ButtonBar#lastButton
*/
public var lastButton:ButtonBarButtonClassFactory;
/**
* @copy spark.components.ButtonBar#middleButton
*/
public var middleButton:ButtonBarButtonClassFactory;
/**
* @copy spark.components.SkinnableDataContainer#dataGroup
*/
public var dataGroup:DataGroup;
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
override protected function createChildren():void
{
// Set up the class factories for the buttons
if (!firstButton)
{
firstButton = new ButtonBarButtonClassFactory(ButtonBarButton);
firstButton.skinClass = spark.skins.ios7.ButtonBarFirstButtonSkin;
}
if (!lastButton)
{
lastButton = new ButtonBarButtonClassFactory(ButtonBarButton);
lastButton.skinClass = spark.skins.ios7.ButtonBarLastButtonSkin;
}
if (!middleButton)
{
middleButton = new ButtonBarButtonClassFactory(ButtonBarButton);
middleButton.skinClass = spark.skins.ios7.ButtonBarMiddleButtonSkin;
}
// create the data group to house the buttons
if (!dataGroup)
{
dataGroup = new DataGroup();
var hLayout:ButtonBarHorizontalLayout = new ButtonBarHorizontalLayout();
hLayout.gap = -1;
dataGroup.layout = hLayout;
addChild(dataGroup);
}
}
/**
* @private
*/
override protected function commitCurrentState():void
{
alpha = (currentState == "disabled") ? 0.5 : 1;
}
/**
* @private
*/
override protected function measure():void
{
measuredWidth = dataGroup.measuredWidth;
measuredHeight = dataGroup.measuredHeight;
measuredMinWidth = dataGroup.measuredMinWidth;
measuredMinHeight = dataGroup.measuredMinHeight;
}
/**
* @private
*/
override protected function layoutContents(unscaledWidth:Number, unscaledHeight:Number):void
{
super.layoutContents(unscaledWidth, unscaledHeight);
setElementPosition(dataGroup, 0, 0);
setElementSize(dataGroup, unscaledWidth, unscaledHeight);
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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.ios7
{
import spark.components.ButtonBar;
import spark.components.ButtonBarButton;
import spark.components.DataGroup;
import spark.components.supportClasses.ButtonBarHorizontalLayout;
import spark.skins.mobile.supportClasses.ButtonBarButtonClassFactory;
import spark.skins.mobile.supportClasses.MobileSkin;
/**
* iOS7+ specific skin class for the Spark ButtonBar component.
*
* @see spark.components.ButtonBar
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public class ButtonBarSkin extends MobileSkin
{
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*
*/
public function ButtonBarSkin()
{
super();
}
//--------------------------------------------------------------------------
//
// Skin parts
//
//--------------------------------------------------------------------------
/**
* @copy spark.skins.spark.ApplicationSkin#hostComponent
*/
public var hostComponent:ButtonBar;
/**
* @copy spark.components.ButtonBar#firstButton
*/
public var firstButton:ButtonBarButtonClassFactory;
/**
* @copy spark.components.ButtonBar#lastButton
*/
public var lastButton:ButtonBarButtonClassFactory;
/**
* @copy spark.components.ButtonBar#middleButton
*/
public var middleButton:ButtonBarButtonClassFactory;
/**
* @copy spark.components.SkinnableDataContainer#dataGroup
*/
public var dataGroup:DataGroup;
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
override protected function createChildren():void
{
// Set up the class factories for the buttons
if (!firstButton)
{
firstButton = new ButtonBarButtonClassFactory(ButtonBarButton);
firstButton.skinClass = spark.skins.ios7.ButtonBarFirstButtonSkin;
}
if (!lastButton)
{
lastButton = new ButtonBarButtonClassFactory(ButtonBarButton);
lastButton.skinClass = spark.skins.ios7.ButtonBarLastButtonSkin;
}
if (!middleButton)
{
middleButton = new ButtonBarButtonClassFactory(ButtonBarButton);
middleButton.skinClass = spark.skins.ios7.ButtonBarMiddleButtonSkin;
}
// create the data group to house the buttons
if (!dataGroup)
{
dataGroup = new DataGroup();
var hLayout:ButtonBarHorizontalLayout = new ButtonBarHorizontalLayout();
//TODO: Gap should vary depending on current DPI
hLayout.gap = -1;
dataGroup.layout = hLayout;
addChild(dataGroup);
}
}
/**
* @private
*/
override protected function commitCurrentState():void
{
alpha = (currentState == "disabled") ? 0.5 : 1;
}
/**
* @private
*/
override protected function measure():void
{
measuredWidth = dataGroup.measuredWidth;
measuredHeight = dataGroup.measuredHeight;
measuredMinWidth = dataGroup.measuredMinWidth;
measuredMinHeight = dataGroup.measuredMinHeight;
}
/**
* @private
*/
override protected function layoutContents(unscaledWidth:Number, unscaledHeight:Number):void
{
super.layoutContents(unscaledWidth, unscaledHeight);
setElementPosition(dataGroup, 0, 0);
setElementSize(dataGroup, unscaledWidth, unscaledHeight);
}
}
}
|
Add TODO
|
Add TODO
|
ActionScript
|
apache-2.0
|
adufilie/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk
|
f4c04b663761dc8c43ac1d6cbd7312d3653c045a
|
src/aerys/minko/render/geometry/stream/VertexStreamList.as
|
src/aerys/minko/render/geometry/stream/VertexStreamList.as
|
package aerys.minko.render.geometry.stream
{
import aerys.minko.ns.minko_stream;
import aerys.minko.render.geometry.stream.format.VertexComponent;
import aerys.minko.render.geometry.stream.format.VertexFormat;
import aerys.minko.type.Signal;
public final class VertexStreamList implements IVertexStream
{
use namespace minko_stream;
private var _streams : Vector.<VertexStream> = new Vector.<VertexStream>();
private var _format : VertexFormat = new VertexFormat();
private var _usage : uint = 0;
private var _changed : Signal = new Signal('VertexStreamList.changed');
private var _boundsChanged : Signal = new Signal('VertexStream.boundsChanged');
public function get usage() : uint
{
return _usage;
}
public function get format() : VertexFormat
{
return _format;
}
public function get numStreams() : uint
{
return _streams.length;
}
public function get numVertices() : uint
{
return _streams.length ? _streams[0].numVertices : 0;
}
public function get changed() : Signal
{
return _changed;
}
public function get boundsChanged() : Signal
{
return _boundsChanged;
}
public function VertexStreamList(...streams)
{
initialize(streams);
}
private function initialize(streams : Array) : void
{
for each (var stream : VertexStream in streams)
pushVertexStream(stream);
}
public function clone() : VertexStreamList
{
var vertexStreamList : VertexStreamList = new VertexStreamList();
vertexStreamList._streams = _streams.concat();
vertexStreamList._format = _format.clone();
return vertexStreamList;
}
public function pushVertexStream(vertexStream : VertexStream, force : Boolean = false) : void
{
if (numVertices && vertexStream.numVertices != numVertices)
throw new Error('All streams must have the same total number of vertices.');
_usage |= vertexStream.usage;
_format.unionWith(vertexStream.format, force);
_streams.push(vertexStream);
vertexStream.changed.add(subStreamChangedHandler);
vertexStream.boundsChanged.add(subStreamBoundsChangedHandler);
}
public function getSubStreamById(id : int) : VertexStream
{
return _streams[id];
}
public function getStreamByComponent(vertexComponent : VertexComponent) : VertexStream
{
var streamLength : int = _streams.length;
for (var i : int = streamLength - 1; i >= 0; --i)
if (_streams[i].format.hasComponent(vertexComponent))
return _streams[i];
return null;
}
public function getVertexStream(id : int = 0) : VertexStream
{
return id < _streams.length ? _streams[id] : null;
}
public function getVertexProperty(index : uint,
component : VertexComponent = null,
offset : uint = 0) : Number
{
if (!format.hasComponent(component))
throw new Error(
'This stream does not provide the \'' + component + '\' vertex component.'
);
return getStreamByComponent(component).getVertexProperty(index, component, offset);
}
public function setVertexProperty(index : uint,
value : Number,
component : VertexComponent = null,
offset : uint = 0) : void
{
if (!format.hasComponent(component))
throw new Error(
'This stream does not provide the \'' + component + '\' vertex component.'
);
return getStreamByComponent(component).setVertexProperty(
index, value, component, offset
);
}
public function deleteVertex(index : uint) : IVertexStream
{
for each (var stream : VertexStream in _streams)
stream.deleteVertex(index);
return this;
}
public function duplicateVertex(index : uint) : IVertexStream
{
for each (var stream : VertexStream in _streams)
stream.duplicateVertex(index);
return this;
}
public function disposeLocalData(waitForUpload : Boolean = true) : void
{
for (var i : int = _streams.length - 1; i >= 0; --i)
_streams[i].disposeLocalData(waitForUpload);
}
public function dispose() : void
{
for (var i : int = _streams.length - 1; i >= 0; --i)
_streams[i].dispose();
}
private function subStreamChangedHandler(subStream : VertexStream) : void
{
_changed.execute(this);
}
private function subStreamBoundsChangedHandler(subStream : VertexStream) : void
{
_boundsChanged.execute(this);
}
}
}
|
package aerys.minko.render.geometry.stream
{
import aerys.minko.ns.minko_stream;
import aerys.minko.render.geometry.stream.format.VertexComponent;
import aerys.minko.render.geometry.stream.format.VertexFormat;
import aerys.minko.type.Signal;
public final class VertexStreamList implements IVertexStream
{
use namespace minko_stream;
private var _streams : Vector.<VertexStream> = new Vector.<VertexStream>();
private var _format : VertexFormat = new VertexFormat();
private var _usage : uint = 0;
private var _changed : Signal = new Signal('VertexStreamList.changed');
private var _boundsChanged : Signal = new Signal('VertexStream.boundsChanged');
public function get usage() : uint
{
return _usage;
}
public function get format() : VertexFormat
{
return _format;
}
public function get numStreams() : uint
{
return _streams.length;
}
public function get numVertices() : uint
{
return _streams.length ? _streams[0].numVertices : 0;
}
public function get changed() : Signal
{
return _changed;
}
public function get boundsChanged() : Signal
{
return _boundsChanged;
}
public function VertexStreamList(...streams)
{
initialize(streams);
}
private function initialize(streams : Array) : void
{
for each (var stream : VertexStream in streams)
pushVertexStream(stream);
}
public function clone() : VertexStreamList
{
var vertexStreamList : VertexStreamList = new VertexStreamList();
vertexStreamList._streams = _streams.concat();
vertexStreamList._format = _format.clone();
return vertexStreamList;
}
public function pushVertexStream(vertexStream : VertexStream,
force : Boolean = false) : void
{
if (numVertices && vertexStream.numVertices != numVertices)
throw new Error('All streams must have the same total number of vertices.');
_usage |= vertexStream.usage;
_format.unionWith(vertexStream.format, force);
_streams.push(vertexStream);
vertexStream.changed.add(subStreamChangedHandler);
vertexStream.boundsChanged.add(subStreamBoundsChangedHandler);
_changed.execute(this);
}
public function getSubStreamById(id : int) : VertexStream
{
return _streams[id];
}
public function getStreamByComponent(vertexComponent : VertexComponent) : VertexStream
{
var streamLength : int = _streams.length;
for (var i : int = streamLength - 1; i >= 0; --i)
if (_streams[i].format.hasComponent(vertexComponent))
return _streams[i];
return null;
}
public function getVertexStream(id : int = 0) : VertexStream
{
return id < _streams.length ? _streams[id] : null;
}
public function getVertexProperty(index : uint,
component : VertexComponent = null,
offset : uint = 0) : Number
{
if (!format.hasComponent(component))
throw new Error(
'This stream does not provide the \'' + component + '\' vertex component.'
);
return getStreamByComponent(component).getVertexProperty(index, component, offset);
}
public function setVertexProperty(index : uint,
value : Number,
component : VertexComponent = null,
offset : uint = 0) : void
{
if (!format.hasComponent(component))
throw new Error(
'This stream does not provide the \'' + component + '\' vertex component.'
);
return getStreamByComponent(component).setVertexProperty(
index, value, component, offset
);
}
public function deleteVertex(index : uint) : IVertexStream
{
for each (var stream : VertexStream in _streams)
stream.deleteVertex(index);
return this;
}
public function duplicateVertex(index : uint) : IVertexStream
{
for each (var stream : VertexStream in _streams)
stream.duplicateVertex(index);
return this;
}
public function disposeLocalData(waitForUpload : Boolean = true) : void
{
for (var i : int = _streams.length - 1; i >= 0; --i)
_streams[i].disposeLocalData(waitForUpload);
}
public function dispose() : void
{
for (var i : int = _streams.length - 1; i >= 0; --i)
_streams[i].dispose();
}
private function subStreamChangedHandler(subStream : VertexStream) : void
{
_changed.execute(this);
}
private function subStreamBoundsChangedHandler(subStream : VertexStream) : void
{
_boundsChanged.execute(this);
}
}
}
|
add missing execution of VertexStreamList.changed in VertexStreamList.pushVertexStream()
|
add missing execution of VertexStreamList.changed in VertexStreamList.pushVertexStream()
|
ActionScript
|
mit
|
aerys/minko-as3
|
b0e7972a9a8e40f48598e9390de3d7b57d007238
|
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
|
51540e17eee78efcf7ce4e9666727c80fbf76848
|
src/gaforflash_example.as
|
src/gaforflash_example.as
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
*/
package
{
import com.google.analytics.AnalyticsTracker;
import com.google.analytics.GATracker;
import com.google.analytics.core.TrackerMode;
import flash.display.Sprite;
import flash.events.Event;
/* note:
Basic example
*/
[SWF(width="800", height="600", backgroundColor='0xffffff', frameRate='24', pageTitle='example', scriptRecursionLimit='1000', scriptTimeLimit='60')]
[ExcludeClass]
public class gaforflash_example extends Sprite
{
/* You need to define a valid GA ID here */
private const GA_ID:String = "UA-111-222";
public var tracker:AnalyticsTracker;
public function gaforflash_example()
{
super();
if( stage )
{
onAddedToStage();
}
else
{
addEventListener( Event.ADDED_TO_STAGE, onAddedToStage );
}
}
private function onAddedToStage( event:Event = null ):void
{
removeEventListener( Event.ADDED_TO_STAGE, onAddedToStage );
main();
}
private function _gasetup():void
{
/* we prevent the factory to build automatically */
GATracker.autobuild = false;
/* instanciation of the Google Analytics tracker */
tracker = new GATracker( this, GA_ID );
/* note:
the 'this' reference need to be a DisplayObject
properly instancied, eg. added to the display list
so we can access the 'stage' property.
*/
/* we configure the tracker */
tracker.mode = TrackerMode.AS3;
tracker.config.sessionTimeout = 60;
tracker.config.conversionTimeout = 180;
/* we force the factory to build the tracker */
GATracker(tracker).build();
}
private function _gatest():void
{
//track pageview test
tracker.trackPageview( "/test" );
//track event test
tracker.trackEvent( "say", "hello world", "test", 123 );
}
public function main():void
{
/* note:
any call ot the GA API before its setup
will be cached temporarily
and once the GATracker build
the cached functions will run in batch
*/
tracker.trackPageview( "/before/setup" );
_gasetup();
/* note:
from this point the GATracker is initialized
and will send data to the Google Analytics server
*/
_gatest();
}
}
}
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
*/
package
{
import com.google.analytics.AnalyticsTracker;
import com.google.analytics.GATracker;
import com.google.analytics.core.TrackerMode;
import flash.display.Sprite;
import flash.events.Event;
/* note:
Basic example
*/
[SWF(width="800", height="600", backgroundColor='0xffffff', frameRate='24', pageTitle='example', scriptRecursionLimit='1000', scriptTimeLimit='60')]
[ExcludeClass]
public class gaforflash_example extends Sprite
{
/* You need to define a valid GA ID here */
//private const GA_ID:String = "UA-111-222";
private const GA_ID:String = "UA-94526-19";
public var tracker:AnalyticsTracker;
public function gaforflash_example()
{
super();
if( stage )
{
onAddedToStage();
}
else
{
addEventListener( Event.ADDED_TO_STAGE, onAddedToStage );
}
}
private function onAddedToStage( event:Event = null ):void
{
removeEventListener( Event.ADDED_TO_STAGE, onAddedToStage );
main();
}
private function _gasetup():void
{
/* we prevent the factory to build automatically */
GATracker.autobuild = false;
/* instanciation of the Google Analytics tracker */
tracker = new GATracker( this, GA_ID );
/* note:
the 'this' reference need to be a DisplayObject
properly instancied, eg. added to the display list
so we can access the 'stage' property.
*/
/* we configure the tracker */
tracker.mode = TrackerMode.AS3;
tracker.config.sessionTimeout = 60;
tracker.config.conversionTimeout = 180;
/* we force the factory to build the tracker */
GATracker(tracker).build();
}
private function _gatest():void
{
//track pageview test
tracker.trackPageview( "/test" );
//track event test
tracker.trackEvent( "say", "hello world", "test", 123 );
}
public function main():void
{
/* note:
any call ot the GA API before its setup
will be cached temporarily
and once the GATracker build
the cached functions will run in batch
*/
//tracker.trackPageview( "/before/setup" );
_gasetup();
/* note:
from this point the GATracker is initialized
and will send data to the Google Analytics server
*/
_gatest();
}
}
}
|
update example
|
update example
|
ActionScript
|
apache-2.0
|
minimedj/gaforflash,nsdevaraj/gaforflash,minimedj/gaforflash,nsdevaraj/gaforflash
|
28270395dfd6d3c914272dc94eb5637da07e76f5
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/binding/ConstantBinding.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/binding/ConstantBinding.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.binding
{
import org.apache.flex.core.IBead;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IDocument;
/**
* The ConstantBinding class is lightweight data-binding class that
* is optimized for simple assignments of one object's constant to
* another object's property.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class ConstantBinding implements IBead, IDocument
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function ConstantBinding()
{
}
/**
* The source object who's property has the value we want.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected var source:Object;
/**
* The host mxml document for the source and
* destination objects. The source object
* is either this document for simple bindings
* like {foo} where foo is a property on
* the mxml documnet, or found as document[sourceID]
* for simple bindings like {someid.someproperty}
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected var document:Object;
/**
* The destination object. It is always the same
* as the strand. ConstantBindings are attached to
* the strand of the destination object.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected var destination:Object;
/**
* If not null, the id of the mxml tag who's property
* is being watched for changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var sourceID:String;
/**
* If not null, the name of a property on the
* mxml document that is being watched for changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var sourcePropertyName:String;
/**
* The name of the property on the strand that
* is set when the source property changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var destinationPropertyName:String;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
destination = value;
source = document[sourceID];
destination[destinationPropertyName] = source[sourcePropertyName];
}
/**
* @copy org.apache.flex.core.IDocument#setDocument()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function setDocument(document:Object, id:String = null):void
{
this.document = document;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.binding
{
import org.apache.flex.core.IBead;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IDocument;
/**
* The ConstantBinding class is lightweight data-binding class that
* is optimized for simple assignments of one object's constant to
* another object's property.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class ConstantBinding implements IBead, IDocument
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function ConstantBinding()
{
}
/**
* The source object who's property has the value we want.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected var source:Object;
/**
* The host mxml document for the source and
* destination objects. The source object
* is either this document for simple bindings
* like {foo} where foo is a property on
* the mxml documnet, or found as document[sourceID]
* for simple bindings like {someid.someproperty}
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected var document:Object;
/**
* The destination object. It is always the same
* as the strand. ConstantBindings are attached to
* the strand of the destination object.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var destination:Object;
/**
* If not null, the id of the mxml tag who's property
* is being watched for changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var sourceID:String;
/**
* If not null, the name of a property on the
* mxml document that is being watched for changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var sourcePropertyName:String;
/**
* The name of the property on the strand that
* is set when the source property changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var destinationPropertyName:String;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
if (destination == null)
destination = value;
source = document[sourceID];
destination[destinationPropertyName] = source[sourcePropertyName];
}
/**
* @copy org.apache.flex.core.IDocument#setDocument()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function setDocument(document:Object, id:String = null):void
{
this.document = document;
}
}
}
|
allow override of destination in ConstantBinding as well
|
allow override of destination in ConstantBinding as well
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
e95eee4b15c9513e122c46553e05950e31321db6
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/TextAreaView.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/TextAreaView.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.beads
{
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.IEventDispatcher;
import flash.text.TextFieldType;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IBeadModel;
import org.apache.flex.core.IScrollBarModel;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IParent;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.html.beads.models.ScrollBarModel;
import org.apache.flex.html.supportClasses.Border;
import org.apache.flex.html.supportClasses.ScrollBar;
/**
* The TextAreaView class is the default view for
* the org.apache.flex.html.TextArea class.
* It implements the classic desktop-like TextArea with
* a border and scrollbars. It does not support right-to-left text.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class TextAreaView extends TextFieldViewBase implements IStrand
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function TextAreaView()
{
super();
textField.selectable = true;
textField.type = TextFieldType.INPUT;
textField.mouseEnabled = true;
textField.multiline = true;
textField.wordWrap = true;
}
private var _border:Border;
/**
* The border.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get border():Border
{
return _border;
}
private var _vScrollBar:ScrollBar;
/**
* The vertical ScrollBar.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get vScrollBar():ScrollBar
{
if (!_vScrollBar)
_vScrollBar = createScrollBar();
return _vScrollBar;
}
/**
* @private
*/
override public function set strand(value:IStrand):void
{
super.strand = value;
// add a border to this
_border = new Border();
_border.model = new (ValuesManager.valuesImpl.getValue(value, "iBorderModel")) as IBeadModel;
_border.addBead(new (ValuesManager.valuesImpl.getValue(value, "iBorderBead")) as IBead);
IParent(host).addElement(border);
var vb:ScrollBar = vScrollBar;
// Default size
var ww:Number = DisplayObject(host).width;
if( isNaN(ww) || ww == 0 ) DisplayObject(host).width = 100;
var hh:Number = DisplayObject(host).height;
if( isNaN(hh) || hh == 0 ) DisplayObject(host).height = 42;
// for input, listen for changes to the _textField and update
// the model
textField.addEventListener(Event.SCROLL, textScrollHandler);
IEventDispatcher(host).addEventListener("widthChanged", sizeChangedHandler);
IEventDispatcher(host).addEventListener("heightChanged", sizeChangedHandler);
sizeChangedHandler(null);
}
private function createScrollBar():ScrollBar
{
var vsb:ScrollBar;
vsb = new ScrollBar();
var vsbm:ScrollBarModel = new ScrollBarModel();
vsbm.maximum = 100;
vsbm.minimum = 0;
vsbm.pageSize = 10;
vsbm.pageStepSize = 10;
vsbm.snapInterval = 1;
vsbm.stepSize = 1;
vsbm.value = 0;
vsb.model = vsbm;
vsb.width = 16;
IParent(strand).addElement(vsb);
vsb.addEventListener("scroll", scrollHandler);
return vsb;
}
private function textScrollHandler(event:Event):void
{
var visibleLines:int = textField.bottomScrollV - textField.scrollV + 1;
var scrollableLines:int = textField.numLines - visibleLines + 1;
var vsbm:ScrollBarModel = ScrollBarModel(vScrollBar.model);
vsbm.minimum = 0;
vsbm.maximum = textField.numLines+1;
vsbm.value = textField.scrollV;
vsbm.pageSize = visibleLines;
vsbm.pageStepSize = visibleLines;
}
private function sizeChangedHandler(event:Event):void
{
var ww:Number = DisplayObject(strand).width - DisplayObject(vScrollBar).width;
if( !isNaN(ww) && ww > 0 ) {
textField.width = ww;
_border.width = ww;
}
var hh:Number = DisplayObject(strand).height;
if( !isNaN(hh) && hh > 0 ) {
textField.height = hh;
_border.height = hh;
}
var sb:DisplayObject = DisplayObject(vScrollBar);
sb.y = 0;
sb.x = textField.width - 1;
sb.height = textField.height;
}
private function scrollHandler(event:Event):void
{
var vpos:Number = IScrollBarModel(vScrollBar.model).value;
textField.scrollV = vpos;
}
/**
* @copy org.apache.flex.core.UIBase#beads
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var beads:Array;
private var _beads:Vector.<IBead>;
/**
* @copy org.apache.flex.core.UIBase#addBead()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function addBead(bead:IBead):void
{
if (!_beads)
_beads = new Vector.<IBead>;
_beads.push(bead);
bead.strand = this;
}
/**
* @copy org.apache.flex.core.UIBase#getBeadByType()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function getBeadByType(classOrInterface:Class):IBead
{
for each (var bead:IBead in _beads)
{
if (bead is classOrInterface)
return bead;
}
return null;
}
/**
* @copy org.apache.flex.core.UIBase#removeBead()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function removeBead(value:IBead):IBead
{
var n:int = _beads.length;
for (var i:int = 0; i < n; i++)
{
var bead:IBead = _beads[i];
if (bead == value)
{
_beads.splice(i, 1);
return bead;
}
}
return null;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.beads
{
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.IEventDispatcher;
import flash.text.TextFieldType;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IBeadModel;
import org.apache.flex.core.IScrollBarModel;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IParent;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.html.beads.models.ScrollBarModel;
import org.apache.flex.html.supportClasses.Border;
import org.apache.flex.html.supportClasses.ScrollBar;
/**
* The TextAreaView class is the default view for
* the org.apache.flex.html.TextArea class.
* It implements the classic desktop-like TextArea with
* a border and scrollbars. It does not support right-to-left text.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class TextAreaView extends TextFieldViewBase implements IStrand
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function TextAreaView()
{
super();
textField.selectable = true;
textField.type = TextFieldType.INPUT;
textField.mouseEnabled = true;
textField.multiline = true;
textField.wordWrap = true;
}
private var _border:Border;
/**
* The border.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get border():Border
{
return _border;
}
private var _vScrollBar:ScrollBar;
/**
* The vertical ScrollBar.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get vScrollBar():ScrollBar
{
if (!_vScrollBar)
_vScrollBar = createScrollBar();
return _vScrollBar;
}
/**
* @private
*/
override public function set strand(value:IStrand):void
{
super.strand = value;
// add a border to this
_border = new Border();
_border.model = new (ValuesManager.valuesImpl.getValue(value, "iBorderModel")) as IBeadModel;
_border.addBead(new (ValuesManager.valuesImpl.getValue(value, "iBorderBead")) as IBead);
IParent(host).addElement(border);
var vb:ScrollBar = vScrollBar;
// Default size
var ww:Number = DisplayObject(host).width;
if( isNaN(ww) || ww == 0 ) DisplayObject(host).width = 100;
var hh:Number = DisplayObject(host).height;
if( isNaN(hh) || hh == 0 ) DisplayObject(host).height = 42;
// for input, listen for changes to the _textField and update
// the model
textField.addEventListener(Event.SCROLL, textScrollHandler);
IEventDispatcher(host).addEventListener("widthChanged", sizeChangedHandler);
IEventDispatcher(host).addEventListener("heightChanged", sizeChangedHandler);
sizeChangedHandler(null);
}
private function createScrollBar():ScrollBar
{
var vsb:ScrollBar;
vsb = new ScrollBar();
var vsbm:ScrollBarModel = new ScrollBarModel();
vsbm.maximum = 100;
vsbm.minimum = 0;
vsbm.pageSize = 10;
vsbm.pageStepSize = 10;
vsbm.snapInterval = 1;
vsbm.stepSize = 1;
vsbm.value = 0;
vsb.model = vsbm;
vsb.width = 16;
IParent(host).addElement(vsb);
vsb.addEventListener("scroll", scrollHandler);
return vsb;
}
private function textScrollHandler(event:Event):void
{
var visibleLines:int = textField.bottomScrollV - textField.scrollV + 1;
var scrollableLines:int = textField.numLines - visibleLines + 1;
var vsbm:ScrollBarModel = ScrollBarModel(vScrollBar.model);
vsbm.minimum = 0;
vsbm.maximum = textField.numLines+1;
vsbm.value = textField.scrollV;
vsbm.pageSize = visibleLines;
vsbm.pageStepSize = visibleLines;
}
private function sizeChangedHandler(event:Event):void
{
var ww:Number = DisplayObject(host).width - DisplayObject(vScrollBar).width;
if( !isNaN(ww) && ww > 0 ) {
textField.width = ww;
_border.width = ww;
}
var hh:Number = DisplayObject(host).height;
if( !isNaN(hh) && hh > 0 ) {
textField.height = hh;
_border.height = hh;
}
var sb:DisplayObject = DisplayObject(vScrollBar);
sb.y = 0;
sb.x = textField.width - 1;
sb.height = textField.height;
}
private function scrollHandler(event:Event):void
{
var vpos:Number = IScrollBarModel(vScrollBar.model).value;
textField.scrollV = vpos;
}
/**
* @copy org.apache.flex.core.UIBase#beads
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var beads:Array;
private var _beads:Vector.<IBead>;
/**
* @copy org.apache.flex.core.UIBase#addBead()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function addBead(bead:IBead):void
{
if (!_beads)
_beads = new Vector.<IBead>;
_beads.push(bead);
bead.strand = this;
}
/**
* @copy org.apache.flex.core.UIBase#getBeadByType()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function getBeadByType(classOrInterface:Class):IBead
{
for each (var bead:IBead in _beads)
{
if (bead is classOrInterface)
return bead;
}
return null;
}
/**
* @copy org.apache.flex.core.UIBase#removeBead()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function removeBead(value:IBead):IBead
{
var n:int = _beads.length;
for (var i:int = 0; i < n; i++)
{
var bead:IBead = _beads[i];
if (bead == value)
{
_beads.splice(i, 1);
return bead;
}
}
return null;
}
}
}
|
use host
|
use host
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
912692ea30af1f186de02f86b8a0687523e9c7e9
|
dolly-framework/src/test/resources/dolly/ClassWithSomeCopyableFields.as
|
dolly-framework/src/test/resources/dolly/ClassWithSomeCopyableFields.as
|
package dolly {
public class ClassWithSomeCopyableFields {
public static var staticProperty1:String;
[Cloneable]
public static var staticProperty2:String;
[Cloneable]
public static var staticProperty3:String;
private var _writableField:String;
private var _readOnlyField:String = "read-only field value";
public var property1:String;
[Cloneable]
public var property2:String;
[Cloneable]
public var property3:String;
public function ClassWithSomeCopyableFields() {
}
[Cloneable]
public function get writableField():String {
return _writableField;
}
public function set writableField(value:String):void {
_writableField = value;
}
[Cloneable]
public function get readOnlyField():String {
return _readOnlyField;
}
}
}
|
package dolly {
public class ClassWithSomeCopyableFields {
public static var staticProperty1:String;
[Copyable]
public static var staticProperty2:String;
[Copyable]
public static var staticProperty3:String;
private var _writableField:String;
private var _readOnlyField:String = "read-only field value";
public var property1:String;
[Copyable]
public var property2:String;
[Copyable]
public var property3:String;
public function ClassWithSomeCopyableFields() {
}
[Copyable]
public function get writableField():String {
return _writableField;
}
public function set writableField(value:String):void {
_writableField = value;
}
[Copyable]
public function get readOnlyField():String {
return _readOnlyField;
}
}
}
|
Change metadata tags to Copyable in test data class.
|
Change metadata tags to Copyable in test data class.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
57a63b038228c1d757dc355a6a636fdce7ae7acb
|
examples/flexjs/DataBindingExample_as/src/DataBindingExample.as
|
examples/flexjs/DataBindingExample_as/src/DataBindingExample.as
|
/**
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package
{
import org.apache.flex.core.Application;
import org.apache.flex.core.ItemRendererClassFactory;
import org.apache.flex.core.SimpleCSSValuesImpl;
import org.apache.flex.events.Event;
import org.apache.flex.html.beads.CSSButtonView;
import org.apache.flex.html.beads.CSSTextButtonView;
import org.apache.flex.html.beads.CSSTextToggleButtonView;
import org.apache.flex.html.beads.CheckBoxView;
import org.apache.flex.html.beads.ContainerView;
import org.apache.flex.html.beads.DataItemRendererFactoryForArrayData;
import org.apache.flex.html.beads.DropDownListView;
import org.apache.flex.html.beads.ListView;
import org.apache.flex.html.beads.RadioButtonView;
import org.apache.flex.html.beads.SingleLineBorderBead;
import org.apache.flex.html.beads.SolidBackgroundBead;
import org.apache.flex.html.beads.TextAreaView;
import org.apache.flex.html.beads.TextButtonMeasurementBead;
import org.apache.flex.html.beads.TextFieldLabelMeasurementBead;
import org.apache.flex.html.beads.TextFieldView;
import org.apache.flex.html.beads.TextInputWithBorderView;
import org.apache.flex.html.beads.TextItemRendererFactoryForArrayData;
import org.apache.flex.html.beads.controllers.DropDownListController;
import org.apache.flex.html.beads.controllers.ItemRendererMouseController;
import org.apache.flex.html.beads.controllers.EditableTextKeyboardController;
import org.apache.flex.html.beads.controllers.ListSingleSelectionMouseController;
import org.apache.flex.html.beads.layouts.VerticalLayout;
import org.apache.flex.html.beads.models.ArraySelectionModel;
import org.apache.flex.html.beads.models.SingleLineBorderModel;
import org.apache.flex.html.beads.models.TextModel;
import org.apache.flex.html.beads.models.ToggleButtonModel;
import org.apache.flex.html.beads.models.ValueToggleButtonModel;
import org.apache.flex.html.supportClasses.DropDownListList;
import org.apache.flex.html.supportClasses.DataGroup;
import org.apache.flex.html.supportClasses.ScrollingViewport;
import org.apache.flex.html.supportClasses.StringItemRenderer;
import org.apache.flex.net.HTTPService;
import org.apache.flex.collections.parsers.JSONInputParser;
import org.apache.flex.collections.LazyCollection;
import org.apache.flex.utils.ViewSourceContextMenuOption;
import models.MyModel;
import controllers.MyController;
public class DataBindingExample extends Application
{
public function DataBindingExample()
{
addEventListener("initialize", initializeHandler);
var vi:SimpleCSSValuesImpl = new SimpleCSSValuesImpl();
setupStyles(vi);
valuesImpl = vi;
initialView = new MyInitialView();
model = new MyModel();
controller = new MyController(this);
service = new HTTPService();
collection = new LazyCollection();
collection.inputParser = new JSONInputParser();
collection.itemConverter = new StockDataJSONItemConverter();
service.addBead(collection);
addBead(service);
addBead(new ViewSourceContextMenuOption());
}
public var service:HTTPService;
public var collection:LazyCollection;
private function initializeHandler(event:Event):void
{
MyModel(model).stockSymbol="ADBE";
}
private function setupStyles(vi:SimpleCSSValuesImpl):void
{
var viv:Object = vi.values = {};
viv["global"] =
{
fontFamily: "Arial",
fontSize: 12
};
var o:Object;
o = viv[makeDefinitionName("org.apache.flex.html::Container")] =
{
iBeadView: ContainerView
};
CONFIG::as_only {
o.iBackgroundBead = SolidBackgroundBead;
o.iBorderBead = SingleLineBorderBead;
}
viv[makeDefinitionName("org.apache.flex.html::List")] =
{
iBeadModel: ArraySelectionModel,
iBeadView: ListView,
iBeadController: ListSingleSelectionMouseController,
iBeadLayout: VerticalLayout,
iDataGroup: DataGroup,
iDataProviderItemRendererMapper: DataItemRendererFactoryForArrayData,
IViewport: ScrollingViewport,
iItemRendererClassFactory: ItemRendererClassFactory,
iItemRenderer: StringItemRenderer
};
o = viv[makeDefinitionName("org.apache.flex.html::Button")] =
{
backgroundColor: 0xd8d8d8,
border: [1, "solid", 0x000000],
padding: 4
};
CONFIG::as_only {
o.iBeadView = CSSButtonView;
}
viv[makeDefinitionName("org.apache.flex.html::Button:hover")] =
{
backgroundColor: 0x9fa0a1,
border: [1, "solid", 0x000000],
padding: 4
};
viv[makeDefinitionName("org.apache.flex.html::Button:active")] =
{
backgroundColor: 0x929496,
border: [1, "solid", 0x000000],
padding: 4
};
CONFIG::as_only {
viv["org.apache.flex.html::CheckBox"] =
{
iBeadModel: ToggleButtonModel,
iBeadView: CheckBoxView
};
viv["org.apache.flex.html::DropDownList"] =
{
iBeadModel: ArraySelectionModel,
iBeadView: DropDownListView,
iBeadController: DropDownListController,
iPopUp: DropDownListList
};
viv["org.apache.flex.html.supportClasses::DropDownListList"] =
{
iBeadModel: ArraySelectionModel,
iDataProviderItemRendererMapper: TextItemRendererFactoryForArrayData,
iItemRendererClassFactory: ItemRendererClassFactory,
iItemRenderer: StringItemRenderer,
iBackgroundBead: SolidBackgroundBead,
borderStyle: "solid",
borderRadius: 4,
borderColor: 0,
borderWidth: 1,
backgroundColor: 0xFFFFFF
};
viv["org.apache.flex.html::Label"] =
{
iBeadModel: TextModel,
iBeadView: TextFieldView,
iMeasurementBead: TextFieldLabelMeasurementBead
};
viv["org.apache.flex.html::List"] =
{
iBorderBead: SingleLineBorderBead,
iBorderModel: SingleLineBorderModel
};
viv["org.apache.flex.html::RadioButton"] =
{
iBeadModel: ValueToggleButtonModel,
iBeadView: RadioButtonView
};
viv["org.apache.flex.html::TextArea"] =
{
iBeadModel: TextModel,
iBeadView: TextAreaView,
iBeadController: EditableTextKeyboardController,
iBorderBead: SingleLineBorderBead,
iBorderModel: SingleLineBorderModel,
borderStyle: "solid",
borderColor: 0,
borderWidth: 1,
backgroundColor: 0xFFFFFF
};
viv["org.apache.flex.html::TextButton"] =
{
iBeadModel: TextModel,
iBeadView: CSSTextButtonView,
iMeasurementBead: TextButtonMeasurementBead
};
viv["org.apache.flex.html::TextInput"] =
{
iBeadModel: TextModel,
iBeadView: TextInputWithBorderView,
iBeadController: EditableTextKeyboardController,
iBorderBead: SingleLineBorderBead,
iBackgroundBead: SolidBackgroundBead,
borderStyle: "solid",
borderColor: 0,
borderWidth: 1,
backgroundColor: 0xFFFFFF
};
viv["org.apache.flex.html::ToggleTextButton"] =
{
iBeadModel: ToggleButtonModel,
iBeadView: CSSTextToggleButtonView
};
viv["org.apache.flex.html::SimpleList"] =
{
iBeadModel: ArraySelectionModel,
iBeadView: ListView,
iBeadController: ListSingleSelectionMouseController,
iBeadLayout: VerticalLayout,
iDataGroup: DataGroup,
iDataProviderItemRendererMapper: TextItemRendererFactoryForArrayData,
IViewport: ScrollingViewport,
iItemRendererClassFactory: ItemRendererClassFactory,
iItemRenderer: StringItemRenderer
}
viv["org.apache.flex.html.supportClasses::StringItemRenderer"] =
{
iBeadController: ItemRendererMouseController,
height: 16
}
}
}
private function makeDefinitionName(s:String):String
{
CONFIG::js_only {
s = s.replace("::", ".");
}
return s;
}
}
}
|
/**
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package
{
import org.apache.flex.core.Application;
import org.apache.flex.core.ItemRendererClassFactory;
import org.apache.flex.core.SimpleCSSValuesImpl;
import org.apache.flex.events.Event;
import org.apache.flex.html.beads.CSSButtonView;
import org.apache.flex.html.beads.CSSTextButtonView;
import org.apache.flex.html.beads.CSSTextToggleButtonView;
import org.apache.flex.html.beads.CheckBoxView;
import org.apache.flex.html.beads.ContainerView;
import org.apache.flex.html.beads.DataItemRendererFactoryForArrayData;
import org.apache.flex.html.beads.DropDownListView;
import org.apache.flex.html.beads.ListView;
import org.apache.flex.html.beads.RadioButtonView;
import org.apache.flex.html.beads.SingleLineBorderBead;
import org.apache.flex.html.beads.SolidBackgroundBead;
import org.apache.flex.html.beads.TextAreaView;
import org.apache.flex.html.beads.TextButtonMeasurementBead;
import org.apache.flex.html.beads.TextFieldLabelMeasurementBead;
import org.apache.flex.html.beads.TextFieldView;
import org.apache.flex.html.beads.TextInputWithBorderView;
import org.apache.flex.html.beads.TextItemRendererFactoryForArrayData;
import org.apache.flex.html.beads.controllers.DropDownListController;
import org.apache.flex.html.beads.controllers.ItemRendererMouseController;
import org.apache.flex.html.beads.controllers.EditableTextKeyboardController;
import org.apache.flex.html.beads.controllers.ListSingleSelectionMouseController;
import org.apache.flex.html.beads.layouts.BasicLayout;
import org.apache.flex.html.beads.layouts.VerticalLayout;
import org.apache.flex.html.beads.models.ArraySelectionModel;
import org.apache.flex.html.beads.models.SingleLineBorderModel;
import org.apache.flex.html.beads.models.TextModel;
import org.apache.flex.html.beads.models.ToggleButtonModel;
import org.apache.flex.html.beads.models.ValueToggleButtonModel;
import org.apache.flex.html.beads.models.ViewportModel;
import org.apache.flex.html.supportClasses.ContainerContentArea;
import org.apache.flex.html.supportClasses.DropDownListList;
import org.apache.flex.html.supportClasses.DataGroup;
import org.apache.flex.html.supportClasses.ScrollingViewport;
import org.apache.flex.html.supportClasses.Viewport;
import org.apache.flex.html.supportClasses.StringItemRenderer;
import org.apache.flex.net.HTTPService;
import org.apache.flex.collections.parsers.JSONInputParser;
import org.apache.flex.collections.LazyCollection;
import org.apache.flex.utils.ViewSourceContextMenuOption;
import models.MyModel;
import controllers.MyController;
public class DataBindingExample extends Application
{
public function DataBindingExample()
{
addEventListener("initialize", initializeHandler);
var vi:SimpleCSSValuesImpl = new SimpleCSSValuesImpl();
setupStyles(vi);
valuesImpl = vi;
initialView = new MyInitialView();
model = new MyModel();
controller = new MyController(this);
service = new HTTPService();
collection = new LazyCollection();
collection.inputParser = new JSONInputParser();
collection.itemConverter = new StockDataJSONItemConverter();
service.addBead(collection);
addBead(service);
addBead(new ViewSourceContextMenuOption());
}
public var service:HTTPService;
public var collection:LazyCollection;
private function initializeHandler(event:Event):void
{
MyModel(model).stockSymbol="ADBE";
}
private function setupStyles(vi:SimpleCSSValuesImpl):void
{
var viv:Object = vi.values = {};
viv["global"] =
{
fontFamily: "Arial",
fontSize: 12
};
var o:Object;
o = viv[makeDefinitionName("org.apache.flex.html::Container")] =
{
iBeadView: ContainerView,
iBeadLayout: BasicLayout,
iContentView: ContainerContentArea,
iViewport: Viewport,
iViewportModel: ViewportModel
};
o = viv[makeDefinitionName("org.apache.flex.core::View")] =
{
iBeadView: ContainerView,
iBeadLayout: BasicLayout,
iContentView: ContainerContentArea,
iViewport: Viewport,
iViewportModel: ViewportModel
};
CONFIG::as_only {
o.iBackgroundBead = SolidBackgroundBead;
o.iBorderBead = SingleLineBorderBead;
}
viv[makeDefinitionName("org.apache.flex.html::List")] =
{
iBeadModel: ArraySelectionModel,
iBeadView: ListView,
iBeadController: ListSingleSelectionMouseController,
iBeadLayout: VerticalLayout,
iContentView: DataGroup,
iDataProviderItemRendererMapper: DataItemRendererFactoryForArrayData,
iViewport: ScrollingViewport,
iViewportModel: ViewportModel,
iItemRendererClassFactory: ItemRendererClassFactory,
iItemRenderer: StringItemRenderer
};
o = viv[makeDefinitionName("org.apache.flex.html::Button")] =
{
backgroundColor: 0xd8d8d8,
border: [1, "solid", 0x000000],
padding: 4
};
CONFIG::as_only {
o.iBeadView = CSSButtonView;
}
viv[makeDefinitionName("org.apache.flex.html::Button:hover")] =
{
backgroundColor: 0x9fa0a1,
border: [1, "solid", 0x000000],
padding: 4
};
viv[makeDefinitionName("org.apache.flex.html::Button:active")] =
{
backgroundColor: 0x929496,
border: [1, "solid", 0x000000],
padding: 4
};
CONFIG::as_only {
viv["org.apache.flex.html::CheckBox"] =
{
iBeadModel: ToggleButtonModel,
iBeadView: CheckBoxView
};
viv["org.apache.flex.html::DropDownList"] =
{
iBeadModel: ArraySelectionModel,
iBeadView: DropDownListView,
iBeadController: DropDownListController,
iPopUp: DropDownListList
};
viv["org.apache.flex.html.supportClasses::DropDownListList"] =
{
iBeadModel: ArraySelectionModel,
iDataProviderItemRendererMapper: TextItemRendererFactoryForArrayData,
iItemRendererClassFactory: ItemRendererClassFactory,
iItemRenderer: StringItemRenderer,
iBackgroundBead: SolidBackgroundBead,
borderStyle: "solid",
borderRadius: 4,
borderColor: 0,
borderWidth: 1,
backgroundColor: 0xFFFFFF
};
viv["org.apache.flex.html::Label"] =
{
iBeadModel: TextModel,
iBeadView: TextFieldView,
iMeasurementBead: TextFieldLabelMeasurementBead
};
viv["org.apache.flex.html::List"] =
{
iBorderBead: SingleLineBorderBead,
iBorderModel: SingleLineBorderModel
};
viv["org.apache.flex.html::RadioButton"] =
{
iBeadModel: ValueToggleButtonModel,
iBeadView: RadioButtonView
};
viv["org.apache.flex.html::TextArea"] =
{
iBeadModel: TextModel,
iBeadView: TextAreaView,
iBeadController: EditableTextKeyboardController,
iBorderBead: SingleLineBorderBead,
iBorderModel: SingleLineBorderModel,
borderStyle: "solid",
borderColor: 0,
borderWidth: 1,
backgroundColor: 0xFFFFFF
};
viv["org.apache.flex.html::TextButton"] =
{
iBeadModel: TextModel,
iBeadView: CSSTextButtonView,
iMeasurementBead: TextButtonMeasurementBead
};
viv["org.apache.flex.html::TextInput"] =
{
iBeadModel: TextModel,
iBeadView: TextInputWithBorderView,
iBeadController: EditableTextKeyboardController,
iBorderBead: SingleLineBorderBead,
iBackgroundBead: SolidBackgroundBead,
borderStyle: "solid",
borderColor: 0,
borderWidth: 1,
backgroundColor: 0xFFFFFF
};
viv["org.apache.flex.html::ToggleTextButton"] =
{
iBeadModel: ToggleButtonModel,
iBeadView: CSSTextToggleButtonView
};
viv["org.apache.flex.html::SimpleList"] =
{
iBeadModel: ArraySelectionModel,
iBeadView: ListView,
iBeadController: ListSingleSelectionMouseController,
iBeadLayout: VerticalLayout,
iContentView: DataGroup,
iDataProviderItemRendererMapper: TextItemRendererFactoryForArrayData,
iViewport: ScrollingViewport,
iViewportModel: ViewportModel,
iItemRendererClassFactory: ItemRendererClassFactory,
iItemRenderer: StringItemRenderer
}
viv["org.apache.flex.html.supportClasses::StringItemRenderer"] =
{
iBeadController: ItemRendererMouseController,
height: 16
}
}
}
private function makeDefinitionName(s:String):String
{
CONFIG::js_only {
s = s.replace("::", ".");
}
return s;
}
}
}
|
fix as example
|
fix as example
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
94cb1704cd0b4b5ab36ccc241b560c65a322790d
|
frameworks/projects/spark/src/spark/components/BusyIndicator.as
|
frameworks/projects/spark/src/spark/components/BusyIndicator.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.components
{
import flash.events.Event;
import mx.core.IUIComponent;
import mx.core.IVisualElement;
import mx.events.FlexEvent;
import mx.states.State;
import spark.components.supportClasses.SkinnableComponent;
[SkinState("rotatingState")]
[SkinState("notRotatingState")]
//--------------------------------------
// Styles
//--------------------------------------
/**
* The interval to delay, in milliseconds, between rotations of this
* component. Controls the speed at which this component spins.
*
* @default 50
*
* @langversion 3.0
* @playerversion AIR 2.5
* @productversion Flex 4.5
*
*/
[Style(name="rotationInterval", type="Number", format="Time", inherit="no")]
/**
* Color of the spokes of the spinner.
*
* @default 0x000000
*
* @langversion 3.0
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
[Style(name="symbolColor", type="uint", format="Color", inherit="yes", theme="spark,mobile")]
//--------------------------------------
// Other metadata
//--------------------------------------
[IconFile("BusyIndicator.png")]
/**
* The BusyIndicator defines a component to display when a long-running
* operation is in progress.
* For Web, Desktop and Android, a circle is drawn that rotates.
* For iOS, a spinner with twelve spoke is drawn.
* The color of the circle or spokes is controlled by the value of the <code>symbolColor</code> style.
* The transparency of this component can be modified using the <code>alpha</code> property,
* but the alpha value of each spoke cannot be modified.
*
* <p>The following image shows the BusyIndicator at the bottom of the screen next
* to the Submit button:</p>
*
* <p>
* <img src="../../images/bi_busy_indicator_bi.png" alt="Busy indicator" />
* </p>
*
* <p>The speed at which this component spins is controlled by the <code>rotationInterval</code>
* style. The <code>rotationInterval</code> style sets the delay, in milliseconds, between
* rotations. Decrease the <code>rotationInterval</code> value to increase the speed of the spin.</p>
*
* <p>The BusyIndicator has the following default characteristics:</p>
* <table class="innertable">
* <tr><th>Characteristic</th><th>Description</th></tr>
* <tr><td>Default size</td><td>160 DPI: 26x26 pixels<br>
* 240 DPI: 40x40 pixels<br>
* 320 DPI: 52x52 pixels<br>
* 380 DPI: 80x80 pixels<br></td></tr>
* <tr><td>Minimum size</td><td>20x20 pixels</td></tr>
* <tr><td>Maximum size</td><td>No limit</td></tr>
* </table>
*
* <p>The diameter of the BusyIndicator's spinner is the minimum of the width and
* height of the component. The diameter must be an even number, and is
* reduced by one if it is set to an odd number.</p>
*
* @mxml
*
* <p>The <code><s:BusyIndicator></code> tag inherits all of the tag
* attributes of its superclass and adds the following tag attributes:</p>
*
* <pre>
* <s:BusyIndicator
* <strong>Common Styles</strong>
* rotationInterval=50
*
* <strong>Spark Styles</strong>
* symbolColor="0x000000"
*
* <strong>Mobile Styles</strong>
* symbolColor="0x000000"
* >
* </pre>
*
* @includeExample examples/BusyIndicatorExample.mxml -noswf
* @includeExample examples/views/BusyIndicatorExampleHomeView.mxml -noswf
*
* @langversion 3.0
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public class BusyIndicator extends SkinnableComponent
{
private var effectiveVisibility:Boolean = false;
private var effectiveVisibilityChanged:Boolean = true;
public function BusyIndicator()
{
super();
// Listen to added to stage and removed from stage.
// Start rotating when we are on the stage and stop
// when we are removed from the stage.
addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
addEventListener(Event.REMOVED_FROM_STAGE, removedFromStageHandler);
states = [
new State({name:"notRotatingState"}),
new State({name:"rotatingState"})
];
}
override protected function getCurrentSkinState():String
{
return currentState;
}
private function addedToStageHandler(event:Event):void
{
// Check our visibility here since we haven't added
// visibility listeners yet.
computeEffectiveVisibility();
if (canRotate())
currentState = "rotatingState";
addVisibilityListeners();
invalidateSkinState();
}
private function removedFromStageHandler(event:Event):void
{
currentState = "notRotatingState";
removeVisibilityListeners();
invalidateSkinState();
}
private function computeEffectiveVisibility():void
{
// Check our design layer first.
if (designLayer && !designLayer.effectiveVisibility)
{
effectiveVisibility = false;
return;
}
// Start out with true visibility and enablement
// then loop up parent-chain to see if any of them are false.
effectiveVisibility = true;
var current:IVisualElement = this;
while (current)
{
if (!current.visible)
{
if (!(current is IUIComponent) || !IUIComponent(current).isPopUp)
{
// Treat all pop ups as if they were visible. This is to
// fix a bug where the BusyIndicator does not spin when it
// is inside modal popup. The problem is in we do not get
// an event when the modal window is made visible in
// PopUpManagerImpl.fadeInEffectEndHandler(). When the modal
// window is made visible, setVisible() is passed "true" so
// as to not send an event. When do get events when the
// non-modal windows are popped up. Only modal windows are
// a problem.
// The downside of this fix is BusyIndicator components that are
// inside of hidden, non-modal, popup windows will paint themselves
// on a timer.
effectiveVisibility = false;
break;
}
}
current = current.parent as IVisualElement;
}
}
/**
* The BusyIndicator can be rotated if it is both on the display list and
* visible.
*
* @returns true if the BusyIndicator can be rotated, false otherwise.
*/
private function canRotate():Boolean
{
if (effectiveVisibility && stage != null)
return true;
return false;
}
/**
* @private
* Add event listeners for SHOW and HIDE on all the ancestors up the parent chain.
* Adding weak event listeners just to be safe.
*/
private function addVisibilityListeners():void
{
var current:IVisualElement = this.parent as IVisualElement;
while (current)
{
// add visibility listeners to the parent
current.addEventListener(FlexEvent.HIDE, visibilityChangedHandler, false, 0, true);
current.addEventListener(FlexEvent.SHOW, visibilityChangedHandler, false, 0, true);
current = current.parent as IVisualElement;
}
}
/**
* @private
* Remove event listeners for SHOW and HIDE on all the ancestors up the parent chain.
*/
private function removeVisibilityListeners():void
{
var current:IVisualElement = this;
while (current)
{
current.removeEventListener(FlexEvent.HIDE, visibilityChangedHandler, false);
current.removeEventListener(FlexEvent.SHOW, visibilityChangedHandler, false);
current = current.parent as IVisualElement;
}
}
/**
* @private
* Event call back whenever the visibility of us or one of our ancestors
* changes
*/
private function visibilityChangedHandler(event:FlexEvent):void
{
effectiveVisibilityChanged = true;
invalidateProperties();
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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.components
{
import flash.events.Event;
import mx.core.IUIComponent;
import mx.core.IVisualElement;
import mx.events.FlexEvent;
import mx.states.State;
import spark.components.supportClasses.SkinnableComponent;
[SkinState("rotatingState")]
[SkinState("notRotatingState")]
//--------------------------------------
// Styles
//--------------------------------------
/**
* The interval to delay, in milliseconds, between rotations of this
* component. Controls the speed at which this component spins.
*
* @default 50
*
* @langversion 3.0
* @playerversion AIR 2.5
* @productversion Flex 4.5
*
*/
[Style(name="rotationInterval", type="Number", format="Time", inherit="no")]
/**
* Color of the spokes of the spinner.
*
* @default 0x000000
*
* @langversion 3.0
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
[Style(name="symbolColor", type="uint", format="Color", inherit="yes", theme="spark,mobile")]
//--------------------------------------
// Other metadata
//--------------------------------------
[IconFile("BusyIndicator.png")]
/**
* The BusyIndicator defines a component to display when a long-running
* operation is in progress.
* For Web, Desktop and iOS, a spinner with twelve spoke is drawn.
* For Android, a circle is drawn that rotates.
* The color of the circle or spokes is controlled by the value of the <code>symbolColor</code> style.
* The transparency of this component can be modified using the <code>alpha</code> property,
* but the alpha value of each spoke cannot be modified.
*
* <p>The following image shows the BusyIndicator at the bottom of the screen next
* to the Submit button:</p>
*
* <p>
* <img src="../../images/bi_busy_indicator_bi.png" alt="Busy indicator" />
* </p>
*
* <p>The speed at which this component spins is controlled by the <code>rotationInterval</code>
* style. The <code>rotationInterval</code> style sets the delay, in milliseconds, between
* rotations. Decrease the <code>rotationInterval</code> value to increase the speed of the spin.</p>
*
* <p>The BusyIndicator has the following default characteristics:</p>
* <table class="innertable">
* <tr><th>Characteristic</th><th>Description</th></tr>
* <tr><td>Default size</td><td>160 DPI: 36x36 pixels<br>
* 120 DPI: 27x27 pixels<br>
* 240 DPI: 54x54 pixels<br>
* 320 DPI: 72x72 pixels<br>
* 480 DPI: 108x108 pixels<br>
* 640 DPI: 144x144 pixels<br></td></tr>
* <tr><td>Minimum size</td><td>20x20 pixels</td></tr>
* <tr><td>Maximum size</td><td>No limit</td></tr>
* </table>
*
* <p>The diameter of the BusyIndicator's spinner is the minimum of the width and
* height of the component. The diameter must be an even number, and is
* reduced by one if it is set to an odd number.</p>
*
* @mxml
*
* <p>The <code><s:BusyIndicator></code> tag inherits all of the tag
* attributes of its superclass and adds the following tag attributes:</p>
*
* <pre>
* <s:BusyIndicator
* <strong>Common Styles</strong>
* rotationInterval=50
*
* <strong>Spark Styles</strong>
* symbolColor="0x000000"
*
* <strong>Mobile Styles</strong>
* symbolColor="0x000000"
* >
* </pre>
*
* @includeExample examples/BusyIndicatorExample.mxml -noswf
* @includeExample examples/views/BusyIndicatorExampleHomeView.mxml -noswf
*
* @langversion 3.0
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public class BusyIndicator extends SkinnableComponent
{
private var effectiveVisibility:Boolean = false;
private var effectiveVisibilityChanged:Boolean = true;
public function BusyIndicator()
{
super();
// Listen to added to stage and removed from stage.
// Start rotating when we are on the stage and stop
// when we are removed from the stage.
addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
addEventListener(Event.REMOVED_FROM_STAGE, removedFromStageHandler);
states = [
new State({name:"notRotatingState"}),
new State({name:"rotatingState"})
];
}
override protected function getCurrentSkinState():String
{
return currentState;
}
private function addedToStageHandler(event:Event):void
{
// Check our visibility here since we haven't added
// visibility listeners yet.
computeEffectiveVisibility();
if (canRotate())
currentState = "rotatingState";
addVisibilityListeners();
invalidateSkinState();
}
private function removedFromStageHandler(event:Event):void
{
currentState = "notRotatingState";
removeVisibilityListeners();
invalidateSkinState();
}
private function computeEffectiveVisibility():void
{
// Check our design layer first.
if (designLayer && !designLayer.effectiveVisibility)
{
effectiveVisibility = false;
return;
}
// Start out with true visibility and enablement
// then loop up parent-chain to see if any of them are false.
effectiveVisibility = true;
var current:IVisualElement = this;
while (current)
{
if (!current.visible)
{
if (!(current is IUIComponent) || !IUIComponent(current).isPopUp)
{
// Treat all pop ups as if they were visible. This is to
// fix a bug where the BusyIndicator does not spin when it
// is inside modal popup. The problem is in we do not get
// an event when the modal window is made visible in
// PopUpManagerImpl.fadeInEffectEndHandler(). When the modal
// window is made visible, setVisible() is passed "true" so
// as to not send an event. When do get events when the
// non-modal windows are popped up. Only modal windows are
// a problem.
// The downside of this fix is BusyIndicator components that are
// inside of hidden, non-modal, popup windows will paint themselves
// on a timer.
effectiveVisibility = false;
break;
}
}
current = current.parent as IVisualElement;
}
}
/**
* The BusyIndicator can be rotated if it is both on the display list and
* visible.
*
* @returns true if the BusyIndicator can be rotated, false otherwise.
*/
private function canRotate():Boolean
{
if (effectiveVisibility && stage != null)
return true;
return false;
}
/**
* @private
* Add event listeners for SHOW and HIDE on all the ancestors up the parent chain.
* Adding weak event listeners just to be safe.
*/
private function addVisibilityListeners():void
{
var current:IVisualElement = this.parent as IVisualElement;
while (current)
{
// add visibility listeners to the parent
current.addEventListener(FlexEvent.HIDE, visibilityChangedHandler, false, 0, true);
current.addEventListener(FlexEvent.SHOW, visibilityChangedHandler, false, 0, true);
current = current.parent as IVisualElement;
}
}
/**
* @private
* Remove event listeners for SHOW and HIDE on all the ancestors up the parent chain.
*/
private function removeVisibilityListeners():void
{
var current:IVisualElement = this;
while (current)
{
current.removeEventListener(FlexEvent.HIDE, visibilityChangedHandler, false);
current.removeEventListener(FlexEvent.SHOW, visibilityChangedHandler, false);
current = current.parent as IVisualElement;
}
}
/**
* @private
* Event call back whenever the visibility of us or one of our ancestors
* changes
*/
private function visibilityChangedHandler(event:FlexEvent):void
{
effectiveVisibilityChanged = true;
invalidateProperties();
}
}
}
|
Update comments to keep up with latest visual changes
|
Update comments to keep up with latest visual changes
|
ActionScript
|
apache-2.0
|
danteinforno/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk
|
723da29e5ee5be82070b5fd663a696d447eea74e
|
src/org/mangui/HLS/muxing/AAC.as
|
src/org/mangui/HLS/muxing/AAC.as
|
package org.mangui.HLS.muxing {
import org.mangui.HLS.HLSAudioTrack;
import flash.utils.ByteArray;
import org.mangui.HLS.utils.Log;
/** Constants and utilities for the AAC audio format. **/
public class AAC implements Demuxer {
/** ADTS Syncword (111111111111), ID (MPEG4), layer (00) and protection_absent (1).**/
private static const SYNCWORD : uint = 0xFFF1;
/** ADTS Syncword with MPEG2 stream ID (used by e.g. Squeeze 7). **/
private static const SYNCWORD_2 : uint = 0xFFF9;
/** ADTS Syncword with MPEG2 stream ID (used by e.g. Envivio 4Caster). **/
private static const SYNCWORD_3 : uint = 0xFFF8;
/** ADTS/ADIF sample rates index. **/
private static const RATES : Array = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
/** ADIF profile index (ADTS doesn't have Null). **/
private static const PROFILES : Array = ['Null', 'Main', 'LC', 'SSR', 'LTP', 'SBR'];
/** Byte data to be read **/
private var _data : ByteArray;
/* callback functions for audio selection, and parsing progress/complete */
private var _callback_audioselect : Function;
private var _callback_progress : Function;
private var _callback_complete : Function;
/** append new data */
public function append(data : ByteArray) : void {
_data.writeBytes(data);
}
/** cancel demux operation */
public function cancel() : void {
_data = null;
}
public function notifycomplete() : void {
Log.debug("AAC: extracting AAC tags");
var audioTags : Vector.<Tag> = new Vector.<Tag>();
/* parse AAC, convert Elementary Streams to TAG */
_data.position = 0;
var id3 : ID3 = new ID3(_data);
// AAC should contain ID3 tag filled with a timestamp
var frames : Vector.<AudioFrame> = AAC.getFrames(_data, _data.position);
var adif : ByteArray = getADIF(_data, 0);
var adifTag : Tag = new Tag(Tag.AAC_HEADER, id3.timestamp, id3.timestamp, true);
adifTag.push(adif, 0, adif.length);
audioTags.push(adifTag);
var audioTag : Tag;
var stamp : Number;
var i : Number = 0;
while (i < frames.length) {
stamp = Math.round(id3.timestamp + i * 1024 * 1000 / frames[i].rate);
audioTag = new Tag(Tag.AAC_RAW, stamp, stamp, false);
if (i != frames.length - 1) {
audioTag.push(_data, frames[i].start, frames[i].length);
} else {
audioTag.push(_data, frames[i].start, _data.length - frames[i].start);
}
audioTags.push(audioTag);
i++;
}
var audiotracks : Vector.<HLSAudioTrack> = new Vector.<HLSAudioTrack>();
audiotracks.push(new HLSAudioTrack('AAC ES', HLSAudioTrack.FROM_DEMUX, 0, true));
// report unique audio track. dont check return value as obviously the track will be selected
_callback_audioselect(audiotracks);
Log.debug("AAC: all tags extracted, callback demux");
_callback_progress(audioTags, new Vector.<Tag>());
_callback_complete();
}
public function AAC(callback_audioselect : Function, callback_progress : Function, callback_complete : Function) : void {
_callback_audioselect = callback_audioselect;
_callback_progress = callback_progress;
_callback_complete = callback_complete;
_data = new ByteArray();
};
public static function probe(data : ByteArray) : Boolean {
var pos : Number = data.position;
var id3 : ID3 = new ID3(data);
// AAC should contain ID3 tag filled with a timestamp
if (id3.hasTimestamp) {
while (data.bytesAvailable > 1) {
// Check for ADTS header
var short : uint = data.readUnsignedShort();
if (short == SYNCWORD || short == SYNCWORD_2 || short == SYNCWORD_3) {
// rewind to sync word
data.position -= 2;
return true;
} else {
data.position--;
}
}
data.position = pos;
}
return false;
}
/** Get ADIF header from ADTS stream. **/
public static function getADIF(adts : ByteArray, position : Number = 0) : ByteArray {
adts.position = position;
var short : uint;
// we need at least 6 bytes, 2 for sync word, 4 for frame length
while ((adts.bytesAvailable > 5) && (short != SYNCWORD) && (short != SYNCWORD_2) && (short != SYNCWORD_3)) {
short = adts.readUnsignedShort();
}
if (short == SYNCWORD || short == SYNCWORD_2 || short == SYNCWORD_3) {
var profile : uint = (adts.readByte() & 0xF0) >> 6;
// Correcting zero-index of ADIF and Flash playing only LC/HE.
if (profile > 3) {
profile = 5;
} else {
profile = 2;
}
adts.position--;
var srate : uint = (adts.readByte() & 0x3C) >> 2;
adts.position--;
var channels : uint = (adts.readShort() & 0x01C0) >> 6;
} else {
throw new Error("Stream did not start with ADTS header.");
return null;
}
// 5 bits profile + 4 bits samplerate + 4 bits channels.
var adif : ByteArray = new ByteArray();
adif.writeByte((profile << 3) + (srate >> 1));
adif.writeByte((srate << 7) + (channels << 3));
if (Log.LOG_DEBUG_ENABLED) {
Log.debug('AAC: ' + PROFILES[profile] + ', ' + RATES[srate] + ' Hz ' + channels + ' channel(s)');
}
// Reset position and return adif.
adts.position -= 4;
adif.position = 0;
return adif;
};
/** Get a list with AAC frames from ADTS stream. **/
public static function getFrames(adts : ByteArray, position : Number) : Vector.<AudioFrame> {
var frames : Vector.<AudioFrame> = new Vector.<AudioFrame>();
var frame_start : uint;
var frame_length : uint;
var id3 : ID3 = new ID3(adts);
position += id3.len;
// Get raw AAC frames from audio stream.
adts.position = position;
var samplerate : uint;
// we need at least 6 bytes, 2 for sync word, 4 for frame length
while (adts.bytesAvailable > 5) {
// Check for ADTS header
var short : uint = adts.readUnsignedShort();
if (short == SYNCWORD || short == SYNCWORD_2 || short == SYNCWORD_3) {
// Store samplerate for offsetting timestamps.
if (!samplerate) {
samplerate = RATES[(adts.readByte() & 0x3C) >> 2];
adts.position--;
}
// Store raw AAC preceding this header.
if (frame_start) {
frames.push(new AudioFrame(frame_start, frame_length, frame_length, samplerate));
}
if (short == SYNCWORD_3) {
// ADTS header is 9 bytes.
frame_length = ((adts.readUnsignedInt() & 0x0003FFE0) >> 5) - 9;
frame_start = adts.position + 3;
adts.position += frame_length + 3;
} else {
// ADTS header is 7 bytes.
frame_length = ((adts.readUnsignedInt() & 0x0003FFE0) >> 5) - 7;
frame_start = adts.position + 1;
adts.position += frame_length + 1;
}
} else {
Log.debug("no ADTS header found, probing...");
adts.position--;
}
}
if (frame_start) {
// check if we have a complete frame available at the end, i.e. last found frame is fitting in this PES packet
var overflow : Number = frame_start + frame_length - adts.length;
if (overflow <= 0 ) {
// no overflow, Write raw AAC after last header.
frames.push(new AudioFrame(frame_start, frame_length, frame_length, samplerate));
} else {
Log.debug2("ADTS overflow at the end of PES packet, missing " + overflow + " bytes to complete the ADTS frame");
}
} else if (frames.length == 0) {
Log.warn("No ADTS headers found in this stream.");
}
adts.position = position;
return frames;
};
}
}
|
package org.mangui.HLS.muxing {
import org.mangui.HLS.HLSAudioTrack;
import flash.utils.ByteArray;
import org.mangui.HLS.utils.Log;
/** Constants and utilities for the AAC audio format. **/
public class AAC implements Demuxer {
/** ADTS Syncword (111111111111), ID (MPEG4), layer (00) and protection_absent (1).**/
private static const SYNCWORD : uint = 0xFFF1;
/** ADTS Syncword with MPEG2 stream ID (used by e.g. Squeeze 7). **/
private static const SYNCWORD_2 : uint = 0xFFF9;
/** ADTS Syncword with MPEG2 stream ID (used by e.g. Envivio 4Caster). **/
private static const SYNCWORD_3 : uint = 0xFFF8;
/** ADTS/ADIF sample rates index. **/
private static const RATES : Array = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
/** ADIF profile index (ADTS doesn't have Null). **/
private static const PROFILES : Array = ['Null', 'Main', 'LC', 'SSR', 'LTP', 'SBR'];
/** Byte data to be read **/
private var _data : ByteArray;
/* callback functions for audio selection, and parsing progress/complete */
private var _callback_audioselect : Function;
private var _callback_progress : Function;
private var _callback_complete : Function;
/** append new data */
public function append(data : ByteArray) : void {
_data.writeBytes(data);
}
/** cancel demux operation */
public function cancel() : void {
_data = null;
}
public function notifycomplete() : void {
Log.debug("AAC: extracting AAC tags");
var audioTags : Vector.<Tag> = new Vector.<Tag>();
/* parse AAC, convert Elementary Streams to TAG */
_data.position = 0;
var id3 : ID3 = new ID3(_data);
// AAC should contain ID3 tag filled with a timestamp
var frames : Vector.<AudioFrame> = AAC.getFrames(_data, _data.position);
var adif : ByteArray = getADIF(_data, 0);
var adifTag : Tag = new Tag(Tag.AAC_HEADER, id3.timestamp, id3.timestamp, true);
adifTag.push(adif, 0, adif.length);
audioTags.push(adifTag);
var audioTag : Tag;
var stamp : Number;
var i : Number = 0;
while (i < frames.length) {
stamp = Math.round(id3.timestamp + i * 1024 * 1000 / frames[i].rate);
audioTag = new Tag(Tag.AAC_RAW, stamp, stamp, false);
if (i != frames.length - 1) {
audioTag.push(_data, frames[i].start, frames[i].length);
} else {
audioTag.push(_data, frames[i].start, _data.length - frames[i].start);
}
audioTags.push(audioTag);
i++;
}
var audiotracks : Vector.<HLSAudioTrack> = new Vector.<HLSAudioTrack>();
audiotracks.push(new HLSAudioTrack('AAC ES', HLSAudioTrack.FROM_DEMUX, 0, true));
// report unique audio track. dont check return value as obviously the track will be selected
_callback_audioselect(audiotracks);
Log.debug("AAC: all tags extracted, callback demux");
_callback_progress(audioTags, new Vector.<Tag>());
_callback_complete();
}
public function AAC(callback_audioselect : Function, callback_progress : Function, callback_complete : Function) : void {
_callback_audioselect = callback_audioselect;
_callback_progress = callback_progress;
_callback_complete = callback_complete;
_data = new ByteArray();
};
public static function probe(data : ByteArray) : Boolean {
var pos : Number = data.position;
var id3 : ID3 = new ID3(data);
// AAC should contain ID3 tag filled with a timestamp
if (id3.hasTimestamp) {
while (data.bytesAvailable > 1) {
// Check for ADTS header
var short : uint = data.readUnsignedShort();
if (short == SYNCWORD || short == SYNCWORD_2 || short == SYNCWORD_3) {
// rewind to sync word
data.position -= 2;
return true;
} else {
data.position--;
}
}
data.position = pos;
}
return false;
}
/** Get ADIF header from ADTS stream. **/
public static function getADIF(adts : ByteArray, position : Number = 0) : ByteArray {
adts.position = position;
var short : uint;
// we need at least 6 bytes, 2 for sync word, 4 for frame length
while ((adts.bytesAvailable > 5) && (short != SYNCWORD) && (short != SYNCWORD_2) && (short != SYNCWORD_3)) {
short = adts.readUnsignedShort();
}
if (short == SYNCWORD || short == SYNCWORD_2 || short == SYNCWORD_3) {
var profile : uint = (adts.readByte() & 0xF0) >> 6;
// Correcting zero-index of ADIF and Flash playing only LC/HE.
if (profile > 3) {
profile = 5;
} else {
profile = 2;
}
adts.position--;
var srate : uint = (adts.readByte() & 0x3C) >> 2;
adts.position--;
var channels : uint = (adts.readShort() & 0x01C0) >> 6;
} else {
throw new Error("Stream did not start with ADTS header.");
}
// 5 bits profile + 4 bits samplerate + 4 bits channels.
var adif : ByteArray = new ByteArray();
adif.writeByte((profile << 3) + (srate >> 1));
adif.writeByte((srate << 7) + (channels << 3));
if (Log.LOG_DEBUG_ENABLED) {
Log.debug('AAC: ' + PROFILES[profile] + ', ' + RATES[srate] + ' Hz ' + channels + ' channel(s)');
}
// Reset position and return adif.
adts.position -= 4;
adif.position = 0;
return adif;
};
/** Get a list with AAC frames from ADTS stream. **/
public static function getFrames(adts : ByteArray, position : Number) : Vector.<AudioFrame> {
var frames : Vector.<AudioFrame> = new Vector.<AudioFrame>();
var frame_start : uint;
var frame_length : uint;
var id3 : ID3 = new ID3(adts);
position += id3.len;
// Get raw AAC frames from audio stream.
adts.position = position;
var samplerate : uint;
// we need at least 6 bytes, 2 for sync word, 4 for frame length
while (adts.bytesAvailable > 5) {
// Check for ADTS header
var short : uint = adts.readUnsignedShort();
if (short == SYNCWORD || short == SYNCWORD_2 || short == SYNCWORD_3) {
// Store samplerate for offsetting timestamps.
if (!samplerate) {
samplerate = RATES[(adts.readByte() & 0x3C) >> 2];
adts.position--;
}
// Store raw AAC preceding this header.
if (frame_start) {
frames.push(new AudioFrame(frame_start, frame_length, frame_length, samplerate));
}
if (short == SYNCWORD_3) {
// ADTS header is 9 bytes.
frame_length = ((adts.readUnsignedInt() & 0x0003FFE0) >> 5) - 9;
frame_start = adts.position + 3;
adts.position += frame_length + 3;
} else {
// ADTS header is 7 bytes.
frame_length = ((adts.readUnsignedInt() & 0x0003FFE0) >> 5) - 7;
frame_start = adts.position + 1;
adts.position += frame_length + 1;
}
} else {
Log.debug("no ADTS header found, probing...");
adts.position--;
}
}
if (frame_start) {
// check if we have a complete frame available at the end, i.e. last found frame is fitting in this PES packet
var overflow : Number = frame_start + frame_length - adts.length;
if (overflow <= 0 ) {
// no overflow, Write raw AAC after last header.
frames.push(new AudioFrame(frame_start, frame_length, frame_length, samplerate));
} else {
Log.debug2("ADTS overflow at the end of PES packet, missing " + overflow + " bytes to complete the ADTS frame");
}
} else if (frames.length == 0) {
Log.warn("No ADTS headers found in this stream.");
}
adts.position = position;
return frames;
};
}
}
|
remove useless return
|
remove useless return
|
ActionScript
|
mpl-2.0
|
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
|
96bdaf9f1fd190db43db7c2c89e7e35a04be4622
|
src/as/com/threerings/util/ObjectMarshaller.as
|
src/as/com/threerings/util/ObjectMarshaller.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.net.registerClassAlias; // function import
import flash.net.ObjectEncoding;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import flash.utils.Endian;
import flash.utils.IExternalizable;
import com.threerings.io.TypedArray;
/**
* Utility methods for transforming flash objects into byte[].
*/
public class ObjectMarshaller
{
/**
* Encode the specified object as either a byte[] or a byte[][] (see below).
* The specific mechanism of encoding is not important,
* as long as decode returns a clone of the original object.
*
* No validation is done to verify that the object can be serialized.
*
* Currently, cycles in the object graph are preserved on the other end.
*
* @param encodeArrayElements if true and the obj is an Array, each element is
* encoded separately, returning a byte[][] instead of a byte[].
*/
public static function encode (
obj :Object, encodeArrayElements :Boolean = false) :Object
{
if (obj == null) {
return null;
}
if (encodeArrayElements && obj is Array) {
var src :Array = (obj as Array);
var dest :TypedArray = TypedArray.create(ByteArray);
for (var ii :int = 0; ii < src.length; ii++) {
dest.push(encode(src[ii], false));
}
return dest;
}
var bytes :ByteArray = new ByteArray();
bytes.endian = Endian.BIG_ENDIAN;
bytes.objectEncoding = ObjectEncoding.AMF3;
// FIX, Because adobe is FUCKING IT UP as usual.
// It seems that with flash 10, they "enhanced" AMF3 encoding. That's great and all,
// except when we try to send this data back to a flash 9 player, which can't read it.
// Guess what, asshats? If you change the encoding spec, IT'S NOT THE SAME VERSION ANYMORE.
// Thanks for breaking all our code where we explicitly set AMF3, even though
// it's currently the default.
// TODO: find out what's doing it. I can't create a small test case- it seems to
// only booch inside Whirled. Even using the viewer seems to always work.
// I suspect it's a SecurityDomain/ApplicationDomain thing that's doing it, but
// have tried correcting for or erasing those differences and I still have the problem.
// Sometime.
if (obj is Dictionary) {
var asArray :Array = [];
for (var key :* in obj) {
asArray.push(key);
asArray.push(obj[key]);
}
obj = asArray;
// then insert our special marker byte before writing this array
bytes.writeByte(DICTIONARY_MARKER);
}
bytes.writeObject(obj);
return bytes;
}
/**
* Validate the value and encode it. Arrays are not broken-up.
* @param maxLength The maximum size of the data after encoding,
* or -1 if no size restriction.
*/
public static function validateAndEncode (obj :Object, maxLength :int = -1) :ByteArray
{
validateValue(obj);
var data :ByteArray = encode(obj, false) as ByteArray;
if (maxLength >= 0 && data != null && data.length > maxLength) {
throw new ArgumentError("Cannot encode data of size " + data.length + " bytes. " +
"May be at most " + maxLength + " bytes.");
}
return data;
}
/**
* Decode the specified byte[] or byte[][] back into a flash Object.
*/
public static function decode (encoded :Object) :Object
{
if (encoded == null) {
return null;
}
if (encoded is TypedArray) {
var src :TypedArray = (encoded as TypedArray);
var dest :Array = [];
for (var ii :int = 0; ii < src.length; ii++) {
dest.push(decode(src[ii] as ByteArray));
}
return dest;
}
var bytes :ByteArray = (encoded as ByteArray);
// Work around dictionary idiocy. Holy shit. See note in encode().
const isDict :Boolean = (bytes[0] === DICTIONARY_MARKER);
// re-set the position in case we're decoding the actual same byte
// array used to encode (and not a network reconstruction)
bytes.position = isDict ? 1 : 0;
bytes.endian = Endian.BIG_ENDIAN;
bytes.objectEncoding = ObjectEncoding.AMF3;
var decoded :Object = bytes.readObject();
if (isDict) {
var decodedArray :Array = decoded as Array;
var asDict :Dictionary = new Dictionary();
for (var jj :int = 0; jj < decodedArray.length; jj += 2) {
asDict[decodedArray[jj]] = decodedArray[jj + 1];
}
decoded = asDict;
}
return decoded;
}
/**
* Validate that the value is kosher for encoding, or throw an ArgumentError if it's not.
*/
public static function validateValue (value :Object) :void
// throws ArgumentError
{
var s :String = getValidationError(value);
if (s != null) {
throw new ArgumentError(s);
}
}
/**
* Get the String reason why this value is not encodable, or null if no error.
*/
public static function getValidationError (value :Object) :String
{
if (value == null) {
return null;
} else if (value is IExternalizable) {
return "IExternalizable is not yet supported";
} else if (value is Array) {
if (ClassUtil.getClassName(value) != "Array") {
// We can't allow arrays to be serialized as IExternalizables
// because we need to know element values (opaquely) on the
// server. Also, we don't allow other types because we wouldn't
// create the right class on the other side.
return "Custom array subclasses are not supported";
}
// then, continue on with the sub-properties check (below)
} else if (value is Dictionary) {
if (ClassUtil.getClassName(value) != "flash.utils.Dictionary") {
return "Custom Dictionary subclasses are not supported";
}
// check all the keys
for (var key :* in value) {
var se :String = getValidationError(key);
if (se != null) {
return se;
}
}
// then, continue on with sub-property check (below)
} else {
var type :String = typeof(value);
if (type == "number" || type == "string" || type == "boolean" ) {
return null; // kosher!
}
if (-1 != VALID_CLASSES.indexOf(ClassUtil.getClassName(value))) {
return null; // kosher
}
if (!Util.isPlainObject(value)) {
return "Non-simple properties may not be set.";
}
// fall through and verify the plain object's sub-properties
}
// check sub-properties (of arrays and objects)
for each (var arrValue :Object in value) {
var s :String = getValidationError(arrValue);
if (s != null) {
return s;
}
}
return null; // it all checks out!
}
// hope and pray that they don't revamp amf3 again and start using this byte. Assholes.
public static const DICTIONARY_MARKER :int = 99;
/**
* Our static initializer.
*/
private static function staticInit () :void
{
registerClassAlias("P", Point);
registerClassAlias("R", Rectangle);
registerClassAlias("D", Dictionary);
}
staticInit();
/** Non-simple classes that we allow, as long as they are not subclassed. */
protected static const VALID_CLASSES :Array = [
"flash.utils.ByteArray", "flash.geom.Point", "flash.geom.Rectangle" ];
}
}
|
//
// $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.net.registerClassAlias; // function import
import flash.net.ObjectEncoding;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import flash.utils.Endian;
import flash.utils.IExternalizable;
import com.threerings.io.TypedArray;
/**
* Utility methods for transforming flash objects into byte[].
*/
public class ObjectMarshaller
{
/**
* Encode the specified object as either a byte[] or a byte[][] (see below).
* The specific mechanism of encoding is not important,
* as long as decode returns a clone of the original object.
*
* No validation is done to verify that the object can be serialized.
*
* Currently, cycles in the object graph are preserved on the other end.
*
* @param encodeArrayElements if true and the obj is an Array, each element is
* encoded separately, returning a byte[][] instead of a byte[].
*/
public static function encode (
obj :Object, encodeArrayElements :Boolean = false) :Object
{
if (obj == null) {
return null;
}
if (encodeArrayElements && obj is Array) {
var src :Array = (obj as Array);
var dest :TypedArray = TypedArray.create(ByteArray);
for (var ii :int = 0; ii < src.length; ii++) {
dest.push(encode(src[ii], false));
}
return dest;
}
var bytes :ByteArray = new ByteArray();
bytes.endian = Endian.BIG_ENDIAN;
bytes.objectEncoding = ObjectEncoding.AMF3;
// FIX, Because adobe is FUCKING IT UP as usual.
// It seems that with flash 10, they "enhanced" AMF3 encoding. That's great and all,
// except when we try to send this data back to a flash 9 player, which can't read it.
// Guess what, asshats? If you change the encoding spec, IT'S NOT THE SAME VERSION ANYMORE.
// Thanks for breaking all our code where we explicitly set AMF3, even though
// it's currently the default.
// TODO: find out what's doing it. I can't create a small test case- it seems to
// only booch inside Whirled. Even using the viewer seems to always work.
// I suspect it's a SecurityDomain/ApplicationDomain thing that's doing it, but
// have tried correcting for or erasing those differences and I still have the problem.
// Sometime.
if (obj is Dictionary) {
var asArray :Array = [];
for (var key :* in obj) {
asArray.push(key);
asArray.push(obj[key]);
}
obj = asArray;
// then insert our special marker byte before writing this array
bytes.writeByte(DICTIONARY_MARKER);
}
bytes.writeObject(obj);
return bytes;
}
/**
* Validate the value and encode it. Arrays are not broken-up.
* @param maxLength The maximum size of the data after encoding,
* or -1 if no size restriction.
*/
public static function validateAndEncode (obj :Object, maxLength :int = -1) :ByteArray
{
validateValue(obj);
var data :ByteArray = encode(obj, false) as ByteArray;
if (maxLength >= 0 && data != null && data.length > maxLength) {
throw new ArgumentError("Cannot encode data of size " + data.length + " bytes. " +
"May be at most " + maxLength + " bytes.");
}
return data;
}
/**
* Decode the specified byte[] or byte[][] back into a flash Object.
*/
public static function decode (encoded :Object) :Object
{
if (encoded == null) {
return null;
}
if (encoded is TypedArray) {
var src :TypedArray = (encoded as TypedArray);
var dest :Array = [];
for (var ii :int = 0; ii < src.length; ii++) {
dest.push(decode(src[ii] as ByteArray));
}
return dest;
}
var bytes :ByteArray = (encoded as ByteArray);
// Work around dictionary idiocy. Holy shit. See note in encode().
const isDict :Boolean = (bytes[0] === DICTIONARY_MARKER);
// re-set the position in case we're decoding the actual same byte
// array used to encode (and not a network reconstruction)
bytes.position = isDict ? 1 : 0;
bytes.endian = Endian.BIG_ENDIAN;
bytes.objectEncoding = ObjectEncoding.AMF3;
var decoded :Object = bytes.readObject();
if (isDict) {
var decodedArray :Array = decoded as Array;
var asDict :Dictionary = new Dictionary();
for (var jj :int = 0; jj < decodedArray.length; jj += 2) {
asDict[decodedArray[jj]] = decodedArray[jj + 1];
}
decoded = asDict;
}
return decoded;
}
/**
* Validate that the value is kosher for encoding, or throw an ArgumentError if it's not.
*/
public static function validateValue (value :Object) :void
// throws ArgumentError
{
var s :String = getValidationError(value);
if (s != null) {
throw new ArgumentError(s);
}
}
/**
* Get the String reason why this value is not encodable, or null if no error.
*/
public static function getValidationError (value :Object) :String
{
if (value == null) {
return null;
} else if (value is IExternalizable) {
return "IExternalizable is not yet supported";
} else if (value is Array) {
if (ClassUtil.getClassName(value) != "Array") {
// We can't allow arrays to be serialized as IExternalizables
// because we need to know element values (opaquely) on the
// server. Also, we don't allow other types because we wouldn't
// create the right class on the other side.
return "Custom array subclasses are not supported";
}
// then, continue on with the sub-properties check (below)
} else if (value is Dictionary) {
if (ClassUtil.getClassName(value) != "flash.utils.Dictionary") {
return "Custom Dictionary subclasses are not supported";
}
// check all the keys
for (var key :* in value) {
var se :String = getValidationError(key);
if (se != null) {
return se;
}
}
// then, continue on with sub-property check (below)
} else {
var type :String = typeof(value);
if (type == "number" || type == "string" || type == "boolean" || type == "xml") {
return null; // kosher!
}
if (-1 != VALID_CLASSES.indexOf(ClassUtil.getClassName(value))) {
return null; // kosher
}
if (!Util.isPlainObject(value)) {
return "Non-simple properties may not be set.";
}
// fall through and verify the plain object's sub-properties
}
// check sub-properties (of arrays and objects)
for each (var arrValue :Object in value) {
var s :String = getValidationError(arrValue);
if (s != null) {
return s;
}
}
return null; // it all checks out!
}
// hope and pray that they don't revamp amf3 again and start using this byte. Assholes.
public static const DICTIONARY_MARKER :int = 99;
/**
* Our static initializer.
*/
private static function staticInit () :void
{
registerClassAlias("P", Point);
registerClassAlias("R", Rectangle);
registerClassAlias("D", Dictionary);
}
staticInit();
/** Non-simple classes that we allow, as long as they are not subclassed. */
protected static const VALID_CLASSES :Array = [
"flash.utils.ByteArray", "flash.geom.Point", "flash.geom.Rectangle" ];
}
}
|
Allow XML to be encoded. Let's try it and see if it works. Let us know Nathan.
|
Allow XML to be encoded.
Let's try it and see if it works. Let us know Nathan.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5728 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
d42638af23bb2d4ed44f9e8b340955bdfca91a21
|
src/Player.as
|
src/Player.as
|
package {
import com.axis.audioclient.AxisTransmit;
import com.axis.ClientEvent;
import com.axis.ErrorManager;
import com.axis.http.url;
import com.axis.httpclient.HTTPClient;
import com.axis.IClient;
import com.axis.Logger;
import com.axis.mjpegclient.MJPEGClient;
import com.axis.rtmpclient.RTMPClient;
import com.axis.rtspclient.IRTSPHandle;
import com.axis.rtspclient.RTSPClient;
import com.axis.rtspclient.RTSPoverHTTPHandle;
import com.axis.rtspclient.RTSPoverTCPHandle;
import flash.display.LoaderInfo;
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.StageAlign;
import flash.display.StageDisplayState;
import flash.display.StageScaleMode;
import flash.display.DisplayObject;
import flash.display.InteractiveObject;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.external.ExternalInterface;
import flash.media.Microphone;
import flash.media.SoundMixer;
import flash.media.SoundTransform;
import flash.media.Video;
import flash.net.NetStream;
import flash.system.Security;
import mx.utils.StringUtil;
[SWF(frameRate="60")]
[SWF(backgroundColor="#efefef")]
public class Player extends Sprite {
[Embed(source = "../VERSION", mimeType = "application/octet-stream")] private var Version:Class;
public static var locomoteID:String = null;
private static const EVENT_STREAM_STARTED:String = "streamStarted";
private static const EVENT_STREAM_PAUSED:String = "streamPaused";
private static const EVENT_STREAM_STOPPED:String = "streamStopped";
private static const EVENT_STREAM_ENDED:String = "streamEnded";
private static const EVENT_FULLSCREEN_ENTERED:String = "fullscreenEntered";
private static const EVENT_FULLSCREEN_EXITED:String = "fullscreenExited";
private static const EVENT_FRAME_READY:String = "frameReady";
public static var config:Object = {
'buffer': 3,
'connectionTimeout': 10,
'scaleUp': false,
'allowFullscreen': true,
'debugLogger': false,
'frameByFrame': false
};
private var audioTransmit:AxisTransmit = new AxisTransmit();
private var meta:Object = {};
private var client:IClient;
private var urlParsed:Object;
private var savedSpeakerVolume:Number;
private var fullscreenAllowed:Boolean = true;
private var currentState:String = "stopped";
private var streamHasAudio:Boolean = false;
private var streamHasVideo:Boolean = false;
private var newPlaylistItem:Boolean = false;
private var startOptions:Object = null;
public function Player() {
var self:Player = this;
Security.allowDomain("*");
Security.allowInsecureDomain("*");
trace('Loaded Locomote, version ' + StringUtil.trim(new Version().toString()));
if (ExternalInterface.available) {
setupAPICallbacks();
} else {
trace("External interface is not available for this container.");
}
/* Set default speaker volume */
this.speakerVolume(50);
/* Stage setup */
this.stage.align = StageAlign.TOP_LEFT;
this.stage.scaleMode = StageScaleMode.NO_SCALE;
addEventListener(Event.ADDED_TO_STAGE, onStageAdded);
/* Fullscreen support setup */
this.stage.doubleClickEnabled = true;
this.stage.addEventListener(MouseEvent.DOUBLE_CLICK, fullscreen);
this.stage.addEventListener(Event.FULLSCREEN, function(event:Event):void {
(StageDisplayState.NORMAL === stage.displayState) ? callAPI(EVENT_FULLSCREEN_EXITED) : callAPI(EVENT_FULLSCREEN_ENTERED);
});
this.stage.addEventListener(Event.RESIZE, function(event:Event):void {
videoResize();
});
this.setConfig(Player.config);
}
/**
* Registers the appropriate API functions with the container, so that
* they can be called, and triggers the apiReady event
* which tells the container that the Player is ready to receive API calls.
*/
public function setupAPICallbacks():void {
ExternalInterface.marshallExceptions = true;
/* Media player API */
ExternalInterface.addCallback("play", play);
ExternalInterface.addCallback("pause", pause);
ExternalInterface.addCallback("resume", resume);
ExternalInterface.addCallback("stop", stop);
ExternalInterface.addCallback("seek", seek);
ExternalInterface.addCallback("playFrames", playFrames);
ExternalInterface.addCallback("streamStatus", streamStatus);
ExternalInterface.addCallback("playerStatus", playerStatus);
ExternalInterface.addCallback("speakerVolume", speakerVolume);
ExternalInterface.addCallback("muteSpeaker", muteSpeaker);
ExternalInterface.addCallback("unmuteSpeaker", unmuteSpeaker);
ExternalInterface.addCallback("microphoneVolume", microphoneVolume);
ExternalInterface.addCallback("muteMicrophone", muteMicrophone);
ExternalInterface.addCallback("unmuteMicrophone", unmuteMicrophone);
ExternalInterface.addCallback("setConfig", setConfig);
/* Audio Transmission API */
ExternalInterface.addCallback("startAudioTransmit", startAudioTransmit);
ExternalInterface.addCallback("stopAudioTransmit", stopAudioTransmit);
}
public function fullscreen(event:MouseEvent):void {
if (config.allowFullscreen) {
this.stage.displayState = (StageDisplayState.NORMAL === stage.displayState) ?
StageDisplayState.FULL_SCREEN : StageDisplayState.NORMAL;
}
}
public function videoResize():void {
if (!this.client) {
return;
}
var stagewidth:uint = (StageDisplayState.NORMAL === stage.displayState) ?
stage.stageWidth : stage.fullScreenWidth;
var stageheight:uint = (StageDisplayState.NORMAL === stage.displayState) ?
stage.stageHeight : stage.fullScreenHeight;
var video:DisplayObject = this.client.getDisplayObject();
var scale:Number = ((stagewidth / meta.width) > (stageheight / meta.height)) ?
(stageheight / meta.height) : (stagewidth / meta.width);
video.width = meta.width;
video.height = meta.height;
if ((scale < 1.0) || (scale > 1.0 && true === config.scaleUp)) {
Logger.log('scaling video, scale:' + scale.toFixed(2) + ' (aspect ratio: ' + (video.width / video.height).toFixed(2) + ')');
video.width = meta.width * scale;
video.height = meta.height * scale;
}
video.x = (stagewidth - video.width) / 2;
video.y = (stageheight - video.height) / 2;
}
public function setConfig(iconfig:Object):void {
if (iconfig.buffer !== undefined) {
if (this.client) {
if (false === this.client.setBuffer(config.buffer)) {
ErrorManager.dispatchError(830);
} else {
config.buffer = iconfig.buffer;
}
} else {
config.buffer = iconfig.buffer;
}
}
if (iconfig.frameByFrame !== undefined) {
if (this.client) {
if (false === this.client.setFrameByFrame(iconfig.frameByFrame)) {
ErrorManager.dispatchError(832);
} else {
config.frameByFrame = iconfig.frameByFrame;
}
} else {
config.frameByFrame = iconfig.frameByFrame;
}
}
if (iconfig.scaleUp !== undefined) {
var scaleUpChanged:Boolean = (config.scaleUp !== iconfig.scaleUp);
config.scaleUp = iconfig.scaleUp;
if (scaleUpChanged && this.client)
this.videoResize();
}
if (iconfig.allowFullscreen !== undefined) {
config.allowFullscreen = iconfig.allowFullscreen;
if (!config.allowFullscreen)
this.stage.displayState = StageDisplayState.NORMAL;
}
if (iconfig.debugLogger !== undefined) {
config.debugLogger = iconfig.debugLogger;
}
if (iconfig.connectionTimeout !== undefined) {
config.connectionTimeout = iconfig.connectionTimeout;
}
}
public function play(param:* = null, options:Object = null):void {
this.streamHasAudio = false;
this.streamHasVideo = false;
if (param is String) {
urlParsed = url.parse(String(param));
} else {
urlParsed = url.parse(param.url);
urlParsed.connect = param.url;
urlParsed.streamName = param.streamName;
}
this.newPlaylistItem = true;
this.startOptions = options;
if (client) {
/* Stop the client, and 'onStopped' will start the new stream. */
client.stop();
return;
}
start();
}
private function start():void {
switch (urlParsed.protocol) {
case 'rtsph':
/* RTSP over HTTP */
client = new RTSPClient(urlParsed, new RTSPoverHTTPHandle(urlParsed));
break;
case 'rtsp':
/* RTSP over TCP */
client = new RTSPClient(urlParsed, new RTSPoverTCPHandle(urlParsed));
break;
case 'http':
case 'https':
/* Progressive download over HTTP */
client = new HTTPClient(urlParsed);
break;
case 'httpm':
/* Progressive mjpg download over HTTP (x-mixed-replace) */
client = new MJPEGClient(urlParsed);
break;
case 'rtmp':
case 'rtmps':
case 'rtmpt':
/* RTMP */
client = new RTMPClient(urlParsed);
break;
default:
ErrorManager.dispatchError(811, [urlParsed.protocol])
return;
}
addChild(this.client.getDisplayObject());
client.addEventListener(ClientEvent.STOPPED, onStopped);
client.addEventListener(ClientEvent.START_PLAY, onStartPlay);
client.addEventListener(ClientEvent.PAUSED, onPaused);
client.addEventListener(ClientEvent.ENDED, onEnded);
client.addEventListener(ClientEvent.META, onMeta);
client.addEventListener(ClientEvent.FRAME, onFrame);
client.start(this.startOptions);
this.newPlaylistItem = false;
}
public function seek(position:String):void {
if (!client || !client.seek(Number(position))) {
ErrorManager.dispatchError(828);
}
}
public function playFrames(timestamp:Number):void {
client && client.playFrames(timestamp);
}
public function pause():void {
try {
client.pause()
} catch (err:Error) {
ErrorManager.dispatchError(808);
}
}
public function resume():void {
if (!client || !client.resume()) {
ErrorManager.dispatchError(809);
}
}
public function stop():void {
if (!client || !client.stop()) {
ErrorManager.dispatchError(810);
return;
}
this.currentState = "stopped";
this.streamHasAudio = false;
this.streamHasVideo = false;
}
public function onMeta(event:ClientEvent):void {
this.meta = event.data;
this.videoResize();
}
public function streamStatus():Object {
if (this.currentState === 'playing') {
/* This causes a crash in some situations */
//this.streamHasAudio = (this.streamHasAudio || this.client.hasAudio());
this.streamHasVideo = (this.streamHasVideo || this.client.hasVideo());
}
var status:Object = {
'fps': (this.client) ? this.client.currentFPS() : null,
'resolution': (this.client) ? { width: meta.width, height: meta.height } : null,
'playbackSpeed': (this.client) ? 1.0 : null,
'protocol': (this.urlParsed) ? this.urlParsed.protocol : null,
'audio': (this.client) ? this.streamHasAudio : null,
'video': (this.client) ? this.streamHasVideo : null,
'state': this.currentState,
'streamURL': (this.urlParsed) ? this.urlParsed.full : null,
'duration': meta.duration ? meta.duration : null,
'currentTime': (this.client) ? this.client.getCurrentTime() : -1,
'bufferedTime': (this.client) ? this.client.bufferedTime() : -1
};
return status;
}
public function playerStatus():Object {
var mic:Microphone = Microphone.getMicrophone();
var status:Object = {
'version': StringUtil.trim(new Version().toString()),
'microphoneVolume': audioTransmit.microphoneVolume,
'speakerVolume': this.savedSpeakerVolume,
'microphoneMuted': (mic.gain === 0),
'speakerMuted': (flash.media.SoundMixer.soundTransform.volume === 0),
'fullscreen': (StageDisplayState.FULL_SCREEN === stage.displayState),
'buffer': (client === null) ? 0 : Player.config.buffer
};
return status;
}
public function speakerVolume(volume:Number):void {
this.savedSpeakerVolume = volume;
var transform:SoundTransform = new SoundTransform(volume / 100.0);
flash.media.SoundMixer.soundTransform = transform;
}
public function muteSpeaker():void {
var transform:SoundTransform = new SoundTransform(0);
flash.media.SoundMixer.soundTransform = transform;
}
public function unmuteSpeaker():void {
if (flash.media.SoundMixer.soundTransform.volume !== 0)
return;
var transform:SoundTransform = new SoundTransform(this.savedSpeakerVolume / 100.0);
flash.media.SoundMixer.soundTransform = transform;
}
public function microphoneVolume(volume:Number):void {
audioTransmit.microphoneVolume = volume;
}
public function muteMicrophone():void {
audioTransmit.muteMicrophone();
}
public function unmuteMicrophone():void {
audioTransmit.unmuteMicrophone();
}
public function startAudioTransmit(url:String = null, type:String = 'axis'):void {
if (type === 'axis') {
audioTransmit.start(url);
} else {
ErrorManager.dispatchError(812);
}
}
public function stopAudioTransmit():void {
audioTransmit.stop();
}
public function allowFullscreen(state:Boolean):void {
this.fullscreenAllowed = state;
if (!state)
this.stage.displayState = StageDisplayState.NORMAL;
}
private function onStageAdded(e:Event):void {
Player.locomoteID = LoaderInfo(this.root.loaderInfo).parameters.locomoteID.toString();
ExternalInterface.call("LocomoteMap['" + Player.locomoteID + "'].__swfReady");
}
private function onStartPlay(event:ClientEvent):void {
this.currentState = "playing";
this.callAPI(EVENT_STREAM_STARTED);
}
private function onEnded(event:ClientEvent):void {
this.currentState = "ended";
this.callAPI(EVENT_STREAM_ENDED, event.data);
}
private function onPaused(event:ClientEvent):void {
this.currentState = "paused";
this.callAPI(EVENT_STREAM_PAUSED, event.data);
}
private function onStopped(event:ClientEvent):void {
this.removeChild(this.client.getDisplayObject());
this.client = null;
this.callAPI(EVENT_STREAM_STOPPED, event.data);
/* If a new `play` has been queued, fire it */
if (this.newPlaylistItem) {
start();
}
}
private function onFrame(event:ClientEvent):void {
this.callAPI(EVENT_FRAME_READY, { timestamp: event.data });
}
private function callAPI(eventName:String, data:Object = null):void {
var functionName:String = "LocomoteMap['" + Player.locomoteID + "'].__playerEvent";
if (data) {
ExternalInterface.call(functionName, eventName, data);
} else {
ExternalInterface.call(functionName, eventName);
}
}
}
}
|
package {
import com.axis.audioclient.AxisTransmit;
import com.axis.ClientEvent;
import com.axis.ErrorManager;
import com.axis.http.url;
import com.axis.httpclient.HTTPClient;
import com.axis.IClient;
import com.axis.Logger;
import com.axis.mjpegclient.MJPEGClient;
import com.axis.rtmpclient.RTMPClient;
import com.axis.rtspclient.IRTSPHandle;
import com.axis.rtspclient.RTSPClient;
import com.axis.rtspclient.RTSPoverHTTPHandle;
import com.axis.rtspclient.RTSPoverTCPHandle;
import flash.display.LoaderInfo;
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.StageAlign;
import flash.display.StageDisplayState;
import flash.display.StageScaleMode;
import flash.display.DisplayObject;
import flash.display.InteractiveObject;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.external.ExternalInterface;
import flash.media.Microphone;
import flash.media.SoundMixer;
import flash.media.SoundTransform;
import flash.media.Video;
import flash.net.NetStream;
import flash.system.Security;
import mx.utils.StringUtil;
[SWF(frameRate="60")]
[SWF(backgroundColor="#efefef")]
public class Player extends Sprite {
[Embed(source = "../VERSION", mimeType = "application/octet-stream")] private var Version:Class;
public static var locomoteID:String = null;
private static const EVENT_STREAM_STARTED:String = "streamStarted";
private static const EVENT_STREAM_PAUSED:String = "streamPaused";
private static const EVENT_STREAM_STOPPED:String = "streamStopped";
private static const EVENT_STREAM_ENDED:String = "streamEnded";
private static const EVENT_FULLSCREEN_ENTERED:String = "fullscreenEntered";
private static const EVENT_FULLSCREEN_EXITED:String = "fullscreenExited";
private static const EVENT_FRAME_READY:String = "frameReady";
public static var config:Object = {
'buffer': 3,
'connectionTimeout': 10,
'scaleUp': false,
'allowFullscreen': true,
'debugLogger': false,
'frameByFrame': false
};
private var audioTransmit:AxisTransmit = new AxisTransmit();
private var meta:Object = {};
private var client:IClient;
private var urlParsed:Object;
private var savedSpeakerVolume:Number;
private var fullscreenAllowed:Boolean = true;
private var currentState:String = "stopped";
private var streamHasAudio:Boolean = false;
private var streamHasVideo:Boolean = false;
private var newPlaylistItem:Boolean = false;
private var startOptions:Object = null;
public function Player() {
var self:Player = this;
Security.allowDomain("*");
Security.allowInsecureDomain("*");
trace('Loaded Locomote, version ' + StringUtil.trim(new Version().toString()));
if (ExternalInterface.available) {
setupAPICallbacks();
} else {
trace("External interface is not available for this container.");
}
/* Set default speaker volume */
this.speakerVolume(50);
/* Stage setup */
this.stage.align = StageAlign.TOP_LEFT;
this.stage.scaleMode = StageScaleMode.NO_SCALE;
addEventListener(Event.ADDED_TO_STAGE, onStageAdded);
/* Fullscreen support setup */
this.stage.doubleClickEnabled = true;
this.stage.addEventListener(MouseEvent.DOUBLE_CLICK, fullscreen);
this.stage.addEventListener(Event.FULLSCREEN, function(event:Event):void {
(StageDisplayState.NORMAL === stage.displayState) ? callAPI(EVENT_FULLSCREEN_EXITED) : callAPI(EVENT_FULLSCREEN_ENTERED);
});
this.stage.addEventListener(Event.RESIZE, function(event:Event):void {
videoResize();
});
this.setConfig(Player.config);
}
/**
* Registers the appropriate API functions with the container, so that
* they can be called, and triggers the apiReady event
* which tells the container that the Player is ready to receive API calls.
*/
public function setupAPICallbacks():void {
ExternalInterface.marshallExceptions = true;
/* Media player API */
ExternalInterface.addCallback("play", play);
ExternalInterface.addCallback("pause", pause);
ExternalInterface.addCallback("resume", resume);
ExternalInterface.addCallback("stop", stop);
ExternalInterface.addCallback("seek", seek);
ExternalInterface.addCallback("playFrames", playFrames);
ExternalInterface.addCallback("streamStatus", streamStatus);
ExternalInterface.addCallback("playerStatus", playerStatus);
ExternalInterface.addCallback("speakerVolume", speakerVolume);
ExternalInterface.addCallback("muteSpeaker", muteSpeaker);
ExternalInterface.addCallback("unmuteSpeaker", unmuteSpeaker);
ExternalInterface.addCallback("microphoneVolume", microphoneVolume);
ExternalInterface.addCallback("muteMicrophone", muteMicrophone);
ExternalInterface.addCallback("unmuteMicrophone", unmuteMicrophone);
ExternalInterface.addCallback("setConfig", setConfig);
/* Audio Transmission API */
ExternalInterface.addCallback("startAudioTransmit", startAudioTransmit);
ExternalInterface.addCallback("stopAudioTransmit", stopAudioTransmit);
}
public function fullscreen(event:MouseEvent):void {
if (config.allowFullscreen) {
this.stage.displayState = (StageDisplayState.NORMAL === stage.displayState) ?
StageDisplayState.FULL_SCREEN : StageDisplayState.NORMAL;
}
}
public function videoResize():void {
if (!this.client) {
return;
}
var stagewidth:uint = (StageDisplayState.NORMAL === stage.displayState) ?
stage.stageWidth : stage.fullScreenWidth;
var stageheight:uint = (StageDisplayState.NORMAL === stage.displayState) ?
stage.stageHeight : stage.fullScreenHeight;
var video:DisplayObject = this.client.getDisplayObject();
var scale:Number = ((stagewidth / meta.width) > (stageheight / meta.height)) ?
(stageheight / meta.height) : (stagewidth / meta.width);
video.width = meta.width;
video.height = meta.height;
if ((scale < 1.0) || (scale > 1.0 && true === config.scaleUp)) {
Logger.log('scaling video, scale:' + scale.toFixed(2) + ' (aspect ratio: ' + (video.width / video.height).toFixed(2) + ')');
video.width = meta.width * scale;
video.height = meta.height * scale;
}
video.x = (stagewidth - video.width) / 2;
video.y = (stageheight - video.height) / 2;
}
public function setConfig(iconfig:Object):void {
if (iconfig.buffer !== undefined) {
if (this.client) {
if (false === this.client.setBuffer(config.buffer)) {
ErrorManager.dispatchError(830);
} else {
config.buffer = iconfig.buffer;
}
} else {
config.buffer = iconfig.buffer;
}
}
if (iconfig.frameByFrame !== undefined) {
if (this.client) {
if (false === this.client.setFrameByFrame(iconfig.frameByFrame)) {
ErrorManager.dispatchError(832);
} else {
config.frameByFrame = iconfig.frameByFrame;
}
} else {
config.frameByFrame = iconfig.frameByFrame;
}
}
if (iconfig.scaleUp !== undefined) {
var scaleUpChanged:Boolean = (config.scaleUp !== iconfig.scaleUp);
config.scaleUp = iconfig.scaleUp;
if (scaleUpChanged && this.client)
this.videoResize();
}
if (iconfig.allowFullscreen !== undefined) {
config.allowFullscreen = iconfig.allowFullscreen;
if (!config.allowFullscreen)
this.stage.displayState = StageDisplayState.NORMAL;
}
if (iconfig.debugLogger !== undefined) {
config.debugLogger = iconfig.debugLogger;
}
if (iconfig.connectionTimeout !== undefined) {
config.connectionTimeout = iconfig.connectionTimeout;
}
}
public function play(param:* = null, options:Object = null):void {
this.streamHasAudio = false;
this.streamHasVideo = false;
if (param is String) {
urlParsed = url.parse(String(param));
} else {
urlParsed = url.parse(param.url);
urlParsed.connect = param.url;
urlParsed.streamName = param.streamName;
}
this.newPlaylistItem = true;
this.startOptions = options;
if (client) {
/* Stop the client, and 'onStopped' will start the new stream. */
client.stop();
return;
}
start();
}
private function start():void {
switch (urlParsed.protocol) {
case 'rtsph':
/* RTSP over HTTP */
client = new RTSPClient(urlParsed, new RTSPoverHTTPHandle(urlParsed));
break;
case 'rtsp':
/* RTSP over TCP */
client = new RTSPClient(urlParsed, new RTSPoverTCPHandle(urlParsed));
break;
case 'http':
case 'https':
/* Progressive download over HTTP */
client = new HTTPClient(urlParsed);
break;
case 'httpm':
/* Progressive mjpg download over HTTP (x-mixed-replace) */
client = new MJPEGClient(urlParsed);
break;
case 'rtmp':
case 'rtmps':
case 'rtmpt':
/* RTMP */
client = new RTMPClient(urlParsed);
break;
default:
ErrorManager.dispatchError(811, [urlParsed.protocol])
return;
}
addChild(this.client.getDisplayObject());
client.addEventListener(ClientEvent.STOPPED, onStopped);
client.addEventListener(ClientEvent.START_PLAY, onStartPlay);
client.addEventListener(ClientEvent.PAUSED, onPaused);
client.addEventListener(ClientEvent.ENDED, onEnded);
client.addEventListener(ClientEvent.META, onMeta);
client.addEventListener(ClientEvent.FRAME, onFrame);
client.start(this.startOptions);
this.newPlaylistItem = false;
}
public function seek(position:String):void {
if (!client || !client.seek(Number(position))) {
ErrorManager.dispatchError(828);
}
}
public function playFrames(timestamp:Number):void {
client && client.playFrames(timestamp);
}
public function pause():void {
try {
client.pause()
} catch (err:Error) {
ErrorManager.dispatchError(808);
}
}
public function resume():void {
if (!client || !client.resume()) {
ErrorManager.dispatchError(809);
}
}
public function stop():void {
if (!client || !client.stop()) {
ErrorManager.dispatchError(810);
return;
}
this.currentState = "stopped";
this.streamHasAudio = false;
this.streamHasVideo = false;
}
public function onMeta(event:ClientEvent):void {
this.meta = event.data;
this.videoResize();
}
public function streamStatus():Object {
if (this.currentState === 'playing') {
/* This causes a crash in some situations */
//this.streamHasAudio = (this.streamHasAudio || this.client.hasAudio());
this.streamHasVideo = (this.streamHasVideo || this.client.hasVideo());
}
var status:Object = {
'fps': (this.client) ? this.client.currentFPS() : null,
'resolution': (this.client) ? { width: meta.width, height: meta.height } : null,
'playbackSpeed': (this.client) ? 1.0 : null,
'protocol': (this.urlParsed) ? this.urlParsed.protocol : null,
'audio': (this.client) ? this.streamHasAudio : null,
'video': (this.client) ? this.streamHasVideo : null,
'state': this.currentState,
'streamURL': (this.urlParsed) ? this.urlParsed.full : null,
'duration': meta.duration ? meta.duration : null,
'currentTime': (this.client) ? this.client.getCurrentTime() : -1,
'bufferedTime': (this.client) ? this.client.bufferedTime() : -1
};
return status;
}
public function playerStatus():Object {
var mic:Microphone = Microphone.getMicrophone();
var status:Object = {
'version': StringUtil.trim(new Version().toString()),
'microphoneVolume': audioTransmit.microphoneVolume,
'speakerVolume': this.savedSpeakerVolume,
'microphoneMuted': (mic.gain === 0),
'speakerMuted': (flash.media.SoundMixer.soundTransform.volume === 0),
'fullscreen': (StageDisplayState.FULL_SCREEN === stage.displayState),
'buffer': (client === null) ? 0 : Player.config.buffer
};
return status;
}
public function speakerVolume(volume:Number):void {
this.savedSpeakerVolume = volume;
var transform:SoundTransform = new SoundTransform(volume / 100.0);
flash.media.SoundMixer.soundTransform = transform;
}
public function muteSpeaker():void {
var transform:SoundTransform = new SoundTransform(0);
flash.media.SoundMixer.soundTransform = transform;
}
public function unmuteSpeaker():void {
if (flash.media.SoundMixer.soundTransform.volume !== 0)
return;
var transform:SoundTransform = new SoundTransform(this.savedSpeakerVolume / 100.0);
flash.media.SoundMixer.soundTransform = transform;
}
public function microphoneVolume(volume:Number):void {
audioTransmit.microphoneVolume = volume;
}
public function muteMicrophone():void {
audioTransmit.muteMicrophone();
}
public function unmuteMicrophone():void {
audioTransmit.unmuteMicrophone();
}
public function startAudioTransmit(url:String = null, type:String = 'axis'):void {
if (type === 'axis') {
audioTransmit.start(url);
} else {
ErrorManager.dispatchError(812);
}
}
public function stopAudioTransmit():void {
audioTransmit.stop();
}
public function allowFullscreen(state:Boolean):void {
this.fullscreenAllowed = state;
if (!state)
this.stage.displayState = StageDisplayState.NORMAL;
}
private function onStageAdded(e:Event):void {
Player.locomoteID = LoaderInfo(this.root.loaderInfo).parameters.locomoteID.toString();
ExternalInterface.call("LocomoteMap['" + Player.locomoteID + "'].__swfReady");
}
private function onStartPlay(event:ClientEvent):void {
this.currentState = "playing";
this.callAPI(EVENT_STREAM_STARTED);
}
private function onEnded(event:ClientEvent):void {
this.currentState = "ended";
this.callAPI(EVENT_STREAM_ENDED, event.data);
}
private function onPaused(event:ClientEvent):void {
this.currentState = "paused";
this.callAPI(EVENT_STREAM_PAUSED, event.data);
}
private function onStopped(event:ClientEvent):void {
this.removeChild(this.client.getDisplayObject());
this.client.removeEventListener(ClientEvent.STOPPED, onStopped);
this.client.removeEventListener(ClientEvent.START_PLAY, onStartPlay);
this.client.removeEventListener(ClientEvent.PAUSED, onPaused);
this.client.removeEventListener(ClientEvent.ENDED, onEnded);
this.client.removeEventListener(ClientEvent.META, onMeta);
this.client.removeEventListener(ClientEvent.FRAME, onFrame);
this.client = null;
this.callAPI(EVENT_STREAM_STOPPED, event.data);
/* If a new `play` has been queued, fire it */
if (this.newPlaylistItem) {
start();
}
}
private function onFrame(event:ClientEvent):void {
this.callAPI(EVENT_FRAME_READY, { timestamp: event.data });
}
private function callAPI(eventName:String, data:Object = null):void {
var functionName:String = "LocomoteMap['" + Player.locomoteID + "'].__playerEvent";
if (data) {
ExternalInterface.call(functionName, eventName, data);
} else {
ExternalInterface.call(functionName, eventName);
}
}
}
}
|
Handle multiple stop events from client.
|
Handle multiple stop events from client.
Handled by removing eventListeners, i.e. not handled.
|
ActionScript
|
bsd-3-clause
|
AxisCommunications/locomote-video-player,gaetancollaud/locomote-video-player
|
3e945196e2217379573042af68e11ef9896852bf
|
src/Testing/Test.as
|
src/Testing/Test.as
|
package Testing {
import flash.utils.Dictionary;
import Modules.Module;
import org.flixel.FlxG;
import Testing.Abstractions.InstructionAbstraction;
import Testing.Abstractions.SaveAbstraction;
import Testing.Abstractions.SetAbstraction;
import Testing.Instructions.Instruction;
import Values.BooleanValue;
import Testing.Types.InstructionType;
import Values.Value;
/**
* ...
* @author Nicholas "PleasingFungus" Feinberg
*/
public class Test {
public var seed:Number;
public var memAddressToSet:int;
public var memValueToSet:int
public var instructions:Vector.<Instruction>;
public function Test(seed:Number = NaN) {
if (isNaN(seed))
seed = FlxG.random();
FlxG.globalSeed = this.seed = seed;
memAddressToSet = C.randomRange(0, U.MAX_INT - U.MIN_INT);
memValueToSet = C.randomRange(U.MIN_INT, U.MAX_INT);
var values:Vector.<int> = C.buildIntVector(memAddressToSet, memValueToSet);
var abstractions:Vector.<InstructionAbstraction> = new Vector.<InstructionAbstraction>;
abstractions.push(new SaveAbstraction( -1, memValueToSet, memAddressToSet));
var minInstructions:int = 10;
for (var depth:int = 0; abstractions.length + values.length < minInstructions; depth++)
genAbstractions(abstractions, values, depth);
genInitializationAbstractions(abstractions, values, depth);
var orderedAbstractions:Vector.<InstructionAbstraction> = new Vector.<InstructionAbstraction>;
while (abstractions.length)
orderedAbstractions.push(abstractions.pop());
log("\n\nSEED: " + seed);
log("PROGRAM START");
for (var i:int = 0; i < orderedAbstractions.length; i++)
log(i + ": " + orderedAbstractions[i]);
log("PROGRAM END\n\n");
var virtualRegisters:Vector.<int> = new Vector.<int>;
instructions = new Vector.<Instruction>;
for (var line:int = 0; line < orderedAbstractions.length; line++) {
var abstraction:InstructionAbstraction = orderedAbstractions[line];
log(line, abstraction);
instructions.push(genInstruction(line, abstraction, virtualRegisters, orderedAbstractions));
log("Virtual registers: " + virtualRegisters);
}
instructions = postProcess(instructions);
//TODO: scramble registers
log("\n\nSEED: " + seed);
log("PROGRAM START");
for (i = 0; i < instructions.length; i++)
log(i + ": " + instructions[i]);
log("PROGRAM END\n\n");
var regCount:int = 8;
var memory:Dictionary = new Dictionary;
var registers:Dictionary = new Dictionary;
executeInEnvironment(memory, registers, instructions);
var mem:String = "Memory: ";
for (var memAddrStr:String in memory)
mem += memAddrStr + ":" + memory[memAddrStr] + ", ";
log(mem);
if (memory[memAddressToSet+""] != memValueToSet)
throw new Error("Memory at " + memAddressToSet + " is " + memory[memAddressToSet+""] + " at end of run, not " + memValueToSet + " as expected!");
else
log("Mem test success");
}
protected function postProcess(instructions:Vector.<Instruction>):Vector.<Instruction> {
return instructions;
}
protected function executeInEnvironment(memory:Dictionary, registers:Dictionary, instructions:Vector.<Instruction>):void {
for (var line:int = 0; line < instructions.length; line ++) {
var instruction:Instruction = instructions[line];
var jump:int = instruction.execute(memory, registers);
if (jump != C.INT_NULL)
line = jump;
}
}
protected function genAbstractions(abstractions:Vector.<InstructionAbstraction>, values:Vector.<int>, depth:int):void {
log("Instructions: " + abstractions);
log("Values: " + values);
while (values.length)
abstractions.push(genAbstraction(values.pop(), depth, getArgs(abstractions, depth)));
for each (var abstraction:InstructionAbstraction in abstractions)
if (abstraction.depth == depth)
for each (var arg:int in abstraction.args)
if (values.indexOf(arg) == -1)
values.push(arg);
}
protected function genAbstraction(value:int, depth:int, args:Vector.<int>):InstructionAbstraction {
var type:InstructionType;
var abstraction:InstructionAbstraction;
var arg:int;
log("Attempting to produce " +value);
log("Args: " + args);
var fullReuseInstrs:Vector.<InstructionType> = new Vector.<InstructionType>;
for each (type in InstructionType.TYPES)
if (type.can_produce_with(value, args))
fullReuseInstrs.push(type);
if (fullReuseInstrs.length) {
log("Full re-use instrs: " + fullReuseInstrs);
abstraction = randomTypeChoice(fullReuseInstrs).produce_with(value, depth, args);
log("Added " + abstraction + " with full re-use");
return abstraction;
}
log("No full re-use instrs")
var partialReuseInstrs:Vector.<InstructionType> = new Vector.<InstructionType>;
for each (type in InstructionType.TYPES)
if (type.can_produce_with_one_of(value, args))
partialReuseInstrs.push(type);
if (partialReuseInstrs.length) {
log("Partial re-use instrs: " + partialReuseInstrs);
type = randomTypeChoice(partialReuseInstrs);
var validArgs:Vector.<int> = new Vector.<int>;
for each (arg in args)
if (type.can_produce_with_one(value, arg))
validArgs.push(arg);
log("Valid args for " + type.name + ": " + validArgs);
arg = C.randomIntChoice(validArgs);
abstraction = type.produce_with_one(value, depth, arg);
log("Added " + abstraction + ", re-using " + arg);
return abstraction;
}
log("No partial re-use instrs")
type = C.randomChoice(InstructionType.TYPES);
abstraction = type.produce_unrestrained(value, depth);
log("Added " + abstraction);
return abstraction;
}
protected function genInitializationAbstractions(abstractions:Vector.<InstructionAbstraction>, values:Vector.<int>, depth:int):void {
for each (var value:int in values)
abstractions.push(new SetAbstraction(depth, value));
}
protected function genInstruction(line:int, abstraction:InstructionAbstraction, virtualRegisters:Vector.<int>,
abstractions:Vector.<InstructionAbstraction>):Instruction {
var registers:Vector.<int> = new Vector.<int>;
for each (var arg:int in abstraction.args)
registers.push(virtualRegisters.indexOf(arg));
if (abstraction.value != C.INT_NULL) {
var destination:int = findRegisterFor(abstraction.depth, line, abstraction.value, virtualRegisters, abstractions);
var noop:Boolean = destination < virtualRegisters.length && virtualRegisters[destination] == abstraction.value;
registers.splice(0, 0, destination);
if (destination < virtualRegisters.length)
virtualRegisters[destination] = abstraction.value;
else
virtualRegisters.push(abstraction.value);
}
var instructionClass:Class = Instruction.mapByType(abstraction.type);
return new instructionClass(registers, abstraction, noop);
}
protected function findRegisterFor(depth:int, line:int, value:int,
virtualRegisters:Vector.<int>,
abstractions:Vector.<InstructionAbstraction>):int {
if (virtualRegisters.indexOf(value) != -1) {
log("Storing " + value + " is a no-op");
return virtualRegisters.indexOf(value);
}
var abstraction:InstructionAbstraction;
var successors:Vector.<InstructionAbstraction> = abstractions.slice(line + 1);
var predependents:Vector.<InstructionAbstraction> = abstractions.slice(0, line + 1);
var blockingInstructions:Vector.<InstructionAbstraction> = new Vector.<InstructionAbstraction>;
for each (abstraction in successors)
if (abstraction.depth <= depth + 1)
blockingInstructions.push(abstraction);
var freeRegValues:Vector.<int> = new Vector.<int>;
for each (var rv:int in virtualRegisters) {
var blocked:Boolean = false;
for each (abstraction in blockingInstructions)
if (abstraction.args.indexOf(rv) != -1) {
blocked = true;
break;
}
if (!blocked)
freeRegValues.push(rv);
}
//var allArgs:Vector.<int> = getArgs(predependents, C.INT_NULL);
//free_reg_values.sort(key=lambda rv: -all_args.index(rv)) #TODO
log("Free register values: " + freeRegValues);
if (freeRegValues.length) {
log("Storing " + value + " in existing slot " + virtualRegisters.indexOf(freeRegValues[0])+" currently holding "+freeRegValues[0]);
return virtualRegisters.indexOf(freeRegValues[0]);
}
log("Storing " + value + " in previously unallocated register " + virtualRegisters.length);
return virtualRegisters.length;
}
protected function getArgs(abstractions:Vector.<InstructionAbstraction>, depth:int):Vector.<int> {
var args:Vector.<int> = new Vector.<int>;
for each (var abstraction:InstructionAbstraction in abstractions)
if (abstraction.depth == depth || depth == C.INT_NULL)
for each (var arg:int in abstraction.args)
if (args.indexOf(arg) == -1)
args.push(arg);
return args;
}
protected function randomTypeChoice(options:Vector.<InstructionType>):InstructionType {
return options[int(FlxG.random() * options.length)];
}
protected function log(...args):void {
if (U.DEBUG && U.DEBUG_PRINT_TESTS)
C.log(args);
}
public function initialMemory():Vector.<Value> {
var mem:Vector.<Value> = new Vector.<Value>;
for each (var instr:Instruction in instructions)
mem.push(instr.toMemValue());
return mem;
}
public function validate(_:Module):Boolean {
if (U.state.memory[memAddressToSet].toNumber() == memValueToSet)
return true;
return false;
}
}
}
|
package Testing {
import flash.utils.Dictionary;
import Modules.Module;
import org.flixel.FlxG;
import Testing.Abstractions.InstructionAbstraction;
import Testing.Abstractions.SaveAbstraction;
import Testing.Abstractions.SetAbstraction;
import Testing.Instructions.Instruction;
import Values.BooleanValue;
import Testing.Types.InstructionType;
import Values.Value;
/**
* ...
* @author Nicholas "PleasingFungus" Feinberg
*/
public class Test {
public var seed:Number;
public var memAddressToSet:int;
public var memValueToSet:int
public var instructions:Vector.<Instruction>;
public function Test(seed:Number = NaN) {
if (isNaN(seed))
seed = FlxG.random();
FlxG.globalSeed = this.seed = seed;
memAddressToSet = C.randomRange(U.MAX_INT, U.MAX_INT - U.MIN_INT);
memValueToSet = C.randomRange(U.MIN_INT, U.MAX_INT+1);
var values:Vector.<int> = C.buildIntVector(memAddressToSet, memValueToSet);
var abstractions:Vector.<InstructionAbstraction> = new Vector.<InstructionAbstraction>;
abstractions.push(new SaveAbstraction( -1, memValueToSet, memAddressToSet));
var minInstructions:int = 10;
for (var depth:int = 0; abstractions.length + values.length < minInstructions; depth++)
genAbstractions(abstractions, values, depth);
genInitializationAbstractions(abstractions, values, depth);
var orderedAbstractions:Vector.<InstructionAbstraction> = new Vector.<InstructionAbstraction>;
while (abstractions.length)
orderedAbstractions.push(abstractions.pop());
log("\n\nSEED: " + seed);
log("PROGRAM START");
for (var i:int = 0; i < orderedAbstractions.length; i++)
log(i + ": " + orderedAbstractions[i]);
log("PROGRAM END\n\n");
var virtualRegisters:Vector.<int> = new Vector.<int>;
instructions = new Vector.<Instruction>;
for (var line:int = 0; line < orderedAbstractions.length; line++) {
var abstraction:InstructionAbstraction = orderedAbstractions[line];
log(line, abstraction);
instructions.push(genInstruction(line, abstraction, virtualRegisters, orderedAbstractions));
log("Virtual registers: " + virtualRegisters);
}
instructions = postProcess(instructions);
//TODO: scramble registers
log("\n\nSEED: " + seed);
log("PROGRAM START");
for (i = 0; i < instructions.length; i++)
log(i + ": " + instructions[i]);
log("PROGRAM END\n\n");
var regCount:int = 8;
var memory:Dictionary = new Dictionary;
var registers:Dictionary = new Dictionary;
executeInEnvironment(memory, registers, instructions);
var mem:String = "Memory: ";
for (var memAddrStr:String in memory)
mem += memAddrStr + ":" + memory[memAddrStr] + ", ";
log(mem);
if (memory[memAddressToSet+""] != memValueToSet)
throw new Error("Memory at " + memAddressToSet + " is " + memory[memAddressToSet+""] + " at end of run, not " + memValueToSet + " as expected!");
else
log("Mem test success");
}
protected function postProcess(instructions:Vector.<Instruction>):Vector.<Instruction> {
return instructions;
}
protected function executeInEnvironment(memory:Dictionary, registers:Dictionary, instructions:Vector.<Instruction>):void {
for (var line:int = 0; line < instructions.length; line ++) {
var instruction:Instruction = instructions[line];
var jump:int = instruction.execute(memory, registers);
if (jump != C.INT_NULL)
line = jump;
}
}
protected function genAbstractions(abstractions:Vector.<InstructionAbstraction>, values:Vector.<int>, depth:int):void {
log("Instructions: " + abstractions);
log("Values: " + values);
while (values.length)
abstractions.push(genAbstraction(values.pop(), depth, getArgs(abstractions, depth)));
for each (var abstraction:InstructionAbstraction in abstractions)
if (abstraction.depth == depth)
for each (var arg:int in abstraction.args)
if (values.indexOf(arg) == -1)
values.push(arg);
}
protected function genAbstraction(value:int, depth:int, args:Vector.<int>):InstructionAbstraction {
var type:InstructionType;
var abstraction:InstructionAbstraction;
var arg:int;
log("Attempting to produce " +value);
log("Args: " + args);
var fullReuseInstrs:Vector.<InstructionType> = new Vector.<InstructionType>;
for each (type in InstructionType.TYPES)
if (type.can_produce_with(value, args))
fullReuseInstrs.push(type);
if (fullReuseInstrs.length) {
log("Full re-use instrs: " + fullReuseInstrs);
abstraction = randomTypeChoice(fullReuseInstrs).produce_with(value, depth, args);
log("Added " + abstraction + " with full re-use");
return abstraction;
}
log("No full re-use instrs")
var partialReuseInstrs:Vector.<InstructionType> = new Vector.<InstructionType>;
for each (type in InstructionType.TYPES)
if (type.can_produce_with_one_of(value, args))
partialReuseInstrs.push(type);
if (partialReuseInstrs.length) {
log("Partial re-use instrs: " + partialReuseInstrs);
type = randomTypeChoice(partialReuseInstrs);
var validArgs:Vector.<int> = new Vector.<int>;
for each (arg in args)
if (type.can_produce_with_one(value, arg))
validArgs.push(arg);
log("Valid args for " + type.name + ": " + validArgs);
arg = C.randomIntChoice(validArgs);
abstraction = type.produce_with_one(value, depth, arg);
log("Added " + abstraction + ", re-using " + arg);
return abstraction;
}
log("No partial re-use instrs")
type = C.randomChoice(InstructionType.TYPES);
abstraction = type.produce_unrestrained(value, depth);
log("Added " + abstraction);
return abstraction;
}
protected function genInitializationAbstractions(abstractions:Vector.<InstructionAbstraction>, values:Vector.<int>, depth:int):void {
for each (var value:int in values)
abstractions.push(new SetAbstraction(depth, value));
}
protected function genInstruction(line:int, abstraction:InstructionAbstraction, virtualRegisters:Vector.<int>,
abstractions:Vector.<InstructionAbstraction>):Instruction {
var registers:Vector.<int> = new Vector.<int>;
for each (var arg:int in abstraction.args)
registers.push(virtualRegisters.indexOf(arg));
if (abstraction.value != C.INT_NULL) {
var destination:int = findRegisterFor(abstraction.depth, line, abstraction.value, virtualRegisters, abstractions);
var noop:Boolean = destination < virtualRegisters.length && virtualRegisters[destination] == abstraction.value;
registers.splice(0, 0, destination);
if (destination < virtualRegisters.length)
virtualRegisters[destination] = abstraction.value;
else
virtualRegisters.push(abstraction.value);
}
var instructionClass:Class = Instruction.mapByType(abstraction.type);
return new instructionClass(registers, abstraction, noop);
}
protected function findRegisterFor(depth:int, line:int, value:int,
virtualRegisters:Vector.<int>,
abstractions:Vector.<InstructionAbstraction>):int {
if (virtualRegisters.indexOf(value) != -1) {
log("Storing " + value + " is a no-op");
return virtualRegisters.indexOf(value);
}
var abstraction:InstructionAbstraction;
var successors:Vector.<InstructionAbstraction> = abstractions.slice(line + 1);
var predependents:Vector.<InstructionAbstraction> = abstractions.slice(0, line + 1);
var blockingInstructions:Vector.<InstructionAbstraction> = new Vector.<InstructionAbstraction>;
for each (abstraction in successors)
if (abstraction.depth <= depth + 1)
blockingInstructions.push(abstraction);
var freeRegValues:Vector.<int> = new Vector.<int>;
for each (var rv:int in virtualRegisters) {
var blocked:Boolean = false;
for each (abstraction in blockingInstructions)
if (abstraction.args.indexOf(rv) != -1) {
blocked = true;
break;
}
if (!blocked)
freeRegValues.push(rv);
}
//var allArgs:Vector.<int> = getArgs(predependents, C.INT_NULL);
//free_reg_values.sort(key=lambda rv: -all_args.index(rv)) #TODO
log("Free register values: " + freeRegValues);
if (freeRegValues.length) {
log("Storing " + value + " in existing slot " + virtualRegisters.indexOf(freeRegValues[0])+" currently holding "+freeRegValues[0]);
return virtualRegisters.indexOf(freeRegValues[0]);
}
log("Storing " + value + " in previously unallocated register " + virtualRegisters.length);
return virtualRegisters.length;
}
protected function getArgs(abstractions:Vector.<InstructionAbstraction>, depth:int):Vector.<int> {
var args:Vector.<int> = new Vector.<int>;
for each (var abstraction:InstructionAbstraction in abstractions)
if (abstraction.depth == depth || depth == C.INT_NULL)
for each (var arg:int in abstraction.args)
if (args.indexOf(arg) == -1)
args.push(arg);
return args;
}
protected function randomTypeChoice(options:Vector.<InstructionType>):InstructionType {
return options[int(FlxG.random() * options.length)];
}
protected function log(...args):void {
if (U.DEBUG && U.DEBUG_PRINT_TESTS)
C.log(args);
}
public function initialMemory():Vector.<Value> {
var mem:Vector.<Value> = new Vector.<Value>;
for each (var instr:Instruction in instructions)
mem.push(instr.toMemValue());
return mem;
}
public function validate(_:Module):Boolean {
if (U.state.memory[memAddressToSet].toNumber() == memValueToSet)
return true;
return false;
}
}
}
|
Tweak values for memset range for tests
|
Tweak values for memset range for tests
|
ActionScript
|
mit
|
PleasingFungus/mde2,PleasingFungus/mde2
|
9a6196182dfa14d736e9baa6daf63092e833dd2b
|
src/aerys/minko/scene/node/Scene.as
|
src/aerys/minko/scene/node/Scene.as
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.Effect;
import aerys.minko.render.Viewport;
import aerys.minko.scene.controller.scene.RenderingController;
import aerys.minko.scene.node.camera.AbstractCamera;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.loader.AssetsLibrary;
import flash.display.BitmapData;
import flash.utils.Dictionary;
import flash.utils.getTimer;
/**
* Scene objects are the root of any 3D scene.
*
* @author Jean-Marc Le Roux
*
*/
public final class Scene extends Group
{
use namespace minko_scene;
minko_scene var _camera : AbstractCamera;
private var _renderingCtrl : RenderingController;
private var _properties : DataProvider;
private var _bindings : DataBindings;
private var _numTriangles : uint;
private var _enterFrame : Signal;
private var _renderingBegin : Signal;
private var _renderingEnd : Signal;
private var _exitFrame : Signal;
private var _assets : AssetsLibrary;
public function get assets() : AssetsLibrary
{
return _assets;
}
public function get activeCamera() : AbstractCamera
{
return _camera;
}
public function get numPasses() : uint
{
return _renderingCtrl.numPasses;
}
public function get numEnabledPasses() : uint
{
return _renderingCtrl.numEnabledPasses;
}
public function get numTriangles() : uint
{
return _numTriangles;
}
public function get postProcessingEffect() : Effect
{
return _renderingCtrl.postProcessingEffect;
}
public function set postProcessingEffect(value : Effect) : void
{
_renderingCtrl.postProcessingEffect = value;
}
public function get postProcessingProperties() : DataProvider
{
return _renderingCtrl.postProcessingProperties;
}
public function get properties() : DataProvider
{
return _properties;
}
public function set properties(value : DataProvider) : void
{
if (_properties != value)
{
if (_properties)
_bindings.removeProvider(_properties);
_properties = value;
if (value)
_bindings.addProvider(value);
}
}
public function get bindings() : DataBindings
{
return _bindings;
}
/**
* The signal executed when the viewport is about to start rendering a frame.
* Callback functions for this signal should accept the following arguments:
* <ul>
* <li>viewport : Viewport, the viewport who starts rendering the frame</li>
* </ul>
* @return
*
*/
public function get enterFrame() : Signal
{
return _enterFrame;
}
/**
* The signal executed when the viewport is done rendering a frame.
* Callback functions for this signal should accept the following arguments:
* <ul>
* <li>viewport : Viewport, the viewport who just finished rendering the frame</li>
* </ul>
* @return
*
*/
public function get exitFrame() : Signal
{
return _exitFrame;
}
public function get renderingBegin() : Signal
{
return _renderingBegin;
}
public function get renderingEnd() : Signal
{
return _renderingEnd;
}
public function Scene(...children)
{
super(children);
}
override protected function initialize() : void
{
_bindings = new DataBindings(this);
_assets = new AssetsLibrary();
this.properties = new DataProvider(DataProviderUsage.EXCLUSIVE);
super.initialize();
}
override protected function initializeSignals() : void
{
super.initializeSignals();
_enterFrame = new Signal('Scene.enterFrame');
_renderingBegin = new Signal('Scene.renderingBegin');
_renderingEnd = new Signal('Scene.renderingEnd');
_exitFrame = new Signal('Scene.exitFrame');
}
override protected function initializeSignalHandlers() : void
{
super.initializeSignalHandlers();
added.add(addedHandler);
}
override protected function initializeContollers() : void
{
_renderingCtrl = new RenderingController();
addController(_renderingCtrl);
super.initializeContollers();
}
public function render(viewport : Viewport, destination : BitmapData = null) : void
{
_enterFrame.execute(this, viewport, destination, getTimer());
if (viewport.ready && viewport.visible)
{
_renderingBegin.execute(this, viewport, destination, getTimer());
_numTriangles = _renderingCtrl.render(viewport, destination);
_renderingEnd.execute(this, viewport, destination, getTimer());
}
_exitFrame.execute(this, viewport, destination, getTimer());
}
private function addedHandler(child : ISceneNode, parent : Group) : void
{
throw new Error();
}
}
}
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.Effect;
import aerys.minko.render.Viewport;
import aerys.minko.scene.controller.scene.RenderingController;
import aerys.minko.scene.node.camera.AbstractCamera;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.loader.AssetsLibrary;
import flash.display.BitmapData;
import flash.utils.Dictionary;
import flash.utils.getTimer;
/**
* Scene objects are the root of any 3D scene.
*
* @author Jean-Marc Le Roux
*
*/
public final class Scene extends Group
{
use namespace minko_scene;
minko_scene var _camera : AbstractCamera;
private var _renderingCtrl : RenderingController;
private var _properties : DataProvider;
private var _bindings : DataBindings;
private var _numTriangles : uint;
private var _enterFrame : Signal;
private var _renderingBegin : Signal;
private var _renderingEnd : Signal;
private var _exitFrame : Signal;
private var _assets : AssetsLibrary;
public function get assets() : AssetsLibrary
{
return _assets;
}
public function get activeCamera() : AbstractCamera
{
return _camera;
}
public function get numPasses() : uint
{
return _renderingCtrl.numPasses;
}
public function get numEnabledPasses() : uint
{
return _renderingCtrl.numEnabledPasses;
}
public function get numTriangles() : uint
{
return _numTriangles;
}
public function get postProcessingEffect() : Effect
{
return _renderingCtrl.postProcessingEffect;
}
public function set postProcessingEffect(value : Effect) : void
{
_renderingCtrl.postProcessingEffect = value;
}
public function get postProcessingProperties() : DataProvider
{
return _renderingCtrl.postProcessingProperties;
}
public function get properties() : DataProvider
{
return _properties;
}
public function set properties(value : DataProvider) : void
{
if (_properties != value)
{
if (_properties)
_bindings.removeProvider(_properties);
_properties = value;
if (value)
_bindings.addProvider(value);
}
}
public function get bindings() : DataBindings
{
return _bindings;
}
/**
* The signal executed when the viewport is about to start rendering a frame.
* Callback functions for this signal should accept the following arguments:
* <ul>
* <li>viewport : Viewport, the viewport who starts rendering the frame</li>
* </ul>
* @return
*
*/
public function get enterFrame() : Signal
{
return _enterFrame;
}
/**
* The signal executed when the viewport is done rendering a frame.
* Callback functions for this signal should accept the following arguments:
* <ul>
* <li>viewport : Viewport, the viewport who just finished rendering the frame</li>
* </ul>
* @return
*
*/
public function get exitFrame() : Signal
{
return _exitFrame;
}
public function get renderingBegin() : Signal
{
return _renderingBegin;
}
public function get renderingEnd() : Signal
{
return _renderingEnd;
}
public function Scene(...children)
{
super(children);
}
override protected function initialize() : void
{
_bindings = new DataBindings(this);
_assets = new AssetsLibrary();
this.properties = new DataProvider(DataProviderUsage.EXCLUSIVE);
super.initialize();
}
override protected function initializeSignals() : void
{
super.initializeSignals();
_enterFrame = new Signal('Scene.enterFrame');
_renderingBegin = new Signal('Scene.renderingBegin');
_renderingEnd = new Signal('Scene.renderingEnd');
_exitFrame = new Signal('Scene.exitFrame');
}
override protected function initializeSignalHandlers() : void
{
super.initializeSignalHandlers();
added.add(addedHandler);
}
override protected function initializeContollers() : void
{
_renderingCtrl = new RenderingController();
addController(_renderingCtrl);
super.initializeContollers();
}
public function render(viewport : Viewport, destination : BitmapData = null) : void
{
_enterFrame.execute(this, viewport, destination, getTimer());
if (viewport.ready && viewport.visible)
{
_renderingBegin.execute(this, viewport, destination, getTimer());
_numTriangles = _renderingCtrl.render(viewport, destination);
_renderingEnd.execute(this, viewport, destination, getTimer());
}
_exitFrame.execute(this, viewport, destination, getTimer());
}
private function addedHandler(child : ISceneNode, parent : Group) : void
{
throw new Error();
}
}
}
|
fix coding style
|
fix coding style
|
ActionScript
|
mit
|
aerys/minko-as3
|
7633f91008aabaa560543a44e9ed75c85eefe5bc
|
src/aerys/minko/type/animation/timeline/MatrixTimeline.as
|
src/aerys/minko/type/animation/timeline/MatrixTimeline.as
|
package aerys.minko.type.animation.timeline
{
import aerys.minko.ns.minko_animation;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.type.math.Matrix4x4;
public class MatrixTimeline extends AbstractTimeline
{
use namespace minko_animation;
private var _timeTable : Vector.<uint>
private var _values : Vector.<Matrix4x4>;
private var _interpolate : Boolean;
private var _interpolateScale : Boolean;
private var _interpolateW : Boolean;
private var _timeTableLength : uint;
minko_animation function get timeTable() : Vector.<uint>
{
return _timeTable;
}
minko_animation function get matrices() : Vector.<Matrix4x4>
{
return _values;
}
public function MatrixTimeline(propertyPath : String,
timeTable : Vector.<uint>,
matrices : Vector.<Matrix4x4>,
interpolate : Boolean = false,
interpolateScale : Boolean = false,
interpolateW : Boolean = false)
{
super(propertyPath, timeTable[uint(timeTable.length - 1)]);
_timeTableLength = timeTable.length;
_timeTable = timeTable;
_values = matrices;
_interpolate = interpolate;
_interpolateScale = interpolateScale;
_interpolateW = interpolateW;
}
override public function updateAt(t : int, target : Object) : void
{
super.updateAt(t, target);
var time : uint = t < 0 ? duration + t : t;
var timeId : uint = getIndexForTime(time);
var timeCount : uint = _timeTableLength;
if (timeId >= timeCount)
timeId = timeCount - 1;
// change matrix value.
var out : Matrix4x4 = _currentTarget[_propertyName];
if (!out)
{
throw new Error(
"'" + _propertyName + "' could not be found in '" + _currentTarget + "'."
);
}
if (_interpolate)
{
var previousTime : Number = _timeTable[int(timeId - 1)];
var nextTime : Number = _timeTable[timeId];
out.interpolateBetween(
_values[int(timeId - 1)],
_values[timeId],
(time - previousTime) / (nextTime - previousTime),
_interpolateScale,
_interpolateW
);
}
else
{
if (timeId == 0)
out.copyFrom(_values[0]);
else
out.copyFrom(_values[uint(timeId - 1)]);
}
}
private function getIndexForTime(t : uint) : uint
{
// use a dichotomy to find the current frame in the time table.
var timeCount : uint = _timeTableLength;
var bottomTimeId : uint = 0;
var upperTimeId : uint = timeCount;
var timeId : uint;
while (upperTimeId - bottomTimeId > 1)
{
timeId = (bottomTimeId + upperTimeId) >> 1;
if (_timeTable[timeId] > t)
upperTimeId = timeId;
else
bottomTimeId = timeId;
}
return upperTimeId;
}
override public function clone() : ITimeline
{
return new MatrixTimeline(
propertyPath,
_timeTable.slice(),
_values.slice()
);
}
}
}
|
package aerys.minko.type.animation.timeline
{
import aerys.minko.ns.minko_animation;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.type.math.Matrix4x4;
public class MatrixTimeline extends AbstractTimeline
{
use namespace minko_animation;
private var _timeTable : Vector.<uint>
private var _values : Vector.<Matrix4x4>;
private var _interpolate : Boolean;
private var _interpolateScale : Boolean;
private var _interpolateW : Boolean;
private var _timeTableLength : uint;
minko_animation function get interpolate() : Boolean
{
return _interpolate;
}
minko_animation function get interpolateScale() : Boolean
{
return _interpolateScale;
}
minko_animation function get interpolateW() : Boolean
{
return _interpolateW;
}
minko_animation function get timeTable() : Vector.<uint>
{
return _timeTable;
}
minko_animation function get matrices() : Vector.<Matrix4x4>
{
return _values;
}
public function MatrixTimeline(propertyPath : String,
timeTable : Vector.<uint>,
matrices : Vector.<Matrix4x4>,
interpolate : Boolean = false,
interpolateScale : Boolean = false,
interpolateW : Boolean = false)
{
super(propertyPath, timeTable[uint(timeTable.length - 1)]);
_timeTableLength = timeTable.length;
_timeTable = timeTable;
_values = matrices;
_interpolate = interpolate;
_interpolateScale = interpolateScale;
_interpolateW = interpolateW;
}
override public function updateAt(t : int, target : Object) : void
{
super.updateAt(t, target);
var time : uint = t < 0 ? duration + t : t;
var timeId : uint = getIndexForTime(time);
var timeCount : uint = _timeTableLength;
if (timeId >= timeCount)
timeId = timeCount - 1;
// change matrix value.
var out : Matrix4x4 = _currentTarget[_propertyName];
if (!out)
{
throw new Error(
"'" + _propertyName + "' could not be found in '" + _currentTarget + "'."
);
}
if (_interpolate)
{
var previousTime : Number = _timeTable[int(timeId - 1)];
var nextTime : Number = _timeTable[timeId];
out.interpolateBetween(
_values[int(timeId - 1)],
_values[timeId],
(time - previousTime) / (nextTime - previousTime),
_interpolateScale,
_interpolateW
);
}
else
{
if (timeId == 0)
out.copyFrom(_values[0]);
else
out.copyFrom(_values[uint(timeId - 1)]);
}
}
private function getIndexForTime(t : uint) : uint
{
// use a dichotomy to find the current frame in the time table.
var timeCount : uint = _timeTableLength;
var bottomTimeId : uint = 0;
var upperTimeId : uint = timeCount;
var timeId : uint;
while (upperTimeId - bottomTimeId > 1)
{
timeId = (bottomTimeId + upperTimeId) >> 1;
if (_timeTable[timeId] > t)
upperTimeId = timeId;
else
bottomTimeId = timeId;
}
return upperTimeId;
}
override public function clone() : ITimeline
{
return new MatrixTimeline(
propertyPath,
_timeTable.slice(),
_values.slice(),
_interpolate,
_interpolateScale,
_interpolateW
);
}
}
}
|
Fix clone function
|
Fix clone function
|
ActionScript
|
mit
|
aerys/minko-as3
|
06cecdcb28980ff6146d25f6640417874af02cbd
|
src/goplayer/Player.as
|
src/goplayer/Player.as
|
package goplayer
{
import flash.utils.getTimer
public class Player implements
FlashNetConnectionListener,
FlashNetStreamListener,
PlayerQueueListener
{
private const DEFAULT_VOLUME : Number = .8
private const START_BUFFER : Duration = Duration.seconds(3)
private const SMALL_BUFFER : Duration = Duration.seconds(5)
private const LARGE_BUFFER : Duration = Duration.seconds(60)
private const SEEK_GRACE_TIME : Duration = Duration.seconds(2)
private const finishingListeners : Array = []
private var connection : FlashNetConnection
private var _movie : Movie
private var bitratePolicy : BitratePolicy
private var enableRTMP : Boolean
private var reporter : MovieEventReporter
private var queue : PlayerQueue
private var sharedVolumeVariable : SharedVariable
private var _started : Boolean = false
private var _finished : Boolean = false
private var triedStandardRTMP : Boolean = false
private var _usingRTMP : Boolean = false
private var measuredBandwidth : Bitrate = null
private var measuredLatency : Duration = null
private var stream : FlashNetStream = null
private var metadata : Object = null
private var _volume : Number = NaN
private var savedVolume : Number = 0
private var _paused : Boolean = false
private var _buffering : Boolean = false
private var seekStopwatch : Stopwatch = new Stopwatch
public function Player
(connection : FlashNetConnection,
movie : Movie,
bitratePolicy : BitratePolicy,
enableRTMP : Boolean,
reporter : MovieEventReporter,
queue : PlayerQueue,
sharedVolumeVariable : SharedVariable)
{
this.connection = connection
_movie = movie
this.bitratePolicy = bitratePolicy
this.enableRTMP = enableRTMP
this.reporter = reporter
this.queue = queue
this.sharedVolumeVariable = sharedVolumeVariable
connection.listener = this
queue.listener = this
reporter.reportMovieViewed(movie.id)
if (sharedVolumeVariable.hasValue)
volume = sharedVolumeVariable.value
else
volume = DEFAULT_VOLUME
}
public function get movie() : Movie
{ return _movie }
public function addFinishingListener
(value : PlayerFinishingListener) : void
{ finishingListeners.push(value) }
public function get started() : Boolean
{ return _started }
public function get running() : Boolean
{ return started && !finished }
public function get finished() : Boolean
{ return _finished }
// -----------------------------------------------------
public function start() : void
{
_started = true
if (enableRTMP && movie.rtmpURL != null)
connectUsingRTMP()
else
connectUsingHTTP()
reporter.reportMoviePlayed(movie.id)
}
public function handleConnectionFailed() : void
{
if (movie.rtmpURL.hasPort && !triedStandardRTMP)
handleCustomRTMPUnavailable()
else
handleRTMPUnavailable()
}
private function handleCustomRTMPUnavailable() : void
{
debug("Trying to connect using default RTMP ports.")
connectUsingStandardRTMP()
}
private function handleRTMPUnavailable() : void
{
debug("Could not connect using RTMP; trying plain HTTP.")
connectUsingHTTP()
}
public function get usingRTMP() : Boolean
{ return _usingRTMP }
private function connectUsingRTMP() : void
{ connection.connect(movie.rtmpURL) }
private function connectUsingStandardRTMP() : void
{
triedStandardRTMP = true
connection.connect(movie.rtmpURL.withoutPort)
}
private function connectUsingHTTP() : void
{
_usingRTMP = false
connection.dontConnect()
startPlaying()
}
public function handleConnectionClosed() : void
{}
// -----------------------------------------------------
public function handleConnectionEstablished() : void
{
_usingRTMP = true
if (bandwidthDeterminationNeeded)
connection.determineBandwidth()
else
startPlaying()
}
private function get bandwidthDeterminationNeeded() : Boolean
{ return bitratePolicy == BitratePolicy.BEST }
public function handleBandwidthDetermined
(bandwidth : Bitrate, latency : Duration) : void
{
measuredBandwidth = bandwidth
measuredLatency = latency
startPlaying()
}
private function get bandwidthDetermined() : Boolean
{ return measuredBandwidth != null }
private function startPlaying() : void
{
stream = connection.getNetStream()
stream.listener = this
stream.volume = volume
useStartBuffer()
if (usingRTMP)
playRTMPStream()
else
playHTTPStream()
if (paused)
stream.paused = true
}
private function playRTMPStream() : void
{ stream.playRTMP(streamPicker.first, streamPicker.all) }
private function playHTTPStream() : void
{ stream.playHTTP(movie.httpURL) }
private function get streamPicker() : RTMPStreamPicker
{
return new RTMPStreamPicker
(movie.rtmpStreams, bitratePolicy, measuredBandwidth)
}
// -----------------------------------------------------
public function handleNetStreamMetadata(data : Object) : void
{
metadata = data
if (!usingRTMP)
debug("Video file size: " + stream.httpFileSize)
maybeProcessCommands()
}
public function handleStreamingStarted() : void
{
useStartBuffer()
_buffering = true
_finished = false
}
public function handleBufferFilled() : void
{ handleBufferingFinished() }
private function handleBufferingFinished() : void
{
_buffering = false
// Give the backend a chance to resume playback before we go
// ahead and raise the buffer size further.
later($handleBufferingFinished)
}
private function $handleBufferingFinished() : void
{
// Make sure playback was not interrupted.
if (!buffering && !finished)
useLargeBuffer()
}
public function handleBufferEmptied() : void
{
if (finishedPlaying)
handleFinishedPlaying()
else
handleBufferingStarted()
}
private function handleBufferingStarted() : void
{
useSmallBuffer()
_buffering = true
_finished = false
}
private function useStartBuffer() : void
{ stream.bufferTime = START_BUFFER }
private function useSmallBuffer() : void
{ stream.bufferTime = SMALL_BUFFER }
private function useLargeBuffer() : void
{ stream.bufferTime = LARGE_BUFFER }
public function get buffering() : Boolean
{ return _buffering }
public function get bufferingUnexpectedly() : Boolean
{ return buffering && !justSeeked }
private function get justSeeked() : Boolean
{ return seekStopwatch.within(SEEK_GRACE_TIME) }
public function handleStreamingStopped() : void
{
_buffering = false
if (finishedPlaying)
handleFinishedPlaying()
}
private function handleFinishedPlaying() : void
{
debug("Finished playing.")
_finished = true
for each (var listener : PlayerFinishingListener in finishingListeners)
listener.handleMovieFinishedPlaying()
}
public function stop() : void
{
debug("Stopping.")
stream.close()
_started = false
stream = null
metadata = null
}
private function get finishedPlaying() : Boolean
{ return timeRemaining.seconds < 1 }
private function get timeRemaining() : Duration
{ return streamLength.minus(playheadPosition) }
// -----------------------------------------------------
public function get paused() : Boolean
{ return _paused }
public function set paused(value : Boolean) : void
{
// Allow pausing before the stream has been created.
_paused = value
if (stream)
stream.paused = value
}
public function togglePaused() : void
{
// Forbid pausing before the stream has been created.
if (stream)
paused = !paused
}
// -----------------------------------------------------
public function get playheadPosition() : Duration
{
return stream != null && stream.playheadPosition != null
? stream.playheadPosition : Duration.ZERO
}
public function get playheadRatio() : Number
{ return getRatio(playheadPosition.seconds, streamLength.seconds) }
public function get bufferRatio() : Number
{ return getRatio(bufferPosition.seconds, streamLength.seconds) }
private function getRatio
(numerator : Number, denominator : Number) : Number
{ return Math.min(1, numerator / denominator) }
private function get bufferPosition() : Duration
{ return playheadPosition.plus(bufferLength) }
public function set playheadPosition(value : Duration) : void
{
if (stream)
$playheadPosition = value
}
private function set $playheadPosition(value : Duration) : void
{
_finished = false
seekStopwatch.start()
useStartBuffer()
stream.playheadPosition = value
}
public function set playheadRatio(value : Number) : void
{ playheadPosition = streamLength.scaledBy(value) }
public function seekBy(delta : Duration) : void
{ playheadPosition = playheadPosition.plus(delta) }
public function rewind() : void
{ playheadPosition = Duration.ZERO }
public function get playing() : Boolean
{ return started && stream != null && !paused && !finished }
// -----------------------------------------------------
public function get volume() : Number
{ return _volume }
public function set volume(value : Number) : void
{
_volume = Math.round(clamp(value, 0, 1) * 100) / 100
if (sharedVolumeVariable.available)
sharedVolumeVariable.value = volume
if (stream)
stream.volume = volume
}
public function changeVolumeBy(delta : Number) : void
{ volume = volume + delta }
public function mute() : void
{
savedVolume = volume
volume = 0
}
public function unmute() : void
{ volume = savedVolume == 0 ? DEFAULT_VOLUME : savedVolume }
public function get muted() : Boolean
{ return volume == 0 }
// -----------------------------------------------------
public function get aspectRatio() : Number
{ return movie.aspectRatio }
public function get bufferTime() : Duration
{
return stream != null && stream.bufferTime != null
? stream.bufferTime : START_BUFFER
}
public function get bufferLength() : Duration
{
return stream != null && stream.bufferLength != null
? stream.bufferLength : Duration.ZERO
}
public function get bufferFillRatio() : Number
{ return getRatio(bufferLength.seconds, bufferTime.seconds) }
public function get streamLength() : Duration
{
return metadata != null
? Duration.seconds(metadata.duration)
: movie.duration
}
public function get currentBitrate() : Bitrate
{
return stream != null && stream.bitrate != null
? stream.bitrate : Bitrate.ZERO
}
public function get currentBandwidth() : Bitrate
{
return stream != null && stream.bandwidth != null
? stream.bandwidth : Bitrate.ZERO
}
public function get highQualityDimensions() : Dimensions
{
var result : Dimensions = Dimensions.ZERO
for each (var stream : RTMPStream in movie.rtmpStreams)
if (stream.dimensions.isGreaterThan(result))
result = stream.dimensions
return result
}
// -----------------------------------------------------
// XXX: Refactor this and remove queue.
public function handleCommandEnqueued() : void
{ maybeProcessCommands() }
private function maybeProcessCommands() : void
{ processCommands() }
private function processCommands() : void
{
while (!queue.empty)
processCommand(queue.dequeue())
}
private function processCommand(command : PlayerCommand) : void
{
if (command == PlayerCommand.PLAY)
started ? metadata != null && (paused = false) : start()
else if (command == PlayerCommand.PAUSE)
metadata != null && (paused = true)
else if (command == PlayerCommand.STOP)
stop()
else
throw new Error
}
}
}
|
package goplayer
{
import flash.utils.getTimer
public class Player implements
FlashNetConnectionListener,
FlashNetStreamListener,
PlayerQueueListener
{
private const DEFAULT_VOLUME : Number = .8
private const START_BUFFER : Duration = Duration.seconds(3)
private const SMALL_BUFFER : Duration = Duration.seconds(5)
private const LARGE_BUFFER : Duration = Duration.seconds(60)
private const SEEK_GRACE_TIME : Duration = Duration.seconds(2)
private const finishingListeners : Array = []
private var connection : FlashNetConnection
private var _movie : Movie
private var bitratePolicy : BitratePolicy
private var enableRTMP : Boolean
private var reporter : MovieEventReporter
private var queue : PlayerQueue
private var sharedVolumeVariable : SharedVariable
private var _started : Boolean = false
private var _finished : Boolean = false
private var triedStandardRTMP : Boolean = false
private var _usingRTMP : Boolean = false
private var measuredBandwidth : Bitrate = null
private var measuredLatency : Duration = null
private var stream : FlashNetStream = null
private var metadata : Object = null
private var _volume : Number = NaN
private var savedVolume : Number = 0
private var _paused : Boolean = false
private var _buffering : Boolean = false
private var seekStopwatch : Stopwatch = new Stopwatch
public function Player
(connection : FlashNetConnection,
movie : Movie,
bitratePolicy : BitratePolicy,
enableRTMP : Boolean,
reporter : MovieEventReporter,
queue : PlayerQueue,
sharedVolumeVariable : SharedVariable)
{
this.connection = connection
_movie = movie
this.bitratePolicy = bitratePolicy
this.enableRTMP = enableRTMP
this.reporter = reporter
this.queue = queue
this.sharedVolumeVariable = sharedVolumeVariable
connection.listener = this
queue.listener = this
reporter.reportMovieViewed(movie.id)
if (sharedVolumeVariable.hasValue)
volume = sharedVolumeVariable.value
else
volume = DEFAULT_VOLUME
}
public function get movie() : Movie
{ return _movie }
public function addFinishingListener
(value : PlayerFinishingListener) : void
{ finishingListeners.push(value) }
public function get started() : Boolean
{ return _started }
public function get running() : Boolean
{ return started && !finished }
public function get finished() : Boolean
{ return _finished }
// -----------------------------------------------------
public function start() : void
{
_started = true
if (enableRTMP && movie.rtmpURL != null)
connectUsingRTMP()
else
connectUsingHTTP()
reporter.reportMoviePlayed(movie.id)
}
public function handleConnectionFailed() : void
{
if (movie.rtmpURL.hasPort && !triedStandardRTMP)
handleCustomRTMPUnavailable()
else
handleRTMPUnavailable()
}
private function handleCustomRTMPUnavailable() : void
{
debug("Trying to connect using default RTMP ports.")
connectUsingStandardRTMP()
}
private function handleRTMPUnavailable() : void
{
debug("Could not connect using RTMP; trying plain HTTP.")
connectUsingHTTP()
}
public function get usingRTMP() : Boolean
{ return _usingRTMP }
private function connectUsingRTMP() : void
{ connection.connect(movie.rtmpURL) }
private function connectUsingStandardRTMP() : void
{
triedStandardRTMP = true
connection.connect(movie.rtmpURL.withoutPort)
}
private function connectUsingHTTP() : void
{
_usingRTMP = false
connection.dontConnect()
startPlaying()
}
public function handleConnectionClosed() : void
{}
// -----------------------------------------------------
public function handleConnectionEstablished() : void
{
_usingRTMP = true
if (bandwidthDeterminationNeeded)
connection.determineBandwidth()
else
startPlaying()
}
private function get bandwidthDeterminationNeeded() : Boolean
{ return bitratePolicy == BitratePolicy.BEST }
public function handleBandwidthDetermined
(bandwidth : Bitrate, latency : Duration) : void
{
measuredBandwidth = bandwidth
measuredLatency = latency
startPlaying()
}
private function get bandwidthDetermined() : Boolean
{ return measuredBandwidth != null }
private function startPlaying() : void
{
stream = connection.getNetStream()
stream.listener = this
stream.volume = volume
useStartBuffer()
if (usingRTMP)
playRTMPStream()
else
playHTTPStream()
if (paused)
stream.paused = true
}
private function playRTMPStream() : void
{ stream.playRTMP(streamPicker.first, streamPicker.all) }
private function playHTTPStream() : void
{ stream.playHTTP(movie.httpURL) }
private function get streamPicker() : RTMPStreamPicker
{
return new RTMPStreamPicker
(movie.rtmpStreams, bitratePolicy, measuredBandwidth)
}
// -----------------------------------------------------
public function handleNetStreamMetadata(data : Object) : void
{
metadata = data
if (!usingRTMP)
debug("Video file size: " + stream.httpFileSize)
maybeProcessCommands()
}
public function handleStreamingStarted() : void
{
useStartBuffer()
_buffering = true
_finished = false
}
public function handleBufferFilled() : void
{ handleBufferingFinished() }
private function handleBufferingFinished() : void
{
_buffering = false
// Give the backend a chance to resume playback before we go
// ahead and raise the buffer size further.
later($handleBufferingFinished)
}
private function $handleBufferingFinished() : void
{
// Make sure playback was not interrupted.
if (!buffering && !finished)
useLargeBuffer()
}
public function handleBufferEmptied() : void
{
if (finishedPlaying)
handleFinishedPlaying()
else
handleBufferingStarted()
}
private function handleBufferingStarted() : void
{
useSmallBuffer()
_buffering = true
_finished = false
}
private function useStartBuffer() : void
{ stream.bufferTime = START_BUFFER }
private function useSmallBuffer() : void
{ stream.bufferTime = SMALL_BUFFER }
private function useLargeBuffer() : void
{ stream.bufferTime = LARGE_BUFFER }
public function get buffering() : Boolean
{ return _buffering }
public function get bufferingUnexpectedly() : Boolean
{ return buffering && !justSeeked }
private function get justSeeked() : Boolean
{ return seekStopwatch.within(SEEK_GRACE_TIME) }
public function handleStreamingStopped() : void
{
_buffering = false
if (finishedPlaying)
handleFinishedPlaying()
}
private function handleFinishedPlaying() : void
{
debug("Finished playing.")
_finished = true
for each (var listener : PlayerFinishingListener in finishingListeners)
listener.handleMovieFinishedPlaying()
}
public function stop() : void
{
debug("Stopping.")
stream.close()
_started = false
stream = null
metadata = null
}
private function get finishedPlaying() : Boolean
{ return timeRemaining.seconds < 1 }
private function get timeRemaining() : Duration
{ return streamLength.minus(playheadPosition) }
// -----------------------------------------------------
public function get paused() : Boolean
{ return _paused }
public function set paused(value : Boolean) : void
{
if (stream != null)
_paused = value, stream.paused = value
}
public function togglePaused() : void
{
if (stream != null)
paused = !paused
}
// -----------------------------------------------------
public function get playheadPosition() : Duration
{
return stream != null && stream.playheadPosition != null
? stream.playheadPosition : Duration.ZERO
}
public function get playheadRatio() : Number
{ return getRatio(playheadPosition.seconds, streamLength.seconds) }
public function get bufferRatio() : Number
{ return getRatio(bufferPosition.seconds, streamLength.seconds) }
private function getRatio
(numerator : Number, denominator : Number) : Number
{ return Math.min(1, numerator / denominator) }
private function get bufferPosition() : Duration
{ return playheadPosition.plus(bufferLength) }
public function set playheadPosition(value : Duration) : void
{
if (stream)
$playheadPosition = value
}
private function set $playheadPosition(value : Duration) : void
{
_finished = false
seekStopwatch.start()
useStartBuffer()
stream.playheadPosition = value
}
public function set playheadRatio(value : Number) : void
{ playheadPosition = streamLength.scaledBy(value) }
public function seekBy(delta : Duration) : void
{ playheadPosition = playheadPosition.plus(delta) }
public function rewind() : void
{ playheadPosition = Duration.ZERO }
public function get playing() : Boolean
{ return started && stream != null && !paused && !finished }
// -----------------------------------------------------
public function get volume() : Number
{ return _volume }
public function set volume(value : Number) : void
{
_volume = Math.round(clamp(value, 0, 1) * 100) / 100
if (sharedVolumeVariable.available)
sharedVolumeVariable.value = volume
if (stream)
stream.volume = volume
}
public function changeVolumeBy(delta : Number) : void
{ volume = volume + delta }
public function mute() : void
{
savedVolume = volume
volume = 0
}
public function unmute() : void
{ volume = savedVolume == 0 ? DEFAULT_VOLUME : savedVolume }
public function get muted() : Boolean
{ return volume == 0 }
// -----------------------------------------------------
public function get aspectRatio() : Number
{ return movie.aspectRatio }
public function get bufferTime() : Duration
{
return stream != null && stream.bufferTime != null
? stream.bufferTime : START_BUFFER
}
public function get bufferLength() : Duration
{
return stream != null && stream.bufferLength != null
? stream.bufferLength : Duration.ZERO
}
public function get bufferFillRatio() : Number
{ return getRatio(bufferLength.seconds, bufferTime.seconds) }
public function get streamLength() : Duration
{
return metadata != null
? Duration.seconds(metadata.duration)
: movie.duration
}
public function get currentBitrate() : Bitrate
{
return stream != null && stream.bitrate != null
? stream.bitrate : Bitrate.ZERO
}
public function get currentBandwidth() : Bitrate
{
return stream != null && stream.bandwidth != null
? stream.bandwidth : Bitrate.ZERO
}
public function get highQualityDimensions() : Dimensions
{
var result : Dimensions = Dimensions.ZERO
for each (var stream : RTMPStream in movie.rtmpStreams)
if (stream.dimensions.isGreaterThan(result))
result = stream.dimensions
return result
}
// -----------------------------------------------------
// XXX: Refactor this and remove queue.
public function handleCommandEnqueued() : void
{ maybeProcessCommands() }
private function maybeProcessCommands() : void
{ processCommands() }
private function processCommands() : void
{
while (!queue.empty)
processCommand(queue.dequeue())
}
private function processCommand(command : PlayerCommand) : void
{
if (command == PlayerCommand.PLAY)
started ? metadata != null && (paused = false) : start()
else if (command == PlayerCommand.PAUSE)
metadata != null && (paused = true)
else if (command == PlayerCommand.STOP)
stop()
else
throw new Error
}
}
}
|
Remove the feature where you could pause the player in advance.
|
Remove the feature where you could pause the player in advance.
|
ActionScript
|
mit
|
dbrock/goplayer,dbrock/goplayer
|
c29c0a814478b0fa8355855ab3a7da319caa867d
|
common1/src/nt/lib/util/assert.as
|
common1/src/nt/lib/util/assert.as
|
package nt.lib.util
{
import flash.system.Capabilities;
/**
* debug 异常抛出类
* @param b 值为flase则抛出异常
* @param m 如果错误类为空则抛出该错误信息
* @param errorClass 错误类
*/
[Inline]
public function assert(b:Boolean, m:String = "", errorClass:Class = null):void
{
if (Capabilities.isDebugger)
{
if (!b)
{
throw new (errorClass ||= Error)(m);
}
}
}
}
|
package nt.lib.util
{
import flash.system.Capabilities;
/**
* debug 异常抛出类
* @param b 值为 false 则抛出异常
* @param m 如果错误类为空则抛出该错误信息
* @param errorClass 错误类
*/
[Inline]
public function assert(b:Boolean, m:String = "", errorClass:Class = null):void
{
if (Capabilities.isDebugger)
{
if (!b)
{
throw new (errorClass ||= Error)(m);
}
}
}
}
|
Fix typo
|
Fix typo
|
ActionScript
|
mit
|
nexttouches/age_client
|
fb1eb6026b04bc4fb360e45f18f6a25207576c7d
|
src/as/com/threerings/flash/AnimationManager.as
|
src/as/com/threerings/flash/AnimationManager.as
|
package com.threerings.flash {
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.events.Event;
import flash.utils.getTimer; // func import
/**
* Manages animations.
*/
public class AnimationManager
{
public function AnimationManager ()
{
throw new Error("Static only");
}
/**
* Start (or restart) the specified animation.
*/
public static function start (anim :Animation) :void
{
var dex :int = _anims.indexOf(anim);
if (dex == -1) {
_anims.push(anim);
_anims.push(NaN);
} else {
_anims[dex + 1] = NaN; // mark it as starting
}
if (!_framer) {
_framer = new Sprite();
_framer.addEventListener(Event.ENTER_FRAME, frameHandler);
}
}
/**
* Stop the specified animation.
*/
public static function stop (anim :Animation) :void
{
var dex :int = _anims.indexOf(anim);
if (dex == -1) {
Log.getLog(AnimationManager).warning("Stopping unknown Animation: " + anim);
return;
}
// remove it
_anims.splice(dex, 2);
// See if we should clean up a bit
if (_anims.length == 0) {
_framer.removeEventListener(Event.ENTER_FRAME, frameHandler);
_framer = null;
}
}
/**
* Track a DisplayObject that is also an Animation- it will
* automatically be started when added to the stage and
* stopped when removed.
*/
public static function addDisplayAnimation (disp :DisplayObject) :void
{
if (!(disp is Animation)) {
throw new ArgumentError("Must be an Animation");
}
disp.addEventListener(Event.ADDED_TO_STAGE, startDisplayAnim);
disp.addEventListener(Event.REMOVED_FROM_STAGE, stopDisplayAnim);
if (disp.stage != null) {
// it's on the stage now!
start(Animation(disp));
}
}
/**
* Stop tracking the specified DisplayObject animation.
*/
public static function removeDisplayAnimation (disp :DisplayObject) :void
{
disp.removeEventListener(Event.ADDED_TO_STAGE, startDisplayAnim);
disp.removeEventListener(Event.REMOVED_FROM_STAGE, stopDisplayAnim);
if (disp.stage != null) {
stop(Animation(disp));
}
}
protected static function startDisplayAnim (event :Event) :void
{
start(event.currentTarget as Animation);
}
protected static function stopDisplayAnim (event :Event) :void
{
stop(event.currentTarget as Animation);
}
/**
* Handle the ENTER_FRAME event.
*/
protected static function frameHandler (event :Event) :void
{
var now :Number = getTimer();
var anim :Animation;
var startStamp :Number;
for (var ii :int = _anims.length - 2; ii >= 0; ii -= 2) {
anim = Animation(_anims[ii]);
startStamp = Number(_anims[ii + 1]);
if (isNaN(startStamp)) {
_anims[ii + 1] = startStamp = now;
}
anim.updateAnimation(now - startStamp);
}
}
/** The current timestamp, accessable to all animations. */
protected static var _now :Number;
/** All the currently running animations. */
protected static var _anims :Array = [];
protected static var _framer :Sprite;
}
}
|
package com.threerings.flash {
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.events.Event;
import flash.utils.getTimer; // func import
/**
* Manages animations.
*/
public class AnimationManager
{
public function AnimationManager ()
{
throw new Error("Static only");
}
/**
* Start (or restart) the specified animation.
*/
public static function start (anim :Animation) :void
{
var dex :int = _anims.indexOf(anim);
if (dex == -1) {
dex = _anims.length;
_anims.push(anim);
}
_anims[dex + 1] = getTimer(); // mark it as starting
// and update it immediately
anim.updateAnimation(0);
if (!_framer) {
_framer = new Sprite();
_framer.addEventListener(Event.ENTER_FRAME, frameHandler);
}
}
/**
* Stop the specified animation.
*/
public static function stop (anim :Animation) :void
{
var dex :int = _anims.indexOf(anim);
if (dex == -1) {
Log.getLog(AnimationManager).warning("Stopping unknown Animation: " + anim);
return;
}
// remove it
_anims.splice(dex, 2);
// See if we should clean up a bit
if (_anims.length == 0) {
_framer.removeEventListener(Event.ENTER_FRAME, frameHandler);
_framer = null;
}
}
/**
* Track a DisplayObject that is also an Animation- it will
* automatically be started when added to the stage and
* stopped when removed.
*/
public static function addDisplayAnimation (disp :DisplayObject) :void
{
if (!(disp is Animation)) {
throw new ArgumentError("Must be an Animation");
}
disp.addEventListener(Event.ADDED_TO_STAGE, startDisplayAnim);
disp.addEventListener(Event.REMOVED_FROM_STAGE, stopDisplayAnim);
if (disp.stage != null) {
// it's on the stage now!
start(Animation(disp));
}
}
/**
* Stop tracking the specified DisplayObject animation.
*/
public static function removeDisplayAnimation (disp :DisplayObject) :void
{
disp.removeEventListener(Event.ADDED_TO_STAGE, startDisplayAnim);
disp.removeEventListener(Event.REMOVED_FROM_STAGE, stopDisplayAnim);
if (disp.stage != null) {
stop(Animation(disp));
}
}
protected static function startDisplayAnim (event :Event) :void
{
start(event.currentTarget as Animation);
}
protected static function stopDisplayAnim (event :Event) :void
{
stop(event.currentTarget as Animation);
}
/**
* Handle the ENTER_FRAME event.
*/
protected static function frameHandler (event :Event) :void
{
var now :Number = getTimer();
var anim :Animation;
var startStamp :Number;
for (var ii :int = _anims.length - 2; ii >= 0; ii -= 2) {
Animation(_anims[ii]).updateAnimation(now - Number(_anims[ii + 1]));
}
}
/** The current timestamp, accessable to all animations. */
protected static var _now :Number;
/** All the currently running animations. */
protected static var _anims :Array = [];
protected static var _framer :Sprite;
}
}
|
Call updateAnimation() immediately on any starting animation.
|
Call updateAnimation() immediately on any starting animation.
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@212 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
636deeb2cda54bbb8e7fca6af3b52279e73288ec
|
src/goplayer/Application.as
|
src/goplayer/Application.as
|
package goplayer
{
import flash.ui.Keyboard
public class Application extends Component
implements SkinSWFLoaderListener, MovieHandler, PlayerListener
{
private const background : Background
= new Background(0x000000, 1)
private const contentLayer : Component
= new Component
private const debugLayer : Component
= new EphemeralComponent
private var configuration : Configuration
private var api : StreamioAPI
private var skinSWF : SkinSWF = null
private var movie : Movie = null
private var player : Player = null
private var view : Component = null
private var _listener : ApplicationListener = null
public function Application(parameters : Object)
{
this.configuration = ConfigurationParser.parse(parameters)
api = new StreamioAPI
(configuration.apiURL,
new StandardHTTP,
configuration.trackerID)
addChild(background)
addChild(contentLayer)
addChild(debugLayer)
installLogger()
}
public function set listener(value : ApplicationListener) : void
{ _listener = value }
private function installLogger() : void
{ new DebugLoggerInstaller(debugLayer).execute() }
override protected function initialize() : void
{
onkeydown(stage, handleKeyDown)
if (configuration.skinURL)
loadSkin()
else
lookUpMovie()
}
private function loadSkin() : void
{ new SkinSWFLoader(configuration.skinURL, this).execute() }
public function handleSkinSWFLoaded(swf : SkinSWF) : void
{
skinSWF = swf
lookUpMovie()
}
private function lookUpMovie() : void
{
debug("Looking up Streamio video “" + configuration.movieID + "”...")
api.fetchMovie(configuration.movieID, this)
}
public function handleMovie(movie : Movie) : void
{
this.movie = movie
logMovieInformation()
createPlayer()
if (configuration.enableAutoplay)
player.start()
}
private function logMovieInformation() : void
{
debug("Movie “" + movie.title + "” found.")
debug("Will use " + configuration.bitratePolicy + ".")
const bitrates : Array = []
for each (var stream : RTMPStream in movie.rtmpStreams)
bitrates.push(stream.bitrate)
if (bitrates.length == 0)
debug("No RTMP streams available.")
else
debug("Available RTMP streams: " + bitrates.join(", "))
if (!configuration.enableRTMP)
debug("Will not use RTMP (disabled by configuration).")
}
private function createPlayer() : void
{
if (player != null)
player.destroy()
const kit : PlayerKit = new PlayerKit
(movie, configuration.bitratePolicy,
configuration.enableRTMP, api)
player = kit.player
player.listener = this
if (skinSWF)
view = new SkinnedPlayerView(kit.video, player, viewConfiguration)
else
view = new SimplePlayerView(kit.video, player)
contentLayer.addChild(view)
}
private function get viewConfiguration() : SkinnedPlayerViewConfiguration
{
const result : SkinnedPlayerViewConfiguration
= new SkinnedPlayerViewConfiguration
result.skin = skinSWF.getSkin()
result.enableChrome = configuration.enableChrome
result.enableTitle = configuration.enableTitle
result.enablePlayPauseButton = configuration.enablePlayPauseButton
result.enableElapsedTime = configuration.enableElapsedTime
result.enableSeekBar = configuration.enableSeekBar
result.enableTotalTime = configuration.enableTotalTime
result.enableVolumeControl = configuration.enableVolumeControl
result.enableFullscreenButton = configuration.enableFullscreenButton
return result
}
public function handleKeyDown(key : Key) : void
{
if (key.code == Keyboard.ENTER)
debugLayer.visible = !debugLayer.visible
else if (player != null)
$handleKeyDown(key)
}
private function $handleKeyDown(key : Key) : void
{
if (key.code == Keyboard.SPACE)
player.togglePaused()
else if (key.code == Keyboard.LEFT)
player.seekBy(Duration.seconds(-3))
else if (key.code == Keyboard.RIGHT)
player.seekBy(Duration.seconds(+3))
else if (key.code == Keyboard.UP)
player.changeVolumeBy(+.1)
else if (key.code == Keyboard.DOWN)
player.changeVolumeBy(-.1)
}
public function handleMovieFinishedPlaying() : void
{
if (configuration.enableLooping)
debug("Looping."), player.rewind()
else if (_listener != null)
_listener.handlePlaybackEnded()
}
public function handleCurrentTimeChanged() : void
{
if (_listener != null)
_listener.handleCurrentTimeChanged()
}
public function play() : void
{
if (player != null)
$play()
}
private function $play() : void
{
if (player.started)
player.paused = false
else
player.start()
}
public function pause() : void
{
if (player != null)
player.paused = true
}
public function stop() : void
{
if (player != null)
player.stop()
}
public function get currentTime() : Duration
{ return player.currentTime }
public function set currentTime(value : Duration) : void
{ player.currentTime = value }
public function get duration() : Duration
{ return player.duration }
}
}
|
package goplayer
{
import flash.ui.Keyboard
public class Application extends Component
implements SkinSWFLoaderListener, MovieHandler, PlayerListener
{
private const background : Background
= new Background(0x000000, 1)
private const contentLayer : Component
= new Component
private const debugLayer : Component
= new EphemeralComponent
private var configuration : Configuration
private var api : StreamioAPI
private var skinSWF : SkinSWF = null
private var movie : Movie = null
private var player : Player = null
private var view : Component = null
private var _listener : ApplicationListener = null
public function Application(parameters : Object)
{
installLogger()
this.configuration = ConfigurationParser.parse(parameters)
api = new StreamioAPI
(configuration.apiURL,
new StandardHTTP,
configuration.trackerID)
addChild(background)
addChild(contentLayer)
addChild(debugLayer)
}
public function set listener(value : ApplicationListener) : void
{ _listener = value }
private function installLogger() : void
{ new DebugLoggerInstaller(debugLayer).execute() }
override protected function initialize() : void
{
onkeydown(stage, handleKeyDown)
if (configuration.skinURL)
loadSkin()
else
lookUpMovie()
}
private function loadSkin() : void
{ new SkinSWFLoader(configuration.skinURL, this).execute() }
public function handleSkinSWFLoaded(swf : SkinSWF) : void
{
skinSWF = swf
lookUpMovie()
}
private function lookUpMovie() : void
{
debug("Looking up Streamio video “" + configuration.movieID + "”...")
api.fetchMovie(configuration.movieID, this)
}
public function handleMovie(movie : Movie) : void
{
this.movie = movie
logMovieInformation()
createPlayer()
if (configuration.enableAutoplay)
player.start()
}
private function logMovieInformation() : void
{
debug("Movie “" + movie.title + "” found.")
debug("Will use " + configuration.bitratePolicy + ".")
const bitrates : Array = []
for each (var stream : RTMPStream in movie.rtmpStreams)
bitrates.push(stream.bitrate)
if (bitrates.length == 0)
debug("No RTMP streams available.")
else
debug("Available RTMP streams: " + bitrates.join(", "))
if (!configuration.enableRTMP)
debug("Will not use RTMP (disabled by configuration).")
}
private function createPlayer() : void
{
if (player != null)
player.destroy()
const kit : PlayerKit = new PlayerKit
(movie, configuration.bitratePolicy,
configuration.enableRTMP, api)
player = kit.player
player.listener = this
if (skinSWF)
view = new SkinnedPlayerView(kit.video, player, viewConfiguration)
else
view = new SimplePlayerView(kit.video, player)
contentLayer.addChild(view)
}
private function get viewConfiguration() : SkinnedPlayerViewConfiguration
{
const result : SkinnedPlayerViewConfiguration
= new SkinnedPlayerViewConfiguration
result.skin = skinSWF.getSkin()
result.enableChrome = configuration.enableChrome
result.enableTitle = configuration.enableTitle
result.enablePlayPauseButton = configuration.enablePlayPauseButton
result.enableElapsedTime = configuration.enableElapsedTime
result.enableSeekBar = configuration.enableSeekBar
result.enableTotalTime = configuration.enableTotalTime
result.enableVolumeControl = configuration.enableVolumeControl
result.enableFullscreenButton = configuration.enableFullscreenButton
return result
}
public function handleKeyDown(key : Key) : void
{
if (key.code == Keyboard.ENTER)
debugLayer.visible = !debugLayer.visible
else if (player != null)
$handleKeyDown(key)
}
private function $handleKeyDown(key : Key) : void
{
if (key.code == Keyboard.SPACE)
player.togglePaused()
else if (key.code == Keyboard.LEFT)
player.seekBy(Duration.seconds(-3))
else if (key.code == Keyboard.RIGHT)
player.seekBy(Duration.seconds(+3))
else if (key.code == Keyboard.UP)
player.changeVolumeBy(+.1)
else if (key.code == Keyboard.DOWN)
player.changeVolumeBy(-.1)
}
public function handleMovieFinishedPlaying() : void
{
if (configuration.enableLooping)
debug("Looping."), player.rewind()
else if (_listener != null)
_listener.handlePlaybackEnded()
}
public function handleCurrentTimeChanged() : void
{
if (_listener != null)
_listener.handleCurrentTimeChanged()
}
public function play() : void
{
if (player != null)
$play()
}
private function $play() : void
{
if (player.started)
player.paused = false
else
player.start()
}
public function pause() : void
{
if (player != null)
player.paused = true
}
public function stop() : void
{
if (player != null)
player.stop()
}
public function get currentTime() : Duration
{ return player.currentTime }
public function set currentTime(value : Duration) : void
{ player.currentTime = value }
public function get duration() : Duration
{ return player.duration }
}
}
|
Install logger before doing anything else.
|
Install logger before doing anything else.
|
ActionScript
|
mit
|
dbrock/goplayer,dbrock/goplayer
|
67e24cff1942e9d81576d97dac888da5c393ce10
|
as3/smartform/src/com/rpath/raf/util/UIHelper.as
|
as3/smartform/src/com/rpath/raf/util/UIHelper.as
|
/*
#
# Copyright (c) 2005-2009 rPath, Inc.
#
# All rights reserved
#
*/
/*
#
# Copyright (c) 2009 rPath, Inc.
#
# This program is distributed under the terms of the MIT License as found
# in a file called LICENSE. If it is not present, the license
# is always available at http://www.opensource.org/licenses/mit-license.php.
#
# This program is distributed in the hope that it will be useful, but
# without any waranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the MIT License for full details.
*/
package com.rpath.raf.util
{
import flash.utils.Dictionary;
import mx.collections.ArrayCollection;
import mx.core.Application;
import mx.core.FlexGlobals;
import mx.core.IFlexDisplayObject;
import mx.formatters.NumberBaseRoundType;
import mx.formatters.NumberFormatter;
import mx.managers.PopUpManager;
import mx.managers.PopUpManagerChildList;
public class UIHelper
{
public static function checkBooleans(...args):Boolean
{
for each (var b:* in args)
{
if (b is Array || b is ArrayCollection)
{
for each (var c:* in b)
{
// allow for nested arrays
checkBooleans(c);
}
}
else
{
if (!b)
return false;
}
}
return true;
}
public static function checkOneOf(...args):Boolean
{
for each (var b:* in args)
{
if (b)
return true;
}
return false;
}
public static function formattedDate(unixTimestamp:Number):String
{
if (isNaN(unixTimestamp))
return "";
var date:Date = new Date(unixTimestamp * 1000);
/*
* Note that we add 1 to month b/c January is 0 in Flex
*/
return padLeft(date.getMonth() +1) + "/" + padLeft(date.getDate()) +
"/" + padLeft(date.getFullYear()) + " " + padLeft(date.getHours()) +
":" + padLeft(date.getMinutes()) + ":" + padLeft(date.getSeconds());
}
private static function padLeft(number:Number):String
{
var strNum:String = number.toString();
if (number.toString().length == 1)
strNum = "0" + strNum;
return strNum;
}
/**
* Replace \r\n with \n, replace \r with \n
*/
public static function processCarriageReturns(value:String):String
{
if (!value)
return value;
var cr:String = String.fromCharCode(13);
var crRegex:RegExp = new RegExp(cr, "gm");
var crnl:String = String.fromCharCode(13, 10);
var crnlRegex:RegExp = new RegExp(crnl, "gm");
// process CRNL first
value = value.replace(crnlRegex, '\n');
// process CR
value = value.replace(crRegex, '\n');
return value;
}
private static var popupModelMap:Dictionary = new Dictionary(true);
private static var popupOwnerMap:Dictionary = new Dictionary(true);
public static function createPopup(clazz:Class):*
{
var popup:Object = PopUpManager.createPopUp(FlexGlobals.topLevelApplication as Application,
clazz, false, PopUpManagerChildList.APPLICATION) as clazz;
return popup as IFlexDisplayObject;
}
public static function createSingletonPopupForModel(clazz:Class, model:Object, owner:Object=null):*
{
var popup:Object;
popup = popupForModel(model);
if (popup == null)
{
popup = PopUpManager.createPopUp(FlexGlobals.topLevelApplication as Application,
clazz, false, PopUpManagerChildList.APPLICATION) as clazz;
popupModelMap[model] = popup;
if (owner)
{
popupOwnerMap[popup] = owner;
}
}
return popup as IFlexDisplayObject;
}
public static function popupForModel(model:Object):*
{
return popupModelMap[model];
}
public static function removePopupForModel(model:Object):void
{
var popup:IFlexDisplayObject = popupModelMap[model];
if (popup)
{
delete popupModelMap[model];
delete popupOwnerMap[popup];
}
}
public static function removePopupsForOwner(owner:Object):void
{
for (var popup:* in popupOwnerMap)
{
if (popupOwnerMap[popup] === owner)
{
delete popupOwnerMap[popup];
// scan the model map too
for (var model:* in popupModelMap)
{
if (popupModelMap[model] === popup)
{
delete popupModelMap[model];
}
}
}
}
}
public static function popupsForOwner(owner:Object):Array
{
var result:Array = [];
for (var popup:* in popupOwnerMap)
{
if (popupOwnerMap[popup] === owner)
{
result.push(popup);
}
}
return result;
}
public static function closePopupsForOwner(owner:Object):void
{
for each (var popup:* in UIHelper.popupsForOwner(owner))
{
PopUpManager.removePopUp(popup);
}
removePopupsForOwner(owner);
}
// make bytes human readable
public static function humanReadableSize(bytes:int, precision:int=1):String
{
var s:String = bytes + ' bytes';
var nf:NumberFormatter = new NumberFormatter();
nf.precision = precision;
nf.useThousandsSeparator = true;
nf.useNegativeSign = true;
nf.rounding = NumberBaseRoundType.NEAREST;
if (bytes > 1073741824)
{
s = nf.format((bytes / 1073741824.0)) + ' GB' + ' (' + (s) + ')';
}
else if (bytes > 1048576)
{
s = nf.format((bytes / 1048576.0)) + ' MB' + ' (' + (s) + ')';
}
else if (bytes > 1024)
{
s = nf.format((bytes / 1024.0)) + ' KB' + ' (' + (s) + ')';
}
return s;
}
}
}
|
/*
#
# Copyright (c) 2005-2009 rPath, Inc.
#
# All rights reserved
#
*/
/*
#
# Copyright (c) 2009 rPath, Inc.
#
# This program is distributed under the terms of the MIT License as found
# in a file called LICENSE. If it is not present, the license
# is always available at http://www.opensource.org/licenses/mit-license.php.
#
# This program is distributed in the hope that it will be useful, but
# without any waranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the MIT License for full details.
*/
package com.rpath.raf.util
{
import flash.utils.Dictionary;
import mx.collections.ArrayCollection;
import spark.components.Application;
import mx.core.FlexGlobals;
import mx.core.IFlexDisplayObject;
import mx.formatters.NumberBaseRoundType;
import mx.formatters.NumberFormatter;
import mx.managers.PopUpManager;
import mx.managers.PopUpManagerChildList;
public class UIHelper
{
public static function checkBooleans(...args):Boolean
{
for each (var b:* in args)
{
if (b is Array || b is ArrayCollection)
{
for each (var c:* in b)
{
// allow for nested arrays
checkBooleans(c);
}
}
else
{
if (!b)
return false;
}
}
return true;
}
public static function checkOneOf(...args):Boolean
{
for each (var b:* in args)
{
if (b)
return true;
}
return false;
}
public static function formattedDate(unixTimestamp:Number):String
{
if (isNaN(unixTimestamp))
return "";
var date:Date = new Date(unixTimestamp * 1000);
/*
* Note that we add 1 to month b/c January is 0 in Flex
*/
return padLeft(date.getMonth() +1) + "/" + padLeft(date.getDate()) +
"/" + padLeft(date.getFullYear()) + " " + padLeft(date.getHours()) +
":" + padLeft(date.getMinutes()) + ":" + padLeft(date.getSeconds());
}
private static function padLeft(number:Number):String
{
var strNum:String = number.toString();
if (number.toString().length == 1)
strNum = "0" + strNum;
return strNum;
}
/**
* Replace \r\n with \n, replace \r with \n
*/
public static function processCarriageReturns(value:String):String
{
if (!value)
return value;
var cr:String = String.fromCharCode(13);
var crRegex:RegExp = new RegExp(cr, "gm");
var crnl:String = String.fromCharCode(13, 10);
var crnlRegex:RegExp = new RegExp(crnl, "gm");
// process CRNL first
value = value.replace(crnlRegex, '\n');
// process CR
value = value.replace(crRegex, '\n');
return value;
}
private static var popupModelMap:Dictionary = new Dictionary(true);
private static var popupOwnerMap:Dictionary = new Dictionary(true);
public static function createPopup(clazz:Class):*
{
var popup:Object = PopUpManager.createPopUp(FlexGlobals.topLevelApplication as Application,
clazz, false, PopUpManagerChildList.APPLICATION) as clazz;
return popup as IFlexDisplayObject;
}
public static function createSingletonPopupForModel(clazz:Class, model:Object, owner:Object=null):*
{
var popup:Object;
popup = popupForModel(model);
if (popup == null)
{
popup = PopUpManager.createPopUp(FlexGlobals.topLevelApplication as Application,
clazz, false, PopUpManagerChildList.APPLICATION) as clazz;
popupModelMap[model] = popup;
if (owner)
{
popupOwnerMap[popup] = owner;
}
}
return popup as IFlexDisplayObject;
}
public static function popupForModel(model:Object):*
{
return popupModelMap[model];
}
public static function removePopupForModel(model:Object):void
{
var popup:IFlexDisplayObject = popupModelMap[model];
if (popup)
{
delete popupModelMap[model];
delete popupOwnerMap[popup];
}
}
public static function removePopupsForOwner(owner:Object):void
{
for (var popup:* in popupOwnerMap)
{
if (popupOwnerMap[popup] === owner)
{
delete popupOwnerMap[popup];
// scan the model map too
for (var model:* in popupModelMap)
{
if (popupModelMap[model] === popup)
{
delete popupModelMap[model];
}
}
}
}
}
public static function popupsForOwner(owner:Object):Array
{
var result:Array = [];
for (var popup:* in popupOwnerMap)
{
if (popupOwnerMap[popup] === owner)
{
result.push(popup);
}
}
return result;
}
public static function closePopupsForOwner(owner:Object):void
{
for each (var popup:* in UIHelper.popupsForOwner(owner))
{
PopUpManager.removePopUp(popup);
}
removePopupsForOwner(owner);
}
// make bytes human readable
public static function humanReadableSize(bytes:int, precision:int=1):String
{
var s:String = bytes + ' bytes';
var nf:NumberFormatter = new NumberFormatter();
nf.precision = precision;
nf.useThousandsSeparator = true;
nf.useNegativeSign = true;
nf.rounding = NumberBaseRoundType.NEAREST;
if (bytes > 1073741824)
{
s = nf.format((bytes / 1073741824.0)) + ' GB' + ' (' + (s) + ')';
}
else if (bytes > 1048576)
{
s = nf.format((bytes / 1048576.0)) + ' MB' + ' (' + (s) + ')';
}
else if (bytes > 1024)
{
s = nf.format((bytes / 1024.0)) + ' KB' + ' (' + (s) + ')';
}
return s;
}
}
}
|
replace mx Application import with spark one
|
replace mx Application import with spark one
|
ActionScript
|
apache-2.0
|
sassoftware/smartform
|
0c6e8abc96ac91e39d17345d6bcc6f5d6da92e05
|
src/stdio/StreamBuffer.as
|
src/stdio/StreamBuffer.as
|
package stdio {
internal class StreamBuffer implements InputStream, OutputStream {
public var buffer: String = ""
public var closed: Boolean = false
public function puts(value: Object): void {
write(value + "\n")
}
public function write(value: Object): void {
buffer += value.toString()
satisfy_read_requests()
}
public function close(): void {
closed = true
satisfy_read_requests()
}
// -----------------------------------------------------
private const requests: Array = []
private function satisfy_read_requests(): void {
while (has_requests && next_request.ready) {
next_request.satisfy()
requests.shift()
}
}
private function get has_requests(): Boolean {
return requests.length > 0
}
private function get next_request(): ReadRequest {
return requests[0]
}
// -----------------------------------------------------
public function gets(callback: Function): void {
add_read_request(new ReadLineRequest(this, callback))
}
public function read(callback: Function): void {
add_read_request(new ReadChunkRequest(this, callback))
}
private function add_read_request(request: ReadRequest): void {
requests.push(request)
satisfy_read_requests()
}
public function get emptied(): Boolean {
return closed && !buffer.length
}
public function get ready(): Boolean {
return new ReadChunkRequest(this, null).ready
}
}
}
|
package stdio {
internal class StreamBuffer implements InputStream, OutputStream {
public var buffer: String = ""
public var closed: Boolean = false
public function puts(value: Object): void {
write(value + "\n")
}
public function write(value: Object): void {
buffer += value.toString()
satisfy_read_requests()
}
public function close(): void {
closed = true
satisfy_read_requests()
}
// -----------------------------------------------------
private const requests: Array = []
private function satisfy_read_requests(): void {
while (requests.length > 0 && requests[0].ready) {
// Note: `shift()` must run before `satisfy()`.
requests.shift().satisfy()
}
}
// -----------------------------------------------------
public function gets(callback: Function): void {
add_read_request(new ReadLineRequest(this, callback))
}
public function read(callback: Function): void {
add_read_request(new ReadChunkRequest(this, callback))
}
private function add_read_request(request: ReadRequest): void {
requests.push(request)
satisfy_read_requests()
}
public function get emptied(): Boolean {
return closed && !buffer.length
}
public function get ready(): Boolean {
return new ReadChunkRequest(this, null).ready
}
}
}
|
Fix subtle side-effect-related bug.
|
Fix subtle side-effect-related bug.
|
ActionScript
|
mit
|
dbrock/stdio.as,dbrock/stdio.as,dbrock/stdio.as
|
89eb4075fcce1fe87758e0ba65a0d7c9be58f26e
|
src/widgets/supportClasses/ResultAttributes.as
|
src/widgets/supportClasses/ResultAttributes.as
|
package widgets.supportClasses
{
import com.esri.ags.FeatureSet;
import com.esri.ags.Graphic;
import com.esri.ags.layers.FeatureLayer;
import com.esri.ags.layers.supportClasses.CodedValue;
import com.esri.ags.layers.supportClasses.CodedValueDomain;
import com.esri.ags.layers.supportClasses.FeatureType;
import com.esri.ags.layers.supportClasses.Field;
import com.esri.ags.layers.supportClasses.LayerDetails;
import mx.formatters.DateFormatter;
[Bindable]
public class ResultAttributes
{
public var attributes:Object;
public var title:String;
public var content:String;
public var link:String;
public var linkAlias:String;
public static function toResultAttributes(fields:XMLList,
textDirection:String = null,
graphic:Graphic = null,
featureSet:FeatureSet = null,
layer:FeatureLayer = null,
layerDetails:LayerDetails = null,
widgetTitle:String = null,
titleField:String = null,
linkField:String = null,
linkAlias:String = null):ResultAttributes
{
var resultAttributes:ResultAttributes = new ResultAttributes;
var value:String = "";
var title:String = "";
var content:String = "";
var link:String = "";
var linkAlias:String;
var fieldsXMLList:XMLList = fields ? fields.field : null;
if (fields && fields[0].@all[0] == "true")
{
if (layerDetails.fields)
{
for each (var field:Field in layerDetails.fields)
{
if (field.name in graphic.attributes)
{
displayFields(field.name, getFieldXML(field.name, fieldsXMLList), field);
}
}
}
else
{
for (var fieldName:String in graphic.attributes)
{
displayFields(fieldName, getFieldXML(fieldName, fieldsXMLList), null);
}
}
}
else
{
for each (var fieldXML:XML in fieldsXMLList) // display the fields in the same order as specified
{
if (fieldXML.@name[0] in graphic.attributes)
{
displayFields(fieldXML.@name[0], fieldXML, getField(layer, fieldXML.@name[0]));
}
}
}
resultAttributes.attributes = graphic.attributes;
resultAttributes.title = title ? title : widgetTitle;
resultAttributes.content = content;
resultAttributes.link = link ? link : null;
resultAttributes.linkAlias = linkAlias;
function displayFields(fieldName:String, fieldXML:XML, field:Field):void
{
var fieldNameTextValue:String = graphic.attributes[fieldName];
value = fieldNameTextValue ? fieldNameTextValue : "";
if (value)
{
var isDateField:Boolean;
var useUTC:Boolean;
var dateFormat:String;
if (fieldXML)
{
useUTC = fieldXML.format.@useutc[0] || fieldXML.@useutc[0] == "true";
dateFormat = fieldXML.format.@dateformat[0] || fieldXML.@dateformat[0];
if (dateFormat)
{
isDateField = true;
}
}
if (!isDateField && field)
{
isDateField = field.type == Field.TYPE_DATE;
}
if (isDateField)
{
var dateMS:Number = Number(value);
if (!isNaN(dateMS))
{
value = msToDate(dateMS, dateFormat, useUTC);
}
}
else
{
var typeID:String = layerDetails.typeIdField ? graphic.attributes[layerDetails.typeIdField] : null;
if (fieldName == layerDetails.typeIdField)
{
var featureType:FeatureType = getFeatureType(layer, typeID);
if (featureType && featureType.name)
{
value = featureType.name;
}
}
else
{
var codedValue:CodedValue = getCodedValue(layer, fieldName, value, typeID);
if (codedValue)
{
value = codedValue.name;
}
}
}
}
if (titleField && fieldName.toUpperCase() == titleField.toUpperCase())
{
title = value;
}
else if (linkField && fieldName.toUpperCase() == linkField.toUpperCase())
{
link = value;
linkAlias = linkAlias;
}
else if (fieldName.toUpperCase() != "SHAPE_LENGTH" && fieldName.toUpperCase() != "SHAPE_AREA")
{
var fieldLabel:String;
if (fieldXML && fieldXML.@alias[0])
{
fieldLabel = fieldXML.@alias[0];
}
else
{
fieldLabel = featureSet.fieldAliases[fieldName];
}
if (textDirection && textDirection == "rtl")
{
content += value + " :" + fieldLabel + "\n";
}
else
{
content += fieldLabel + ": " + value + "\n";
}
}
}
return resultAttributes;
}
private static function getFieldXML(fieldName:String, fields:XMLList):XML
{
var result:XML;
for each (var fieldXML:XML in fields)
{
if (fieldName == fieldXML.@name[0])
{
result = fieldXML;
break;
}
}
return result;
}
private static function getField(layer:FeatureLayer, fieldName:String):Field
{
var result:Field;
if (layer)
{
for each (var field:Field in layer.layerDetails.fields)
{
if (fieldName == field.name)
{
result = field;
break;
}
}
}
return result;
}
private static function getFeatureType(layer:FeatureLayer, typeID:String):FeatureType
{
var result:FeatureType;
if (layer)
{
for each (var featureType:FeatureType in layer.layerDetails.types)
{
if (typeID == featureType.id)
{
result = featureType;
break;
}
}
}
return result;
}
private static function msToDate(ms:Number, dateFormat:String, useUTC:Boolean):String
{
var date:Date = new Date(ms);
if (date.milliseconds == 999) // workaround for REST bug
{
date.milliseconds++;
}
if (useUTC)
{
date.minutes += date.timezoneOffset;
}
if (dateFormat)
{
var dateFormatter:DateFormatter = new DateFormatter();
dateFormatter.formatString = dateFormat;
var result:String = dateFormatter.format(date);
if (result)
{
return result;
}
else
{
return dateFormatter.error;
}
}
else
{
return date.toLocaleString();
}
}
private static function getCodedValue(layer:FeatureLayer, fieldName:String, fieldValue:String, typeID:String):CodedValue
{
var result:CodedValue;
var codedValueDomain:CodedValueDomain;
if (typeID)
{
var featureType:FeatureType = getFeatureType(layer, typeID);
if (featureType)
{
codedValueDomain = featureType.domains[fieldName] as CodedValueDomain;
}
}
else
{
var field:Field = getField(layer, fieldName);
if (field)
{
codedValueDomain = field.domain as CodedValueDomain;
}
}
if (codedValueDomain)
{
for each (var codedValue:CodedValue in codedValueDomain.codedValues)
{
if (fieldValue == codedValue.code)
{
result = codedValue;
break;
}
}
}
return result;
}
}
}
|
package widgets.supportClasses
{
import com.esri.ags.FeatureSet;
import com.esri.ags.Graphic;
import com.esri.ags.layers.FeatureLayer;
import com.esri.ags.layers.supportClasses.CodedValue;
import com.esri.ags.layers.supportClasses.CodedValueDomain;
import com.esri.ags.layers.supportClasses.FeatureType;
import com.esri.ags.layers.supportClasses.Field;
import com.esri.ags.layers.supportClasses.LayerDetails;
import mx.formatters.DateFormatter;
[Bindable]
public class ResultAttributes
{
public var attributes:Object;
public var title:String;
public var content:String;
public var link:String;
public var linkAlias:String;
public static function toResultAttributes(fields:XMLList,
textDirection:String = null,
graphic:Graphic = null,
featureSet:FeatureSet = null,
layer:FeatureLayer = null,
layerDetails:LayerDetails = null,
fallbackTitle:String = null,
titleField:String = null,
linkField:String = null,
linkAlias:String = null):ResultAttributes
{
var resultAttributes:ResultAttributes = new ResultAttributes;
var value:String = "";
var title:String = "";
var content:String = "";
var link:String = "";
var linkAlias:String;
var fieldsXMLList:XMLList = fields ? fields.field : null;
if (fields && fields[0].@all[0] == "true")
{
if (layerDetails.fields)
{
for each (var field:Field in layerDetails.fields)
{
if (field.name in graphic.attributes)
{
displayFields(field.name, getFieldXML(field.name, fieldsXMLList), field);
}
}
}
else
{
for (var fieldName:String in graphic.attributes)
{
displayFields(fieldName, getFieldXML(fieldName, fieldsXMLList), null);
}
}
}
else
{
for each (var fieldXML:XML in fieldsXMLList) // display the fields in the same order as specified
{
if (fieldXML.@name[0] in graphic.attributes)
{
displayFields(fieldXML.@name[0], fieldXML, getField(layer, fieldXML.@name[0]));
}
}
}
resultAttributes.attributes = graphic.attributes;
resultAttributes.title = title ? title : fallbackTitle;
resultAttributes.content = content;
resultAttributes.link = link ? link : null;
resultAttributes.linkAlias = linkAlias;
function displayFields(fieldName:String, fieldXML:XML, field:Field):void
{
var fieldNameTextValue:String = graphic.attributes[fieldName];
value = fieldNameTextValue ? fieldNameTextValue : "";
if (value)
{
var isDateField:Boolean;
var useUTC:Boolean;
var dateFormat:String;
if (fieldXML)
{
useUTC = fieldXML.format.@useutc[0] || fieldXML.@useutc[0] == "true";
dateFormat = fieldXML.format.@dateformat[0] || fieldXML.@dateformat[0];
if (dateFormat)
{
isDateField = true;
}
}
if (!isDateField && field)
{
isDateField = field.type == Field.TYPE_DATE;
}
if (isDateField)
{
var dateMS:Number = Number(value);
if (!isNaN(dateMS))
{
value = msToDate(dateMS, dateFormat, useUTC);
}
}
else
{
var typeID:String = layerDetails.typeIdField ? graphic.attributes[layerDetails.typeIdField] : null;
if (fieldName == layerDetails.typeIdField)
{
var featureType:FeatureType = getFeatureType(layer, typeID);
if (featureType && featureType.name)
{
value = featureType.name;
}
}
else
{
var codedValue:CodedValue = getCodedValue(layer, fieldName, value, typeID);
if (codedValue)
{
value = codedValue.name;
}
}
}
}
if (titleField && fieldName.toUpperCase() == titleField.toUpperCase())
{
title = value;
}
else if (linkField && fieldName.toUpperCase() == linkField.toUpperCase())
{
link = value;
linkAlias = linkAlias;
}
else if (fieldName.toUpperCase() != "SHAPE_LENGTH" && fieldName.toUpperCase() != "SHAPE_AREA")
{
var fieldLabel:String;
if (fieldXML && fieldXML.@alias[0])
{
fieldLabel = fieldXML.@alias[0];
}
else
{
fieldLabel = featureSet.fieldAliases[fieldName];
}
if (textDirection && textDirection == "rtl")
{
content += value + " :" + fieldLabel + "\n";
}
else
{
content += fieldLabel + ": " + value + "\n";
}
}
}
return resultAttributes;
}
private static function getFieldXML(fieldName:String, fields:XMLList):XML
{
var result:XML;
for each (var fieldXML:XML in fields)
{
if (fieldName == fieldXML.@name[0])
{
result = fieldXML;
break;
}
}
return result;
}
private static function getField(layer:FeatureLayer, fieldName:String):Field
{
var result:Field;
if (layer)
{
for each (var field:Field in layer.layerDetails.fields)
{
if (fieldName == field.name)
{
result = field;
break;
}
}
}
return result;
}
private static function getFeatureType(layer:FeatureLayer, typeID:String):FeatureType
{
var result:FeatureType;
if (layer)
{
for each (var featureType:FeatureType in layer.layerDetails.types)
{
if (typeID == featureType.id)
{
result = featureType;
break;
}
}
}
return result;
}
private static function msToDate(ms:Number, dateFormat:String, useUTC:Boolean):String
{
var date:Date = new Date(ms);
if (date.milliseconds == 999) // workaround for REST bug
{
date.milliseconds++;
}
if (useUTC)
{
date.minutes += date.timezoneOffset;
}
if (dateFormat)
{
var dateFormatter:DateFormatter = new DateFormatter();
dateFormatter.formatString = dateFormat;
var result:String = dateFormatter.format(date);
if (result)
{
return result;
}
else
{
return dateFormatter.error;
}
}
else
{
return date.toLocaleString();
}
}
private static function getCodedValue(layer:FeatureLayer, fieldName:String, fieldValue:String, typeID:String):CodedValue
{
var result:CodedValue;
var codedValueDomain:CodedValueDomain;
if (typeID)
{
var featureType:FeatureType = getFeatureType(layer, typeID);
if (featureType)
{
codedValueDomain = featureType.domains[fieldName] as CodedValueDomain;
}
}
else
{
var field:Field = getField(layer, fieldName);
if (field)
{
codedValueDomain = field.domain as CodedValueDomain;
}
}
if (codedValueDomain)
{
for each (var codedValue:CodedValue in codedValueDomain.codedValues)
{
if (fieldValue == codedValue.code)
{
result = codedValue;
break;
}
}
}
return result;
}
}
}
|
Rename default title argument name in ResultAttributes#toResultAttributes.
|
Rename default title argument name in ResultAttributes#toResultAttributes.
|
ActionScript
|
apache-2.0
|
CanterburyRegionalCouncil/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex,Esri/arcgis-viewer-flex,Esri/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex
|
aa726be77a9666e10eb542914849856974fae22a
|
KeyGenerator.as
|
KeyGenerator.as
|
package dse{
import com.hurlant.crypto.prng.Random;
import com.hurlant.crypto.rsa.RSAKey;
import com.hurlant.util.Hex;
import flash.external.ExternalInterface;
import flash.utils.ByteArray;
public class KeyGenerator
{
public static function generateKeys():void{
var exp:String = "10001";
var rsa:RSAKey = RSAKey.generate(1024, exp);
ExternalInterface.call("setvalue", "publickey", rsa.n.toString());
ExternalInterface.call("setvalue", "d", rsa.d.toString());
ExternalInterface.call("setvalue", "p", rsa.p.toString());
ExternalInterface.call("setvalue", "q", rsa.q.toString());
ExternalInterface.call("setvalue", "dmp", rsa.dmp1.toString());
ExternalInterface.call("setvalue", "dmq", rsa.dmq1.toString());
ExternalInterface.call("setvalue", "qinv", rsa.coeff.toString());
var data:ByteArray, prehashedkey:ByteArray, hashedkey:ByteArray;
var r:Random = new Random;
var rankey:ByteArray = new ByteArray
r.nextBytes(rankey, 32);
ExternalInterface.call("setvalue", "rk", Hex.fromArray(rankey));
}
}
}
|
package dse{
import com.hurlant.crypto.prng.Random;
import com.hurlant.crypto.rsa.RSAKey;
import com.hurlant.util.Hex;
import com.hurlant.crypto.prng.TLSPRF;
import flash.external.ExternalInterface;
import flash.utils.ByteArray;
public class KeyGenerator
{
public static function generateKeys():void{
var exp:String = "10001";
var rsa:RSAKey = RSAKey.generate(1024, exp);
ExternalInterface.call("setvalue", "publickey", rsa.n.toString());
ExternalInterface.call("setvalue", "d", rsa.d.toString());
ExternalInterface.call("setvalue", "p", rsa.p.toString());
ExternalInterface.call("setvalue", "q", rsa.q.toString());
ExternalInterface.call("setvalue", "dmp", rsa.dmp1.toString());
ExternalInterface.call("setvalue", "dmq", rsa.dmq1.toString());
ExternalInterface.call("setvalue", "qinv", rsa.coeff.toString());
var data:ByteArray, prehashedkey:ByteArray, hashedkey:ByteArray;
var r:Random = new Random(TLSPRF);
var rankey:ByteArray = new ByteArray;
r.nextBytes(rankey, 32);
ExternalInterface.call("setvalue", "rk", Hex.fromArray(rankey));
}
}
}
|
change random used for generating aes to TLS from ARC4
|
change random used for generating aes to TLS from ARC4
|
ActionScript
|
mit
|
snoble/dse
|
0025dc59e91b565e7c5afe13c5dc69d5bb7c43c8
|
src/aerys/minko/scene/controller/mesh/MeshVisibilityController.as
|
src/aerys/minko/scene/controller/mesh/MeshVisibilityController.as
|
package aerys.minko.scene.controller.mesh
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
import aerys.minko.scene.node.camera.AbstractCamera;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.FrustumCulling;
import aerys.minko.type.math.BoundingBox;
import aerys.minko.type.math.BoundingSphere;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
/**
* The MeshVisibilityController watches the Mesh and the active Camera of a Scene
* to determine whether the object is actually inside the view frustum or not.
*
* @author Jean-Marc Le Roux
*
*/
public final class MeshVisibilityController extends AbstractController
{
use namespace minko_math;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
private static const STATE_UNDEFINED : uint = 0;
private static const STATE_INSIDE : uint = 1;
private static const STATE_OUTSIDE : uint = 2;
private var _mesh : Mesh;
private var _state : uint;
private var _lastTest : int;
private var _boundingBox : BoundingBox;
private var _boundingSphere : BoundingSphere;
private var _data : DataProvider;
private var _frustumCulling : uint;
private var _insideFrustum : Boolean;
// private var _data.computedVisibility : Boolean;
public function get frustumCulling() : uint
{
return _frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
_frustumCulling = value;
if (_mesh && _mesh.root is Scene)
testCulling();
}
public function get insideFrustum() : Boolean
{
return _insideFrustum;
}
public function get computedVisibility() : Boolean
{
return _data.computedVisibility;
}
public function MeshVisibilityController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
_data = new DataProvider();
_data.setProperty('computedVisibility', false);
_boundingBox = new BoundingBox(Vector4.ZERO, Vector4.ONE);
_boundingSphere = new BoundingSphere(Vector4.ZERO, 0.);
_state = STATE_UNDEFINED;
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
if (_mesh != null)
throw new Error();
_mesh = target;
target.added.add(addedHandler);
target.removed.add(removedHandler);
if (target.root is Scene)
addedHandler(target, target.root as Scene);
if (_frustumCulling)
testCulling();
}
private function targetRemovedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
_mesh = null;
target.added.remove(addedHandler);
target.removed.remove(removedHandler);
if (target.root is Scene)
removedHandler(target, target.root as Scene);
}
private function addedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = mesh.scene;
if (!scene)
return ;
scene.bindings.addCallback('worldToScreen', worldToScreenChangedHandler);
meshLocalToWorldChangedHandler(mesh, mesh.getLocalToWorldTransform());
mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler);
mesh.visibilityChanged.add(visiblityChangedHandler);
mesh.parent.computedVisibilityChanged.add(visiblityChangedHandler);
mesh.removed.add(meshRemovedHandler);
}
private function meshRemovedHandler(mesh : Mesh, ancestor : Group) : void
{
if (!mesh.parent)
ancestor.computedVisibilityChanged.remove(visiblityChangedHandler);
}
private function removedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = ancestor.scene;
if (!scene)
return ;
scene.bindings.removeCallback('worldToScreen', worldToScreenChangedHandler);
mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler);
mesh.visibilityChanged.remove(visiblityChangedHandler);
mesh.removed.remove(meshRemovedHandler);
if (mesh.parent)
mesh.parent.computedVisibilityChanged.remove(visiblityChangedHandler);
}
private function visiblityChangedHandler(node : ISceneNode, visibility : Boolean) : void
{
var computedVisibility : Boolean = _mesh.visible && _mesh.parent.computedVisibility
&& (_frustumCulling == FrustumCulling.DISABLED || _insideFrustum);
_data.computedVisibility = computedVisibility;
_mesh.computedVisibilityChanged.execute(_mesh, computedVisibility);
}
private function worldToScreenChangedHandler(bindings : DataBindings,
propertyName : String,
oldValue : Matrix4x4,
newValue : Matrix4x4) : void
{
testCulling();
}
private function meshLocalToWorldChangedHandler(mesh : Mesh, transform : Matrix4x4) : void
{
var geom : Geometry = _mesh.geometry;
var culling : uint = _frustumCulling;
if (!geom.boundingBox || !geom.boundingSphere || culling == FrustumCulling.DISABLED)
return ;
if (culling & FrustumCulling.BOX)
transform.transformRawVectors(geom.boundingBox._vertices, _boundingBox._vertices);
if (culling & FrustumCulling.SPHERE)
{
var center : Vector4 = transform.transformVector(geom.boundingSphere.center);
var scale : Vector4 = transform.deltaTransformVector(Vector4.ONE);
var radius : Number = geom.boundingSphere.radius * Math.max(
Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z)
);
_boundingSphere.update(center, radius);
}
testCulling();
}
private function testCulling() : void
{
var culling : uint = _frustumCulling;
if (culling != FrustumCulling.DISABLED)
{
_data.computedVisibility = true;
return;
}
if (_mesh && _mesh.geometry.boundingBox && _mesh.visible)
{
var camera : AbstractCamera = (_mesh.root as Scene).activeCamera;
if (!camera)
return ;
_lastTest = camera.frustum.testBoundingVolume(
_boundingSphere,
_boundingBox,
null,
culling,
_lastTest
);
var inside : Boolean = _lastTest == -1;
if (inside && _state != STATE_INSIDE)
{
_insideFrustum = true;
_data.computedVisibility = _mesh.parent.computedVisibility && _mesh.visible;
_mesh.computedVisibilityChanged.execute(_mesh, computedVisibility);
_state = STATE_INSIDE;
}
else if (!inside && _state != STATE_OUTSIDE)
{
_insideFrustum = false;
_data.computedVisibility = false;
_mesh.computedVisibilityChanged.execute(_mesh, false);
_state = STATE_OUTSIDE;
}
}
}
override public function clone() : AbstractController
{
return new MeshVisibilityController();;
}
}
}
|
package aerys.minko.scene.controller.mesh
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
import aerys.minko.scene.node.camera.AbstractCamera;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.FrustumCulling;
import aerys.minko.type.math.BoundingBox;
import aerys.minko.type.math.BoundingSphere;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
/**
* The MeshVisibilityController watches the Mesh and the active Camera of a Scene
* to determine whether the object is actually inside the view frustum or not.
*
* @author Jean-Marc Le Roux
*
*/
public final class MeshVisibilityController extends AbstractController
{
use namespace minko_math;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
private static const STATE_UNDEFINED : uint = 0;
private static const STATE_INSIDE : uint = 1;
private static const STATE_OUTSIDE : uint = 2;
private var _mesh : Mesh;
private var _state : uint;
private var _lastTest : int;
private var _boundingBox : BoundingBox;
private var _boundingSphere : BoundingSphere;
private var _data : DataProvider;
private var _frustumCulling : uint;
private var _insideFrustum : Boolean;
public function get frustumCulling() : uint
{
return _frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
_frustumCulling = value;
if (_mesh && _mesh.root is Scene)
testCulling();
}
public function get insideFrustum() : Boolean
{
return _insideFrustum;
}
public function get computedVisibility() : Boolean
{
return _data.computedVisibility;
}
public function MeshVisibilityController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
_data = new DataProvider();
_data.setProperty('computedVisibility', false);
_boundingBox = new BoundingBox(Vector4.ZERO, Vector4.ONE);
_boundingSphere = new BoundingSphere(Vector4.ZERO, 0.);
_state = STATE_UNDEFINED;
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
if (_mesh != null)
throw new Error();
_mesh = target;
target.added.add(addedHandler);
target.removed.add(removedHandler);
if (target.root is Scene)
addedHandler(target, target.root as Scene);
if (_frustumCulling)
testCulling();
}
private function targetRemovedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
_mesh = null;
target.added.remove(addedHandler);
target.removed.remove(removedHandler);
if (target.root is Scene)
removedHandler(target, target.root as Scene);
}
private function addedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = mesh.scene;
if (!scene)
return ;
scene.bindings.addCallback('worldToScreen', worldToScreenChangedHandler);
meshLocalToWorldChangedHandler(mesh, mesh.getLocalToWorldTransform());
mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler);
mesh.computedVisibilityChanged.add(computedVisiblityChangedHandler);
mesh.bindings.addProvider(_data);
}
private function removedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = ancestor.scene;
if (!scene)
return ;
scene.bindings.removeCallback('worldToScreen', worldToScreenChangedHandler);
mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler);
mesh.computedVisibilityChanged.remove(computedVisiblityChangedHandler);
mesh.bindings.removeProvider(_data);
}
private function computedVisiblityChangedHandler(node : ISceneNode,
computedVisibility : Boolean) : void
{
_data.computedVisibility = computedVisibility;
}
private function worldToScreenChangedHandler(bindings : DataBindings,
propertyName : String,
oldValue : Matrix4x4,
newValue : Matrix4x4) : void
{
testCulling();
}
private function meshLocalToWorldChangedHandler(mesh : Mesh, transform : Matrix4x4) : void
{
var geom : Geometry = _mesh.geometry;
var culling : uint = _frustumCulling;
if (!geom.boundingBox || !geom.boundingSphere || culling == FrustumCulling.DISABLED)
return ;
if (culling & FrustumCulling.BOX)
transform.transformRawVectors(geom.boundingBox._vertices, _boundingBox._vertices);
if (culling & FrustumCulling.SPHERE)
{
var center : Vector4 = transform.transformVector(geom.boundingSphere.center);
var scale : Vector4 = transform.deltaTransformVector(Vector4.ONE);
var radius : Number = geom.boundingSphere.radius * Math.max(
Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z)
);
_boundingSphere.update(center, radius);
}
testCulling();
}
private function testCulling() : void
{
var culling : uint = _frustumCulling;
if (culling != FrustumCulling.DISABLED)
{
_data.computedVisibility = true;
return;
}
if (_mesh && _mesh.geometry.boundingBox && _mesh.visible)
{
var camera : AbstractCamera = (_mesh.root as Scene).activeCamera;
if (!camera)
return ;
_lastTest = camera.frustum.testBoundingVolume(
_boundingSphere,
_boundingBox,
null,
culling,
_lastTest
);
var inside : Boolean = _lastTest == -1;
if (inside && _state != STATE_INSIDE)
{
_insideFrustum = true;
_data.computedVisibility = _mesh.parent.computedVisibility && _mesh.visible;
_mesh.computedVisibilityChanged.execute(_mesh, computedVisibility);
_state = STATE_INSIDE;
}
else if (!inside && _state != STATE_OUTSIDE)
{
_insideFrustum = false;
_data.computedVisibility = false;
_mesh.computedVisibilityChanged.execute(_mesh, false);
_state = STATE_OUTSIDE;
}
}
}
override public function clone() : AbstractController
{
return new MeshVisibilityController();
}
}
}
|
fix MeshVisiblityController to make sure it adds its data provider to the mesh bindings when its added to the scene
|
fix MeshVisiblityController to make sure it adds its data provider to the mesh bindings when its added to the scene
|
ActionScript
|
mit
|
aerys/minko-as3
|
788715ea0d2ec2cf60df8ace3f79f63afe3e932a
|
src/com/google/analytics/core/DomainNameMode.as
|
src/com/google/analytics/core/DomainNameMode.as
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
* Marc Alcaraz <[email protected]>.
*/
package com.google.analytics.core
{
/**
* The domain name mode enumeration class.
*/
public class DomainNameMode
{
/**
* @private
*/
private var _value:int;
/**
* @private
*/
private var _name:String;
/**
* Creates a new DomainNameMode instance.
* @param value The enumeration value representation.
* @param name The enumeration name representation.
*/
public function DomainNameMode( value:int = 0, name:String = "" )
{
_value = value;
_name = name;
}
/**
* Returns the primitive value of the object.
* @return the primitive value of the object.
*/
public function valueOf():int
{
return _value;
}
/**
* Returns the String representation of the object.
* @return the String representation of the object.
*/
public function toString():String
{
return _name;
}
/**
* Determinates the "none" DomainNameMode value.
* <p>"none" is used in the following two situations :</p>
* <p>- You want to disable tracking across hosts.</p>
* <p>- You want to set up tracking across two separate domains.</p>
* <p>Cross- domain tracking requires configuration of the setAllowLinker() and link() methods.</p>
*/
public static const none:DomainNameMode = new DomainNameMode( 0, "none" );
/**
* Attempts to automaticaly resolve the domain name.
*/
public static const auto:DomainNameMode = new DomainNameMode( 1, "auto" );
/**
* Custom is used to set explicitly to your domain name if your website spans multiple hostnames,
* and you want to track visitor behavior across all hosts.
* <p>For example, if you have two hosts : <code>server1.example.com</code> and <code>server2.example.com</code>,
* you would set the domain name as follows :
* <pre class="prettyprint">
* pageTracker.setDomainName( new Domain( DomainName.custom, ".example.com" ) ) ;
* </p>
*/
public static const custom:DomainNameMode = new DomainNameMode( 2, "custom" );
}
}
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
* Marc Alcaraz <[email protected]>.
*/
package com.google.analytics.core
{
/**
* The domain name mode enumeration class.
*/
public class DomainNameMode
{
/**
* @private
*/
private var _value:int;
/**
* @private
*/
private var _name:String;
/**
* Creates a new DomainNameMode instance.
* @param value The enumeration value representation.
* @param name The enumeration name representation.
*/
public function DomainNameMode( value:int = 0, name:String = "" )
{
_value = value;
_name = name;
}
/**
* Returns the primitive value of the object.
* @return the primitive value of the object.
*/
public function valueOf():int
{
return _value;
}
/**
* Returns the String representation of the object.
* @return the String representation of the object.
*/
public function toString():String
{
return _name;
}
/**
* Determinates the "none" DomainNameMode value.
* <p>"none" is used in the following two situations :</p>
* <p>- You want to disable tracking across hosts.</p>
* <p>- You want to set up tracking across two separate domains.</p>
* <p>Cross- domain tracking requires configuration of the setAllowLinker() and link() methods.</p>
*/
public static const none:DomainNameMode = new DomainNameMode( 0, "none" );
/**
* Attempts to automaticaly resolve the domain name.
*/
public static const auto:DomainNameMode = new DomainNameMode( 1, "auto" );
/**
* Custom is used to set explicitly to your domain name if your website spans multiple hostnames,
* and you want to track visitor behavior across all hosts.
* <p>For example, if you have two hosts : <code>server1.example.com</code> and <code>server2.example.com</code>,
* you would set the domain name as follows : </p>
* <pre class="prettyprint">
* pageTracker.setDomainName( new Domain( DomainName.custom, ".example.com" ) ) ;
* </pre>
*/
public static const custom:DomainNameMode = new DomainNameMode( 2, "custom" );
}
}
|
fix asdoc comment again
|
fix asdoc comment again
|
ActionScript
|
apache-2.0
|
nsdevaraj/gaforflash,nsdevaraj/gaforflash,minimedj/gaforflash,minimedj/gaforflash
|
1bb2d98a5ff0ed355424df3e4f33fc65cc927f75
|
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 {
// 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;
}
}
|
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 = {};
// internal event
public static const ACTIVATE:String = "ksp.activate";
//------------------------------------------------------------
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);
}
sendMessage(KrewScenarioPlayer.ACTIVATE);
}
//------------------------------------------------------------
// 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;
}
}
|
Update KrewScenarioPlayer
|
Update KrewScenarioPlayer
|
ActionScript
|
mit
|
tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework
|
4fe6860e926ea6407c71d60c7a01f3738ca7f556
|
src/main/as/flump/export/Atlas.as
|
src/main/as/flump/export/Atlas.as
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.export {
import flash.display.Sprite;
import flash.filesystem.File;
import flash.geom.Rectangle;
public class Atlas
{
public var name :String;
public var w :int, h :int, id :int;
public var bins :Vector.<Rectangle> = new Vector.<Rectangle>();
public const textures :Vector.<PackedTexture> = new Vector.<PackedTexture>();
public function Atlas(name :String, w :int, h :int) {
this.name = name;
this.w = w;
this.h = h;
bins.push(new Rectangle(0, 0, w, h));
}
public function place (tex :PackedTexture, target :Rectangle, rotated :Boolean) :void {
tex.atlasX = target.x;
tex.atlasY = target.y;
tex.atlasRotated = rotated;
textures.push(tex);
trace("Packer " + tex);
var used :Rectangle =
new Rectangle(tex.atlasX, tex.atlasY, rotated ? tex.h : tex.w, rotated ? tex.w : tex.h);
const newBins :Vector.<Rectangle> = new Vector.<Rectangle>();
for each (var bin :Rectangle in bins) {
for each (var newBin :Rectangle in subtract(bin, used)) {
newBins.push(newBin);
}
}
bins = newBins;
}
public function subtract (space :Rectangle, area :Rectangle) :Vector.<Rectangle> {
const left :Vector.<Rectangle> = new Vector.<Rectangle>();
if (space.x < area.x) {
left.push(new Rectangle(space.x, space.y, area.left - space.x, space.height));
}
if (space.right > area.right) {
left.push(new Rectangle(area.right, space.y, space.right - area.right, space.height));
}
if (space.y < area.y) {
left.push(new Rectangle(space.x, space.y, space.width, area.top - space.y));
}
if (space.bottom > area.bottom) {
left.push(new Rectangle(space.x, area.bottom, space.width, space.bottom - area.bottom));
}
return left;
}
public function publish (dir :File) :void {
var constructed :Sprite = new Sprite();
for each (var tex :PackedTexture in textures) {
constructed.addChild(tex.holder);
tex.holder.x = tex.atlasX;
tex.holder.y = tex.atlasY;
}
PngPublisher.publish(dir.resolvePath(name + ".png"), w, h, constructed);
}
public function toXml () :String {
var xml :String = "<atlas name='" + name + "' filename='" + name + ".png'>\n";
for each (var tex :PackedTexture in textures) {
xml += " <texture name='" + tex.tex.name + "' xOffset='" + tex.offset.x +
"' yOffset='" + tex.offset.y + "' md5='" + tex.tex.md5 +
"' xAtlas='" + tex.atlasX + "' yAtlas='" + tex.atlasY + "'/>\n";
}
return xml + "</atlas>\n";
}
}
}
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.export {
import flash.display.Sprite;
import flash.filesystem.File;
import flash.geom.Rectangle;
public class Atlas
{
public var name :String;
public var w :int, h :int, id :int;
public var bins :Vector.<Rectangle> = new Vector.<Rectangle>();
public const textures :Vector.<PackedTexture> = new Vector.<PackedTexture>();
public function Atlas(name :String, w :int, h :int) {
this.name = name;
this.w = w;
this.h = h;
bins.push(new Rectangle(0, 0, w, h));
}
public function place (tex :PackedTexture, target :Rectangle, rotated :Boolean) :void {
tex.atlasX = target.x;
tex.atlasY = target.y;
tex.atlasRotated = rotated;
textures.push(tex);
trace("Packer " + tex);
var used :Rectangle =
new Rectangle(tex.atlasX, tex.atlasY, rotated ? tex.h : tex.w, rotated ? tex.w : tex.h);
const newBins :Vector.<Rectangle> = new Vector.<Rectangle>();
for each (var bin :Rectangle in bins) {
for each (var newBin :Rectangle in subtract(bin, used)) {
newBins.push(newBin);
}
}
bins = newBins;
}
public function subtract (space :Rectangle, area :Rectangle) :Vector.<Rectangle> {
const left :Vector.<Rectangle> = new Vector.<Rectangle>();
if (space.x < area.x) {
left.push(new Rectangle(space.x, space.y, area.left - space.x, space.height));
}
if (space.right > area.right) {
left.push(new Rectangle(area.right, space.y, space.right - area.right, space.height));
}
if (space.y < area.y) {
left.push(new Rectangle(space.x, space.y, space.width, area.top - space.y));
}
if (space.bottom > area.bottom) {
left.push(new Rectangle(space.x, area.bottom, space.width, space.bottom - area.bottom));
}
return left;
}
public function publish (dir :File) :void {
var constructed :Sprite = new Sprite();
for each (var tex :PackedTexture in textures) {
constructed.addChild(tex.holder);
tex.holder.x = tex.atlasX;
tex.holder.y = tex.atlasY;
}
PngPublisher.publish(dir.resolvePath(name + ".png"), w, h, constructed);
}
public function toXml () :String {
var xml :String = "<atlas name='" + name + "' filename='" + name + ".png'>\n";
for each (var tex :PackedTexture in textures) {
xml += " <texture name='" + tex.tex.name + "' xOffset='" + tex.offset.x +
"' yOffset='" + tex.offset.y + "' md5='" + tex.tex.md5 +
"' xAtlas='" + tex.atlasX + "' yAtlas='" + tex.atlasY +
"' wAtlas='" + tex.w + "' hAtlas='" + tex.h + "'/>\n";
}
return xml + "</atlas>\n";
}
}
}
|
Include the width of the image in the atlas in the xml
|
Include the width of the image in the atlas in the xml
|
ActionScript
|
mit
|
tconkling/flump,funkypandagame/flump,mathieuanthoine/flump,mathieuanthoine/flump,mathieuanthoine/flump,funkypandagame/flump,tconkling/flump
|
2aed725803def0e1680996dae641112226c1d4ef
|
exporter/src/main/as/flump/export/Atlas.as
|
exporter/src/main/as/flump/export/Atlas.as
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.export {
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.utils.IDataOutput;
import com.adobe.images.PNGEncoder;
import flump.SwfTexture;
import flump.mold.AtlasMold;
import flump.mold.AtlasTextureMold;
import com.threerings.util.Arrays;
public class Atlas
{
// The empty border size around the right and bottom edges of each texture, to prevent bleeding
public static const PADDING :int = 1;
public var name :String;
public function Atlas (name :String, w :int, h :int) {
this.name = name;
_width = w;
_height = h;
_mask = Arrays.create(_width * _height, false);
}
public function get area () :int { return _width * _height; }
public function get filename () :String { return name + ".png"; }
public function get used () :int {
var used :int = 0;
_nodes.forEach(function (n :Node, ..._) :void { used += n.bounds.width * n.bounds.height; });
return used;
}
public function writePNG (bytes :IDataOutput) :void {
var constructed :Sprite = new Sprite();
_nodes.forEach(function (node :Node, ..._) :void {
const tex :SwfTexture = node.texture;
const bm :Bitmap = new Bitmap(node.texture.toBitmapData(), "auto", true);
constructed.addChild(bm);
bm.x = node.bounds.x;
bm.y = node.bounds.y;
});
const bd :BitmapData =
SwfTexture.renderToBitmapData(constructed, _width, _height);
bytes.writeBytes(PNGEncoder.encode(bd));
}
public function toMold () :AtlasMold {
const mold :AtlasMold = new AtlasMold();
mold.file = name + ".png";
_nodes.forEach(function (node :Node, ..._) :void {
const tex :SwfTexture = node.texture;
const texMold :AtlasTextureMold = new AtlasTextureMold();
texMold.symbol = tex.symbol;
texMold.bounds = new Rectangle(node.bounds.x, node.bounds.y, tex.w, tex.h);
texMold.offset = new Point(tex.offset.x, tex.offset.y);
mold.textures.push(texMold);
});
return mold;
}
// Try to place a texture in this atlas, return true if it fit
public function place (tex :SwfTexture) :Boolean {
var w :int = tex.w + PADDING;
var h :int = tex.h + PADDING;
if (w > _width || h > _height) {
return false;
}
var found :Boolean = false;
for (var yy :int = 0; yy < _height - h && !found; ++yy) {
for (var xx :int = 0; xx <= _width - w; ++xx) {
// if our right-most pixel is masked, jump ahead by that much
if (maskAt(xx + w - 1, yy)) {
xx += w;
continue;
}
if (!isMasked(xx, yy, w, h)) {
_nodes.push(new Node(xx, yy, tex));
setMasked(xx, yy, w, h);
found = true;
break;
}
}
}
return found;
}
protected function isMasked (x :int, y :int, w :int, h :int) :Boolean {
var xMax :int = x + w - 1;
var yMax :int = y + h - 1;
// fail fast on extents
if (maskAt(x, y) || maskAt(x, yMax) || maskAt(xMax, y) || maskAt(xMax, yMax)) {
return true;
}
for (var yy :int = y + 1; yy < yMax; ++yy) {
for (var xx :int = x + 1; xx < xMax; ++xx) {
if (maskAt(xx, yy)) {
return true;
}
}
}
return false;
}
protected function setMasked (x :int, y :int, w: int, h :int) :void {
for (var yy :int = y; yy < y + h; ++yy) {
for (var xx :int = x; xx < x + w; ++xx) {
_mask[(yy * _width) + xx] = true;
}
}
}
protected function maskAt (xx :int, yy :int) :Boolean {
return _mask[(yy * _width) + xx];
}
protected var _nodes :Array = [];
protected var _width :int;
protected var _height :int;
protected var _mask :Array;
}
}
import flash.geom.Rectangle;
import flump.SwfTexture;
class Node
{
public var bounds :Rectangle;
public var texture :SwfTexture;
public function Node (x :int, y :int, texture :SwfTexture) {
this.texture = texture;
this.bounds = new Rectangle(x, y, texture.w, texture.h);
}
}
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.export {
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.utils.IDataOutput;
import com.adobe.images.PNGEncoder;
import flump.SwfTexture;
import flump.mold.AtlasMold;
import flump.mold.AtlasTextureMold;
import com.threerings.util.Arrays;
public class Atlas
{
// The empty border size around the right and bottom edges of each texture, to prevent bleeding
public static const PADDING :int = 1;
public var name :String;
public function Atlas (name :String, w :int, h :int) {
this.name = name;
_width = w;
_height = h;
_mask = Arrays.create(_width * _height, false);
}
public function get area () :int { return _width * _height; }
public function get filename () :String { return name + ".png"; }
public function get used () :int {
var used :int = 0;
_nodes.forEach(function (n :Node, ..._) :void { used += n.bounds.width * n.bounds.height; });
return used;
}
public function writePNG (bytes :IDataOutput) :void {
var constructed :Sprite = new Sprite();
_nodes.forEach(function (node :Node, ..._) :void {
const tex :SwfTexture = node.texture;
const bm :Bitmap = new Bitmap(node.texture.toBitmapData(), "auto", true);
constructed.addChild(bm);
bm.x = node.bounds.x;
bm.y = node.bounds.y;
});
const bd :BitmapData =
SwfTexture.renderToBitmapData(constructed, _width, _height);
bytes.writeBytes(PNGEncoder.encode(bd));
}
public function toMold () :AtlasMold {
const mold :AtlasMold = new AtlasMold();
mold.file = name + ".png";
_nodes.forEach(function (node :Node, ..._) :void {
const tex :SwfTexture = node.texture;
const texMold :AtlasTextureMold = new AtlasTextureMold();
texMold.symbol = tex.symbol;
texMold.bounds = new Rectangle(node.bounds.x, node.bounds.y, tex.w, tex.h);
texMold.offset = new Point(tex.offset.x, tex.offset.y);
mold.textures.push(texMold);
});
return mold;
}
// Try to place a texture in this atlas, return true if it fit
public function place (tex :SwfTexture) :Boolean {
var w :int = tex.w + PADDING;
var h :int = tex.h + PADDING;
if (w > _width || h > _height) {
return false;
}
var found :Boolean = false;
for (var yy :int = 0; yy <= _height - h && !found; ++yy) {
for (var xx :int = 0; xx <= _width - w; ++xx) {
// if our right-most pixel is masked, jump ahead by that much
if (maskAt(xx + w - 1, yy)) {
xx += w;
continue;
}
if (!isMasked(xx, yy, w, h)) {
_nodes.push(new Node(xx, yy, tex));
setMasked(xx, yy, w, h);
found = true;
break;
}
}
}
return found;
}
protected function isMasked (x :int, y :int, w :int, h :int) :Boolean {
var xMax :int = x + w - 1;
var yMax :int = y + h - 1;
// fail fast on extents
if (maskAt(x, y) || maskAt(x, yMax) || maskAt(xMax, y) || maskAt(xMax, yMax)) {
return true;
}
for (var yy :int = y + 1; yy < yMax; ++yy) {
for (var xx :int = x + 1; xx < xMax; ++xx) {
if (maskAt(xx, yy)) {
return true;
}
}
}
return false;
}
protected function setMasked (x :int, y :int, w: int, h :int) :void {
for (var yy :int = y; yy < y + h; ++yy) {
for (var xx :int = x; xx < x + w; ++xx) {
_mask[(yy * _width) + xx] = true;
}
}
}
protected function maskAt (xx :int, yy :int) :Boolean {
return _mask[(yy * _width) + xx];
}
protected var _nodes :Array = [];
protected var _width :int;
protected var _height :int;
protected var _mask :Array;
}
}
import flash.geom.Rectangle;
import flump.SwfTexture;
class Node
{
public var bounds :Rectangle;
public var texture :SwfTexture;
public function Node (x :int, y :int, texture :SwfTexture) {
this.texture = texture;
this.bounds = new Rectangle(x, y, texture.w, texture.h);
}
}
|
Fix an off-by-one error causing an occasional infinite loop
|
Fix an off-by-one error causing an occasional infinite loop
|
ActionScript
|
mit
|
mathieuanthoine/flump,funkypandagame/flump,mathieuanthoine/flump,tconkling/flump,tconkling/flump,funkypandagame/flump,mathieuanthoine/flump
|
b8bf177636594010164556b3251dfe6cb683186b
|
frameworks/projects/Core/src/main/flex/org/apache/flex/utils/StringUtil.as
|
frameworks/projects/Core/src/main/flex/org/apache/flex/utils/StringUtil.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.utils
{
/**
* The StringUtil utility class is an all-static class with methods for
* working with String objects.
* You do not create instances of StringUtil;
* instead you call methods such as
* the <code>StringUtil.substitute()</code> method.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
* @productversion FlexJS 0.0
*/
public class StringUtil extends StringTrimmer
{
public function StringUtil()
{
throw new Error("StringUtil should not be instantiated.");
}
/**
* Substitutes "{n}" tokens within the specified string
* with the respective arguments passed in.
*
* Note that this uses String.replace and "$" can have special
* meaning in the argument strings escape by using "$$".
*
* @param str The string to make substitutions in.
* This string can contain special tokens of the form
* <code>{n}</code>, where <code>n</code> is a zero based index,
* that will be replaced with the additional parameters
* found at that index if specified.
*
* @param rest Additional parameters that can be substituted
* in the <code>str</code> parameter at each <code>{n}</code>
* location, where <code>n</code> is an integer (zero based)
* index value into the array of values specified.
* If the first parameter is an array this array will be used as
* a parameter list.
* This allows reuse of this routine in other methods that want to
* use the ... rest signature.
* For example <pre>
* public function myTracer(str:String, ... rest):void
* {
* label.text += StringUtil.substitute(str, rest) + "\n";
* } </pre>
*
* @return New string with all of the <code>{n}</code> tokens
* replaced with the respective arguments specified.
*
* @example
*
* var str:String = "here is some info '{0}' and {1}";
* trace(StringUtil.substitute(str, 15.4, true));
*
* // this will output the following string:
* // "here is some info '15.4' and true"
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
* @productversion FlexJS 0.0
*/
public static function substitute(str:String, ... rest):String
{
if (str == null) return '';
// Replace all of the parameters in the msg string.
var len:uint = rest.length;
var args:Array;
if (len == 1 && rest[0] is Array)
{
args = rest[0] as Array;
len = args.length;
}
else
{
args = rest;
}
for (var i:int = 0; i < len; i++)
{
str = str.replace(new RegExp("\\{"+i+"\\}", "g"), args[i]);
}
return str;
}
/**
* Returns a string consisting of a specified string
* concatenated with itself a specified number of times.
*
* @param str The string to be repeated.
*
* @param n The repeat count.
*
* @return The repeated string.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4.1
* @productversion FlexJS 0.0
*/
public static function repeat(str:String, n:int):String
{
if (n == 0)
return "";
var a:Array = [];
for (var i:int = 0; i < n; i++)
{
a.push(str);
}
return a.join("");
}
/**
* Removes "unallowed" characters from a string.
* A "restriction string" such as <code>"A-Z0-9"</code>
* is used to specify which characters are allowed.
* This method uses the same logic as the <code>restrict</code>
* property of TextField.
*
* @param str The input string.
*
* @param restrict The restriction string.
*
* @return The input string, minus any characters
* that are not allowed by the restriction string.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4.1
* @productversion FlexJS 0.0
*/
public static function restrict(str:String, restrict:String):String
{
// A null 'restrict' string means all characters are allowed.
if (restrict == null)
return str;
// An empty 'restrict' string means no characters are allowed.
if (restrict == "")
return "";
// Otherwise, we need to test each character in 'str'
// to determine whether the 'restrict' string allows it.
var charCodes:Array = [];
var n:int = str.length;
for (var i:int = 0; i < n; i++)
{
var charCode:uint = str.charCodeAt(i);
if (testCharacter(charCode, restrict))
charCodes.push(charCode);
}
return String.fromCharCode.apply(null, charCodes);
}
/**
* @private
* Helper method used by restrict() to test each character
* in the input string against the restriction string.
* The logic in this method implements the same algorithm
* as in TextField's 'restrict' property (which is quirky,
* such as how it handles a '-' at the beginning of the
* restriction string).
*/
private static function testCharacter(charCode:uint,
restrict:String):Boolean
{
var allowIt:Boolean = false;
var inBackSlash:Boolean = false;
var inRange:Boolean = false;
var setFlag:Boolean = true;
var lastCode:uint = 0;
var n:int = restrict.length;
var code:uint;
if (n > 0)
{
code = restrict.charCodeAt(0);
if (code == 94) // caret
allowIt = true;
}
for (var i:int = 0; i < n; i++)
{
code = restrict.charCodeAt(i)
var acceptCode:Boolean = false;
if (!inBackSlash)
{
if (code == 45) // hyphen
inRange = true;
else if (code == 94) // caret
setFlag = !setFlag;
else if (code == 92) // backslash
inBackSlash = true;
else
acceptCode = true;
}
else
{
acceptCode = true;
inBackSlash = false;
}
if (acceptCode)
{
if (inRange)
{
if (lastCode <= charCode && charCode <= code)
allowIt = setFlag;
inRange = false;
lastCode = 0;
}
else
{
if (charCode == code)
allowIt = setFlag;
lastCode = code;
}
}
}
return allowIt;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.utils
{
/**
* The StringUtil utility class is an all-static class with methods for
* working with String objects.
* You do not create instances of StringUtil;
* instead you call methods such as
* the <code>StringUtil.substitute()</code> method.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
* @productversion FlexJS 0.0
*/
public class StringUtil
{
public function StringUtil()
{
throw new Error("StringUtil should not be instantiated.");
}
/**
* Substitutes "{n}" tokens within the specified string
* with the respective arguments passed in.
*
* Note that this uses String.replace and "$" can have special
* meaning in the argument strings escape by using "$$".
*
* @param str The string to make substitutions in.
* This string can contain special tokens of the form
* <code>{n}</code>, where <code>n</code> is a zero based index,
* that will be replaced with the additional parameters
* found at that index if specified.
*
* @param rest Additional parameters that can be substituted
* in the <code>str</code> parameter at each <code>{n}</code>
* location, where <code>n</code> is an integer (zero based)
* index value into the array of values specified.
* If the first parameter is an array this array will be used as
* a parameter list.
* This allows reuse of this routine in other methods that want to
* use the ... rest signature.
* For example <pre>
* public function myTracer(str:String, ... rest):void
* {
* label.text += StringUtil.substitute(str, rest) + "\n";
* } </pre>
*
* @return New string with all of the <code>{n}</code> tokens
* replaced with the respective arguments specified.
*
* @example
*
* var str:String = "here is some info '{0}' and {1}";
* trace(StringUtil.substitute(str, 15.4, true));
*
* // this will output the following string:
* // "here is some info '15.4' and true"
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
* @productversion FlexJS 0.0
*/
public static function substitute(str:String, ... rest):String
{
if (str == null) return '';
// Replace all of the parameters in the msg string.
var len:uint = rest.length;
var args:Array;
if (len == 1 && rest[0] is Array)
{
args = rest[0] as Array;
len = args.length;
}
else
{
args = rest;
}
for (var i:int = 0; i < len; i++)
{
str = str.replace(new RegExp("\\{"+i+"\\}", "g"), args[i]);
}
return str;
}
/**
* Returns a string consisting of a specified string
* concatenated with itself a specified number of times.
*
* @param str The string to be repeated.
*
* @param n The repeat count.
*
* @return The repeated string.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4.1
* @productversion FlexJS 0.0
*/
public static function repeat(str:String, n:int):String
{
if (n == 0)
return "";
var a:Array = [];
for (var i:int = 0; i < n; i++)
{
a.push(str);
}
return a.join("");
}
/**
* Removes "unallowed" characters from a string.
* A "restriction string" such as <code>"A-Z0-9"</code>
* is used to specify which characters are allowed.
* This method uses the same logic as the <code>restrict</code>
* property of TextField.
*
* @param str The input string.
*
* @param restrict The restriction string.
*
* @return The input string, minus any characters
* that are not allowed by the restriction string.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4.1
* @productversion FlexJS 0.0
*/
public static function restrict(str:String, restrict:String):String
{
// A null 'restrict' string means all characters are allowed.
if (restrict == null)
return str;
// An empty 'restrict' string means no characters are allowed.
if (restrict == "")
return "";
// Otherwise, we need to test each character in 'str'
// to determine whether the 'restrict' string allows it.
var charCodes:Array = [];
var n:int = str.length;
for (var i:int = 0; i < n; i++)
{
var charCode:uint = str.charCodeAt(i);
if (testCharacter(charCode, restrict))
charCodes.push(charCode);
}
return String.fromCharCode.apply(null, charCodes);
}
/**
* Removes all whitespace characters from the beginning and end
* of the specified string.
*
* @param str The String whose whitespace should be trimmed.
*
* @return Updated String where whitespace was removed from the
* beginning and end.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function trim(str:String):String
{
return StringTrimmer.trim(str);
}
/**
* Removes all whitespace characters from the beginning and end
* of each element in an Array, where the Array is stored as a String.
*
* @param value The String whose whitespace should be trimmed.
*
* @param separator The String that delimits each Array element in the string.
*
* @return Array where whitespace was removed from the
* beginning and end of each element.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function splitAndTrim(value:String, delimiter:String):Array
{
return StringTrimmer.splitAndTrim(value,delimiter);
}
/**
* Removes all whitespace characters from the beginning and end
* of each element in an Array, where the Array is stored as a String.
*
* @param value The String whose whitespace should be trimmed.
*
* @param separator The String that delimits each Array element in the string.
*
* @return Updated String where whitespace was removed from the
* beginning and end of each element.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function trimArrayElements(value:String, delimiter:String):String
{
return StringTrimmer.trimArrayElements(value,delimiter);
}
/**
* Returns <code>true</code> if the specified string is
* a single space, tab, carriage return, newline, or formfeed character.
*
* @param str The String that is is being queried.
*
* @return <code>true</code> if the specified string is
* a single space, tab, carriage return, newline, or formfeed character.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function isWhitespace(character:String):Boolean
{
return StringTrimmer.isWhitespace(character);
}
/**
* @private
* Helper method used by restrict() to test each character
* in the input string against the restriction string.
* The logic in this method implements the same algorithm
* as in TextField's 'restrict' property (which is quirky,
* such as how it handles a '-' at the beginning of the
* restriction string).
*/
private static function testCharacter(charCode:uint,
restrict:String):Boolean
{
var allowIt:Boolean = false;
var inBackSlash:Boolean = false;
var inRange:Boolean = false;
var setFlag:Boolean = true;
var lastCode:uint = 0;
var n:int = restrict.length;
var code:uint;
if (n > 0)
{
code = restrict.charCodeAt(0);
if (code == 94) // caret
allowIt = true;
}
for (var i:int = 0; i < n; i++)
{
code = restrict.charCodeAt(i)
var acceptCode:Boolean = false;
if (!inBackSlash)
{
if (code == 45) // hyphen
inRange = true;
else if (code == 94) // caret
setFlag = !setFlag;
else if (code == 92) // backslash
inBackSlash = true;
else
acceptCode = true;
}
else
{
acceptCode = true;
inBackSlash = false;
}
if (acceptCode)
{
if (inRange)
{
if (lastCode <= charCode && charCode <= code)
allowIt = setFlag;
inRange = false;
lastCode = 0;
}
else
{
if (charCode == code)
allowIt = setFlag;
lastCode = code;
}
}
}
return allowIt;
}
}
}
|
Make StringUtil not extend StringTrimmer, and delegate relevant methods instead.
|
Make StringUtil not extend StringTrimmer, and delegate relevant methods instead.
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
06672804bf658b04680377333b5907e45edff608
|
src/aerys/minko/render/shader/part/phong/attenuation/CubeShadowMapAttenuationShaderPart.as
|
src/aerys/minko/render/shader/part/phong/attenuation/CubeShadowMapAttenuationShaderPart.as
|
package aerys.minko.render.shader.part.phong.attenuation
{
import aerys.minko.render.material.phong.PhongProperties;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.part.phong.LightAwareShaderPart;
import aerys.minko.type.enum.SamplerDimension;
import aerys.minko.type.enum.SamplerFiltering;
import aerys.minko.type.enum.SamplerMipMapping;
import aerys.minko.type.enum.SamplerWrapping;
public class CubeShadowMapAttenuationShaderPart extends LightAwareShaderPart implements IAttenuationShaderPart
{
private static const DEFAULT_BIAS : Number = 1 / 10000;
public function CubeShadowMapAttenuationShaderPart(main : Shader)
{
super(main);
}
public function getAttenuation(lightId : uint) : SFloat
{
// retrieve shadow bias
var shadowBias : SFloat;
if (meshBindings.propertyExists(PhongProperties.SHADOW_BIAS))
shadowBias = meshBindings.getParameter(PhongProperties.SHADOW_BIAS, 1);
else if (sceneBindings.propertyExists(PhongProperties.SHADOW_BIAS))
shadowBias = sceneBindings.getParameter(PhongProperties.SHADOW_BIAS, 1);
else
shadowBias = float(DEFAULT_BIAS);
// retrieve depthmap, transformation matrix, zNear and zFar
var worldToLight : SFloat = getLightParameter(lightId, 'worldToLocal', 16);
var zNear : SFloat = getLightParameter(lightId, 'zNear', 1);
var zFar : SFloat = getLightParameter(lightId, 'zFar', 1);
var cubeDepthMap : SFloat = getLightTextureParameter(lightId, 'shadowMapCube',
SamplerFiltering.NEAREST,
SamplerMipMapping.DISABLE,
SamplerWrapping.CLAMP,
SamplerDimension.CUBE);
// retrieve precompute depth
var positionFromLight : SFloat = interpolate(multiply4x4(vsWorldPosition, worldToLight));
var precomputedDepth : SFloat = unpack(sampleTexture(cubeDepthMap, positionFromLight));
// retrieve real depth
var currentDepth : SFloat = divide(subtract(length(positionFromLight.xyz), zNear), subtract(zFar, zNear));
currentDepth = min(subtract(1, shadowBias), currentDepth);
return lessEqual(currentDepth, add(shadowBias, precomputedDepth));
}
}
}
|
package aerys.minko.render.shader.part.phong.attenuation
{
import aerys.minko.render.material.phong.PhongProperties;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.part.phong.LightAwareShaderPart;
import aerys.minko.type.enum.SamplerDimension;
import aerys.minko.type.enum.SamplerFiltering;
import aerys.minko.type.enum.SamplerMipMapping;
import aerys.minko.type.enum.SamplerWrapping;
public class CubeShadowMapAttenuationShaderPart extends LightAwareShaderPart implements IAttenuationShaderPart
{
private static const DEFAULT_BIAS : Number = 1 / 10000;
public function CubeShadowMapAttenuationShaderPart(main : Shader)
{
super(main);
}
public function getAttenuation(lightId : uint) : SFloat
{
// retrieve shadow bias
var shadowBias : SFloat;
if (meshBindings.propertyExists(PhongProperties.SHADOW_BIAS))
shadowBias = meshBindings.getParameter(PhongProperties.SHADOW_BIAS, 1);
else if (sceneBindings.propertyExists(PhongProperties.SHADOW_BIAS))
shadowBias = sceneBindings.getParameter(PhongProperties.SHADOW_BIAS, 1);
else
shadowBias = float(DEFAULT_BIAS);
// retrieve depthmap, transformation matrix, zNear and zFar
var worldToLight : SFloat = getLightParameter(lightId, 'worldToLocal', 16);
var zNear : SFloat = getLightParameter(lightId, 'shadowZNear', 1);
var zFar : SFloat = getLightParameter(lightId, 'shadowZFar', 1);
var cubeDepthMap : SFloat = getLightTextureParameter(lightId, 'shadowMapCube',
SamplerFiltering.NEAREST,
SamplerMipMapping.DISABLE,
SamplerWrapping.CLAMP,
SamplerDimension.CUBE);
// retrieve precompute depth
var positionFromLight : SFloat = interpolate(multiply4x4(vsWorldPosition, worldToLight));
var precomputedDepth : SFloat = unpack(sampleTexture(cubeDepthMap, positionFromLight));
// retrieve real depth
var currentDepth : SFloat = divide(subtract(length(positionFromLight.xyz), zNear), subtract(zFar, zNear));
currentDepth = min(subtract(1, shadowBias), currentDepth);
return lessEqual(currentDepth, add(shadowBias, precomputedDepth));
}
}
}
|
fix broken references to the 'zFar' and 'zNear' light properties in CubeShadowMapAttenuationShaderPart
|
fix broken references to the 'zFar' and 'zNear' light properties in CubeShadowMapAttenuationShaderPart
|
ActionScript
|
mit
|
aerys/minko-as3
|
ed45c5b41da97a0441c126bfdd5a509ee330b6c3
|
frameworks/projects/Core/src/main/flex/org/apache/flex/utils/StringTrimmer.as
|
frameworks/projects/Core/src/main/flex/org/apache/flex/utils/StringTrimmer.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.utils
{
/**
* The StringTrimmer class is a collection of static functions that provide utility
* features for trimming whitespace off Strings.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class StringTrimmer
{
/**
* @private
*/
public function StringTrimmer()
{
throw new Error("StringTrimmer should not be instantiated.");
}
/**
* Removes all whitespace characters from the beginning and end
* of the specified string.
*
* @param str The String whose whitespace should be trimmed.
*
* @return Updated String where whitespace was removed from the
* beginning and end.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function trim(str:String):String
{
if (str == null) return '';
var startIndex:int = 0;
while (isWhitespace(str.charAt(startIndex)))
++startIndex;
var endIndex:int = str.length - 1;
while (isWhitespace(str.charAt(endIndex)))
--endIndex;
if (endIndex >= startIndex)
return str.slice(startIndex, endIndex + 1);
else
return "";
}
/**
* Removes all whitespace characters from the beginning and end
* of each element in an Array, where the Array is stored as a String.
*
* @param value The String whose whitespace should be trimmed.
*
* @param separator The String that delimits each Array element in the string.
*
* @return Array where whitespace was removed from the
* beginning and end of each element.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function splitAndTrim(value:String, delimiter:String):Array
{
if (value != "" && value != null)
{
var items:Array = value.split(delimiter);
var len:int = items.length;
for (var i:int = 0; i < len; i++)
{
items[i] = StringTrimmer.trim(items[i]);
}
return items;
}
return [];
}
/**
* Removes all whitespace characters from the beginning and end
* of each element in an Array, where the Array is stored as a String.
*
* @param value The String whose whitespace should be trimmed.
*
* @param separator The String that delimits each Array element in the string.
*
* @return Updated String where whitespace was removed from the
* beginning and end of each element.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function trimArrayElements(value:String, delimiter:String):String
{
if (value != "" && value != null)
{
var items:Array = splitAndTrim(value, delimiter);
if (items.length > 0)
{
value = items.join(delimiter);
}
}
return value;
}
/**
* Returns <code>true</code> if the specified string is
* a single space, tab, carriage return, newline, or formfeed character.
*
* @param str The String that is is being queried.
*
* @return <code>true</code> if the specified string is
* a single space, tab, carriage return, newline, or formfeed character.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function isWhitespace(character:String):Boolean
{
switch (character)
{
case " ":
case "\t":
case "\r":
case "\n":
case "\f":
// non breaking space
case "\u00A0":
// line seperator
case "\u2028":
// paragraph seperator
case "\u2029":
// ideographic space
case "\u3000":
return true;
default:
return false;
}
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.utils
{
/**
* The StringTrimmer class is a collection of static functions that provide utility
* features for trimming whitespace off Strings.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class StringTrimmer
{
/**
* @private
*/
public function StringTrimmer()
{
throw new Error("StringTrimmer should not be instantiated.");
}
/**
* Removes all whitespace characters from the beginning and end
* of the specified string.
*
* @param str The String whose whitespace should be trimmed.
*
* @return Updated String where whitespace was removed from the
* beginning and end.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
COMPILE::SWF
public static function trim(str:String):String
{
if (str == null) return '';
var startIndex:int = 0;
while (isWhitespace(str.charAt(startIndex)))
++startIndex;
var endIndex:int = str.length - 1;
while (isWhitespace(str.charAt(endIndex)))
--endIndex;
if (endIndex >= startIndex)
return str.slice(startIndex, endIndex + 1);
else
return "";
}
COMPILE::JS
public static function trim(str:String):String
{
if (str == null) return '';
return str.trim();
}
/**
* Removes all whitespace characters from the beginning and end
* of each element in an Array, where the Array is stored as a String.
*
* @param value The String whose whitespace should be trimmed.
*
* @param separator The String that delimits each Array element in the string.
*
* @return Array where whitespace was removed from the
* beginning and end of each element.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function splitAndTrim(value:String, delimiter:String):Array
{
if (value != "" && value != null)
{
var items:Array = value.split(delimiter);
var len:int = items.length;
for (var i:int = 0; i < len; i++)
{
items[i] = StringTrimmer.trim(items[i]);
}
return items;
}
return [];
}
/**
* Removes all whitespace characters from the beginning and end
* of each element in an Array, where the Array is stored as a String.
*
* @param value The String whose whitespace should be trimmed.
*
* @param separator The String that delimits each Array element in the string.
*
* @return Updated String where whitespace was removed from the
* beginning and end of each element.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function trimArrayElements(value:String, delimiter:String):String
{
if (value != "" && value != null)
{
var items:Array = splitAndTrim(value, delimiter);
if (items.length > 0)
{
value = items.join(delimiter);
}
}
return value;
}
/**
* Returns <code>true</code> if the specified string is
* a single space, tab, carriage return, newline, or formfeed character.
*
* @param str The String that is is being queried.
*
* @return <code>true</code> if the specified string is
* a single space, tab, carriage return, newline, or formfeed character.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function isWhitespace(character:String):Boolean
{
switch (character)
{
case " ":
case "\t":
case "\r":
case "\n":
case "\f":
// non breaking space
case "\u00A0":
// line seperator
case "\u2028":
// paragraph seperator
case "\u2029":
// ideographic space
case "\u3000":
return true;
default:
return false;
}
}
}
}
|
Use native trim() method in JS
|
Use native trim() method in JS
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
3ff51054946809f9381cf9d821af0c246de8db02
|
VectorEditorStandalone/src/org/jbei/registry/utils/StandaloneUtils.as
|
VectorEditorStandalone/src/org/jbei/registry/utils/StandaloneUtils.as
|
package org.jbei.registry.utils
{
import mx.collections.ArrayCollection;
import org.jbei.bio.enzymes.RestrictionEnzyme;
import org.jbei.registry.models.DNAFeature;
import org.jbei.registry.models.FeaturedDNASequence;
import org.jbei.registry.models.UserPreferences;
import org.jbei.registry.models.UserRestrictionEnzymes;
/**
* @author Zinovii Dmytriv
*/
public class StandaloneUtils
{
public static function standaloneSequence():FeaturedDNASequence {
var sequence:FeaturedDNASequence = new FeaturedDNASequence();
sequence.name = "pUC19"
sequence.sequence = "tcgcgcgtttcggtgatgacggtgaaaacctctgacacatgcagctcccggagacggtcacagcttgtctgtaagcggatgccgggagcagacaagcccgtcagggcgcgtcagcgggtgttggcgggtgtcggggctggcttaactatgcggcatcagagcagattgtactgagagtgcaccatatgcggtgtgaaataccgcacagatgcgtaaggagaaaataccgcatcaggcgccattcgccattcaggctgcgcaactgttgggaagggcgatcggtgcgggcctcttcgctattacgccagctggcgaaagggggatgtgctgcaaggcgattaagttgggtaacgccagggttttcccagtcacgacgttgtaaaacgacggccagtgaattcgagctcggtacccggggatcctctagagtcgacctgcaggcatgcaagcttggcgtaatcatggtcatagctgtttcctgtgtgaaattgttatccgctcacaattccacacaacatacgagccggaagcataaagtgtaaagcctggggtgcctaatgagtgagctaactcacattaattgcgttgcgctcactgcccgctttccagtcgggaaacctgtcgtgccagctgcattaatgaatcggccaacgcgcggggagaggcggtttgcgtattgggcgctcttccgcttcctcgctcactgactcgctgcgctcggtcgttcggctgcggcgagcggtatcagctcactcaaaggcggtaatacggttatccacagaatcaggggataacgcaggaaagaacatgtgagcaaaaggccagcaaaaggccaggaaccgtaaaaaggccgcgttgctggcgtttttccataggctccgcccccctgacgagcatcacaaaaatcgacgctcaagtcagaggtggcgaaacccgacaggactataaagataccaggcgtttccccctggaagctccctcgtgcgctctcctgttccgaccctgccgcttaccggatacctgtccgcctttctcccttcgggaagcgtggcgctttctcatagctcacgctgtaggtatctcagttcggtgtaggtcgttcgctccaagctgggctgtgtgcacgaaccccccgttcagcccgaccgctgcgccttatccggtaactatcgtcttgagtccaacccggtaagacacgacttatcgccactggcagcagccactggtaacaggattagcagagcgaggtatgtaggcggtgctacagagttcttgaagtggtggcctaactacggctacactagaagaacagtatttggtatctgcgctctgctgaagccagttaccttcggaaaaagagttggtagctcttgatccggcaaacaaaccaccgctggtagcggtggtttttttgtttgcaagcagcagattacgcgcagaaaaaaaggatctcaagaagatcctttgatcttttctacggggtctgacgctcagtggaacgaaaactcacgttaagggattttggtcatgagattatcaaaaaggatcttcacctagatccttttaaattaaaaatgaagttttaaatcaatctaaagtatatatgagtaaacttggtctgacagttaccaatgcttaatcagtgaggcacctatctcagcgatctgtctatttcgttcatccatagttgcctgactccccgtcgtgtagataactacgatacgggagggcttaccatctggccccagtgctgcaatgataccgcgagacccacgctcaccggctccagatttatcagcaataaaccagccagccggaagggccgagcgcagaagtggtcctgcaactttatccgcctccatccagtctattaattgttgccgggaagctagagtaagtagttcgccagttaatagtttgcgcaacgttgttgccattgctacaggcatcgtggtgtcacgctcgtcgtttggtatggcttcattcagctccggttcccaacgatcaaggcgagttacatgatcccccatgttgtgcaaaaaagcggttagctccttcggtcctccgatcgttgtcagaagtaagttggccgcagtgttatcactcatggttatggcagcactgcataattctcttactgtcatgccatccgtaagatgcttttctgtgactggtgagtactcaaccaagtcattctgagaatagtgtatgcggcgaccgagttgctcttgcccggcgtcaatacgggataataccgcgccacatagcagaactttaaaagtgctcatcattggaaaacgttcttcggggcgaaaactctcaaggatcttaccgctgttgagatccagttcgatgtaacccactcgtgcacccaactgatcttcagcatcttttactttcaccagcgtttctgggtgagcaaaaacaggaaggcaaaatgccgcaaaaaagggaataagggcgacacggaaatgttgaatactcatactcttcctttttcaatattattgaagcatttatcagggttattgtctcatgagcggatacatatttgaatgtatttagaaaaataaacaaataggggttccgcgcacatttccccgaaaagtgccacctgacgtctaagaaaccattattatcatgacattaacctataaaaataggcgtatcacgaggccctttcgtc";
sequence.features = new ArrayCollection();
sequence.features.addItem(new DNAFeature(146, 469, -1, "lacZalpha", null, "CDS"));
sequence.features.addItem(new DNAFeature(396, 452, -1, "multple cloning site", null, "misc_feature"));
sequence.features.addItem(new DNAFeature(514, 519, -1, "Plac promoter", null, "-10_signal"));
sequence.features.addItem(new DNAFeature(538, 543, -1, "Plac promoter", null, "-35_signal"));
sequence.features.addItem(new DNAFeature(563, 575, -1, "CAP protein binding site", null, "protein_bind"));
sequence.features.addItem(new DNAFeature(867, 1445, -1, "pMB1 origin of replication", null, "rep_origin"));
sequence.features.addItem(new DNAFeature(876, 1419, -1, "RNAII transcript", null, "misc_RNA"));
sequence.features.addItem(new DNAFeature(1273, 1278, 1, "RNAI promoter (clockwise); TTGAAG", null, "-35_signal"));
sequence.features.addItem(new DNAFeature(1295, 1300, 1, "RNAI promoter (clockwise) GCTACA", null, "-10_signal"));
sequence.features.addItem(new DNAFeature(1309, 1416, 1, "RNAI transcript", null, "misc_RNA"));
sequence.features.addItem(new DNAFeature(1429, 1434, -1, "RNAII promoter", null, "-10_signal"));
sequence.features.addItem(new DNAFeature(1450, 1455, -1, "RNAII promoter", null, "-35_signal"));
sequence.features.addItem(new DNAFeature(1626, 2486, -1, "bla", null, "CDS"));
sequence.features.addItem(new DNAFeature(2418, 2486, -1, "bla", null, "sig_peptide"));
sequence.features.addItem(new DNAFeature(2530, 2535, -1, "bla promoter", null, "-10_signal"));
sequence.features.addItem(new DNAFeature(2551, 2556, -1, "bla promoter", null, "-35_signal"));
/*CONFIG::digestion {
sequence.sequence = "CCTAATGAGTGAGCTAACTTACATTAATTGCGTTGCGCTCACTGCCCGGAATTCTTTCCAGTCGGGAAACCTGTCGTGCCAGCTGCATTAATGAATCGGCCAACGCGCGGGGAGAGGCGGTTTGCGTATTGGGCGCCAGGGTGGTTTTTCTTTTCACCAGTGAGACGGGCAACAGCTGATTGCCCTTCACCGCCTGGCCCTGAGAGAGTTGCAGCAAGCGGTCCACGCTGGTTTGCCCCAGCAGGCGAAAATCCTGTTTGATGGTGGTTAACGGCGGGATATAACATGAGCTGTCTTCGGTATCGTCGTATCCCACTACCGAGATGTCCGCACCAACGCGCAGCCCGGACTCGGTAATGGCGCGCATTGCGCCCAGCGCCATCTGATCGTTGGCAACCAGCATCGCAGTGGGAACGATGCCCTCATTCAGCATTTGCATGGTTTGTTGAAAACCGGACATGGCACTCCAGTCGCCTTCCCGTTCCGCTATCGGCTGAATTTGATTGCGAGTGAGATATTTATGCCAGCCAGCCAGACGCAGACGCGCCGAGACAGAACTTAATGGGCCCGCTAACAGCGCGATTTGCTGGTGACCCAATGCGACCAGATGCTCCACGCCCAGTCGCGTACCGTCTTCATGGGAGAAAATAATACTGTTGATGGGTGTCTGGTCAGAGACATCAAGAAATAACGCCGGAACATTAGTGCAGGCAGCTTCCACAGCAATGGCATCCTGGTCATCCAGCGGATAGTTAATGATCAGCCCACTGACGCGTTGCGCGAGAAGATTGTGCACCGCCGCTTTACAGGCTTCGACGCGCCAATCAGCAACGACTGTTTGCCCGCCAGTTGTTGTGCCACGCGGTTGGGAATGTAATTCAGCTCCGCCATCGCCGCTTCCACTTTTTCCCGCGTTTTCGCAGAAACGTGGCTGGCCTGGTTCACCACGCGGGAAACGGTCTGATAAGAGACACCGGCATACTCTGCGACATCGTATAACGTTACTGGTTTCACATTCACCACCCTGAATTGACTCTCTTCCGGGCGCTATCATGCCATACCGCGAAAGGTTTTGCGCCATTCGATGGTGTCCGGGATCTCGACGCTCTCCCTTATGCGACTCCTGCATTAGGAAGCAGCCCAGTAGTAGGTTGAGGCCGTTGAGCACCGCCGCCGCAAGGAATGGTGCATGCAAGGAAAGGCGATCGCGTTGCGTTGATGATGCCTAATTTATTGCAATATCCGGTGGCGCTGTTTGGCATTTTGCGTGCCGGGATGATCGTCGTAAACGTTAACCCGTTGTATACCCCGCGTGAGCTTGAGCATCAGCTTAACGATAGCGGCGCATCGGCGATTGTTATCGTGTCTAACTTTGCTCACACACTGGAAAAAGTGGTTGATAAAACCGCCGTTCAGCACGTAATTCTGACCCGTATGGGCGATCAGCTATCTACGGCAAAAGGCACGGTAGTCAATTTCGTTGTTAAATACATCAAGCGTTTGGTGCCGAAATACCATCTCGAGCTGCCAGATGCCATTTCATTTCGTAGCGCACTGCATAACGGCTACCGGATGCAGTACGTCAAACCCGAACTGGTGCCGGAAGATTTAGCTTTTCTGCAATACACCGGCGGCACCACTGGTGTGGCGAAAATCGGTTTGCCGGTGCCGTCGACGGAAGCCAAACTGGTGGATGATGATGATAATGAAGTACCACCAGGTCAACCGGGTGAGCTTTGTGTCAAAGGACCGCAGGTGATGCTGGGTTACTGGCAGCGTCCCGATGCTACCGATGAAATCATCAAAAATGGCTGGTTACACACCGGCGACCGGATATCAAAATCAATCCCTGTTCCACCATTCAACAATAAACTGAATGGGCTTTTTTGGGATGAAGATGAAGAGTTTGATTTAGGAGGAAACAGAATGCGCCCATTACATCCGATTGATTTTATATTCCTGTCACTAGAAAAAAGACAACAGCCTATGCATGTAGGTGGTTTATTTTTGTTTCAGATTCCTGATAACGCCCCAGACACCTTTATTCAGGATCTGGTGAATGATATCC";
sequence.features = new ArrayCollection();
sequence.features.addItem(new DNAFeature(1500, 1575, 1, "lacUV5 promoter", null, "promoter"));
sequence.features.addItem(new DNAFeature(1516, 1579, 1, "lac operator", null, "misc_binding"));
sequence.features.addItem(new DNAFeature(1595, 1614, 1, "RBS", null, "RBS"));
sequence.features.addItem(new DNAFeature(1615, 1800, 1, "fadD", null, "CDS"));
sequence.features.addItem(new DNAFeature(49, 1131, -1, "lacI", null, "CDS"));
}*/
return sequence;
}
public static function standaloneUserPreferences():UserPreferences
{
var userPreferences:UserPreferences = new UserPreferences();
userPreferences.bpPerRow = -1;
userPreferences.orfMinimumLength = 300;
userPreferences.sequenceFontSize = 11;
return userPreferences;
}
public static function standaloneUserRestrictionEnzymes():UserRestrictionEnzymes
{
return new UserRestrictionEnzymes();
}
}
}
|
package org.jbei.registry.utils
{
import mx.collections.ArrayCollection;
import org.jbei.bio.enzymes.RestrictionEnzyme;
import org.jbei.registry.models.DNAFeature;
import org.jbei.registry.models.FeaturedDNASequence;
import org.jbei.registry.models.UserPreferences;
import org.jbei.registry.models.UserRestrictionEnzymes;
/**
* @author Zinovii Dmytriv
*/
public class StandaloneUtils
{
public static function standaloneSequence():FeaturedDNASequence {
var sequence:FeaturedDNASequence = new FeaturedDNASequence();
sequence.name = "pUC19"
sequence.sequence = "tcgcgcgtttcggtgatgacggtgaaaacctctgacacatgcagctcccggagacggtcacagcttgtctgtaagcggatgccgggagcagacaagcccgtcagggcgcgtcagcgggtgttggcgggtgtcggggctggcttaactatgcggcatcagagcagattgtactgagagtgcaccatatgcggtgtgaaataccgcacagatgcgtaaggagaaaataccgcatcaggcgccattcgccattcaggctgcgcaactgttgggaagggcgatcggtgcgggcctcttcgctattacgccagctggcgaaagggggatgtgctgcaaggcgattaagttgggtaacgccagggttttcccagtcacgacgttgtaaaacgacggccagtgaattcgagctcggtacccggggatcctctagagtcgacctgcaggcatgcaagcttggcgtaatcatggtcatagctgtttcctgtgtgaaattgttatccgctcacaattccacacaacatacgagccggaagcataaagtgtaaagcctggggtgcctaatgagtgagctaactcacattaattgcgttgcgctcactgcccgctttccagtcgggaaacctgtcgtgccagctgcattaatgaatcggccaacgcgcggggagaggcggtttgcgtattgggcgctcttccgcttcctcgctcactgactcgctgcgctcggtcgttcggctgcggcgagcggtatcagctcactcaaaggcggtaatacggttatccacagaatcaggggataacgcaggaaagaacatgtgagcaaaaggccagcaaaaggccaggaaccgtaaaaaggccgcgttgctggcgtttttccataggctccgcccccctgacgagcatcacaaaaatcgacgctcaagtcagaggtggcgaaacccgacaggactataaagataccaggcgtttccccctggaagctccctcgtgcgctctcctgttccgaccctgccgcttaccggatacctgtccgcctttctcccttcgggaagcgtggcgctttctcatagctcacgctgtaggtatctcagttcggtgtaggtcgttcgctccaagctgggctgtgtgcacgaaccccccgttcagcccgaccgctgcgccttatccggtaactatcgtcttgagtccaacccggtaagacacgacttatcgccactggcagcagccactggtaacaggattagcagagcgaggtatgtaggcggtgctacagagttcttgaagtggtggcctaactacggctacactagaagaacagtatttggtatctgcgctctgctgaagccagttaccttcggaaaaagagttggtagctcttgatccggcaaacaaaccaccgctggtagcggtggtttttttgtttgcaagcagcagattacgcgcagaaaaaaaggatctcaagaagatcctttgatcttttctacggggtctgacgctcagtggaacgaaaactcacgttaagggattttggtcatgagattatcaaaaaggatcttcacctagatccttttaaattaaaaatgaagttttaaatcaatctaaagtatatatgagtaaacttggtctgacagttaccaatgcttaatcagtgaggcacctatctcagcgatctgtctatttcgttcatccatagttgcctgactccccgtcgtgtagataactacgatacgggagggcttaccatctggccccagtgctgcaatgataccgcgagacccacgctcaccggctccagatttatcagcaataaaccagccagccggaagggccgagcgcagaagtggtcctgcaactttatccgcctccatccagtctattaattgttgccgggaagctagagtaagtagttcgccagttaatagtttgcgcaacgttgttgccattgctacaggcatcgtggtgtcacgctcgtcgtttggtatggcttcattcagctccggttcccaacgatcaaggcgagttacatgatcccccatgttgtgcaaaaaagcggttagctccttcggtcctccgatcgttgtcagaagtaagttggccgcagtgttatcactcatggttatggcagcactgcataattctcttactgtcatgccatccgtaagatgcttttctgtgactggtgagtactcaaccaagtcattctgagaatagtgtatgcggcgaccgagttgctcttgcccggcgtcaatacgggataataccgcgccacatagcagaactttaaaagtgctcatcattggaaaacgttcttcggggcgaaaactctcaaggatcttaccgctgttgagatccagttcgatgtaacccactcgtgcacccaactgatcttcagcatcttttactttcaccagcgtttctgggtgagcaaaaacaggaaggcaaaatgccgcaaaaaagggaataagggcgacacggaaatgttgaatactcatactcttcctttttcaatattattgaagcatttatcagggttattgtctcatgagcggatacatatttgaatgtatttagaaaaataaacaaataggggttccgcgcacatttccccgaaaagtgccacctgacgtctaagaaaccattattatcatgacattaacctataaaaataggcgtatcacgaggccctttcgtc";
sequence.features = new ArrayCollection();
sequence.features.addItem(new DNAFeature(146, 469, -1, "lacZalpha", null, "CDS"));
sequence.features.addItem(new DNAFeature(396, 452, -1, "multple cloning site", null, "misc_feature"));
sequence.features.addItem(new DNAFeature(514, 519, -1, "Plac promoter", null, "-10_signal"));
sequence.features.addItem(new DNAFeature(538, 543, -1, "Plac promoter", null, "-35_signal"));
sequence.features.addItem(new DNAFeature(563, 575, -1, "CAP protein binding site", null, "protein_bind"));
sequence.features.addItem(new DNAFeature(867, 1445, -1, "pMB1 origin of replication", null, "rep_origin"));
sequence.features.addItem(new DNAFeature(876, 1419, -1, "RNAII transcript", null, "misc_RNA"));
sequence.features.addItem(new DNAFeature(1273, 1278, 1, "RNAI promoter (clockwise); TTGAAG", null, "-35_signal"));
sequence.features.addItem(new DNAFeature(1295, 1300, 1, "RNAI promoter (clockwise) GCTACA", null, "-10_signal"));
sequence.features.addItem(new DNAFeature(1309, 1416, 1, "RNAI transcript", null, "misc_RNA"));
sequence.features.addItem(new DNAFeature(1429, 1434, -1, "RNAII promoter", null, "-10_signal"));
sequence.features.addItem(new DNAFeature(1450, 1455, -1, "RNAII promoter", null, "-35_signal"));
sequence.features.addItem(new DNAFeature(1626, 2486, -1, "bla", null, "CDS"));
sequence.features.addItem(new DNAFeature(2418, 2486, -1, "bla", null, "sig_peptide"));
sequence.features.addItem(new DNAFeature(2530, 2535, -1, "bla promoter", null, "-10_signal"));
sequence.features.addItem(new DNAFeature(2551, 2556, -1, "bla promoter", null, "-35_signal"));
/*CONFIG::digestion {
sequence.sequence = "CCTAATGAGTGAGCTAACTTACATTAATTGCGTTGCGCTCACTGCCCGGAATTCTTTCCAGTCGGGAAACCTGTCGTGCCAGCTGCATTAATGAATCGGCCAACGCGCGGGGAGAGGCGGTTTGCGTATTGGGCGCCAGGGTGGTTTTTCTTTTCACCAGTGAGACGGGCAACAGCTGATTGCCCTTCACCGCCTGGCCCTGAGAGAGTTGCAGCAAGCGGTCCACGCTGGTTTGCCCCAGCAGGCGAAAATCCTGTTTGATGGTGGTTAACGGCGGGATATAACATGAGCTGTCTTCGGTATCGTCGTATCCCACTACCGAGATGTCCGCACCAACGCGCAGCCCGGACTCGGTAATGGCGCGCATTGCGCCCAGCGCCATCTGATCGTTGGCAACCAGCATCGCAGTGGGAACGATGCCCTCATTCAGCATTTGCATGGTTTGTTGAAAACCGGACATGGCACTCCAGTCGCCTTCCCGTTCCGCTATCGGCTGAATTTGATTGCGAGTGAGATATTTATGCCAGCCAGCCAGACGCAGACGCGCCGAGACAGAACTTAATGGGCCCGCTAACAGCGCGATTTGCTGGTGACCCAATGCGACCAGATGCTCCACGCCCAGTCGCGTACCGTCTTCATGGGAGAAAATAATACTGTTGATGGGTGTCTGGTCAGAGACATCAAGAAATAACGCCGGAACATTAGTGCAGGCAGCTTCCACAGCAATGGCATCCTGGTCATCCAGCGGATAGTTAATGATCAGCCCACTGACGCGTTGCGCGAGAAGATTGTGCACCGCCGCTTTACAGGCTTCGACGCGCCAATCAGCAACGACTGTTTGCCCGCCAGTTGTTGTGCCACGCGGTTGGGAATGTAATTCAGCTCCGCCATCGCCGCTTCCACTTTTTCCCGCGTTTTCGCAGAAACGTGGCTGGCCTGGTTCACCACGCGGGAAACGGTCTGATAAGAGACACCGGCATACTCTGCGACATCGTATAACGTTACTGGTTTCACATTCACCACCCTGAATTGACTCTCTTCCGGGCGCTATCATGCCATACCGCGAAAGGTTTTGCGCCATTCGATGGTGTCCGGGATCTCGACGCTCTCCCTTATGCGACTCCTGCATTAGGAAGCAGCCCAGTAGTAGGTTGAGGCCGTTGAGCACCGCCGCCGCAAGGAATGGTGCATGCAAGGAAAGGCGATCGCGTTGCGTTGATGATGCCTAATTTATTGCAATATCCGGTGGCGCTGTTTGGCATTTTGCGTGCCGGGATGATCGTCGTAAACGTTAACCCGTTGTATACCCCGCGTGAGCTTGAGCATCAGCTTAACGATAGCGGCGCATCGGCGATTGTTATCGTGTCTAACTTTGCTCACACACTGGAAAAAGTGGTTGATAAAACCGCCGTTCAGCACGTAATTCTGACCCGTATGGGCGATCAGCTATCTACGGCAAAAGGCACGGTAGTCAATTTCGTTGTTAAATACATCAAGCGTTTGGTGCCGAAATACCATCTCGAGCTGCCAGATGCCATTTCATTTCGTAGCGCACTGCATAACGGCTACCGGATGCAGTACGTCAAACCCGAACTGGTGCCGGAAGATTTAGCTTTTCTGCAATACACCGGCGGCACCACTGGTGTGGCGAAAATCGGTTTGCCGGTGCCGTCGACGGAAGCCAAACTGGTGGATGATGATGATAATGAAGTACCACCAGGTCAACCGGGTGAGCTTTGTGTCAAAGGACCGCAGGTGATGCTGGGTTACTGGCAGCGTCCCGATGCTACCGATGAAATCATCAAAAATGGCTGGTTACACACCGGCGACCGGATATCAAAATCAATCCCTGTTCCACCATTCAACAATAAACTGAATGGGCTTTTTTGGGATGAAGATGAAGAGTTTGATTTAGGAGGAAACAGAATGCGCCCATTACATCCGATTGATTTTATATTCCTGTCACTAGAAAAAAGACAACAGCCTATGCATGTAGGTGGTTTATTTTTGTTTCAGATTCCTGATAACGCCCCAGACACCTTTATTCAGGATCTGGTGAATGATATCC";
sequence.features = new ArrayCollection();
sequence.features.addItem(new DNAFeature(1500, 1575, 1, "lacUV5 promoter", null, "promoter"));
sequence.features.addItem(new DNAFeature(1516, 1579, 1, "lac operator", null, "misc_binding"));
sequence.features.addItem(new DNAFeature(1595, 1614, 1, "RBS", null, "RBS"));
sequence.features.addItem(new DNAFeature(1615, 1800, 1, "fadD", null, "CDS"));
sequence.features.addItem(new DNAFeature(49, 1131, -1, "lacI", null, "CDS"));
}*/
sequence = new FeaturedDNASequence();
sequence.features = new ArrayCollection();
sequence.name = "unknown";
return sequence;
}
public static function standaloneUserPreferences():UserPreferences
{
var userPreferences:UserPreferences = new UserPreferences();
userPreferences.bpPerRow = -1;
userPreferences.orfMinimumLength = 300;
userPreferences.sequenceFontSize = 11;
return userPreferences;
}
public static function standaloneUserRestrictionEnzymes():UserRestrictionEnzymes
{
return new UserRestrictionEnzymes();
}
}
}
|
clean standalone sequence
|
[VectorEditor] clean standalone sequence
git-svn-id: adbdea8fc1759bd16b0eaf24a244a7e5f870a654@261 fe3f0490-d73e-11de-a956-c71e7d3a9d2f
|
ActionScript
|
bsd-3-clause
|
CIDARLAB/mage-editor,CIDARLAB/mage-editor,CIDARLAB/mage-editor
|
bfd0dd7a8a74dbdcbf0b20a0278149d65608e299
|
flash/org/windmill/astest/ASTest.as
|
flash/org/windmill/astest/ASTest.as
|
/*
Copyright 2009, Matthew Eernisse ([email protected]) and Slide, 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.
*/
package org.windmill.astest {
import org.windmill.WMLogger;
import flash.utils.*;
import flash.external.ExternalInterface;
public class ASTest {
// How long to wait between each test action
private static const TEST_INTERVAL:int = 10;
// List of all the test classes for this test run
public static var testClassList:Array = [];
// The complete list of all methods for each class
// in this test run
private static var testListComplete:Array = [];
// Copy of the list of tests -- items are popped
// of to run the tests
private static var testList:Array = [];
// The last test action -- used to do reporting on
// success/failure of each test. Waits happen
// async in a setTimeout loop, so reporting happens
// for the *previous* test at the beginning of each
// runNextTest call, before grabbing and running the
// next test
private static var previousTest:Object = null;
// Error for the previous test if it was unsuccessful
// Used in the reporting as described above
public static var previousError:Object = false;
// Tests are running or not
public static var inProgress:Boolean = false;
// In waiting mode, the runNextTest loop just idles
public static var waiting:Boolean = false;
public static function run(files:* = null):void {
//['/flash/TestFoo.swf', '/flash/TestBar.swf']
// If we're passed some files, load 'em up first
// the loader will call back to this again when
// it's done, with no args
if (files) {
// **** Ugly hack ****
// -------------
if (!(files is Array)) {
// The files param passed in from XPCOM trusted JS
// loses its Array-ness -- fails the 'is Array' test,
// and has no 'length' property. It's just a generic
// Object with integers for keys
// In that case, reconstitute the Array by manually
// stepping through it until we run out of items
var filesTemp:Array = [];
var incr:int = 0;
var item:*;
var keepGoing:Boolean = true;
while (keepGoing) {
item = files[incr];
if (item) {
filesTemp.push(item);
}
else {
keepGoing = false;
}
incr++;
}
files = filesTemp;
}
// -------------
ASTest.loadTestFiles(files);
return;
}
ASTest.getCompleteListOfTests();
ASTest.start();
}
public static function loadTestFiles(files:Array):void {
// Clear out the list of tests before loading
ASTest.testClassList = [];
ASTest.testList = [];
// Load the shit
WMLoader.load(files);
}
public static function start():void {
// Make a copy of the tests to work on
ASTest.testList = ASTest.testListComplete.slice();
ASTest.inProgress = true;
// Run recursively in a setTimeout loop so
// we can implement sleeps and waits
ASTest.runNextTest();
}
public static function runNextTest():void {
var test:Object = null;
var res:*; // Result from ExternalInterface calls
var data:Object;
// If we're idling in a wait, just move along ...
// Nothing to see here
if (ASTest.waiting) {
// Let's try again in a second or so
setTimeout(function ():void {
ASTest.runNextTest.call(ASTest);
}, 1000);
return;
}
// Do reporting for the previous test -- we do this here
// because waits happen async in a setTimeout loop,
// and we only know when it has finished by when the next
// test actually starts
if (ASTest.previousTest) {
test = ASTest.previousTest;
data = {
test: {
className: test.className,
methodName: test.methodName
},
error: null
};
// Error
if (ASTest.previousError) {
data.error = ASTest.previousError;
ASTest.previousError = null;
}
// Report via ExternalInterface, or log results
res = ExternalInterface.call('wm_asTestResult', data);
if (!res) {
if (data.error) {
WMLogger.log('FAILURE: ' + data.error.message);
}
else {
WMLogger.log('SUCCESS');
}
}
ASTest.previousTest = null;
}
// If we're out of tests, we're all done
// TODO: Add some kind of final report
if (ASTest.testList.length == 0) {
ASTest.inProgress = false;
}
// If we still have tests to run, grab the next one
// and run that bitch
else {
test = ASTest.testList.shift();
// Save a ref to this test to use for reporting
// at the beginning of the next call
ASTest.previousTest = test;
data = {
test: {
className: test.className,
methodName: test.methodName
}
};
res = ExternalInterface.call('wm_asTestStart', data);
if (!res) {
WMLogger.log('Running ' + test.className + '.' + test.methodName + ' ...');
}
// Run the test
// -----------
try {
test.instance[test.methodName].call(test.instance);
}
catch (e:Error) {
// Save a ref to the error to use for reporting
// at the beginning of the next call
ASTest.previousError = e;
}
// Recurse until done -- note this is not actually a
// tail call because the setTimeout invokes the function
// in the global execution context
setTimeout(function ():void {
ASTest.runNextTest.call(ASTest);
}, ASTest.TEST_INTERVAL);
}
}
public static function getCompleteListOfTests():void {
var createTestItem:Function = function (item:Object,
methodName:String):Object {
return {
methodName: methodName,
instance: item.instance,
className: item.className,
classDescription: item.classDescription
};
}
var testList:Array = [];
// No args -- this is being re-invoked from WMLoader
// now that we have our tests loaded
for each (var item:Object in ASTest.testClassList) {
var currTestList:Array = [];
var descr:XML;
var hasSetup:Boolean = false;
var hasTeardown:Boolean = false;
descr = flash.utils.describeType(
item.classDescription);
var meth:*;
var methods:Object = {};
for each (meth in descr..method) {
var methodName:String = [email protected]();
if (/^test/.test(methodName)) {
methods[methodName] = item;
}
// If there's a setup or teardown somewhere in there
// flag them so we can prepend/append after adding all
// the tests
if (methodName == 'setup') {
hasSetup = true;
}
if (methodName == 'teardown') {
hasTeardown = true;
}
}
// Normal test methods
// -----
// If there's an 'order' array defined, run any tests
// it contains in the defined order
var key:String;
if ('order' in item.instance) {
for each (key in item.instance.order) {
if (!key in methods) {
throw new Error(key + ' is not a method in ' + item.className);
}
currTestList.push(createTestItem(methods[key], key));
delete methods[key];
}
}
// Run any other methods in whatever order
for (key in methods) {
currTestList.push(createTestItem(methods[key], key));
}
// Setup/teardown
// -----
// Prepend list with setup if one exists
if (hasSetup) {
currTestList.unshift(createTestItem(item, 'setup'));
}
// Append list with teardown if one exists
if (hasTeardown) {
currTestList.push(createTestItem(item, 'teardown'));
}
testList = testList.concat.apply(testList, currTestList);
}
ASTest.testListComplete = testList;
}
}
}
|
/*
Copyright 2009, Matthew Eernisse ([email protected]) and Slide, 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.
*/
package org.windmill.astest {
import org.windmill.WMLogger;
import flash.utils.*;
import flash.external.ExternalInterface;
public class ASTest {
// How long to wait between each test action
private static const TEST_INTERVAL:int = 10;
// List of all the test classes for this test run
public static var testClassList:Array = [];
// The complete list of all methods for each class
// in this test run
private static var testListComplete:Array = [];
// Copy of the list of tests -- items are popped
// of to run the tests
private static var testList:Array = [];
// The last test action -- used to do reporting on
// success/failure of each test. Waits happen
// async in a setTimeout loop, so reporting happens
// for the *previous* test at the beginning of each
// runNextTest call, before grabbing and running the
// next test
private static var previousTest:Object = null;
// Error for the previous test if it was unsuccessful
// Used in the reporting as described above
public static var previousError:Object = false;
// Tests are running or not
public static var inProgress:Boolean = false;
// In waiting mode, the runNextTest loop just idles
public static var waiting:Boolean = false;
public static function run(files:* = null):void {
//['/flash/TestFoo.swf', '/flash/TestBar.swf']
// If we're passed some files, load 'em up first
// the loader will call back to this again when
// it's done, with no args
if (files) {
// **** Ugly hack ****
// -------------
if (!(files is Array)) {
// The files param passed in from XPCOM trusted JS
// loses its Array-ness -- fails the 'is Array' test,
// and has no 'length' property. It's just a generic
// Object with integers for keys
// In that case, reconstitute the Array by manually
// stepping through it until we run out of items
var filesTemp:Array = [];
var incr:int = 0;
var item:*;
var keepGoing:Boolean = true;
while (keepGoing) {
item = files[incr];
if (item) {
filesTemp.push(item);
}
else {
keepGoing = false;
}
incr++;
}
files = filesTemp;
}
// -------------
ASTest.loadTestFiles(files);
return;
}
ASTest.getCompleteListOfTests();
ASTest.start();
}
public static function loadTestFiles(files:Array):void {
// Clear out the list of tests before loading
ASTest.testClassList = [];
ASTest.testList = [];
// Load the shit
WMLoader.load(files);
}
public static function start():void {
// Make a copy of the tests to work on
ASTest.testList = ASTest.testListComplete.slice();
ASTest.inProgress = true;
// Run recursively in a setTimeout loop so
// we can implement sleeps and waits
ASTest.runNextTest();
}
public static function runNextTest():void {
var test:Object = null;
var res:*; // Result from ExternalInterface calls
var data:Object;
// If we're idling in a wait, just move along ...
// Nothing to see here
if (ASTest.waiting) {
// Let's try again in a second or so
setTimeout(function ():void {
ASTest.runNextTest.call(ASTest);
}, 1000);
return;
}
// Do reporting for the previous test -- we do this here
// because waits happen async in a setTimeout loop,
// and we only know when it has finished by when the next
// test actually starts
if (ASTest.previousTest) {
test = ASTest.previousTest;
data = {
test: {
className: test.className,
methodName: test.methodName
},
error: null
};
// Error
if (ASTest.previousError) {
data.error = ASTest.previousError;
ASTest.previousError = null;
}
// Report via ExternalInterface, or log results
res = ExternalInterface.call('wm_asTestResult', data);
if (!res) {
if (data.error) {
WMLogger.log('FAILURE: ' + data.error.message);
}
else {
WMLogger.log('SUCCESS');
}
}
ASTest.previousTest = null;
}
// If we're out of tests, we're all done
// TODO: Add some kind of final report
if (ASTest.testList.length == 0) {
ASTest.inProgress = false;
}
// If we still have tests to run, grab the next one
// and run that bitch
else {
test = ASTest.testList.shift();
// Save a ref to this test to use for reporting
// at the beginning of the next call
ASTest.previousTest = test;
data = {
test: {
className: test.className,
methodName: test.methodName
}
};
res = ExternalInterface.call('wm_asTestStart', data);
if (!res) {
WMLogger.log('Running ' + test.className + '.' + test.methodName + ' ...');
}
// Run the test
// -----------
try {
if (!(test.methodName in test.instance)) {
throw new Error('"' + test.methodName +
'" is not a valid method in' + test.instance.toString());
}
test.instance[test.methodName].call(test.instance);
}
catch (e:Error) {
// Save a ref to the error to use for reporting
// at the beginning of the next call
ASTest.previousError = e;
}
// Recurse until done -- note this is not actually a
// tail call because the setTimeout invokes the function
// in the global execution context
setTimeout(function ():void {
ASTest.runNextTest.call(ASTest);
}, ASTest.TEST_INTERVAL);
}
}
public static function getCompleteListOfTests():void {
var createTestItem:Function = function (item:Object,
methodName:String):Object {
return {
methodName: methodName,
instance: item.instance,
className: item.className,
classDescription: item.classDescription
};
}
var testList:Array = [];
// No args -- this is being re-invoked from WMLoader
// now that we have our tests loaded
for each (var item:Object in ASTest.testClassList) {
var currTestList:Array = [];
var descr:XML;
var hasSetup:Boolean = false;
var hasTeardown:Boolean = false;
descr = flash.utils.describeType(
item.classDescription);
var meth:*;
var methods:Object = {};
for each (meth in descr..method) {
var methodName:String = [email protected]();
if (/^test/.test(methodName)) {
methods[methodName] = item;
}
// If there's a setup or teardown somewhere in there
// flag them so we can prepend/append after adding all
// the tests
if (methodName == 'setup') {
hasSetup = true;
}
if (methodName == 'teardown') {
hasTeardown = true;
}
}
// Normal test methods
// -----
// If there's an 'order' array defined, run any tests
// it contains in the defined order
var key:String;
if ('order' in item.instance) {
for each (key in item.instance.order) {
// If the item specified in the 'order' list is an actual
// method, add it to the list -- if it doesn't actually exist
// (e.g., if the method has been commented out), just ignore it
if (key in methods) {
currTestList.push(createTestItem(methods[key], key));
delete methods[key];
}
}
}
// Run any other methods in whatever order
for (key in methods) {
currTestList.push(createTestItem(methods[key], key));
}
// Setup/teardown
// -----
// Prepend list with setup if one exists
if (hasSetup) {
currTestList.unshift(createTestItem(item, 'setup'));
}
// Append list with teardown if one exists
if (hasTeardown) {
currTestList.push(createTestItem(item, 'teardown'));
}
testList = testList.concat.apply(testList, currTestList);
}
ASTest.testListComplete = testList;
}
}
}
|
Check to make sure the method in the test-ordering actually, you know, exists, before trying to use it.
|
Check to make sure the method in the test-ordering actually, you know, exists, before trying to use it.
|
ActionScript
|
apache-2.0
|
windmill/windmill,windmill/windmill,windmill/windmill,windmill/windmill,windmill/windmill,windmill/windmill
|
fbb4f7ad19063264a6d556a9fafd5002a0290b00
|
test/stutter/StutterTest.as
|
test/stutter/StutterTest.as
|
package stutter
{
import org.flexunit.assertThat;
import org.hamcrest.collection.array;
import org.hamcrest.collection.emptyArray;
import org.hamcrest.object.equalTo;
import org.hamcrest.object.isFalse;
import org.hamcrest.object.isTrue;
public class StutterTest
{
private var runtime:StutterRunTime;
private var reader:StutterReader;
[Before]
public function setup():void
{
runtime = new StutterRunTime();
reader = new StutterReader();
}
[Test]
public function math():void
{
assertThat('+', eval('(+ 2 3)'), equalTo(5));
assertThat('-', eval('(- 2 3)'), equalTo(-1));
assertThat('*', eval('(* 2 3)'), equalTo(6));
assertThat('/', eval('(/ 6 2)'), equalTo(3));
}
[Test]
public function lambdas():void
{
eval('(label second (quote (lambda (x) (car (cdr x)))))');
assertThat(eval('(second (quote (1 2 3)))'), equalTo(2));
}
[Test]
public function truth():void
{
assertThat(eval('t'), equalTo(TRUE));
}
[Test]
public function falsey():void
{
assertThat(eval('nil'), equalTo(FALSE));
}
[Test]
public function scoping():void
{
eval(<![CDATA[
(label test (quote (lambda (a b c)
(+ a (* b c) 4)
]]>.toString())
assertThat(eval('(test 1 2 3)'), equalTo(11));
}
[Ignore]
[Test]
public function and_():void
{
eval(<![CDATA[
(label and (quote (lambda (and_x and_y)
(if (eq and_x t)
(if (eq and_y t) nil)
nil))))
]]>.toString());
assertThat('true?', eval('(and (eq 2 2) (eq 3 3))'), equalTo(TRUE));
assertThat('false?', eval('(and (eq 2 2) (eq 3 4))'), equalTo(FALSE));
}
private function eval(expression:String):*
{
return runtime.eval(reader.read(expression));
}
}
}
|
package stutter
{
import org.flexunit.assertThat;
import org.hamcrest.Matcher;
import org.hamcrest.collection.array;
import org.hamcrest.collection.emptyArray;
import org.hamcrest.object.equalTo;
import org.hamcrest.object.isFalse;
import org.hamcrest.object.isTrue;
public class StutterTest
{
private var runtime:StutterRunTime;
private var reader:StutterReader;
[Before]
public function setup():void
{
runtime = new StutterRunTime();
reader = new StutterReader();
}
private function eval(expression:String):*
{
reader.load(expression);
var sexp:*;
var result:*;
while (reader.hasTokens() && (sexp = reader.parse()))
{
result = runtime.eval(sexp);
}
return result;
}
private function assert(expression:String, result:*):void
{
assertThat(expression, eval(expression), result is Matcher ? result : equalTo(result));
}
[Test]
public function math():void
{
assertThat('+', eval('(+ 2 3)'), equalTo(5));
assertThat('-', eval('(- 2 3)'), equalTo(-1));
assertThat('*', eval('(* 2 3)'), equalTo(6));
assertThat('/', eval('(/ 6 2)'), equalTo(3));
}
[Test]
public function lambdas():void
{
eval('(label second (quote (lambda (x) (car (cdr x)))))');
assertThat(eval('(second (quote (1 2 3)))'), equalTo(2));
}
[Test]
public function truth():void
{
assertThat(eval('t'), equalTo(TRUE));
}
[Test]
public function falsey():void
{
assertThat(eval('nil'), equalTo(FALSE));
}
[Test]
public function scoping():void
{
eval(<![CDATA[
(label test (quote (lambda (a b c)
(+ a (* b c) 4)
]]>.toString())
assertThat(eval('(test 1 2 3)'), equalTo(11));
}
[Ignore]
[Test]
public function and_():void
{
eval(<![CDATA[
(label and (quote (lambda (and_x and_y)
(if (eq and_x t)
(if (eq and_y t) nil)
nil))))
]]>.toString());
assertThat('true?', eval('(and (eq 2 2) (eq 3 3))'), equalTo(TRUE));
assertThat('false?', eval('(and (eq 2 2) (eq 3 4))'), equalTo(FALSE));
}
[Test]
public function cond_():void
{
assert('(cond)', FALSE);
assert('(cond (t 1))', 1);
assert('(cond (nil 1) (t 2))', 2);
assert('(cond (else 3))', 3);
assert('(cond ((= 1 2) 3) (else 4))', 4);
eval(<![CDATA[
(label cond-test (quote (lambda (x)
(cond ((= x 1) 1)
((= x 2) 2)
((= x 3) 3)))))
]]>.toString());
assert('(cond-test 3)', 3);
}
}
}
|
add cond tests
|
runtime: add cond tests
|
ActionScript
|
mit
|
drewbourne/stutter
|
31a1c9fb6ed1eaf2ea66ba39586826807192bd8f
|
WEB-INF/lps/lfc/views/LzInput6.as
|
WEB-INF/lps/lfc/views/LzInput6.as
|
/******************************************************************************
* LzText.as
*****************************************************************************/
//* A_LZ_COPYRIGHT_BEGIN ******************************************************
//* Copyright 2001-2004 Laszlo Systems, Inc. All Rights Reserved. *
//* Use is subject to license terms. *
//* A_LZ_COPYRIGHT_END ********************************************************
//=============================================================================
// DEFINE OBJECT: LzNewInputText
// This class is used for input text.
//
//=============================================================================
var LzInputText = Class ( "LzInputText" , LzText );
// +++ Hey, are we still saying that input text is non- HTML ?
// If so then we need to override a number of methods in LzText which
LzInputText.prototype.defaultattrs.selectable = true;
LzInputText.prototype.defaultattrs.enabled = true;
//-----------------------------------------------------------------------------
// @keywords private
//-----------------------------------------------------------------------------
LzInputText.prototype.construct = function ( parent , args ){
super.construct( parent , args );
var mc = this.__LZtextclip;
// We do not support html in input fields.
if (this.enabled) {
mc.type = 'input';
} else {
mc.type = 'dynamic';
}
// set a pointer back to this view from the TextField object
this.__LZtextclip.__lzview = this;
mc.onSetFocus = TextField.prototype.__gotFocus;
mc.onKillFocus = TextField.prototype.__lostFocus;
mc.onChanged = TextField.prototype.__onChanged;
// handle onkeydown events
this.onfocusDel = new _root.LzDelegate( this , "handleOnFocus" , this ,
"onfocus" );
this.onblurDel = new _root.LzDelegate( this , "handleOnBlur" , this ,
"onblur" );
this.hasFocus = false;
}
// [hqm]??? what did this do?
//Object.class.extends( LzText, LzInputText );
LzInputText.prototype.focusable = true;
//-----------------------------------------------------------------------------
// @keywords private
//-----------------------------------------------------------------------------
LzInputText.prototype.handleOnFocus = function ( ){
if ( this.hasFocus ) { return; }
var sf = targetPath(this.__LZtextclip);
// calling setFocus() seems to bash the scroll value, so save it
var myscroll = this.__LZtextclip.scroll;
if( Selection.getFocus() != sf ) {
Selection.setFocus( sf );
}
this.__LZtextclip.hscroll = 0;
// restore the scroll value
this.__LZtextclip.scroll = myscroll;
this.hasFocus = true;
this.__LZtextclip.background = false;
}
//-----------------------------------------------------------------------------
// @keywords private
//-----------------------------------------------------------------------------
LzInputText.prototype.handleOnBlur = function ( ){
this.hasFocus = false;
var sf = targetPath(this.__LZtextclip);
if( Selection.getFocus() == sf ) {
Selection.setFocus( null );
}
}
//-----------------------------------------------------------------------------
// Register for update on every frame when the text field gets the focus.
// Set the behavior of the enter key depending on whether the field is
// multiline or not.
//
// @keywords private
//-----------------------------------------------------------------------------
TextField.prototype.__gotFocus = function ( oldfocus ){
// scroll text fields horizontally back to start
if (!(LzFocus.getFocus() == this.__lzview)) {
var tabdown = LzKeys.isKeyDown('tab');
_root.LzFocus.setFocus(this.__lzview, tabdown);
}
}
//-----------------------------------------------------------------------------
// Register to be called when the text field is modified. Convert this
// into a LFC ontext event.
// @keywords private
//-----------------------------------------------------------------------------
TextField.prototype.__onChanged = function ( ){
//this.__lzview.setText(this.text);
this.__lzview.ontext.sendEvent( );
}
//-----------------------------------------------------------------------------
// @keywords private
//-----------------------------------------------------------------------------
TextField.prototype.__lostFocus = function ( ){
if (this['__handlelostFocusdel'] == null) this.__handlelostFocusdel = new LzDelegate(this, "__handlelostFocus");
_root.LzIdle.callOnIdle(this.__handlelostFocusdel);
}
//-----------------------------------------------------------------------------
// must be called after an idle event to prevent the selection from being
// cleared prematurely, e.g. before a button click. If the selection is
// cleared, the button doesn't send mouse events.
// @keywords private
//-----------------------------------------------------------------------------
TextField.prototype.__handlelostFocus = function ( ){
//_root.Debug.write('lostfocus', this.__lzview.hasFocus, dunno, LzFocus.lastfocus, this, LzFocus.getFocus(), this.__lzview);
if (this.__lzview.hasFocus) LzFocus.clearFocus();
}
//------------------------------------------------------------------------------
// Retrieves the contents of the text field for use by a datapath. See
// <code>LzDatapath.updateData</code> for more on this.
// @keywords protected
//------------------------------------------------------------------------------
LzInputText.prototype.updateData = function (){
return this.__LZtextclip.text;
}
//------------------------------------------------------------------------------
// Sets whether user can modify input text field
// @param Boolean enabled: true if the text field can be edited
//------------------------------------------------------------------------------
LzInputText.prototype.setEnabled = function (enabled){
var mc = this.__LZtextclip;
this.enabled = enabled;
if (enabled) {
mc.type = 'input';
} else {
mc.type = 'dynamic';
}
}
//---
//@keywords private
//---
LzInputText.prototype.setters.enabled = "setEnabled";
//-----------------------------------------------------------------------------
// @keywords private
//-----------------------------------------------------------------------------
LzInputText.prototype.getText = function ( ){
return this.__LZtextclip.text;
}
LzInputText.prototype.getText.dependencies = function ( who , self){
return [ self , "text" ];
}
//-----------------------------------------------------------------------------
// Set the html flag on this text view
//-----------------------------------------------------------------------------
LzInputText.prototype.setHTML = function (htmlp) {
this.__LZtextclip.html = htmlp;
}
//-----------------------------------------------------------------------------
// setText sets the text of the field to display
//
// @param String t: the string to which to set the text
//-----------------------------------------------------------------------------
LzInputText.prototype.setText = function ( t ){
if (typeof(t) == 'undefined' || t == null) {
t = "";
} else if (typeof(t) != "string") {
t = t.toString();
}
this.text = t;// this.format + t if proper measurement were working
var mc = this.__LZtextclip;
// these must be done in this order, to get Flash to take the HTML styling
// but not to ignore CR linebreak chars that might be in the string.
if (mc.html) {
mc.htmlText = this.format;
}
mc.text = t;
if (this.resize && (this.multiline == false)) {
// single line resizable fields adjust their width to match the text
this.setWidth(this.getTextWidth());
}
//multiline resizable fields adjust their height
if (this.multiline && this.sizeToHeight) {
this.setHeight(mc._height);
}
if (this.multiline && this.scroll == 0 ) {
var scrolldel = new LzDelegate(this, "__LZforceScrollAttrs");
_root.LzIdle.callOnIdle(scrolldel);
}
//@event ontext: Sent whenever the text in the field changes.
this.ontext.sendEvent( );
}
|
/******************************************************************************
* LzText.as
*****************************************************************************/
//* A_LZ_COPYRIGHT_BEGIN ******************************************************
//* Copyright 2001-2007 Laszlo Systems, Inc. All Rights Reserved. *
//* Use is subject to license terms. *
//* A_LZ_COPYRIGHT_END ********************************************************
//=============================================================================
// DEFINE OBJECT: LzNewInputText
// This class is used for input text.
//
//=============================================================================
var LzInputText = Class ( "LzInputText" , LzText );
// +++ Hey, are we still saying that input text is non- HTML ?
// If so then we need to override a number of methods in LzText which
LzInputText.prototype.defaultattrs.selectable = true;
LzInputText.prototype.defaultattrs.enabled = true;
//-----------------------------------------------------------------------------
// @keywords private
//-----------------------------------------------------------------------------
LzInputText.prototype.construct = function ( parent , args ){
super.construct( parent , args );
var mc = this.__LZtextclip;
// We do not support html in input fields.
if (this.enabled) {
mc.type = 'input';
} else {
mc.type = 'dynamic';
}
// set a pointer back to this view from the TextField object
this.__LZtextclip.__lzview = this;
mc.onSetFocus = TextField.prototype.__gotFocus;
mc.onKillFocus = TextField.prototype.__lostFocus;
mc.onChanged = TextField.prototype.__onChanged;
// handle onkeydown events
this.onfocusDel = new _root.LzDelegate( this , "handleOnFocus" , this ,
"onfocus" );
this.onblurDel = new _root.LzDelegate( this , "handleOnBlur" , this ,
"onblur" );
this.hasFocus = false;
}
// [hqm]??? what did this do?
//Object.class.extends( LzText, LzInputText );
LzInputText.prototype.focusable = true;
//-----------------------------------------------------------------------------
// @keywords private
//-----------------------------------------------------------------------------
LzInputText.prototype.handleOnFocus = function ( ){
if ( this.hasFocus ) { return; }
var sf = targetPath(this.__LZtextclip);
// calling setFocus() seems to bash the scroll value, so save it
var myscroll = this.__LZtextclip.scroll;
if( Selection.getFocus() != sf ) {
Selection.setFocus( sf );
}
this.__LZtextclip.hscroll = 0;
// restore the scroll value
this.__LZtextclip.scroll = myscroll;
this.hasFocus = true;
this.__LZtextclip.background = false;
}
//-----------------------------------------------------------------------------
// @keywords private
//-----------------------------------------------------------------------------
LzInputText.prototype.handleOnBlur = function ( ){
this.hasFocus = false;
var sf = targetPath(this.__LZtextclip);
if( Selection.getFocus() == sf ) {
Selection.setFocus( null );
}
}
//-----------------------------------------------------------------------------
// Register for update on every frame when the text field gets the focus.
// Set the behavior of the enter key depending on whether the field is
// multiline or not.
//
// @keywords private
//-----------------------------------------------------------------------------
TextField.prototype.__gotFocus = function ( oldfocus ){
// scroll text fields horizontally back to start
if (!(LzFocus.getFocus() == this.__lzview)) {
var tabdown = LzKeys.isKeyDown('tab');
_root.LzFocus.setFocus(this.__lzview, tabdown);
}
}
//-----------------------------------------------------------------------------
// Register to be called when the text field is modified. Convert this
// into a LFC ontext event.
// @keywords private
//-----------------------------------------------------------------------------
TextField.prototype.__onChanged = function ( ){
//this.__lzview.setText(this.text);
//multiline resizable fields adjust their height
if ( this.__lzview.multiline &&
this.__lzview.sizeToHeight &&
this.__lzview.height != this._height ) {
this.__lzview.setHeight(this._height);
}
this.__lzview.ontext.sendEvent( );
}
//-----------------------------------------------------------------------------
// @keywords private
//-----------------------------------------------------------------------------
TextField.prototype.__lostFocus = function ( ){
if (this['__handlelostFocusdel'] == null) this.__handlelostFocusdel = new LzDelegate(this, "__handlelostFocus");
_root.LzIdle.callOnIdle(this.__handlelostFocusdel);
}
//-----------------------------------------------------------------------------
// must be called after an idle event to prevent the selection from being
// cleared prematurely, e.g. before a button click. If the selection is
// cleared, the button doesn't send mouse events.
// @keywords private
//-----------------------------------------------------------------------------
TextField.prototype.__handlelostFocus = function ( ){
//_root.Debug.write('lostfocus', this.__lzview.hasFocus, dunno, LzFocus.lastfocus, this, LzFocus.getFocus(), this.__lzview);
if (this.__lzview.hasFocus) LzFocus.clearFocus();
}
//------------------------------------------------------------------------------
// Retrieves the contents of the text field for use by a datapath. See
// <code>LzDatapath.updateData</code> for more on this.
// @keywords protected
//------------------------------------------------------------------------------
LzInputText.prototype.updateData = function (){
return this.__LZtextclip.text;
}
//------------------------------------------------------------------------------
// Sets whether user can modify input text field
// @param Boolean enabled: true if the text field can be edited
//------------------------------------------------------------------------------
LzInputText.prototype.setEnabled = function (enabled){
var mc = this.__LZtextclip;
this.enabled = enabled;
if (enabled) {
mc.type = 'input';
} else {
mc.type = 'dynamic';
}
}
//---
//@keywords private
//---
LzInputText.prototype.setters.enabled = "setEnabled";
//-----------------------------------------------------------------------------
// @keywords private
//-----------------------------------------------------------------------------
LzInputText.prototype.getText = function ( ){
return this.__LZtextclip.text;
}
LzInputText.prototype.getText.dependencies = function ( who , self){
return [ self , "text" ];
}
//-----------------------------------------------------------------------------
// Set the html flag on this text view
//-----------------------------------------------------------------------------
LzInputText.prototype.setHTML = function (htmlp) {
this.__LZtextclip.html = htmlp;
}
//-----------------------------------------------------------------------------
// setText sets the text of the field to display
//
// @param String t: the string to which to set the text
//-----------------------------------------------------------------------------
LzInputText.prototype.setText = function ( t ){
if (typeof(t) == 'undefined' || t == null) {
t = "";
} else if (typeof(t) != "string") {
t = t.toString();
}
this.text = t;// this.format + t if proper measurement were working
var mc = this.__LZtextclip;
// these must be done in this order, to get Flash to take the HTML styling
// but not to ignore CR linebreak chars that might be in the string.
if (mc.html) {
mc.htmlText = this.format;
}
mc.text = t;
if (this.resize && (this.multiline == false)) {
// single line resizable fields adjust their width to match the text
this.setWidth(this.getTextWidth());
}
//multiline resizable fields adjust their height
if (this.multiline && this.sizeToHeight) {
this.setHeight(mc._height);
}
if (this.multiline && this.scroll == 0 ) {
var scrolldel = new LzDelegate(this, "__LZforceScrollAttrs");
_root.LzIdle.callOnIdle(scrolldel);
}
//@event ontext: Sent whenever the text in the field changes.
this.ontext.sendEvent( );
}
|
Fix height resizing for multiline text fields New Features: Bugs Fixed: N/A Technical Reviewer: max QA Reviewer: pablo Doc Reviewer: n/a Documentation: Release Notes: Details: Multiline inputtext fields don't resize their height as they wrap while the user is inputting text. There needs to be code to update the view height when the text changes Tests: See attached
|
Summary: Fix height resizing for multiline text fields
New Features:
Bugs Fixed: N/A
Technical Reviewer: max
QA Reviewer: pablo
Doc Reviewer: n/a
Documentation:
Release Notes:
Details: Multiline inputtext fields don't resize their height as they wrap
while the user is inputting text. There needs to be code to update the view
height when the text changes
Tests: See attached
git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@3501 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
|
ActionScript
|
epl-1.0
|
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
|
ea9803cfcd70742743de373e368153706c92518d
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/utils/MXMLDataInterpreter.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/utils/MXMLDataInterpreter.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.utils
{
import flash.display.DisplayObject;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IContainer;
import org.apache.flex.core.IDocument;
import org.apache.flex.core.IMXMLDocument;
import org.apache.flex.core.IParent;
import org.apache.flex.core.IStrand;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
/**
* The MXMLDataInterpreter class is the class that interprets the
* encoded information generated by the compiler that describes
* the contents of an MXML document.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class MXMLDataInterpreter
{
/**
* Constructor. All methods are static so should not be instantiated.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function MXMLDataInterpreter()
{
super();
}
/**
* Generates an object based on the encoded data.
*
* @param document The MXML document. If the object has an id
* it will be assigned in this document in this method.
* @param data The encoded data.
* @return The object.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function generateMXMLObject(document:Object, data:Array):Object
{
var i:int = 0;
var cls:Class = data[i++];
var comp:Object = new cls();
if (comp is IStrand)
initializeStrandBasedObject(document, null, comp, data, i);
else
{
var m:int;
var j:int;
var name:String;
var simple:*;
var value:Object;
var id:String;
m = data[i++]; // num props
for (j = 0; j < m; j++)
{
name = data[i++];
simple = data[i++];
value = data[i++];
if (simple == null)
value = generateMXMLArray(document, null, value as Array);
else if (simple == false)
value = generateMXMLObject(document, value as Array);
if (name == "id")
{
document[value] = comp;
id = value as String;
}
else if (name == "_id")
{
document[value] = comp;
id = value as String;
continue; // skip assignment to comp
}
comp[name] = value;
}
if (comp is IDocument)
comp.setDocument(document, id);
}
return comp;
}
/**
* Generates an Array of objects based on the encoded data.
*
* @param document The MXML document. If the object has an id
* it will be assigned in this document in this method.
* @param parent The parent for any display objects encoded in the array.
* @param data The encoded data.
* @return The Array.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function generateMXMLArray(document:Object, parent:IParent, data:Array):Array
{
var comps:Array = [];
var n:int = data.length;
var i:int = 0;
while (i < n)
{
var cls:Class = data[i++];
var comp:Object = new cls();
i = initializeStrandBasedObject(document, parent, comp, data, i);
comps.push(comp);
}
return comps;
}
private static function initializeStrandBasedObject(document:Object, parent:IParent, comp:Object, data:Array, i:int):int
{
var m:int;
var j:int;
var name:String;
var simple:*;
var value:Object;
var id:String = null;
m = data[i++]; // num props
if (m > 0 && data[0] == "model")
{
m--;
name = data[i++];
simple = data[i++];
value = data[i++];
if (simple == null)
value = generateMXMLArray(document, parent, value as Array);
else if (simple == false)
value = generateMXMLObject(document, value as Array);
comp[name] = value;
if (value is IBead && comp is IStrand)
IStrand(comp).addBead(value as IBead);
}
var beadOffset:int = i + (m - 1) * 3;
//if (beadOffset >= -1)
// trace(beadOffset, data[beadOffset]);
if (m > 0 && data[beadOffset] == "beads")
{
m--;
}
else
beadOffset = -1;
for (j = 0; j < m; j++)
{
name = data[i++];
simple = data[i++];
value = data[i++];
if (simple == null)
value = generateMXMLArray(document, null, value as Array);
else if (simple == false)
value = generateMXMLObject(document, value as Array);
if (name == "id")
id = value as String;
if (name == "document" && !comp.document)
comp.document = document;
else if (name == "_id")
id = value as String; // and don't assign to comp
else if (name == "id")
{
// not all objects have to have their own id property
try {
comp["id"] = value;
} catch (e:Error)
{
}
}
else
comp[name] = value;
}
if (beadOffset > -1)
{
name = data[i++];
simple = data[i++];
value = data[i++];
if (simple == null)
value = generateMXMLArray(document, null, value as Array);
else if (simple == false)
value = generateMXMLObject(document, value as Array);
comp[name] = value;
}
m = data[i++]; // num styles
for (j = 0; j < m; j++)
{
name = data[i++];
simple = data[i++];
value = data[i++];
if (simple == null)
value = generateMXMLArray(document, null, value as Array);
else if (simple == false)
value = generateMXMLObject(document, value as Array);
comp.setStyle(name, value);
}
m = data[i++]; // num effects
for (j = 0; j < m; j++)
{
name = data[i++];
simple = data[i++];
value = data[i++];
if (simple == null)
value = generateMXMLArray(document, null, value as Array);
else if (simple == false)
value = generateMXMLObject(document, value as Array);
comp.setStyle(name, value);
}
m = data[i++]; // num events
for (j = 0; j < m; j++)
{
name = data[i++];
value = data[i++];
comp.addEventListener(name, value);
}
var children:Array = data[i++];
if (children && comp is IMXMLDocument)
{
comp.setMXMLDescriptor(document, children);
}
if (parent && comp is DisplayObject)
{
parent.addElement(comp, !(comp is IContainer));
}
if (children)
{
if (!(comp is IMXMLDocument))
{
generateMXMLInstances(document, comp as IParent, children);
// maybe we can remove this. All IContainers should be IMXMLDocuments?
if (comp is IContainer)
{
IContainer(comp).childrenAdded();
}
}
}
if (id)
document[id] = comp;
if (comp is IDocument)
comp.setDocument(document, id);
return i;
}
/**
* Generates the instances of objects in an MXML document based on the encoded data.
*
* @param document The MXML document. If the object has an id
* it will be assigned in this document in this method.
* @param parent The parent for any display objects encoded in the array.
* @param data The encoded data.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function generateMXMLInstances(document:Object, parent:IParent, data:Array):void
{
if (!data) return;
generateMXMLArray(document, parent, data);
}
/**
* Generates the properties of the top-level object in an MXML document
* based on the encoded data. This basically means setting the attributes
* found on the tag and child tags that aren't in the default property.
*
* @param host The MXML document. If the object has an id
* it will be assigned in this document in this method.
* @param data The encoded data.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function generateMXMLProperties(host:Object, data:Array):void
{
if (!data) return;
var i:int = 0;
var m:int;
var j:int;
var name:String;
var simple:*;
var value:Object;
var id:String = null;
m = data[i++]; // num props
var beadOffset:int = i + (m - 1) * 3;
//if (beadOffset >= -1)
// (beadOffset, data[beadOffset]);
if (m > 0 && data[beadOffset] == "beads")
{
m--;
}
else
beadOffset = -1;
for (j = 0; j < m; j++)
{
name = data[i++];
simple = data[i++];
value = data[i++];
if (simple == null)
value = generateMXMLArray(host, null, value as Array);
else if (simple == false)
value = generateMXMLObject(host, value as Array);
if (name == "id")
id = value as String;
if (name == "_id")
id = value as String; // and don't assign
else
host[name] = value;
}
if (beadOffset > -1)
{
name = data[i++];
simple = data[i++];
value = data[i++];
if (simple == null)
value = generateMXMLArray(host, null, value as Array);
else if (simple == false)
value = generateMXMLObject(host, value as Array);
host[name] = value;
}
m = data[i++]; // num styles
for (j = 0; j < m; j++)
{
name = data[i++];
simple = data[i++];
value = data[i++];
if (simple == null)
value = generateMXMLArray(host, null, value as Array);
else if (simple == false)
value = generateMXMLObject(host, value as Array);
host[name] = value;
}
m = data[i++]; // num effects
for (j = 0; j < m; j++)
{
name = data[i++];
simple = data[i++];
value = data[i++];
if (simple == null)
value = generateMXMLArray(host, null, value as Array);
else if (simple == false)
value = generateMXMLObject(host, value as Array);
host[name] = value;
}
m = data[i++]; // num events
for (j = 0; j < m; j++)
{
name = data[i++];
value = data[i++];
host.addEventListener(name, value as Function);
}
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.utils
{
import flash.display.DisplayObject;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IContainer;
import org.apache.flex.core.IDocument;
import org.apache.flex.core.IMXMLDocument;
import org.apache.flex.core.IParent;
import org.apache.flex.core.IStrand;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
/**
* The MXMLDataInterpreter class is the class that interprets the
* encoded information generated by the compiler that describes
* the contents of an MXML document.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class MXMLDataInterpreter
{
/**
* Constructor. All methods are static so should not be instantiated.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function MXMLDataInterpreter()
{
super();
}
/**
* Generates an object based on the encoded data.
*
* @param document The MXML document. If the object has an id
* it will be assigned in this document in this method.
* @param data The encoded data.
* @return The object.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function generateMXMLObject(document:Object, data:Array):Object
{
var i:int = 0;
var cls:Class = data[i++];
var comp:Object = new cls();
if (comp is IStrand)
initializeStrandBasedObject(document, null, comp, data, i);
else
{
var m:int;
var j:int;
var name:String;
var simple:*;
var value:Object;
var id:String;
m = data[i++]; // num props
for (j = 0; j < m; j++)
{
name = data[i++];
simple = data[i++];
value = data[i++];
if (simple == null)
value = generateMXMLArray(document, null, value as Array);
else if (simple == false)
value = generateMXMLObject(document, value as Array);
if (name == "id")
id = value as String;
if (name == "document" && !comp.document)
comp.document = document;
else if (name == "_id")
id = value as String; // and don't assign to comp
else if (name == "id")
{
// not all objects have to have their own id property
try {
comp["id"] = value;
} catch (e:Error)
{
}
}
else
comp[name] = value;
}
if (id)
document[id] = comp;
if (comp is IDocument)
comp.setDocument(document, id);
}
return comp;
}
/**
* Generates an Array of objects based on the encoded data.
*
* @param document The MXML document. If the object has an id
* it will be assigned in this document in this method.
* @param parent The parent for any display objects encoded in the array.
* @param data The encoded data.
* @return The Array.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function generateMXMLArray(document:Object, parent:IParent, data:Array):Array
{
var comps:Array = [];
var n:int = data.length;
var i:int = 0;
while (i < n)
{
var cls:Class = data[i++];
var comp:Object = new cls();
i = initializeStrandBasedObject(document, parent, comp, data, i);
comps.push(comp);
}
return comps;
}
private static function initializeStrandBasedObject(document:Object, parent:IParent, comp:Object, data:Array, i:int):int
{
var m:int;
var j:int;
var name:String;
var simple:*;
var value:Object;
var id:String = null;
m = data[i++]; // num props
if (m > 0 && data[0] == "model")
{
m--;
name = data[i++];
simple = data[i++];
value = data[i++];
if (simple == null)
value = generateMXMLArray(document, parent, value as Array);
else if (simple == false)
value = generateMXMLObject(document, value as Array);
comp[name] = value;
if (value is IBead && comp is IStrand)
IStrand(comp).addBead(value as IBead);
}
var beadOffset:int = i + (m - 1) * 3;
//if (beadOffset >= -1)
// trace(beadOffset, data[beadOffset]);
if (m > 0 && data[beadOffset] == "beads")
{
m--;
}
else
beadOffset = -1;
for (j = 0; j < m; j++)
{
name = data[i++];
simple = data[i++];
value = data[i++];
if (simple == null)
value = generateMXMLArray(document, null, value as Array);
else if (simple == false)
value = generateMXMLObject(document, value as Array);
if (name == "id")
id = value as String;
if (name == "document" && !comp.document)
comp.document = document;
else if (name == "_id")
id = value as String; // and don't assign to comp
else if (name == "id")
{
// not all objects have to have their own id property
try {
comp["id"] = value;
} catch (e:Error)
{
}
}
else
comp[name] = value;
}
if (beadOffset > -1)
{
name = data[i++];
simple = data[i++];
value = data[i++];
if (simple == null)
value = generateMXMLArray(document, null, value as Array);
else if (simple == false)
value = generateMXMLObject(document, value as Array);
comp[name] = value;
}
m = data[i++]; // num styles
for (j = 0; j < m; j++)
{
name = data[i++];
simple = data[i++];
value = data[i++];
if (simple == null)
value = generateMXMLArray(document, null, value as Array);
else if (simple == false)
value = generateMXMLObject(document, value as Array);
comp.setStyle(name, value);
}
m = data[i++]; // num effects
for (j = 0; j < m; j++)
{
name = data[i++];
simple = data[i++];
value = data[i++];
if (simple == null)
value = generateMXMLArray(document, null, value as Array);
else if (simple == false)
value = generateMXMLObject(document, value as Array);
comp.setStyle(name, value);
}
m = data[i++]; // num events
for (j = 0; j < m; j++)
{
name = data[i++];
value = data[i++];
comp.addEventListener(name, value);
}
var children:Array = data[i++];
if (children && comp is IMXMLDocument)
{
comp.setMXMLDescriptor(document, children);
}
if (parent && comp is DisplayObject)
{
parent.addElement(comp, !(comp is IContainer));
}
if (children)
{
if (!(comp is IMXMLDocument))
{
generateMXMLInstances(document, comp as IParent, children);
// maybe we can remove this. All IContainers should be IMXMLDocuments?
if (comp is IContainer)
{
IContainer(comp).childrenAdded();
}
}
}
if (id)
document[id] = comp;
if (comp is IDocument)
comp.setDocument(document, id);
return i;
}
/**
* Generates the instances of objects in an MXML document based on the encoded data.
*
* @param document The MXML document. If the object has an id
* it will be assigned in this document in this method.
* @param parent The parent for any display objects encoded in the array.
* @param data The encoded data.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function generateMXMLInstances(document:Object, parent:IParent, data:Array):void
{
if (!data) return;
generateMXMLArray(document, parent, data);
}
/**
* Generates the properties of the top-level object in an MXML document
* based on the encoded data. This basically means setting the attributes
* found on the tag and child tags that aren't in the default property.
*
* @param host The MXML document. If the object has an id
* it will be assigned in this document in this method.
* @param data The encoded data.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function generateMXMLProperties(host:Object, data:Array):void
{
if (!data) return;
var i:int = 0;
var m:int;
var j:int;
var name:String;
var simple:*;
var value:Object;
var id:String = null;
m = data[i++]; // num props
var beadOffset:int = i + (m - 1) * 3;
//if (beadOffset >= -1)
// (beadOffset, data[beadOffset]);
if (m > 0 && data[beadOffset] == "beads")
{
m--;
}
else
beadOffset = -1;
for (j = 0; j < m; j++)
{
name = data[i++];
simple = data[i++];
value = data[i++];
if (simple == null)
value = generateMXMLArray(host, null, value as Array);
else if (simple == false)
value = generateMXMLObject(host, value as Array);
if (name == "id")
id = value as String;
if (name == "_id")
id = value as String; // and don't assign
else
host[name] = value;
}
if (beadOffset > -1)
{
name = data[i++];
simple = data[i++];
value = data[i++];
if (simple == null)
value = generateMXMLArray(host, null, value as Array);
else if (simple == false)
value = generateMXMLObject(host, value as Array);
host[name] = value;
}
m = data[i++]; // num styles
for (j = 0; j < m; j++)
{
name = data[i++];
simple = data[i++];
value = data[i++];
if (simple == null)
value = generateMXMLArray(host, null, value as Array);
else if (simple == false)
value = generateMXMLObject(host, value as Array);
host[name] = value;
}
m = data[i++]; // num effects
for (j = 0; j < m; j++)
{
name = data[i++];
simple = data[i++];
value = data[i++];
if (simple == null)
value = generateMXMLArray(host, null, value as Array);
else if (simple == false)
value = generateMXMLObject(host, value as Array);
host[name] = value;
}
m = data[i++]; // num events
for (j = 0; j < m; j++)
{
name = data[i++];
value = data[i++];
host.addEventListener(name, value as Function);
}
}
}
}
|
fix id handling on objects
|
fix id handling on objects
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
53ff189d30e5c1add43fd695db6bccf8c0d29dfc
|
src/goplayer/ConfigurationParser.as
|
src/goplayer/ConfigurationParser.as
|
package goplayer
{
public class ConfigurationParser
{
public static const DEFAULT_API_URL : String
= "http://staging.streamio.se/api"
public static const DEFAULT_SKIN_URL : String = "goplayer-skin.swf"
public static const DEFAULT_TRACKER_ID : String = "global"
public static const VALID_PARAMETERS : Array = [
"api", "tracker", "skin", "video", "bitrate",
"enablertmp", "autoplay", "loop",
"skin:showchrome", "skin:showtitle" ]
private const result : Configuration = new Configuration
private var parameters : Object
private var originalParameterNames : Object
public function ConfigurationParser
(parameters : Object, originalParameterNames : Object)
{
this.parameters = parameters
this.originalParameterNames = originalParameterNames
}
public function execute() : void
{
result.apiURL = getString("api", DEFAULT_API_URL)
result.trackerID = getString("tracker", DEFAULT_TRACKER_ID)
result.skinURL = getString("skin", DEFAULT_SKIN_URL)
result.movieID = getString("video", null)
result.bitratePolicy = getBitratePolicy("bitrate", BitratePolicy.BEST)
result.enableRTMP = getBoolean("enablertmp", true)
result.enableAutoplay = getBoolean("autoplay", false)
result.enableLooping = getBoolean("loop", false)
result.enableChrome = getBoolean("skin:showchrome", true)
result.enableTitle = getBoolean("skin:showtitle", true)
}
public static function parse(parameters : Object) : Configuration
{
const normalizedParameters : Object = {}
const originalParameterNames : Object = {}
for (var name : String in parameters)
if (VALID_PARAMETERS.indexOf(normalize(name)) == -1)
reportUnknownParameter(name)
else
normalizedParameters[normalize(name)] = parameters[name],
originalParameterNames[normalize(name)] = name
const parser : ConfigurationParser = new ConfigurationParser
(normalizedParameters, originalParameterNames)
parser.execute()
return parser.result
}
private static function normalize(name : String) : String
{ return name.toLowerCase().replace(/[^a-z:]/g, "") }
private static function reportUnknownParameter(name : String) : void
{ debug("Error: Unknown parameter: " + name) }
// -----------------------------------------------------
private function getString(name : String, fallback : String) : String
{ return name in parameters ? parameters[name] : fallback }
private function getBoolean
(name : String, fallback : Boolean) : Boolean
{
if (name in parameters)
return $getBoolean(name, parameters[name], fallback)
else
return fallback
}
private function $getBoolean
(name : String, value : String, fallback : Boolean) : Boolean
{
try
{ return $$getBoolean(value) }
catch (error : Error)
{
reportInvalidParameter(name, value, ["true", "false"])
return fallback
}
throw new Error
}
private function $$getBoolean(value : String) : Boolean
{
if (value == "true")
return true
else if (value == "false")
return false
else
throw new Error
}
// -----------------------------------------------------
private function getBitratePolicy
(name : String, fallback : BitratePolicy) : BitratePolicy
{
if (name in parameters)
return $getBitratePolicy(name, parameters[name], fallback)
else
return fallback
}
private function $getBitratePolicy
(name : String, value : String,
fallback : BitratePolicy) : BitratePolicy
{
try
{ return $$getBitratePolicy(value) }
catch (error : Error)
{
reportInvalidParameter(name, value, BITRATE_POLICY_VALUES)
return fallback
}
throw new Error
}
private const BITRATE_POLICY_VALUES : Array =
["<number>kbps", "min", "max", "best"]
private function $$getBitratePolicy(value : String) : BitratePolicy
{
if (value == "max")
return BitratePolicy.MAX
else if (value == "min")
return BitratePolicy.MIN
else if (value == "best")
return BitratePolicy.BEST
else if (Bitrate.parse(value))
return BitratePolicy.specific(Bitrate.parse(value))
else
throw new Error
}
// -----------------------------------------------------
private function reportInvalidParameter
(name : String, value : String, validValues : Array) : void
{
debug("Error: Invalid parameter: " +
"“" + originalParameterNames[name] + "=" + value + "”; " +
getInvalidParameterHint(validValues) + ".")
}
private function getInvalidParameterHint(values : Array) : String
{ return $getInvalidParameterHint(getQuotedValues(values)) }
private function $getInvalidParameterHint(values : Array) : String
{
return "please use " +
"either " + values.slice(0, -1).join(", ") + " " +
"or " + values[values.length - 1]
}
private function getQuotedValues(values : Array) : Array
{
var result : Array = []
for each (var value : String in values)
result.push("“" + value + "”")
return result
}
}
}
|
package goplayer
{
public class ConfigurationParser
{
public static const DEFAULT_API_URL : String
= "http://staging.streamio.com/api"
public static const DEFAULT_SKIN_URL : String = "goplayer-skin.swf"
public static const DEFAULT_TRACKER_ID : String = "global"
public static const VALID_PARAMETERS : Array = [
"api", "tracker", "skin", "video", "bitrate",
"enablertmp", "autoplay", "loop",
"skin:showchrome", "skin:showtitle" ]
private const result : Configuration = new Configuration
private var parameters : Object
private var originalParameterNames : Object
public function ConfigurationParser
(parameters : Object, originalParameterNames : Object)
{
this.parameters = parameters
this.originalParameterNames = originalParameterNames
}
public function execute() : void
{
result.apiURL = getString("api", DEFAULT_API_URL)
result.trackerID = getString("tracker", DEFAULT_TRACKER_ID)
result.skinURL = getString("skin", DEFAULT_SKIN_URL)
result.movieID = getString("video", null)
result.bitratePolicy = getBitratePolicy("bitrate", BitratePolicy.BEST)
result.enableRTMP = getBoolean("enablertmp", true)
result.enableAutoplay = getBoolean("autoplay", false)
result.enableLooping = getBoolean("loop", false)
result.enableChrome = getBoolean("skin:showchrome", true)
result.enableTitle = getBoolean("skin:showtitle", true)
}
public static function parse(parameters : Object) : Configuration
{
const normalizedParameters : Object = {}
const originalParameterNames : Object = {}
for (var name : String in parameters)
if (VALID_PARAMETERS.indexOf(normalize(name)) == -1)
reportUnknownParameter(name)
else
normalizedParameters[normalize(name)] = parameters[name],
originalParameterNames[normalize(name)] = name
const parser : ConfigurationParser = new ConfigurationParser
(normalizedParameters, originalParameterNames)
parser.execute()
return parser.result
}
private static function normalize(name : String) : String
{ return name.toLowerCase().replace(/[^a-z:]/g, "") }
private static function reportUnknownParameter(name : String) : void
{ debug("Error: Unknown parameter: " + name) }
// -----------------------------------------------------
private function getString(name : String, fallback : String) : String
{ return name in parameters ? parameters[name] : fallback }
private function getBoolean
(name : String, fallback : Boolean) : Boolean
{
if (name in parameters)
return $getBoolean(name, parameters[name], fallback)
else
return fallback
}
private function $getBoolean
(name : String, value : String, fallback : Boolean) : Boolean
{
try
{ return $$getBoolean(value) }
catch (error : Error)
{
reportInvalidParameter(name, value, ["true", "false"])
return fallback
}
throw new Error
}
private function $$getBoolean(value : String) : Boolean
{
if (value == "true")
return true
else if (value == "false")
return false
else
throw new Error
}
// -----------------------------------------------------
private function getBitratePolicy
(name : String, fallback : BitratePolicy) : BitratePolicy
{
if (name in parameters)
return $getBitratePolicy(name, parameters[name], fallback)
else
return fallback
}
private function $getBitratePolicy
(name : String, value : String,
fallback : BitratePolicy) : BitratePolicy
{
try
{ return $$getBitratePolicy(value) }
catch (error : Error)
{
reportInvalidParameter(name, value, BITRATE_POLICY_VALUES)
return fallback
}
throw new Error
}
private const BITRATE_POLICY_VALUES : Array =
["<number>kbps", "min", "max", "best"]
private function $$getBitratePolicy(value : String) : BitratePolicy
{
if (value == "max")
return BitratePolicy.MAX
else if (value == "min")
return BitratePolicy.MIN
else if (value == "best")
return BitratePolicy.BEST
else if (Bitrate.parse(value))
return BitratePolicy.specific(Bitrate.parse(value))
else
throw new Error
}
// -----------------------------------------------------
private function reportInvalidParameter
(name : String, value : String, validValues : Array) : void
{
debug("Error: Invalid parameter: " +
"“" + originalParameterNames[name] + "=" + value + "”; " +
getInvalidParameterHint(validValues) + ".")
}
private function getInvalidParameterHint(values : Array) : String
{ return $getInvalidParameterHint(getQuotedValues(values)) }
private function $getInvalidParameterHint(values : Array) : String
{
return "please use " +
"either " + values.slice(0, -1).join(", ") + " " +
"or " + values[values.length - 1]
}
private function getQuotedValues(values : Array) : Array
{
var result : Array = []
for each (var value : String in values)
result.push("“" + value + "”")
return result
}
}
}
|
Change default Streamio API URL to use .com instead of .se.
|
Change default Streamio API URL to use .com instead of .se.
|
ActionScript
|
mit
|
dbrock/goplayer,dbrock/goplayer
|
fc02505592e859a72535209d016c0299432d91b8
|
nuxeo-platform-ui-flex/nuxeo-flex-components/src/main/flex/org/nuxeo/ecm/flex/dto/FlexDocumentModel.as
|
nuxeo-platform-ui-flex/nuxeo-flex-components/src/main/flex/org/nuxeo/ecm/flex/dto/FlexDocumentModel.as
|
package org.nuxeo.ecm.flex.dto
{
import mx.collections.ArrayCollection;
import flash.utils.IExternalizable;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import mx.core.IUID;
[RemoteClass(alias="org.nuxeo.ecm.flex.javadto.FlexDocumentModel")]
public class FlexDocumentModel implements IExternalizable, IUID
{
private var _docRef:String;
private var _name:String;
private var _path:String;
private var _lifeCycleState:String;
private var _data:Object;
private var _dirty:Object;
private var _type:String;
private var _isFolder:Boolean;
public function FlexDocumentModel()
{
_name="init_from_flex";
}
public function setup(type:String,name:String,parentPath:String):void
{
_type=type;
_name=name;
_path=parentPath+_name;
_dirty = new Object();
_data = new Object();
}
public function get uid(): String
{
return _docRef;
}
public function set uid(uid:String): void
{
}
public function readExternal(input:IDataInput):void {
_docRef = input.readUTF();
_name = input.readUTF();
_path = input.readUTF();
_lifeCycleState = input.readUTF();
_type=input.readUTF();
_isFolder=input.readBoolean();
_data = input.readObject();
_dirty = new Object();
}
public function writeExternal(output:IDataOutput):void {
output.writeUTF(_docRef);
output.writeUTF(_name);
output.writeUTF(_path);
output.writeUTF(_lifeCycleState);
output.writeUTF(_type);
output.writeObject(_dirty);
//output.writeObject(_data);
}
public function get id():String
{
return _docRef;
}
public function get name():String
{
return _name;
}
public function get contentdata():Object
{
return _data;
}
public function set name(value:String):void
{
_name= value;
}
public function getTitle():String
{
//return "fakeTitle";
return _data.dublincore.title;
}
public function setTitle(value:String):void
{
_data.dublincore.title=value;
_dirty.dublincore_title=value;
}
public function getProperty(schemaName:String, fieldName:String):String
{
return _data[schemaName][fieldName];
}
public function setProperty(schemaName:String, fieldName:String, value:String):void
{
_data[schemaName][fieldName]=value;
_dirty[schemaName+":"+fieldName]=value;
}
public function isFolder():Boolean
{
return _isFolder;
}
}
}
|
package org.nuxeo.ecm.flex.dto
{
import mx.collections.ArrayCollection;
import flash.utils.IExternalizable;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import mx.core.IUID;
[RemoteClass(alias="org.nuxeo.ecm.flex.javadto.FlexDocumentModel")]
public class FlexDocumentModel implements IExternalizable, IUID
{
private var _docRef:String;
private var _name:String;
private var _path:String;
private var _lifeCycleState:String;
private var _data:Object;
private var _dirty:Object;
private var _type:String;
private var _isFolder:Boolean;
public function FlexDocumentModel()
{
_name="init_from_flex";
}
public function setup(type:String,name:String,parentPath:String):void
{
_type=type;
_name=name;
_path=parentPath+_name;
_dirty = new Object();
_data = new Object();
}
public function get uid(): String
{
return _docRef;
}
public function set uid(uid:String): void
{
}
public function readExternal(input:IDataInput):void {
_docRef = input.readUTF();
_name = input.readUTF();
_path = input.readUTF();
_lifeCycleState = input.readUTF();
_type=input.readUTF();
_isFolder=input.readBoolean();
_data = input.readObject();
_dirty = new Object();
}
public function writeExternal(output:IDataOutput):void {
output.writeUTF(_docRef);
output.writeUTF(_name);
output.writeUTF(_path);
output.writeUTF(_lifeCycleState);
output.writeUTF(_type);
output.writeObject(_dirty);
//output.writeObject(_data);
}
public function get id():String
{
return _docRef;
}
public function get name():String
{
return _name;
}
public function get doctype():String
{
return _type;
}
public function get contentdata():Object
{
return _data;
}
public function set name(value:String):void
{
_name= value;
}
public function getTitle():String
{
//return "fakeTitle";
return _data.dublincore.title;
}
public function setTitle(value:String):void
{
_data.dublincore.title=value;
_dirty.dublincore_title=value;
}
public function getProperty(schemaName:String, fieldName:String):String
{
return _data[schemaName][fieldName];
}
public function setProperty(schemaName:String, fieldName:String, value:String):void
{
_data[schemaName][fieldName]=value;
_dirty[schemaName+":"+fieldName]=value;
}
public function isFolder():Boolean
{
return _isFolder;
}
public function getSchemas():Array
{
var schemas:Array = new Array();
var schemaName:Object;
for (schemaName in _data)
{
schemas.push(schemaName);
}
return schemas;
}
public function getSchema(schemaName:String):Object
{
return _data[schemaName];
}
public function getFieldNames(schemaName:String):Array
{
var fieldNames:Array = new Array();
var fieldName:Object;
for (fieldName in _data[schemaName])
{
fieldNames.push(fieldName);
}
return fieldNames;
}
}
}
|
Add introspection to FlexDocumentModel
|
Add introspection to FlexDocumentModel
|
ActionScript
|
lgpl-2.1
|
nuxeo-archives/nuxeo-features,deadcyclo/nuxeo-features,deadcyclo/nuxeo-features,nuxeo-archives/nuxeo-features,deadcyclo/nuxeo-features,nuxeo-archives/nuxeo-features,bjalon/nuxeo-features,nuxeo-archives/nuxeo-features,deadcyclo/nuxeo-features,bjalon/nuxeo-features,nuxeo-archives/nuxeo-features,bjalon/nuxeo-features,deadcyclo/nuxeo-features,bjalon/nuxeo-features,bjalon/nuxeo-features,bjalon/nuxeo-features,deadcyclo/nuxeo-features
|
4864b87d44bcb7bd5413eaa247266e2c45fef99f
|
mustella/as3/src/mustella/ConditionalValue.as
|
mustella/as3/src/mustella/ConditionalValue.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package
{
import flash.events.*;
import mx.utils.*;
[Event(name="valueExpression", type="RunCodeEvent")]
public class ConditionalValue extends EventDispatcher
{
// Asserts such as AssertPropertyValue use value=...
public var value:Object = null;
// CompareBitmap uses url=...
public var url:String = null;
/**
* These are possibilities for the environment.
* Use Inspectable so that test authoring is a little easier.
* For details: https://zerowing.corp.adobe.com/display/flexmobile/Multiple+Device%2C+DPI%2C+OS+Support
**/
[Inspectable(enumeration="win,mac,android,iphone,ios,qnx")]
public var os:String = null;
[Inspectable(enumeration="android22,android23,android234,android31,iphone421,iphone50,ios4,ios5,ios6")]
public var osVersion:String = null;
/**
* The targetOS is either null or set in the UnitTester's cv as the value to match
* against the os properties from <ConditionalValue> elements present in the test
* cases. See MultiResult.chooseCV()
*/
[Inspectable(enumeration="android,ios")]
public var targetOS:String = null;
// General, "marketing number" pixel density
[Inspectable(enumeration="160,240,320,480")]
public var deviceDensity:Number = -1;
// Exact pixel density reported by AIR's Capabilities.screenDPI
public var screenDPI:Number = -1;
// Exact
public var deviceWidth:Number = -1;
// Exact
public var deviceHeight:Number = -1;
[Inspectable(enumeration="16,32")]
public var color:Number = -1;
[Inspectable(enumeration="air,desire,droid,droid2,droidPro,droidX,evo,incredible,iPad,iPad2,iPodTouch3GS,iPodTouch4G,nexusOne,playbook,xoom")]
public var device:String = null;
/**
* These are used to make file name legible to humans and allow
* parsing of them.
**/
public static const SCREENDPI_SUFFIX:String = "scrDPI";
public static const DENSITY_SUFFIX:String = "ppi";
public static const WIDTH_SUFFIX:String = "w";
public static const HEIGHT_SUFFIX:String = "h";
public static const COLOR_SUFFIX:String = "bit";
public static const PNG_SUFFIX:String = ".png";
public static const DELIMITER1:String = "@"; // between testID and settings
public static const DELIMITER2:String = "_"; // between settings
/**
* Constructor
**/
public function ConditionalValue(){}
/**
* Returns true if all items are at default values (e.g. the default, catch-all CV).
**/
public function isDefault():Boolean{
return ((os == null) &&
(osVersion == null) &&
(screenDPI == -1) &&
(deviceDensity == -1) &&
(deviceWidth == -1) &&
(deviceHeight == -1) &&
(color == -1) &&
(device == null) &&
(targetOS == null)
);
}
/**
* Uses the properties which are set to create a file name for a baseline image.
**/
public function createFilename(testID:String):String{
var ret:String = null;
var consistent:Boolean = false;
var testCV:ConditionalValue = new ConditionalValue();
ret = testID + DELIMITER1;
if( os != null ) {
ret += os + DELIMITER2;
}
/* if( targetOS != null ) {
ret += targetOS + DELIMITER2;
}*/
if( osVersion != null ){
ret += osVersion + DELIMITER2;
}
if( screenDPI > -1 ){
ret += screenDPI.toString() + SCREENDPI_SUFFIX + DELIMITER2;
}
if( deviceDensity > -1 ){
ret += deviceDensity.toString() + DENSITY_SUFFIX + DELIMITER2;
}
if( deviceWidth > -1 ){
ret += deviceWidth.toString() + WIDTH_SUFFIX + DELIMITER2;
}
if( deviceHeight > -1 ){
ret += deviceHeight.toString() + HEIGHT_SUFFIX + DELIMITER2;
}
if( color > -1 ){
ret += color.toString() + COLOR_SUFFIX + DELIMITER2;
}
if( device != null ){
ret += device;
}else{
// Remove last DELIMITER2.
if( ret.lastIndexOf(DELIMITER2) == ret.length - 1 ){
ret = ret.substr(0, ret.length - 1);
}
}
ret += PNG_SUFFIX;
trace("ConditionalValue ret="+ret+"; screenDPI="+screenDPI+"; density="+deviceDensity);
// Be sure we'll be able to parse what we wrote when we read it later.
if( testCV.parseFilename( ret ) ){
consistent = (testCV.os == os &&
testCV.osVersion == osVersion &&
testCV.screenDPI == screenDPI &&
testCV.deviceDensity == deviceDensity &&
testCV.deviceWidth == deviceWidth &&
testCV.deviceHeight == deviceHeight &&
testCV.color == color &&
testCV.device == device );
}
if( consistent ){
return ret;
}else{
trace("ConditionalValue inconsistency:");
trace("\twhat\ttestCV\tactualCV");
trace("\tos\t" + testCV.os + "\t" + os);
trace("\tosVersion\t" + testCV.osVersion + "\t" + osVersion);
trace("\tscreenDPI\t" + testCV.screenDPI + "\t" + screenDPI);
trace("\tdeviceDensity\t" + testCV.deviceDensity + "\t" + deviceDensity);
trace("\tdeviceWidth\t" + testCV.deviceWidth + "\t" + deviceWidth);
trace("\tdeviceHeight\t" + testCV.deviceHeight + "\t" + deviceHeight);
trace("\tcolor\t" + testCV.color + "\t" + color);
trace("\tdevice\t" + testCV.device + "\t" + device);
return null;
}
}
/**
* Populate values from a filename.
**/
public function parseFilename(filename:String):Boolean{
var tokens:Array = null;
var curToken:String = null;
var tokenDone:Boolean = false;
var i:int = 0;
var j:int = 0;
if( filename != null ){
// Remove the extension.
if( filename.indexOf( PNG_SUFFIX ) > -1 ){
filename = filename.substring( 0, filename.indexOf( PNG_SUFFIX ) );
}
if( (filename != null) && (StringUtil.trim( filename ) != "") ){
tokens = filename.split( DELIMITER1 );
}
// tokens[0] is the test case, and tokens[1] is the data.
tokens = tokens[1].split( DELIMITER2 );
if( (tokens != null) && (tokens.length > 0) ){
for( i = 0; i < tokens.length; ++i ){
curToken = tokens[ i ];
tokenDone = false;
// Look for os.
for( j = 0; j < DeviceNames.OS_VALUES.length; ++j ){
if( curToken == DeviceNames.OS_VALUES[ j ] ){
os = curToken;
targetOS = curToken;
tokenDone = true;
break;
}
}
if( !tokenDone ){
// Look for os version.
for( j = 0; j < DeviceNames.OS_VERSION_VALUES.length; ++j ){
if( curToken == DeviceNames.OS_VERSION_VALUES[ j ] ){
osVersion = curToken;
tokenDone = true;
break;
}
}
}
if( !tokenDone ){
// Look for screenDPI
if( curToken.indexOf( SCREENDPI_SUFFIX ) > -1 ){
curToken = curToken.substring( 0, curToken.indexOf( SCREENDPI_SUFFIX ) );
if( (curToken != null) && (StringUtil.trim( curToken ) != "") ){
screenDPI = new Number( curToken );
tokenDone = true;
}
}
}
if( !tokenDone ){
// Look for density.
if( curToken.indexOf( DENSITY_SUFFIX ) > -1 ){
curToken = curToken.substring( 0, curToken.indexOf( DENSITY_SUFFIX ) );
if( (curToken != null) && (StringUtil.trim( curToken ) != "") ){
deviceDensity = new Number( curToken );
tokenDone = true;
}
}
}
if( !tokenDone ){
// Look for width.
if( curToken.indexOf( WIDTH_SUFFIX ) > -1 ){
curToken = curToken.substring( 0, curToken.indexOf( WIDTH_SUFFIX ) );
if( (curToken != null) && (StringUtil.trim( curToken ) != "") ){
deviceWidth = new Number( curToken );
tokenDone = true;
}
}
}
if( !tokenDone ){
// Look for height.
if( curToken.indexOf( HEIGHT_SUFFIX ) > -1 ){
curToken = curToken.substring( 0, curToken.indexOf( HEIGHT_SUFFIX ) );
if( (curToken != null) && (StringUtil.trim( curToken ) != "") ){
deviceHeight = new Number( curToken );
tokenDone = true;
}
}
}
if( !tokenDone ){
// Look for color.
if( curToken.indexOf( COLOR_SUFFIX ) > -1 ){
curToken = curToken.substring( 0, curToken.indexOf( COLOR_SUFFIX ) );
if( (curToken != null) && (StringUtil.trim( curToken ) != "") ){
color = new Number( curToken );
tokenDone = true;
}
}
}
if( !tokenDone ){
// Look for device.
for( j = 0; j < DeviceNames.DEVICE_VALUES.length; ++j ){
if( curToken == DeviceNames.DEVICE_VALUES[ j ] ){
device = curToken;
tokenDone = true;
break;
}
}
}
if( !tokenDone ){
trace("trouble with token: " + curToken);
}
}
}
}
// If anything went wrong, tokenDone will be false.
return tokenDone;
}
/**
* Return a list of the properties.
**/
override public function toString():String{
var ret:String;
ret = "\tvalue=" + String(value);
ret += "\n\turl=" + url;
ret += "\n\tos=" + os;
ret += "\n\ttargetOS=" + targetOS;
ret += "\n\tosVersion=" + osVersion;
ret += "\n\tscreenDPI=" + screenDPI;
ret += "\n\tdeviceDensity=" + deviceDensity;
ret += "\n\tdeviceWidth=" + deviceWidth;
ret += "\n\tdeviceHeight=" + deviceHeight;
ret += "\n\tcolor=" + color;
ret += "\n\tdevice=" + device;
return ret;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package
{
import flash.events.*;
import mx.utils.*;
[Event(name="valueExpression", type="RunCodeEvent")]
public class ConditionalValue extends EventDispatcher
{
// Asserts such as AssertPropertyValue use value=...
public var value:Object = null;
// CompareBitmap uses url=...
public var url:String = null;
/**
* These are possibilities for the environment.
* Use Inspectable so that test authoring is a little easier.
* For details: https://zerowing.corp.adobe.com/display/flexmobile/Multiple+Device%2C+DPI%2C+OS+Support
**/
[Inspectable(enumeration="win,mac,android,iphone,ios,qnx")]
public var os:String = null;
[Inspectable(enumeration="android22,android23,android234,android31,iphone421,iphone50,ios4,ios5,ios6")]
public var osVersion:String = null;
/**
* The targetOS is either null or set in the UnitTester's cv as the value to match
* against the os properties from <ConditionalValue> elements present in the test
* cases. See MultiResult.chooseCV()
*/
[Inspectable(enumeration="android,ios")]
public var targetOS:String = null;
// General, "marketing number" pixel density
[Inspectable(enumeration="120,160,240,320,480,640")]
public var deviceDensity:Number = -1;
// Exact pixel density reported by AIR's Capabilities.screenDPI
public var screenDPI:Number = -1;
// Exact
public var deviceWidth:Number = -1;
// Exact
public var deviceHeight:Number = -1;
[Inspectable(enumeration="16,32")]
public var color:Number = -1;
[Inspectable(enumeration="air,desire,droid,droid2,droidPro,droidX,evo,incredible,iPad,iPad2,iPodTouch3GS,iPodTouch4G,nexusOne,playbook,xoom")]
public var device:String = null;
/**
* These are used to make file name legible to humans and allow
* parsing of them.
**/
public static const SCREENDPI_SUFFIX:String = "scrDPI";
public static const DENSITY_SUFFIX:String = "ppi";
public static const WIDTH_SUFFIX:String = "w";
public static const HEIGHT_SUFFIX:String = "h";
public static const COLOR_SUFFIX:String = "bit";
public static const PNG_SUFFIX:String = ".png";
public static const DELIMITER1:String = "@"; // between testID and settings
public static const DELIMITER2:String = "_"; // between settings
/**
* Constructor
**/
public function ConditionalValue(){}
/**
* Returns true if all items are at default values (e.g. the default, catch-all CV).
**/
public function isDefault():Boolean{
return ((os == null) &&
(osVersion == null) &&
(screenDPI == -1) &&
(deviceDensity == -1) &&
(deviceWidth == -1) &&
(deviceHeight == -1) &&
(color == -1) &&
(device == null) &&
(targetOS == null)
);
}
/**
* Uses the properties which are set to create a file name for a baseline image.
**/
public function createFilename(testID:String):String{
var ret:String = null;
var consistent:Boolean = false;
var testCV:ConditionalValue = new ConditionalValue();
ret = testID + DELIMITER1;
if( os != null ) {
ret += os + DELIMITER2;
}
/* if( targetOS != null ) {
ret += targetOS + DELIMITER2;
}*/
if( osVersion != null ){
ret += osVersion + DELIMITER2;
}
if( screenDPI > -1 ){
ret += screenDPI.toString() + SCREENDPI_SUFFIX + DELIMITER2;
}
if( deviceDensity > -1 ){
ret += deviceDensity.toString() + DENSITY_SUFFIX + DELIMITER2;
}
if( deviceWidth > -1 ){
ret += deviceWidth.toString() + WIDTH_SUFFIX + DELIMITER2;
}
if( deviceHeight > -1 ){
ret += deviceHeight.toString() + HEIGHT_SUFFIX + DELIMITER2;
}
if( color > -1 ){
ret += color.toString() + COLOR_SUFFIX + DELIMITER2;
}
if( device != null ){
ret += device;
}else{
// Remove last DELIMITER2.
if( ret.lastIndexOf(DELIMITER2) == ret.length - 1 ){
ret = ret.substr(0, ret.length - 1);
}
}
ret += PNG_SUFFIX;
trace("ConditionalValue ret="+ret+"; screenDPI="+screenDPI+"; density="+deviceDensity);
// Be sure we'll be able to parse what we wrote when we read it later.
if( testCV.parseFilename( ret ) ){
consistent = (testCV.os == os &&
testCV.osVersion == osVersion &&
testCV.screenDPI == screenDPI &&
testCV.deviceDensity == deviceDensity &&
testCV.deviceWidth == deviceWidth &&
testCV.deviceHeight == deviceHeight &&
testCV.color == color &&
testCV.device == device );
}
if( consistent ){
return ret;
}else{
trace("ConditionalValue inconsistency:");
trace("\twhat\ttestCV\tactualCV");
trace("\tos\t" + testCV.os + "\t" + os);
trace("\tosVersion\t" + testCV.osVersion + "\t" + osVersion);
trace("\tscreenDPI\t" + testCV.screenDPI + "\t" + screenDPI);
trace("\tdeviceDensity\t" + testCV.deviceDensity + "\t" + deviceDensity);
trace("\tdeviceWidth\t" + testCV.deviceWidth + "\t" + deviceWidth);
trace("\tdeviceHeight\t" + testCV.deviceHeight + "\t" + deviceHeight);
trace("\tcolor\t" + testCV.color + "\t" + color);
trace("\tdevice\t" + testCV.device + "\t" + device);
return null;
}
}
/**
* Populate values from a filename.
**/
public function parseFilename(filename:String):Boolean{
var tokens:Array = null;
var curToken:String = null;
var tokenDone:Boolean = false;
var i:int = 0;
var j:int = 0;
if( filename != null ){
// Remove the extension.
if( filename.indexOf( PNG_SUFFIX ) > -1 ){
filename = filename.substring( 0, filename.indexOf( PNG_SUFFIX ) );
}
if( (filename != null) && (StringUtil.trim( filename ) != "") ){
tokens = filename.split( DELIMITER1 );
}
// tokens[0] is the test case, and tokens[1] is the data.
tokens = tokens[1].split( DELIMITER2 );
if( (tokens != null) && (tokens.length > 0) ){
for( i = 0; i < tokens.length; ++i ){
curToken = tokens[ i ];
tokenDone = false;
// Look for os.
for( j = 0; j < DeviceNames.OS_VALUES.length; ++j ){
if( curToken == DeviceNames.OS_VALUES[ j ] ){
os = curToken;
targetOS = curToken;
tokenDone = true;
break;
}
}
if( !tokenDone ){
// Look for os version.
for( j = 0; j < DeviceNames.OS_VERSION_VALUES.length; ++j ){
if( curToken == DeviceNames.OS_VERSION_VALUES[ j ] ){
osVersion = curToken;
tokenDone = true;
break;
}
}
}
if( !tokenDone ){
// Look for screenDPI
if( curToken.indexOf( SCREENDPI_SUFFIX ) > -1 ){
curToken = curToken.substring( 0, curToken.indexOf( SCREENDPI_SUFFIX ) );
if( (curToken != null) && (StringUtil.trim( curToken ) != "") ){
screenDPI = new Number( curToken );
tokenDone = true;
}
}
}
if( !tokenDone ){
// Look for density.
if( curToken.indexOf( DENSITY_SUFFIX ) > -1 ){
curToken = curToken.substring( 0, curToken.indexOf( DENSITY_SUFFIX ) );
if( (curToken != null) && (StringUtil.trim( curToken ) != "") ){
deviceDensity = new Number( curToken );
tokenDone = true;
}
}
}
if( !tokenDone ){
// Look for width.
if( curToken.indexOf( WIDTH_SUFFIX ) > -1 ){
curToken = curToken.substring( 0, curToken.indexOf( WIDTH_SUFFIX ) );
if( (curToken != null) && (StringUtil.trim( curToken ) != "") ){
deviceWidth = new Number( curToken );
tokenDone = true;
}
}
}
if( !tokenDone ){
// Look for height.
if( curToken.indexOf( HEIGHT_SUFFIX ) > -1 ){
curToken = curToken.substring( 0, curToken.indexOf( HEIGHT_SUFFIX ) );
if( (curToken != null) && (StringUtil.trim( curToken ) != "") ){
deviceHeight = new Number( curToken );
tokenDone = true;
}
}
}
if( !tokenDone ){
// Look for color.
if( curToken.indexOf( COLOR_SUFFIX ) > -1 ){
curToken = curToken.substring( 0, curToken.indexOf( COLOR_SUFFIX ) );
if( (curToken != null) && (StringUtil.trim( curToken ) != "") ){
color = new Number( curToken );
tokenDone = true;
}
}
}
if( !tokenDone ){
// Look for device.
for( j = 0; j < DeviceNames.DEVICE_VALUES.length; ++j ){
if( curToken == DeviceNames.DEVICE_VALUES[ j ] ){
device = curToken;
tokenDone = true;
break;
}
}
}
if( !tokenDone ){
trace("trouble with token: " + curToken);
}
}
}
}
// If anything went wrong, tokenDone will be false.
return tokenDone;
}
/**
* Return a list of the properties.
**/
override public function toString():String{
var ret:String;
ret = "\tvalue=" + String(value);
ret += "\n\turl=" + url;
ret += "\n\tos=" + os;
ret += "\n\ttargetOS=" + targetOS;
ret += "\n\tosVersion=" + osVersion;
ret += "\n\tscreenDPI=" + screenDPI;
ret += "\n\tdeviceDensity=" + deviceDensity;
ret += "\n\tdeviceWidth=" + deviceWidth;
ret += "\n\tdeviceHeight=" + deviceHeight;
ret += "\n\tcolor=" + color;
ret += "\n\tdevice=" + device;
return ret;
}
}
}
|
support 120 and 640 dpi in mustella tests
|
support 120 and 640 dpi in mustella tests
|
ActionScript
|
apache-2.0
|
shyamalschandra/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk
|
58eb5cda60de22a2eb4b1b04bf39ba6513621170
|
WEB-INF/lps/lfc/debugger/platform/swf/LzRemote.as
|
WEB-INF/lps/lfc/debugger/platform/swf/LzRemote.as
|
/******************************************************************************
* LzRemote.as
*****************************************************************************/
//* A_LZ_COPYRIGHT_BEGIN ******************************************************
//* Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved. *
//* Use is subject to license terms. *
//* A_LZ_COPYRIGHT_END ********************************************************
// This file implements the remote debugger protocol.
// When the app starts up, if the query arg remotedebug (global.remotedebug)
// is defined, it is treated as a TCP port number and a remote debug
// socket is opened to that port.
Debug.seqnum = 0;
Debug.inEvalRequest = false;
/**
* @access private
*/
Debug.sockOpen = function (port) {
var url = lz.Browser.getLoadURLAsLzURL();
// Security requires us to talk back to the server we were loaded from
var host = url.host;
this.xsock = new XMLSocket();
this.xsock.onClose = this.brokensocket;
this.xsock.onXML = this.socketXMLAvailable;
if (! this.xsock.connect(host, port)) {
Debug.log("remote debugger could not connect to listener " + host + ":" + port);
}
this.writeInitMessage();
}
/**
* @access private
*/
Debug.writeInitMessage = function () {
var filename = lz.Browser.getLoadURLAsLzURL();
var myXML = new XML();
var init = myXML.createElement("init");
myXML.appendChild(init);
init.attributes.filename = filename;
init.attributes.language = "LZX";
init.attributes.protocol_version = "1.0";
init.attributes.build = canvas.lpsbuild;
init.attributes.lpsversion = canvas.lpsversion;
init.attributes.lpsrelease = canvas.lpsrelease;
init.attributes.runtime = canvas.runtime;
init.attributes.appid = "0";
this.xsock.send(myXML);
}
/**
* @access private
*/
Debug.sockWriteWarning = function (filename, lineNumber, msg){
var myXML = new XML();
var warn = myXML.createElement("warning");
myXML.appendChild(warn);
warn.attributes.filename = filename;
warn.attributes.line = lineNumber;
warn.attributes.msg = msg;
this.xsock.send(myXML);
}
/**
* @access private
*/
Debug.sockWriteLog = function (msg) {
var myXML = new XML();
var response = myXML.createElement("log");
myXML.appendChild(response);
response.attributes.msg = msg;
this.xsock.send(myXML);
}
/**
* @access private
*/
Debug.sockWrite = function (s) {
this.xsock.send(s);
this.xsock.send("\n");
return s;
}
/**
* @access private
* Writes out an object as XML
*/
Debug.sockWriteAsXML = function (obj, seqnum) {
var myXML = new XML();
var response = myXML.createElement("response");
response.attributes.seq = seqnum;
myXML.appendChild(response);
var val = myXML.createElement("value");
response.appendChild(val);
var objtype = typeof(obj);
val.attributes.type = Debug.__typeof(obj);
val.attributes.value = String(obj);
if (objtype == "object") {
var id = Debug.IDForObject(obj);
if (id != null) {
val.attributes.id = id;
}
}
for (var attr in obj) {
var child = obj[attr];
var prop = myXML.createElement("property");
prop.attributes.name = attr;
prop.attributes.type = Debug.__typeof(child);
prop.attributes.value = String(child);
var objtype = typeof(child);
if (objtype == "object") {
var id = Debug.IDForObject(child);
if (id != null) {
prop.attributes.id = id;
}
}
val.appendChild(prop);
}
for (var i = 0; i < this.xmlwarnings.length; i++) {
var w = this.xmlwarnings[i];
var filename = w[0];
var line = w[1];
var msg = w[2];
var warn = myXML.createElement("warning");
warn.attributes.filename = filename;
warn.attributes.line = line;
warn.attributes.msg = msg;
response.appendChild(warn);
}
this.xsock.send(myXML);
Debug.inEvalRequest = false;
return obj;
}
/**
* @access private
*/
Debug.sockClose = function () {
Debug.xsock.close();
}
/**
* @access private
* send message to server that socket is gone
*/
Debug.brokensocket = function () {
Debug.error("socket connection is broken");
}
////////////////////////////////////////////////////////////////
// Redefine the handler for eval warnings, to grab them so we can send them
// back as XML.
/**
* @access private
*/
Debug.resetWarningHistory = function () {
Debug.xmlwarnings = [];
}
Debug.resetWarningHistory();
////////////////////////////////////////////////////////////////
/**
* @access private
*/
Debug.socketXMLAvailable = function (doc) {
var e = doc.firstChild;
var rloader = Debug.rdbloader;
if (e != null) {
// clear warnings history
Debug.resetWarningHistory();
Debug.inEvalRequest = true;
var seqnum = e.attributes['seq'];
if (seqnum == null) {
seqnum = Debug.seqnum++;
}
if (e.nodeName == "exec") {
var expr = e.firstChild.nodeValue;
rloader.request( { lz_load : false,
lzt : "eval",
proxied: true,
lzrdbseq : seqnum,
lz_script : "#file evalString\n#line 0\n" + expr } );
} else if (e.nodeName == "eval") {
var expr = e.firstChild.nodeValue;
rloader.request( { lz_load : false,
lzt : "eval",
proxied: true,
lzrdbseq : seqnum,
lz_script : "#file evalString\n#line 0\n" + expr } );
} else if (e.nodeName == "inspect") {
Debug.inEvalRequest = false;
var id = e.attributes.id;
Debug.sockWriteAsXML(Debug.ObjectForID(id), seqnum);
} else {
Debug.inEvalRequest = false;
Debug.sockWrite("<response seq='"+seqnum+"'><error msg='unknown remote debug command'>"+e.nodeName+"</error></response>");
}
} else {
Debug.inEvalRequest = false;
Debug.sockWrite("<response seq='-1'><error msg='null remote debug command'/></response>");
}
}
/**
* @access private
*/
Debug.makeRDBLoader = function () {
this.rdbloader = new LzLoader(canvas, { attachname: 'rdebugloader' });
this.rdbloader.queuing = true;
}
/**
* @access private
* query arg 'remotedebug', if supplied, specifies a TCP port to connect to
*/
Debug.startupRemote = function () {
if (typeof(remotedebug) != 'undefined') {
Debug.remoteDebug = true;
Debug.makeRDBLoader();
Debug.sockOpen(remotedebug);
}
}
|
/******************************************************************************
* LzRemote.as
*****************************************************************************/
//* A_LZ_COPYRIGHT_BEGIN ******************************************************
//* Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved. *
//* Use is subject to license terms. *
//* A_LZ_COPYRIGHT_END ********************************************************
// This file implements the remote debugger protocol.
// When the app starts up, if the query arg remotedebug (global.remotedebug)
// is defined, it is treated as a TCP port number and a remote debug
// socket is opened to that port.
Debug.seqnum = 0;
Debug.inEvalRequest = false;
Debug.remoteDebug = false;
/**
* @access private
*/
Debug.sockOpen = function (port) {
var url = lz.Browser.getLoadURLAsLzURL();
// Security requires us to talk back to the server we were loaded from
var host = url.host;
this.xsock = new XMLSocket();
this.xsock.onClose = this.brokensocket;
this.xsock.onXML = this.socketXMLAvailable;
if (! this.xsock.connect(host, port)) {
Debug.log("remote debugger could not connect to listener " + host + ":" + port);
}
this.writeInitMessage();
}
/**
* @access private
*/
Debug.writeInitMessage = function () {
var filename = lz.Browser.getLoadURLAsLzURL();
var myXML = new XML();
var init = myXML.createElement("init");
myXML.appendChild(init);
init.attributes.filename = filename;
init.attributes.language = "LZX";
init.attributes.protocol_version = "1.0";
init.attributes.build = canvas.lpsbuild;
init.attributes.lpsversion = canvas.lpsversion;
init.attributes.lpsrelease = canvas.lpsrelease;
init.attributes.runtime = canvas.runtime;
init.attributes.appid = "0";
this.xsock.send(myXML);
}
/**
* @access private
*/
Debug.sockWriteWarning = function (filename, lineNumber, msg){
var myXML = new XML();
var warn = myXML.createElement("warning");
myXML.appendChild(warn);
warn.attributes.filename = filename;
warn.attributes.line = lineNumber;
warn.attributes.msg = msg;
this.xsock.send(myXML);
}
/**
* @access private
*/
Debug.sockWriteLog = function (msg) {
var myXML = new XML();
var response = myXML.createElement("log");
myXML.appendChild(response);
response.attributes.msg = msg;
this.xsock.send(myXML);
}
/**
* @access private
*/
Debug.sockWrite = function (s) {
this.xsock.send(s);
this.xsock.send("\n");
return s;
}
/**
* @access private
* Writes out an object as XML
*/
Debug.sockWriteAsXML = function (obj, seqnum) {
var myXML = new XML();
var response = myXML.createElement("response");
response.attributes.seq = seqnum;
myXML.appendChild(response);
var val = myXML.createElement("value");
response.appendChild(val);
var objtype = typeof(obj);
val.attributes.type = Debug.__typeof(obj);
val.attributes.value = String(obj);
if (objtype == "object") {
var id = Debug.IDForObject(obj);
if (id != null) {
val.attributes.id = id;
}
}
for (var attr in obj) {
var child = obj[attr];
var prop = myXML.createElement("property");
prop.attributes.name = attr;
prop.attributes.type = Debug.__typeof(child);
prop.attributes.value = String(child);
var objtype = typeof(child);
if (objtype == "object") {
var id = Debug.IDForObject(child);
if (id != null) {
prop.attributes.id = id;
}
}
val.appendChild(prop);
}
for (var i = 0; i < this.xmlwarnings.length; i++) {
var w = this.xmlwarnings[i];
var filename = w[0];
var line = w[1];
var msg = w[2];
var warn = myXML.createElement("warning");
warn.attributes.filename = filename;
warn.attributes.line = line;
warn.attributes.msg = msg;
response.appendChild(warn);
}
this.xsock.send(myXML);
Debug.inEvalRequest = false;
return obj;
}
/**
* @access private
*/
Debug.sockClose = function () {
Debug.xsock.close();
}
/**
* @access private
* send message to server that socket is gone
*/
Debug.brokensocket = function () {
Debug.error("socket connection is broken");
}
////////////////////////////////////////////////////////////////
// Redefine the handler for eval warnings, to grab them so we can send them
// back as XML.
/**
* @access private
*/
Debug.resetWarningHistory = function () {
Debug.xmlwarnings = [];
}
Debug.resetWarningHistory();
////////////////////////////////////////////////////////////////
/**
* @access private
*/
Debug.socketXMLAvailable = function (doc) {
var e = doc.firstChild;
var rloader = Debug.rdbloader;
if (e != null) {
// clear warnings history
Debug.resetWarningHistory();
Debug.inEvalRequest = true;
var seqnum = e.attributes['seq'];
if (seqnum == null) {
seqnum = Debug.seqnum++;
}
if (e.nodeName == "exec") {
var expr = e.firstChild.nodeValue;
rloader.request( { lz_load : false,
lzt : "eval",
proxied: true,
lzrdbseq : seqnum,
lz_script : "#file evalString\n#line 0\n" + expr } );
} else if (e.nodeName == "eval") {
var expr = e.firstChild.nodeValue;
rloader.request( { lz_load : false,
lzt : "eval",
proxied: true,
lzrdbseq : seqnum,
lz_script : "#file evalString\n#line 0\n" + expr } );
} else if (e.nodeName == "inspect") {
Debug.inEvalRequest = false;
var id = e.attributes.id;
Debug.sockWriteAsXML(Debug.ObjectForID(id), seqnum);
} else {
Debug.inEvalRequest = false;
Debug.sockWrite("<response seq='"+seqnum+"'><error msg='unknown remote debug command'>"+e.nodeName+"</error></response>");
}
} else {
Debug.inEvalRequest = false;
Debug.sockWrite("<response seq='-1'><error msg='null remote debug command'/></response>");
}
}
/**
* @access private
*/
Debug.makeRDBLoader = function () {
this.rdbloader = new LzLoader(canvas, { attachname: 'rdebugloader' });
this.rdbloader.queuing = true;
}
/**
* @access private
* query arg 'remotedebug', if supplied, specifies a TCP port to connect to
*/
Debug.startupRemote = function () {
if (typeof(remotedebug) != 'undefined') {
Debug.remoteDebug = true;
Debug.makeRDBLoader();
Debug.sockOpen(remotedebug);
}
}
|
Change 20081030-bargull-zr6 by bargull@dell--p4--2-53 on 2008-10-30 17:35:53 in /home/Admin/src/svn/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk
|
Change 20081030-bargull-zr6 by bargull@dell--p4--2-53 on 2008-10-30 17:35:53
in /home/Admin/src/svn/openlaszlo/trunk
for http://svn.openlaszlo.org/openlaszlo/trunk
Summary: define "remoteDebug"
New Features:
Bugs Fixed: LPP-7145
Technical Reviewer: ptw
QA Reviewer: (pending)
Doc Reviewer: (pending)
Documentation:
Release Notes:
Details:
Define "remoteDebug" to avoid runtime warning
Tests:
git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@11660 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
|
ActionScript
|
epl-1.0
|
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
|
9099c8d16a7bc646650adea98c39fc9082dccb11
|
HLSPlugin/src/org/denivip/osmf/net/httpstreaming/hls/HTTPStreamingHLSIndexHandler.as
|
HLSPlugin/src/org/denivip/osmf/net/httpstreaming/hls/HTTPStreamingHLSIndexHandler.as
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.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 the at.matthew.httpstreaming package.
*
* The Initial Developer of the Original Code is
* Matthew Kaufman.
* Portions created by the Initial Developer are Copyright (C) 2011
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
package org.denivip.osmf.net.httpstreaming.hls
{
import flash.net.URLRequest;
import flash.utils.ByteArray;
import org.denivip.osmf.elements.m3u8Classes.M3U8Item;
import org.denivip.osmf.elements.m3u8Classes.M3U8Playlist;
import org.denivip.osmf.elements.m3u8Classes.M3U8PlaylistParser;
import org.osmf.events.DVRStreamInfoEvent;
import org.osmf.events.HTTPStreamingEvent;
import org.osmf.events.HTTPStreamingIndexHandlerEvent;
import org.osmf.events.MediaError;
import org.osmf.events.MediaErrorEvent;
import org.osmf.events.ParseEvent;
import org.osmf.logging.Log;
import org.osmf.logging.Logger;
import org.osmf.net.httpstreaming.HTTPStreamRequest;
import org.osmf.net.httpstreaming.HTTPStreamRequestKind;
import org.osmf.net.httpstreaming.HTTPStreamingIndexHandlerBase;
import org.osmf.net.httpstreaming.dvr.DVRInfo;
import org.osmf.net.httpstreaming.flv.FLVTagScriptDataMode;
import org.osmf.net.httpstreaming.flv.FLVTagScriptDataObject;
[Event(name="notifyIndexReady", type="org.osmf.events.HTTPStreamingFileIndexHandlerEvent")]
[Event(name="notifyRates", type="org.osmf.events.HTTPStreamingFileIndexHandlerEvent")]
[Event(name="notifyTotalDuration", type="org.osmf.events.HTTPStreamingFileIndexHandlerEvent")]
[Event(name="requestLoadIndex", type="org.osmf.events.HTTPStreamingFileIndexHandlerEvent")]
[Event(name="notifyError", type="org.osmf.events.HTTPStreamingFileIndexHandlerEvent")]
[Event(name="DVRStreamInfo", type="org.osmf.events.DVRStreamInfoEvent")]
/**
*
*/
public class HTTPStreamingHLSIndexHandler extends HTTPStreamingIndexHandlerBase
{
private static const MAX_ERRORS:int = 10;
private var _indexInfo:HTTPStreamingHLSIndexInfo;
private var _baseURL:String;
private var _rateVec:Vector.<HTTPStreamingM3U8IndexRateItem>;
private var _segment:int;
private var _absoluteSegment:int;
private var _quality:int;
private var _streamNames:Array;
private var _streamQualityRates:Array;
// for error handling (if playlist don't update on server)
private var _prevPlaylist:String;
private var _matchCounter:int;
private var _fromDVR:Boolean;
override public function dvrGetStreamInfo(indexInfo:Object):void{
_fromDVR = true;
initialize(indexInfo);
}
override public function initialize(indexInfo:Object):void{
_indexInfo = indexInfo as HTTPStreamingHLSIndexInfo;
if(_indexInfo == null){
logger.error("Incorrect indexInfo!");
dispatchEvent(new HTTPStreamingEvent(HTTPStreamingEvent.INDEX_ERROR));
return;
}
_streamNames = [];
_streamQualityRates = [];
_quality = 0;
_rateVec = _indexInfo.streams;
// prepare data for multiquality
var streamsCount:int = _rateVec.length;
for(var quality:int = 0; quality < streamsCount; quality++){
var item:HTTPStreamingM3U8IndexRateItem = _rateVec[quality];
if(item){
_streamNames[quality] = item.url;
_streamQualityRates[quality] = item.bw;
}
}
notifyRatesReady();
notifyIndexReady(_quality);
}
override public function dispose():void{
_indexInfo = null;
_rateVec = null;
_streamNames = null;
_streamQualityRates = null;
_prevPlaylist = null;
}
/*
used only in live streaming
*/
override public function processIndexData(data:*, indexContext:Object):void{
// refresh index context
var rateItem:HTTPStreamingM3U8IndexRateItem = HTTPStreamingM3U8IndexRateItem(indexContext)
if(indexContext){
if(_absoluteSegment > 0){
rateItem.clearManifest();
}
}
// get playlist from binary data
var ba:ByteArray = ByteArray(data);
var pl_str:String = ba.readUTFBytes(ba.length);
if(pl_str.localeCompare(_prevPlaylist) == 0)
++_matchCounter;
if(_matchCounter == MAX_ERRORS){ // if delivered playlist again not changed then alert!
var mediaErr:MediaError = new MediaError(0, "Stream is stuck. Playlist on server don't updated!");
dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR, false, false, mediaErr));
logger.error("Stream is stuck. Playlist on server don't updated!");
}
_prevPlaylist = pl_str;
// simple parsing && update rate items
var parser:M3U8PlaylistParser = new M3U8PlaylistParser();
parser.addEventListener(ParseEvent.PARSE_COMPLETE, onComplete);
parser.addEventListener(ParseEvent.PARSE_ERROR, onError);
parser.parse(pl_str, rateItem.urlBase);
// service functions
function onComplete(e:ParseEvent):void{
parser.removeEventListener(ParseEvent.PARSE_COMPLETE, onComplete);
parser.removeEventListener(ParseEvent.PARSE_ERROR, onError);
var pl:M3U8Playlist = M3U8Playlist(e.data);
updateRateItem(pl, rateItem);
notifyRatesReady();
notifyIndexReady(_quality);
}
function onError(e:ParseEvent):void{
parser.removeEventListener(ParseEvent.PARSE_COMPLETE, onComplete);
parser.removeEventListener(ParseEvent.PARSE_ERROR, onError);
// maybe add notification?... do it if you want =)
logger.warn("Parse error! Maybe incorrect playlist");
}
}
override public function getFileForTime(time:Number, quality:int):HTTPStreamRequest{
_quality = quality;
var item:HTTPStreamingM3U8IndexRateItem = _rateVec[quality];
var manifest:Vector.<HTTPStreamingM3U8IndexItem> = item.manifest;
var len:int = manifest.length;
var i:int;
for(i = 0; i < len; i++){
if(time < manifest[i].startTime)
break;
}
if(i > 0) --i;
_segment = i;
_absoluteSegment = item.sequenceNumber + _segment;
return getNextFile(quality);
}
override public function getNextFile(quality:int):HTTPStreamRequest{
var item:HTTPStreamingM3U8IndexRateItem = _rateVec[quality];
var manifest:Vector.<HTTPStreamingM3U8IndexItem> = item.manifest;
var request:HTTPStreamRequest;
notifyTotalDuration(item.totalTime, quality, item.live);
if(item.live){
if(_absoluteSegment == 0 && _segment == 0){ // Initialize live playback
_absoluteSegment = item.sequenceNumber + _segment;
}
if(_absoluteSegment != (item.sequenceNumber + _segment)){ // We re-loaded the live manifest, need to re-normalize the list
_segment = _absoluteSegment - item.sequenceNumber;
if(_segment < 0)
{
_segment=0;
_absoluteSegment = item.sequenceNumber;
}
_matchCounter = 0; // reset error counter!
}
if(_segment >= manifest.length){ // Try to force a reload
dispatchEvent(new HTTPStreamingIndexHandlerEvent(HTTPStreamingIndexHandlerEvent.REQUEST_LOAD_INDEX, false, false, item.live, 0, _streamNames, _streamQualityRates, new URLRequest(_rateVec[quality].url), _rateVec[quality], false));
return new HTTPStreamRequest(HTTPStreamRequestKind.LIVE_STALL, null, 1.0);
}
}
if(_segment >= manifest.length) // if playlist ended, then end =)
return new HTTPStreamRequest(HTTPStreamRequestKind.DONE);
else{ // load new chunk
request = new HTTPStreamRequest(HTTPStreamRequestKind.DOWNLOAD, manifest[_segment].url);
dispatchEvent(new HTTPStreamingEvent(HTTPStreamingEvent.FRAGMENT_DURATION, false, false, manifest[_segment].duration));
++_segment;
++_absoluteSegment;
}
return request;
}
/*
Private secton
*/
private function notifyRatesReady():void{
dispatchEvent(
new HTTPStreamingIndexHandlerEvent(
HTTPStreamingIndexHandlerEvent.RATES_READY,
false,
false,
false,
0,
_streamNames,
_streamQualityRates
)
);
}
private function notifyIndexReady(quality:int):void{
var item:HTTPStreamingM3U8IndexRateItem = _rateVec[quality];
dispatchDVRStreamInfo(item);
if(!_fromDVR){
var initialOffset:Number = NaN;
if(item.live && _indexInfo.dvrInfo == null)
initialOffset = item.totalTime - ((item.totalTime/item.manifest.length) * 3);
dispatchEvent(
new HTTPStreamingIndexHandlerEvent(
HTTPStreamingIndexHandlerEvent.INDEX_READY,
false,
false,
item.live,
initialOffset
)
);
}
_fromDVR = false;
}
private function notifyTotalDuration(duration:Number, quality:int, live:Boolean):void{
var sdo:FLVTagScriptDataObject = new FLVTagScriptDataObject();
var metaInfo:Object = new Object();
if(!live)
metaInfo.duration = duration;
else
metaInfo.duration = 0;
sdo.objects = ["onMetaData", metaInfo];
dispatchEvent(
new HTTPStreamingEvent(
HTTPStreamingEvent.SCRIPT_DATA,
false,
false,
0,
sdo,
FLVTagScriptDataMode.IMMEDIATE
)
);
}
private function dispatchDVRStreamInfo(item:HTTPStreamingM3U8IndexRateItem):void{
var dvrInfo:DVRInfo = _indexInfo.dvrInfo;
if(dvrInfo == null) // Nothing todo here!
return;
dvrInfo.isRecording = item.live; // it's simple if not live then VOD =)
var currentDuration:Number = item.totalTime;
// make some cheating...
var currentTime:Number = item.totalTime - ((item.totalTime/item.manifest.length) * 3);
// update current length of the DVR window
dvrInfo.curLength = currentTime;// because dvrInfo.startTime is "0.0" =);
// adjust the start time if we have a DVR rooling window active
if ((dvrInfo.windowDuration != -1) && (dvrInfo.curLength > dvrInfo.windowDuration))
{
dvrInfo.startTime += dvrInfo.curLength - dvrInfo.windowDuration;
dvrInfo.curLength = dvrInfo.windowDuration;
}
dispatchEvent(new DVRStreamInfoEvent(
DVRStreamInfoEvent.DVRSTREAMINFO,
false,
false,
dvrInfo
)
);
}
private function updateRateItem(playlist:M3U8Playlist, item:HTTPStreamingM3U8IndexRateItem):void{
// refresh manifest items
for each(var m3u8Item:M3U8Item in playlist.streamItems){
var iItem:HTTPStreamingM3U8IndexItem = new HTTPStreamingM3U8IndexItem(m3u8Item.duration, m3u8Item.url);
item.addIndexItem(iItem);
}
item.setSequenceNumber(playlist.sequenceNumber);
item.setLive(playlist.isLive);
}
protected var logger:Logger = Log.getLogger("org.denivip.osmf.plugins.hls.HTTPStreamingM3U8IndexHandler");
}
}
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.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 the at.matthew.httpstreaming package.
*
* The Initial Developer of the Original Code is
* Matthew Kaufman.
* Portions created by the Initial Developer are Copyright (C) 2011
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
package org.denivip.osmf.net.httpstreaming.hls
{
import flash.external.ExternalInterface;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import org.denivip.osmf.elements.m3u8Classes.M3U8Item;
import org.denivip.osmf.elements.m3u8Classes.M3U8Playlist;
import org.denivip.osmf.elements.m3u8Classes.M3U8PlaylistParser;
import org.osmf.events.DVRStreamInfoEvent;
import org.osmf.events.HTTPStreamingEvent;
import org.osmf.events.HTTPStreamingIndexHandlerEvent;
import org.osmf.events.MediaError;
import org.osmf.events.MediaErrorEvent;
import org.osmf.events.ParseEvent;
import org.osmf.logging.Log;
import org.osmf.logging.Logger;
import org.osmf.net.httpstreaming.HTTPStreamRequest;
import org.osmf.net.httpstreaming.HTTPStreamRequestKind;
import org.osmf.net.httpstreaming.HTTPStreamingIndexHandlerBase;
import org.osmf.net.httpstreaming.dvr.DVRInfo;
import org.osmf.net.httpstreaming.flv.FLVTagScriptDataMode;
import org.osmf.net.httpstreaming.flv.FLVTagScriptDataObject;
[Event(name="notifyIndexReady", type="org.osmf.events.HTTPStreamingFileIndexHandlerEvent")]
[Event(name="notifyRates", type="org.osmf.events.HTTPStreamingFileIndexHandlerEvent")]
[Event(name="notifyTotalDuration", type="org.osmf.events.HTTPStreamingFileIndexHandlerEvent")]
[Event(name="requestLoadIndex", type="org.osmf.events.HTTPStreamingFileIndexHandlerEvent")]
[Event(name="notifyError", type="org.osmf.events.HTTPStreamingFileIndexHandlerEvent")]
[Event(name="DVRStreamInfo", type="org.osmf.events.DVRStreamInfoEvent")]
/**
*
*/
public class HTTPStreamingHLSIndexHandler extends HTTPStreamingIndexHandlerBase
{
private static const MAX_ERRORS:int = 10;
private var _indexInfo:HTTPStreamingHLSIndexInfo;
private var _baseURL:String;
private var _rateVec:Vector.<HTTPStreamingM3U8IndexRateItem>;
private var _segment:int;
private var _absoluteSegment:int;
private var _quality:int;
private var _streamNames:Array;
private var _streamQualityRates:Array;
// for error handling (if playlist don't update on server)
private var _prevPlaylist:String;
private var _matchCounter:int;
private var _fromDVR:Boolean;
override public function dvrGetStreamInfo(indexInfo:Object):void{
_fromDVR = true;
initialize(indexInfo);
}
override public function initialize(indexInfo:Object):void{
_indexInfo = indexInfo as HTTPStreamingHLSIndexInfo;
if(_indexInfo == null){
logger.error("Incorrect indexInfo!");
dispatchEvent(new HTTPStreamingEvent(HTTPStreamingEvent.INDEX_ERROR));
return;
}
_streamNames = [];
_streamQualityRates = [];
_quality = 0;
_rateVec = _indexInfo.streams;
// prepare data for multiquality
var streamsCount:int = _rateVec.length;
for(var quality:int = 0; quality < streamsCount; quality++){
var item:HTTPStreamingM3U8IndexRateItem = _rateVec[quality];
if(item){
_streamNames[quality] = item.url;
_streamQualityRates[quality] = item.bw;
}
}
notifyRatesReady();
notifyIndexReady(_quality);
}
override public function dispose():void{
_indexInfo = null;
_rateVec = null;
_streamNames = null;
_streamQualityRates = null;
_prevPlaylist = null;
}
/*
used only in live streaming
*/
override public function processIndexData(data:*, indexContext:Object):void{
// refresh index context
var rateItem:HTTPStreamingM3U8IndexRateItem = HTTPStreamingM3U8IndexRateItem(indexContext)
if(indexContext){
if(_absoluteSegment > 0){
rateItem.clearManifest();
}
}
// get playlist from binary data
var ba:ByteArray = ByteArray(data);
var pl_str:String = ba.readUTFBytes(ba.length);
if(pl_str.localeCompare(_prevPlaylist) == 0)
++_matchCounter;
if(_matchCounter == MAX_ERRORS){ // if delivered playlist again not changed then alert!
var mediaErr:MediaError = new MediaError(0, "Stream is stuck. Playlist on server don't updated!");
dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR, false, false, mediaErr));
logger.error("Stream is stuck. Playlist on server don't updated!");
}
_prevPlaylist = pl_str;
// simple parsing && update rate items
var parser:M3U8PlaylistParser = new M3U8PlaylistParser();
parser.addEventListener(ParseEvent.PARSE_COMPLETE, onComplete);
parser.addEventListener(ParseEvent.PARSE_ERROR, onError);
parser.parse(pl_str, rateItem.urlBase);
// service functions
function onComplete(e:ParseEvent):void{
parser.removeEventListener(ParseEvent.PARSE_COMPLETE, onComplete);
parser.removeEventListener(ParseEvent.PARSE_ERROR, onError);
var pl:M3U8Playlist = M3U8Playlist(e.data);
updateRateItem(pl, rateItem);
notifyRatesReady();
notifyIndexReady(_quality);
}
function onError(e:ParseEvent):void{
parser.removeEventListener(ParseEvent.PARSE_COMPLETE, onComplete);
parser.removeEventListener(ParseEvent.PARSE_ERROR, onError);
// maybe add notification?... do it if you want =)
logger.warn("Parse error! Maybe incorrect playlist");
}
}
override public function getFileForTime(time:Number, quality:int):HTTPStreamRequest{
_quality = quality;
var item:HTTPStreamingM3U8IndexRateItem = _rateVec[quality];
var manifest:Vector.<HTTPStreamingM3U8IndexItem> = item.manifest;
var len:int = manifest.length;
var i:int;
for(i = 0; i < len; i++){
if(time < manifest[i].startTime)
break;
}
if(i > 0) --i;
_segment = i;
_absoluteSegment = item.sequenceNumber + _segment;
return getNextFile(quality);
}
override public function getNextFile(quality:int):HTTPStreamRequest{
var item:HTTPStreamingM3U8IndexRateItem = _rateVec[quality];
var manifest:Vector.<HTTPStreamingM3U8IndexItem> = item.manifest;
var request:HTTPStreamRequest;
notifyTotalDuration(item.totalTime, quality, item.live);
if(item.live){
if(_absoluteSegment == 0 && _segment == 0){ // Initialize live playback
_absoluteSegment = item.sequenceNumber + _segment;
}
if(_absoluteSegment != (item.sequenceNumber + _segment)){ // We re-loaded the live manifest, need to re-normalize the list
_segment = _absoluteSegment - item.sequenceNumber;
if(_segment < 0)
{
_segment=0;
_absoluteSegment = item.sequenceNumber;
}
_matchCounter = 0; // reset error counter!
}
if(_segment >= manifest.length){ // Try to force a reload
dispatchEvent(new HTTPStreamingIndexHandlerEvent(HTTPStreamingIndexHandlerEvent.REQUEST_LOAD_INDEX, false, false, item.live, 0, _streamNames, _streamQualityRates, new URLRequest(_rateVec[quality].url), _rateVec[quality], false));
return new HTTPStreamRequest(HTTPStreamRequestKind.LIVE_STALL, null, 1.0);
}
}
if(_segment >= manifest.length){ // if playlist ended, then end =)
return new HTTPStreamRequest(HTTPStreamRequestKind.DONE);
}else{ // load new chunk
request = new HTTPStreamRequest(HTTPStreamRequestKind.DOWNLOAD, manifest[_segment].url);
dispatchEvent(new HTTPStreamingEvent(HTTPStreamingEvent.FRAGMENT_DURATION, false, false, manifest[_segment].duration));
++_segment;
++_absoluteSegment;
}
return request;
}
/*
Private secton
*/
private function notifyRatesReady():void{
dispatchEvent(
new HTTPStreamingIndexHandlerEvent(
HTTPStreamingIndexHandlerEvent.RATES_READY,
false,
false,
false,
0,
_streamNames,
_streamQualityRates
)
);
}
private function notifyIndexReady(quality:int):void{
var item:HTTPStreamingM3U8IndexRateItem = _rateVec[quality];
dispatchDVRStreamInfo(item);
if(!_fromDVR){
var initialOffset:Number = NaN;
if(item.live && _indexInfo.dvrInfo == null)
initialOffset = item.totalTime - ((item.totalTime/item.manifest.length) * 3);
dispatchEvent(
new HTTPStreamingIndexHandlerEvent(
HTTPStreamingIndexHandlerEvent.INDEX_READY,
false,
false,
item.live,
initialOffset
)
);
}
_fromDVR = false;
}
private function notifyTotalDuration(duration:Number, quality:int, live:Boolean):void{
var sdo:FLVTagScriptDataObject = new FLVTagScriptDataObject();
var metaInfo:Object = new Object();
if(!live || (live && _indexInfo.dvrInfo))
metaInfo.duration = duration;
else
metaInfo.duration = 0;
sdo.objects = ["onMetaData", metaInfo];
dispatchEvent(
new HTTPStreamingEvent(
HTTPStreamingEvent.SCRIPT_DATA,
false,
false,
0,
sdo,
FLVTagScriptDataMode.IMMEDIATE
)
);
}
private function dispatchDVRStreamInfo(item:HTTPStreamingM3U8IndexRateItem):void{
var dvrInfo:DVRInfo = _indexInfo.dvrInfo;
if(dvrInfo == null) // Nothing todo here!
return;
dvrInfo.isRecording = item.live; // it's simple if not live then VOD =)
var currentDuration:Number = item.totalTime;
// make some cheating...
var currentTime:Number = item.totalTime - ((item.totalTime/item.manifest.length) * 3);
// update current length of the DVR window
dvrInfo.curLength = currentTime;// because dvrInfo.startTime is "0.0" =);
// adjust the start time if we have a DVR rooling window active
if ((dvrInfo.windowDuration != -1) && (dvrInfo.curLength > dvrInfo.windowDuration))
{
dvrInfo.startTime += dvrInfo.curLength - dvrInfo.windowDuration;
dvrInfo.curLength = dvrInfo.windowDuration;
}
dispatchEvent(new DVRStreamInfoEvent(
DVRStreamInfoEvent.DVRSTREAMINFO,
false,
false,
dvrInfo
)
);
}
private function updateRateItem(playlist:M3U8Playlist, item:HTTPStreamingM3U8IndexRateItem):void{
// refresh manifest items
for each(var m3u8Item:M3U8Item in playlist.streamItems){
var iItem:HTTPStreamingM3U8IndexItem = new HTTPStreamingM3U8IndexItem(m3u8Item.duration, m3u8Item.url);
item.addIndexItem(iItem);
}
item.setSequenceNumber(playlist.sequenceNumber);
item.setLive(playlist.isLive);
}
protected var logger:Logger = Log.getLogger("org.denivip.osmf.plugins.hls.HTTPStreamingM3U8IndexHandler");
}
}
|
fix incorrect seek for dvr
|
fix incorrect seek for dvr
correct duration value in notifyTotalDuration() func for DVR stream
|
ActionScript
|
isc
|
denivip/osmf-hls-plugin,mruse/osmf-hls-plugin,denivip/osmf-hls-plugin,mruse/osmf-hls-plugin
|
28475ae71f43ab724b65420bce369ae515a79fae
|
src/aerys/minko/render/shader/part/DiffuseShaderPart.as
|
src/aerys/minko/render/shader/part/DiffuseShaderPart.as
|
package aerys.minko.render.shader.part
{
import aerys.minko.render.geometry.stream.format.VertexComponent;
import aerys.minko.render.material.basic.BasicProperties;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.type.enum.SamplerFiltering;
import aerys.minko.type.enum.SamplerFormat;
import aerys.minko.type.enum.SamplerMipMapping;
import aerys.minko.type.enum.SamplerWrapping;
public class DiffuseShaderPart extends ShaderPart
{
/**
* The shader part to use a diffuse map or fallback and use a solid color.
*
* @param main
*
*/
public function DiffuseShaderPart(main : Shader)
{
super(main);
}
public function getDiffuseColor(killOnAlphaThreshold : Boolean = true, uv : SFloat = null) : SFloat
{
var diffuseColor : SFloat = null;
var useVertexUv : Boolean = uv == null;
uv ||= vertexUV.xy;
if (meshBindings.propertyExists(BasicProperties.UV_SCALE))
uv.scaleBy(meshBindings.getParameter(BasicProperties.UV_SCALE, 2));
if (meshBindings.propertyExists(BasicProperties.UV_OFFSET))
uv.incrementBy(meshBindings.getParameter(BasicProperties.UV_OFFSET, 2));
if (useVertexUv)
uv = interpolate(uv);
if (meshBindings.propertyExists(BasicProperties.DIFFUSE_MAP) && meshBindings.propertyExists(VertexComponent.UV.toString()))
{
var diffuseMap : SFloat = meshBindings.getTextureParameter(
BasicProperties.DIFFUSE_MAP,
meshBindings.getProperty(BasicProperties.DIFFUSE_MAP_FILTERING, SamplerFiltering.LINEAR),
meshBindings.getProperty(BasicProperties.DIFFUSE_MAP_MIPMAPPING, SamplerMipMapping.LINEAR),
meshBindings.getProperty(BasicProperties.DIFFUSE_MAP_WRAPPING, SamplerWrapping.REPEAT),
0,
meshBindings.getProperty(BasicProperties.DIFFUSE_MAP_FORMAT, SamplerFormat.RGBA)
);
diffuseColor = sampleTexture(diffuseMap, uv);
}
else if (meshBindings.propertyExists(BasicProperties.DIFFUSE_COLOR))
{
diffuseColor = meshBindings.getParameter(BasicProperties.DIFFUSE_COLOR, 4);
}
else
{
diffuseColor = float4(0., 0., 0., 1.);
}
if (meshBindings.propertyExists(BasicProperties.ALPHA_MAP))
{
var alphaMap : SFloat = meshBindings.getTextureParameter(
BasicProperties.ALPHA_MAP,
meshBindings.getProperty(BasicProperties.ALPHA_MAP_FILTERING, SamplerFiltering.LINEAR),
meshBindings.getProperty(BasicProperties.ALPHA_MAP_MIPMAPPING, SamplerMipMapping.LINEAR),
meshBindings.getProperty(BasicProperties.ALPHA_MAP_WRAPPING, SamplerWrapping.REPEAT),
0,
meshBindings.getProperty(BasicProperties.ALPHA_MAP_FORMAT, SamplerFormat.RGBA));
var alphaSample : SFloat = sampleTexture(alphaMap, uv);
diffuseColor = float4(diffuseColor.rgb, alphaSample.r);
}
if (meshBindings.propertyExists(BasicProperties.DIFFUSE_TRANSFORM))
{
diffuseColor = multiply4x4(
diffuseColor,
meshBindings.getParameter(BasicProperties.DIFFUSE_TRANSFORM, 16)
);
}
if (killOnAlphaThreshold && meshBindings.propertyExists(BasicProperties.ALPHA_THRESHOLD))
{
var alphaThreshold : SFloat = meshBindings.getParameter(
BasicProperties.ALPHA_THRESHOLD, 1
);
kill(subtract(0.5, lessThan(diffuseColor.w, alphaThreshold)));
}
return diffuseColor;
}
}
}
|
package aerys.minko.render.shader.part
{
import aerys.minko.render.geometry.stream.format.VertexComponent;
import aerys.minko.render.material.basic.BasicProperties;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.type.enum.SamplerFiltering;
import aerys.minko.type.enum.SamplerFormat;
import aerys.minko.type.enum.SamplerMipMapping;
import aerys.minko.type.enum.SamplerWrapping;
public class DiffuseShaderPart extends ShaderPart
{
/**
* The shader part to use a diffuse map or fallback and use a solid color.
*
* @param main
*
*/
public function DiffuseShaderPart(main : Shader)
{
super(main);
}
public function getDiffuseColor(killOnAlphaThreshold : Boolean = true, uv : SFloat = null) : SFloat
{
var diffuseColor : SFloat = null;
var useVertexUv : Boolean = uv == null;
uv ||= vertexUV.xy;
if (meshBindings.propertyExists(BasicProperties.UV_SCALE))
uv.scaleBy(meshBindings.getParameter(BasicProperties.UV_SCALE, 2));
if (meshBindings.propertyExists(BasicProperties.UV_OFFSET))
uv.incrementBy(meshBindings.getParameter(BasicProperties.UV_OFFSET, 2));
if (useVertexUv)
uv = interpolate(uv);
if (meshBindings.propertyExists(BasicProperties.DIFFUSE_MAP) &&
(meshBindings.propertyExists(VertexComponent.UV.toString()) || meshBindings.propertyExists(VertexComponent.XY.toString()))) // uv or sprite
{
var diffuseMap : SFloat = meshBindings.getTextureParameter(
BasicProperties.DIFFUSE_MAP,
meshBindings.getProperty(BasicProperties.DIFFUSE_MAP_FILTERING, SamplerFiltering.LINEAR),
meshBindings.getProperty(BasicProperties.DIFFUSE_MAP_MIPMAPPING, SamplerMipMapping.LINEAR),
meshBindings.getProperty(BasicProperties.DIFFUSE_MAP_WRAPPING, SamplerWrapping.REPEAT),
0,
meshBindings.getProperty(BasicProperties.DIFFUSE_MAP_FORMAT, SamplerFormat.RGBA)
);
diffuseColor = sampleTexture(diffuseMap, uv);
}
else if (meshBindings.propertyExists(BasicProperties.DIFFUSE_COLOR))
{
diffuseColor = meshBindings.getParameter(BasicProperties.DIFFUSE_COLOR, 4);
}
else
{
diffuseColor = float4(0., 0., 0., 1.);
}
if (meshBindings.propertyExists(BasicProperties.ALPHA_MAP))
{
var alphaMap : SFloat = meshBindings.getTextureParameter(
BasicProperties.ALPHA_MAP,
meshBindings.getProperty(BasicProperties.ALPHA_MAP_FILTERING, SamplerFiltering.LINEAR),
meshBindings.getProperty(BasicProperties.ALPHA_MAP_MIPMAPPING, SamplerMipMapping.LINEAR),
meshBindings.getProperty(BasicProperties.ALPHA_MAP_WRAPPING, SamplerWrapping.REPEAT),
0,
meshBindings.getProperty(BasicProperties.ALPHA_MAP_FORMAT, SamplerFormat.RGBA));
var alphaSample : SFloat = sampleTexture(alphaMap, uv);
diffuseColor = float4(diffuseColor.rgb, alphaSample.r);
}
if (meshBindings.propertyExists(BasicProperties.DIFFUSE_TRANSFORM))
{
diffuseColor = multiply4x4(
diffuseColor,
meshBindings.getParameter(BasicProperties.DIFFUSE_TRANSFORM, 16)
);
}
if (killOnAlphaThreshold && meshBindings.propertyExists(BasicProperties.ALPHA_THRESHOLD))
{
var alphaThreshold : SFloat = meshBindings.getParameter(
BasicProperties.ALPHA_THRESHOLD, 1
);
kill(subtract(0.5, lessThan(diffuseColor.w, alphaThreshold)));
}
return diffuseColor;
}
}
}
|
Fix vertex component existence for sprites
|
Fix vertex component existence for sprites
|
ActionScript
|
mit
|
aerys/minko-as3
|
c0df6a28c42ffde3f2798b4459187d2ee7269519
|
source/com/kemsky/support/Compare.as
|
source/com/kemsky/support/Compare.as
|
/*
* Copyright: (c) 2015. Turtsevich Alexander
*
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.html
*/
package com.kemsky.support
{
import com.kemsky.Stream;
import flash.utils.Dictionary;
import flash.utils.getQualifiedClassName;
/**
* todo: register custom compare functions for custom types
* @private
*/
public class Compare
{
private static const classToFullName:Dictionary = new Dictionary(true);
public static const NUMBER:String = "Number";
public static const STRING:String = "String";
public static const BOOLEAN:String = "Boolean";
public static const DATE:String = "Date";
public static const XML_TYPE:String = "XML";
public static const XML_LIST:String = "XMLList";
public static const CLASS:String = "Class";
public static const ARRAY:String = "Array";
public static const UNDEFINED:String = "void";
/**
* Allows to use generic compare functions(le, ge, lt and others) for the following types:
* Number, Date, XML, String or Boolean
* @param a first item
* @param b second item
* @param options combination of Stream.CASEINSENSITIVE | Stream.DESCENDING | Stream.NUMERIC
* @param equals compare is used to check equality
* @return -1 if a < b, 0 if a == b and 1 if a > b
*/
public static function compare(a:Object, b:Object, options:uint = 0, equals:Boolean = false):int
{
var result:int = 0;
if (a == null && b == null)
{
result = 0;
}
else if (a == null)
{
result = -1;
}
else if (b == null)
{
result = 1;
}
else
{
var numeric:Boolean = (options & Stream.NUMERIC) == Stream.NUMERIC;
var caseInsensitive:Boolean = (options & Stream.CASEINSENSITIVE) == Stream.CASEINSENSITIVE;
var typeOfA:String = getClassName(a);
var typeOfB:String = getClassName(b);
if (typeOfA == typeOfB)
{
switch (typeOfA)
{
case BOOLEAN:
result = compareNumber(Number(a), Number(b));
break;
case NUMBER:
result = compareNumber(a as Number, b as Number);
break;
case STRING:
result = compareString(a as String, b as String, caseInsensitive);
break;
case DATE:
result = compareDate(a as Date, b as Date);
break;
case XML_TYPE:
result = compareXML(a as XML, b as XML, numeric, caseInsensitive);
break;
default:
if (equals)
{
result = a == b ? 0 : -1;
}
else
{
throw new StreamError("Sort is not supported: " + typeOfA);
}
}
}
else
{
result = compareString(typeOfA, typeOfB, caseInsensitive);
}
}
if ((options & Stream.DESCENDING) == Stream.DESCENDING)
{
result *= -1;
}
return result;
}
public static function getClassName(object:*):String
{
var cls:Class;
if (object is XML)
{
return XML_TYPE;
}
else if (object is XMLList)
{
return XML_LIST;
}
else if (object is Class)
{
cls = object as Class;
}
else if (object === undefined)
{
return UNDEFINED;
}
else if (object != null)
{
cls = object.constructor;
}
var name:String = classToFullName[cls];
if (name == null)
{
name = getQualifiedClassName(cls);
classToFullName[cls] = name;
}
return name;
}
/**
* @private
*/
public static function compareXML(a:XML, b:XML, numeric:Boolean, caseInsensitive:Boolean):int
{
var result:int = 0;
if (numeric)
{
result = compareNumber(parseFloat(a.toString()), parseFloat(b.toString()));
}
else
{
result = compareString(a.toString(), b.toString(), caseInsensitive);
}
return result;
}
/**
* @private
*/
public static function compareString(fa:String, fb:String, caseInsensitive:Boolean):int
{
// Convert to lowercase if we are case insensitive.
if (caseInsensitive)
{
fa = fa.toLocaleLowerCase();
fb = fb.toLocaleLowerCase();
}
var result:int = fa.localeCompare(fb);
if (result < -1)
{
result = -1;
}
else if (result > 1)
{
result = 1;
}
return result;
}
/**
* @private
*/
public static function compareNumber(fa:Number, fb:Number):int
{
if ((fa != fa) && (fb != fb))
{
return 0;
}
if (fa != fa)
{
return -1;
}
if (fb != fb)
{
return 1;
}
if (fa < fb)
{
return -1;
}
if (fa > fb)
{
return 1;
}
return 0;
}
/**
* @private
*/
public static function compareDate(fa:Date, fb:Date):int
{
var na:Number = fa.getTime();
var nb:Number = fb.getTime();
if (na < nb)
{
return -1;
}
if (na > nb)
{
return 1;
}
return 0;
}
}
}
|
/*
* Copyright: (c) 2015. Turtsevich Alexander
*
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.html
*/
package com.kemsky.support
{
import com.kemsky.Stream;
import flash.utils.Dictionary;
import flash.utils.getQualifiedClassName;
/**
* todo: register custom compare functions for custom types
* @private
*/
public class Compare
{
private static const classToFullName:Dictionary = new Dictionary(true);
public static const NUMBER:String = "Number";
public static const STRING:String = "String";
public static const BOOLEAN:String = "Boolean";
public static const DATE:String = "Date";
public static const XML_TYPE:String = "XML";
public static const XML_LIST:String = "XMLList";
public static const CLASS:String = "Class";
public static const ARRAY:String = "Array";
public static const UNDEFINED:String = "void";
/**
* Allows to use generic compare functions(le, ge, lt and others) for the following types:
* Number, Date, XML, String or Boolean
* @param a first item
* @param b second item
* @param options combination of Stream.CASEINSENSITIVE | Stream.DESCENDING | Stream.NUMERIC
* @param equals compare is used to check equality
* @return -1 if a < b, 0 if a == b and 1 if a > b
*/
public static function compare(a:Object, b:Object, options:uint = 0, equals:Boolean = false):int
{
var result:int = 0;
if (a == null && b == null)
{
result = 0;
}
else if (a == null)
{
result = -1;
}
else if (b == null)
{
result = 1;
}
else
{
var numeric:Boolean = (options & Stream.NUMERIC) == Stream.NUMERIC;
var caseInsensitive:Boolean = (options & Stream.CASEINSENSITIVE) == Stream.CASEINSENSITIVE;
var typeOfA:String = getClassName(a);
var typeOfB:String = getClassName(b);
if (typeOfA == typeOfB)
{
switch (typeOfA)
{
case BOOLEAN:
result = compareNumber(Number(a), Number(b));
break;
case NUMBER:
result = compareNumber(a as Number, b as Number);
break;
case STRING:
result = compareString(a as String, b as String, caseInsensitive);
break;
case DATE:
result = compareDate(a as Date, b as Date);
break;
case XML_TYPE:
result = compareXML(a as XML, b as XML, numeric, caseInsensitive);
break;
default:
if (equals)
{
result = a == b ? 0 : -1;
}
else
{
throw new StreamError("Compare is not supported: " + typeOfA);
}
}
}
else
{
result = compareString(typeOfA, typeOfB, caseInsensitive);
}
}
if ((options & Stream.DESCENDING) == Stream.DESCENDING)
{
result *= -1;
}
return result;
}
public static function getClassName(object:*):String
{
var cls:Class;
if (object is XML)
{
return XML_TYPE;
}
else if (object is XMLList)
{
return XML_LIST;
}
else if (object is Class)
{
cls = object as Class;
}
else if (object === undefined)
{
return UNDEFINED;
}
else if (object != null)
{
cls = object.constructor;
}
var name:String = classToFullName[cls];
if (name == null)
{
name = getQualifiedClassName(cls);
classToFullName[cls] = name;
}
return name;
}
/**
* @private
*/
public static function compareXML(a:XML, b:XML, numeric:Boolean, caseInsensitive:Boolean):int
{
var result:int = 0;
if (numeric)
{
result = compareNumber(parseFloat(a.toString()), parseFloat(b.toString()));
}
else
{
result = compareString(a.toString(), b.toString(), caseInsensitive);
}
return result;
}
/**
* @private
*/
public static function compareString(fa:String, fb:String, caseInsensitive:Boolean):int
{
// Convert to lowercase if we are case insensitive.
if (caseInsensitive)
{
fa = fa.toLocaleLowerCase();
fb = fb.toLocaleLowerCase();
}
var result:int = fa.localeCompare(fb);
if (result < -1)
{
result = -1;
}
else if (result > 1)
{
result = 1;
}
return result;
}
/**
* @private
*/
public static function compareNumber(fa:Number, fb:Number):int
{
if ((fa != fa) && (fb != fb))
{
return 0;
}
if (fa != fa)
{
return -1;
}
if (fb != fb)
{
return 1;
}
if (fa < fb)
{
return -1;
}
if (fa > fb)
{
return 1;
}
return 0;
}
/**
* @private
*/
public static function compareDate(fa:Date, fb:Date):int
{
var na:Number = fa.getTime();
var nb:Number = fb.getTime();
if (na < nb)
{
return -1;
}
if (na > nb)
{
return 1;
}
return 0;
}
}
}
|
clean up
|
clean up
|
ActionScript
|
mit
|
kemsky/stream
|
f1b5419be4f8a300f2f56f6fb425847277745213
|
com/axis/mjpgplayer/MJPG.as
|
com/axis/mjpgplayer/MJPG.as
|
package com.axis.mjpgplayer
{
import com.axis.mjpgplayer.MJPGImage;
import flash.display.Bitmap;
import flash.display.LoaderInfo;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.utils.ByteArray;
import flash.external.ExternalInterface;
public class MJPG extends Sprite
{
private var ipCam:IPCam;
private var maxImages:uint = 2;
private var firstImage:Boolean = true;
private var imgBuf:Vector.<Object> = new Vector.<Object>();
private var idleQue:Vector.<MJPGImage> = new Vector.<MJPGImage>();
private var _playing:Boolean = false;
// Statistics Variables
private var sTime:Number = 0;
private var decTime:uint = 0;
private var _fRecCount:uint = 0;
private var _fDecCount:uint = 0;
private var _fps:Number = 0.0;
public function MJPG(ipCam:IPCam)
{
this.ipCam = ipCam;
addEventListener(Event.ADDED_TO_STAGE, onStageAdded);
}
private function onStageAdded(e:Event):void
{
ExternalInterface.addCallback("getFps", getFps);
for (var i:uint = 0; i < maxImages; i++)
{
var loader:MJPGImage = new MJPGImage();
loader.cacheAsBitmap = false;
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onImageError);
this.addChild(loader);
}
stage.addEventListener(Event.RESIZE, resizeListener);
}
private function resizeListener(e:Event):void {
for each (var loader:MJPGImage in getChildren())
{
scaleAndPosition(loader);
}
}
public function getChildren():Array
{
var children:Array = [];
for (var i:uint = 0; i < this.numChildren; i++)
{
children.push(this.getChildAt(i));
}
return children;
}
[Bindable(event='framesDecChanged')]
public function get framesDecoded():uint
{
return _fDecCount;
}
private function updateDecFrames(v:uint):void
{
_fDecCount = v;
dispatchEvent(new Event("framesDecChanged"));
}
[Bindable(event='playingChanged')]
public function get playing():Boolean
{
return _playing;
}
private function updatePlaying(v:Boolean):void
{
_playing = v;
dispatchEvent(new Event("playingChanged"));
}
[Bindable(event='fpsChanged')]
public function get fps():Number
{
return _fps;
}
public function getFps():Number
{
return _fps;
}
private function updateFps(v:Number):void
{
_fps = v;
dispatchEvent(new Event("fpsChanged"));
}
private function loadImage(loader:MJPGImage, obj:Object):void
{
loader.data.loading = true;
loader.data.inQue = false;
loader.data.loadTime = new Date().getTime();
loader.data.frame = obj.frame;
loader.loadBytes(obj.data as ByteArray);
obj = null;
}
public function load(image:ByteArray):void
{
if (imgBuf.length >= maxImages + 3)
{
var obj:Object = imgBuf.shift();
obj = null;
}
_fRecCount++;
imgBuf.push({frame: _fRecCount, data: image});
if (!playing)
{
sTime = new Date().getTime();
decTime = 0;
_fRecCount = 1;
updateDecFrames(0);
updatePlaying(true);
for each (var loader:MJPGImage in getChildren())
{
loader.data.inQue = true;
idleQue.push(loader);
}
}
if (idleQue.length > 0)
{
loadImage(idleQue.shift(), imgBuf.shift());
}
}
private function scaleAndPosition(loader:MJPGImage):void
{
// Scale to fit stage
var loaderAspectRatio:Number = loader.width / loader.height;
var stageAspectRatio:Number = stage.stageWidth / stage.stageHeight;
var scale:Number;
if (loaderAspectRatio > stageAspectRatio)
{
scale = stage.stageWidth / loader.width;
}
else
{
scale = stage.stageHeight / loader.height;
}
loader.width *= scale;
loader.height *= scale;
// Center on stage
loader.x = (stage.stageWidth - loader.width) / 2;
loader.y = (stage.stageHeight - loader.height) / 2;
}
private function onLoadComplete(event:Event):void
{
if (!playing)
{
return;
}
var arr:Array = getChildren();
var loader:MJPGImage = event.currentTarget.loader as MJPGImage;
var bitmap:Bitmap = event.currentTarget.content;
if (bitmap != null)
{
bitmap.smoothing = true;
}
loader.data.loading = false;
scaleAndPosition(loader);
var curTime:Number = new Date().getTime();
decTime += curTime - loader.data.loadTime;
if (arr[arr.length - 1].data.loadTime <= loader.data.loadTime)
{
if (maxImages > 2)
{
removeChild(loader);
addChild(loader);
}
else if (maxImages == 2)
{
this.swapChildren(arr[0], arr[1]);
}
updateDecFrames(framesDecoded + 1);
updateFps((framesDecoded * 1000) / (curTime - sTime));
}
arr = getChildren();
for (var i:uint = 0; i < arr.length - 1; i++)
{
loader = arr[i] as MJPGImage;
if (loader.data.inQue == true || loader.data.loading)
{
continue;
}
if (imgBuf.length == 0)
{
loader.data.inQue = true;
idleQue.push(loader);
}
else
{
loadImage(loader, imgBuf.shift());
}
}
if (firstImage) {
ExternalInterface.call(ipCam.getJsEventCallbackName(), "started");
firstImage = false;
}
}
private function onImageError(event:IOErrorEvent):void
{
var loader:MJPGImage = event.currentTarget.loader as MJPGImage;
loader.data.loading = false;
if (imgBuf.length == 0)
{
loader.data.inQue = true;
idleQue.push(loader);
}
else
loadImage(loader, imgBuf.shift());
}
public function reset(clear:Boolean = false):void
{
firstImage = true;
updatePlaying(false);
idleQue.length = 0;
while (imgBuf.length != 0)
{
_fRecCount--;
var obj:Object = imgBuf.shift();
obj = null;
}
var arr:Array = getChildren();
for each (var loader:MJPGImage in arr)
{
if (loader.data.loading)
{
updateDecFrames(framesDecoded + 1);
}
loader.data.loading = false;
loader.data.inQue = false;
loader.data.loadTime = 0.0;
if (clear)
{
loader.unload();
}
}
updateFps((framesDecoded * 1000) / (new Date().getTime() - sTime));
var recvFps:Number = (_fRecCount * 1000) / (new Date().getTime() - sTime);
}
}
}
|
package com.axis.mjpgplayer
{
import com.axis.mjpgplayer.MJPGImage;
import flash.display.Bitmap;
import flash.display.LoaderInfo;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.utils.ByteArray;
import flash.external.ExternalInterface;
public class MJPG extends Sprite
{
private var ipCam:IPCam;
private var maxImages:uint = 2;
private var firstImage:Boolean = true;
private var imgBuf:Vector.<Object> = new Vector.<Object>();
private var idleQue:Vector.<MJPGImage> = new Vector.<MJPGImage>();
private var _playing:Boolean = false;
// Statistics Variables
private var sTime:Number = 0;
private var decTime:uint = 0;
private var _fRecCount:uint = 0;
private var _fDecCount:uint = 0;
private var _fps:Number = 0.0;
public function MJPG(ipCam:IPCam)
{
this.ipCam = ipCam;
addEventListener(Event.ADDED_TO_STAGE, onStageAdded);
}
private function onStageAdded(e:Event):void
{
ExternalInterface.addCallback("getFps", getFps);
createLoaders();
stage.addEventListener(Event.RESIZE, resizeListener);
}
private function createLoaders():void {
for (var i:uint = 0; i < maxImages; i++)
{
var loader:MJPGImage = new MJPGImage();
loader.cacheAsBitmap = false;
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onImageError);
this.addChild(loader);
}
}
private function destroyLoaders():void {
for each (var loader:MJPGImage in getChildren())
{
loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onLoadComplete);
loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onImageError);
}
removeChildren();
}
private function resizeListener(e:Event):void {
for each (var loader:MJPGImage in getChildren())
{
scaleAndPosition(loader);
}
}
public function getChildren():Array
{
var children:Array = [];
for (var i:uint = 0; i < this.numChildren; i++)
{
children.push(this.getChildAt(i));
}
return children;
}
[Bindable(event='framesDecChanged')]
public function get framesDecoded():uint
{
return _fDecCount;
}
private function updateDecFrames(v:uint):void
{
_fDecCount = v;
dispatchEvent(new Event("framesDecChanged"));
}
[Bindable(event='playingChanged')]
public function get playing():Boolean
{
return _playing;
}
private function updatePlaying(v:Boolean):void
{
_playing = v;
dispatchEvent(new Event("playingChanged"));
}
[Bindable(event='fpsChanged')]
public function get fps():Number
{
return _fps;
}
public function getFps():Number
{
return _fps;
}
private function updateFps(v:Number):void
{
_fps = v;
dispatchEvent(new Event("fpsChanged"));
}
private function loadImage(loader:MJPGImage, obj:Object):void
{
loader.data.loading = true;
loader.data.inQue = false;
loader.data.loadTime = new Date().getTime();
loader.data.frame = obj.frame;
loader.loadBytes(obj.data as ByteArray);
obj = null;
}
public function load(image:ByteArray):void
{
if (imgBuf.length >= maxImages + 3)
{
var obj:Object = imgBuf.shift();
obj = null;
}
_fRecCount++;
imgBuf.push({frame: _fRecCount, data: image});
if (!playing)
{
sTime = new Date().getTime();
decTime = 0;
_fRecCount = 1;
updateDecFrames(0);
updatePlaying(true);
for each (var loader:MJPGImage in getChildren())
{
loader.data.inQue = true;
idleQue.push(loader);
}
}
if (idleQue.length > 0)
{
loadImage(idleQue.shift(), imgBuf.shift());
}
}
private function scaleAndPosition(loader:MJPGImage):void
{
// Scale to fit stage
var loaderAspectRatio:Number = loader.width / loader.height;
var stageAspectRatio:Number = stage.stageWidth / stage.stageHeight;
var scale:Number;
if (loaderAspectRatio > stageAspectRatio)
{
scale = stage.stageWidth / loader.width;
}
else
{
scale = stage.stageHeight / loader.height;
}
loader.width *= scale;
loader.height *= scale;
// Center on stage
loader.x = (stage.stageWidth - loader.width) / 2;
loader.y = (stage.stageHeight - loader.height) / 2;
}
private function onLoadComplete(event:Event):void
{
if (!playing)
{
return;
}
var arr:Array = getChildren();
var loader:MJPGImage = event.currentTarget.loader as MJPGImage;
var bitmap:Bitmap = event.currentTarget.content;
if (bitmap != null)
{
bitmap.smoothing = true;
}
loader.data.loading = false;
scaleAndPosition(loader);
var curTime:Number = new Date().getTime();
decTime += curTime - loader.data.loadTime;
if (arr[arr.length - 1].data.loadTime <= loader.data.loadTime)
{
if (maxImages > 2)
{
removeChild(loader);
addChild(loader);
}
else if (maxImages == 2)
{
this.swapChildren(arr[0], arr[1]);
}
updateDecFrames(framesDecoded + 1);
updateFps((framesDecoded * 1000) / (curTime - sTime));
}
arr = getChildren();
for (var i:uint = 0; i < arr.length - 1; i++)
{
loader = arr[i] as MJPGImage;
if (loader.data.inQue == true || loader.data.loading)
{
continue;
}
if (imgBuf.length == 0)
{
loader.data.inQue = true;
idleQue.push(loader);
}
else
{
loadImage(loader, imgBuf.shift());
}
}
if (firstImage) {
ExternalInterface.call(ipCam.getJsEventCallbackName(), "started");
firstImage = false;
}
}
private function onImageError(event:IOErrorEvent):void
{
var loader:MJPGImage = event.currentTarget.loader as MJPGImage;
loader.data.loading = false;
if (imgBuf.length == 0)
{
loader.data.inQue = true;
idleQue.push(loader);
}
else
loadImage(loader, imgBuf.shift());
}
public function reset(clear:Boolean = false):void
{
firstImage = true;
updatePlaying(false);
idleQue.length = 0;
while (imgBuf.length != 0)
{
_fRecCount--;
var obj:Object = imgBuf.shift();
obj = null;
}
var arr:Array = getChildren();
for each (var loader:MJPGImage in arr)
{
if (loader.data.loading)
{
updateDecFrames(framesDecoded + 1);
}
loader.data.loading = false;
loader.data.inQue = false;
loader.data.loadTime = 0.0;
}
if (clear)
{
destroyLoaders();
createLoaders();
}
updateFps((framesDecoded * 1000) / (new Date().getTime() - sTime));
var recvFps:Number = (_fRecCount * 1000) / (new Date().getTime() - sTime);
}
}
}
|
Make sure JPEG image is removed when player is stopped
|
Make sure JPEG image is removed when player is stopped
|
ActionScript
|
bsd-3-clause
|
AxisCommunications/locomote-video-player,gaetancollaud/locomote-video-player
|
304f6b9623ef0692e8ea8ebe0f3d00d3c18008fc
|
exporter/src/main/as/flump/export/Exporter.as
|
exporter/src/main/as/flump/export/Exporter.as
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.export {
import flash.desktop.NativeApplication;
import flash.display.NativeWindow;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.filesystem.File;
import flash.net.SharedObject;
import com.adobe.crypto.MD5;
import deng.fzip.FZip;
import deng.fzip.FZipFile;
import flump.bytesToXML;
import flump.display.Movie;
import flump.executor.Executor;
import flump.executor.Future;
import flump.export.Ternary;
import flump.xfl.ParseError;
import flump.xfl.XflLibrary;
import flump.xfl.XflMovie;
import mx.collections.ArrayCollection;
import spark.components.DataGrid;
import spark.components.DropDownList;
import spark.components.List;
import spark.components.Window;
import spark.events.GridSelectionEvent;
import starling.display.Sprite;
import com.threerings.util.F;
import com.threerings.util.Log;
import com.threerings.util.StringUtil;
public class Exporter
{
public static const NA :NativeApplication = NativeApplication.nativeApplication;
protected static const IMPORT_ROOT :String = "IMPORT_ROOT";
protected static const AUTHORED_RESOLUTION :String = "AUTHORED_RESOLUTION";
public function Exporter (win :ExporterWindow) {
_win = win;
_errors = _win.errors;
_libraries = _win.libraries;
_authoredResolution = _win.authoredResolutionPopup;
_authoredResolution.dataProvider = new ArrayCollection(DeviceType.values().map(
function (type :DeviceType, ..._) :Object {
return new DeviceSelection(type);
}));
var initialSelection :DeviceType = null;
if (_settings.data.hasOwnProperty(AUTHORED_RESOLUTION)) {
try {
initialSelection = DeviceType.valueOf(_settings.data[AUTHORED_RESOLUTION]);
} catch (e :Error) {}
}
if (initialSelection == null) {
initialSelection = DeviceType.IPHONE_RETINA;
}
_authoredResolution.selectedIndex = DeviceType.values().indexOf(initialSelection);
_authoredResolution.addEventListener(Event.CHANGE, function (..._) :void {
var selectedType :DeviceType = DeviceSelection(_authoredResolution.selectedItem).type;
_settings.data[AUTHORED_RESOLUTION] = selectedType.name();
});
function updateExportEnabled (..._) :void {
_win.export.enabled = _exportChooser.dir != null && _libraries.selectionLength > 0 &&
_libraries.selectedItems.some(function (status :DocStatus, ..._) :Boolean {
return status.isValid;
});
}
_libraries.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void {
log.info("Changed", "selected", _libraries.selectedIndices);
updateExportEnabled();
_win.preview.enabled = _libraries.selectedItem.isValid;
});
_win.export.addEventListener(MouseEvent.CLICK, function (..._) :void {
for each (var status :DocStatus in _libraries.selectedItems) {
exportFlashDocument(status);
}
});
_win.preview.addEventListener(MouseEvent.CLICK, function (..._) :void {
showPreviewWindow(_libraries.selectedItem.lib);
});
_importChooser =
new DirChooser(_settings, "IMPORT_ROOT", _win.importRoot, _win.browseImport);
_importChooser.changed.add(setImport);
setImport(_importChooser.dir);
_exportChooser =
new DirChooser(_settings, "EXPORT_ROOT", _win.exportRoot, _win.browseExport);
_exportChooser.changed.add(updateExportEnabled);
_win.addEventListener(Event.CLOSE, function (..._) :void { NA.exit(0); });
}
protected function setImport (root :File) :void {
_libraries.dataProvider.removeAll();
_errors.dataProvider.removeAll();
if (root == null) return;
_rootLen = root.nativePath.length + 1;
if (_docFinder != null) _docFinder.shutdownNow();
_docFinder = new Executor(2);
findFlashDocuments(root, _docFinder);
}
protected function showPreviewWindow (lib :XflLibrary) :void {
if (_previewController == null || _previewWindow.closed || _previewControls.closed) {
_previewWindow = new PreviewWindow();
_previewControls = new PreviewControlsWindow();
_previewWindow.started = function (container :Sprite) :void {
_previewController = new PreviewController(lib, container, _previewControls);
}
_previewWindow.open();
_previewControls.open();
preventWindowClose(_previewWindow.nativeWindow);
preventWindowClose(_previewControls.nativeWindow);
} else {
_previewController.lib = lib;
_previewWindow.nativeWindow.visible = true;
_previewControls.nativeWindow.visible = true;
}
}
// Causes a window to be hidden, rather than closed, when its close box is clicked
protected static function preventWindowClose (window :NativeWindow) :void {
window.addEventListener(Event.CLOSING, function (e :Event) :void {
e.preventDefault();
window.visible = false;
});
}
protected var _previewController :PreviewController;
protected var _previewWindow :PreviewWindow;
protected var _previewControls :PreviewControlsWindow;
protected function findFlashDocuments (base :File, exec :Executor) :void {
Files.list(base, exec).succeeded.add(function (files :Array) :void {
if (exec.isShutdown) return;
for each (var file :File in files) {
if (Files.hasExtension(file, "xfl")) {
addFlashDocument(file.parent);
return;
}
}
for each (file in files) {
if (file.isDirectory) findFlashDocuments(file, exec);
else if (Files.hasExtension(file, "fla")) addFlashDocument(file);
}
});
}
protected function addFlashDocument (file :File) :void {
const status :DocStatus = new DocStatus(file, _rootLen, Ternary.UNKNOWN, Ternary.UNKNOWN, null);
_libraries.dataProvider.addItem(status);
loadFlashDocument(status);
}
protected function exportFlashDocument (status :DocStatus) :void {
BetwixtPublisher.publish(status.lib, status.file,
DeviceSelection(_authoredResolution.selectedItem).type, _exportChooser.dir);
status.updateModified(Ternary.FALSE);
}
protected function loadFlashDocument (status :DocStatus) :void {
if (Files.hasExtension(status.file, "xfl")) status.file = status.file.parent;
if (status.file.isDirectory) {
const name :String = status.file.nativePath
.substring(_rootLen).replace(File.separator, "/");
const load :Future = new XflLoader().load(name, status.file);
load.succeeded.add(function (lib :XflLibrary) :void {
// Don't blow up if the export directory hasn't been chosen
var isMod :Boolean = true;
if (_exportChooser.dir != null) {
var metadata :File = _exportChooser.dir.resolvePath(
lib.location + "/resources.xml");
isMod = BetwixtPublisher.modified(lib, metadata);
}
status.lib = lib;
status.updateModified(Ternary.of(isMod));
for each (var err :ParseError in lib.getErrors()) {
_errors.dataProvider.addItem(err);
trace(err);
}
status.updateValid(Ternary.of(lib.valid));
});
} else loadFla(status.file);
}
protected function loadFla (file :File) :void {
log.info("Loading fla", "path", file.nativePath);
Files.load(file).succeeded.add(function (file :File) :void {
const zip :FZip = new FZip();
zip.loadBytes(file.data);
const files :Array = [];
for (var ii :int = 0; ii < zip.getFileCount(); ii++) files.push(zip.getFileAt(ii));
const xmls :Array = F.filter(files, function (fz :FZipFile) :Boolean {
return StringUtil.endsWith(fz.filename, ".xml");
});
const movies :Array = F.filter(xmls, function (fz :FZipFile) :Boolean {
return StringUtil.startsWith(fz.filename, "LIBRARY/Animations/");
});
const textures :Array = F.filter(xmls, function (fz :FZipFile) :Boolean {
return StringUtil.startsWith(fz.filename, "LIBRARY/Textures/");
});
function toFn (fz :FZipFile) :String { return fz.filename };
log.info("Loaded", "bytes", file.data.length, "movies", F.map(movies, toFn),
"textures", F.map(textures, toFn));
for each (var fz :FZipFile in movies) {
new XflMovie(fz.filename, bytesToXML(fz.content), MD5.hashBytes(fz.content));
}
NA.exit(0);
});
}
protected var _rootLen :int;
protected var _docFinder :Executor;
protected var _win :ExporterWindow;
protected var _libraries :DataGrid;
protected var _errors :DataGrid;
protected var _exportChooser :DirChooser;
protected var _importChooser :DirChooser;
protected var _authoredResolution :DropDownList;
protected const _settings :SharedObject = SharedObject.getLocal("flump/Exporter");
private static const log :Log = Log.getLog(Exporter);
}
}
import flash.events.EventDispatcher;
import flash.filesystem.File;
import flump.export.DeviceType;
import flump.export.Ternary;
import flump.xfl.XflLibrary;
import mx.core.IPropertyChangeNotifier;
import mx.events.PropertyChangeEvent;
class DeviceSelection {
public var type :DeviceType;
public function DeviceSelection (type :DeviceType) {
this.type = type;
}
public function toString () :String {
return type.displayName + " (" + type.resWidth + "x" + type.resHeight + ")";
}
}
class DocStatus extends EventDispatcher implements IPropertyChangeNotifier {
public var path :String;
public var modified :String;
public var valid :String = QUESTION;
public var file :File;
public var lib :XflLibrary;
public function DocStatus (file :File, rootLen :int, modified :Ternary, valid :Ternary, lib :XflLibrary) {
this.file = file;
this.lib = lib;
path = file.nativePath.substring(rootLen);
_uid = path;
updateModified(modified);
updateValid(valid);
}
public function updateValid (newValid :Ternary) :void {
changeField("valid", function (..._) :void {
if (newValid == Ternary.TRUE) valid = CHECK;
else if (newValid == Ternary.FALSE) valid = FROWN;
else valid = QUESTION;
});
}
public function get isValid () :Boolean { return valid == CHECK; }
public function updateModified (newModified :Ternary) :void {
changeField("modified", function (..._) :void {
if (newModified == Ternary.TRUE) modified = CHECK;
else if (newModified == Ternary.FALSE) modified = " ";
else modified = QUESTION;
});
}
protected function changeField(fieldName :String, modifier :Function) :void {
const oldValue :Object = this[fieldName];
modifier();
const newValue :Object = this[fieldName];
dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, fieldName, oldValue, newValue));
}
public function get uid () :String { return _uid; }
public function set uid (uid :String) :void { _uid = uid; }
protected var _uid :String;
protected static const QUESTION :String = "?";
protected static const FROWN :String = "☹";
protected static const CHECK :String = "✓";
}
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.export {
import flash.desktop.NativeApplication;
import flash.display.NativeWindow;
import flash.display.Stage;
import flash.display.StageQuality;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.filesystem.File;
import flash.net.SharedObject;
import com.adobe.crypto.MD5;
import deng.fzip.FZip;
import deng.fzip.FZipFile;
import flump.bytesToXML;
import flump.display.Movie;
import flump.executor.Executor;
import flump.executor.Future;
import flump.export.Ternary;
import flump.xfl.ParseError;
import flump.xfl.XflLibrary;
import flump.xfl.XflMovie;
import mx.collections.ArrayCollection;
import spark.components.DataGrid;
import spark.components.DropDownList;
import spark.components.List;
import spark.components.Window;
import spark.events.GridSelectionEvent;
import starling.display.Sprite;
import com.threerings.util.F;
import com.threerings.util.Log;
import com.threerings.util.StringUtil;
public class Exporter
{
public static const NA :NativeApplication = NativeApplication.nativeApplication;
protected static const IMPORT_ROOT :String = "IMPORT_ROOT";
protected static const AUTHORED_RESOLUTION :String = "AUTHORED_RESOLUTION";
public function Exporter (win :ExporterWindow) {
_win = win;
_errors = _win.errors;
_libraries = _win.libraries;
_authoredResolution = _win.authoredResolutionPopup;
_authoredResolution.dataProvider = new ArrayCollection(DeviceType.values().map(
function (type :DeviceType, ..._) :Object {
return new DeviceSelection(type);
}));
var initialSelection :DeviceType = null;
if (_settings.data.hasOwnProperty(AUTHORED_RESOLUTION)) {
try {
initialSelection = DeviceType.valueOf(_settings.data[AUTHORED_RESOLUTION]);
} catch (e :Error) {}
}
if (initialSelection == null) {
initialSelection = DeviceType.IPHONE_RETINA;
}
_authoredResolution.selectedIndex = DeviceType.values().indexOf(initialSelection);
_authoredResolution.addEventListener(Event.CHANGE, function (..._) :void {
var selectedType :DeviceType = DeviceSelection(_authoredResolution.selectedItem).type;
_settings.data[AUTHORED_RESOLUTION] = selectedType.name();
});
function updateExportEnabled (..._) :void {
_win.export.enabled = _exportChooser.dir != null && _libraries.selectionLength > 0 &&
_libraries.selectedItems.some(function (status :DocStatus, ..._) :Boolean {
return status.isValid;
});
}
_libraries.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void {
log.info("Changed", "selected", _libraries.selectedIndices);
updateExportEnabled();
_win.preview.enabled = _libraries.selectedItem.isValid;
});
_win.export.addEventListener(MouseEvent.CLICK, function (..._) :void {
for each (var status :DocStatus in _libraries.selectedItems) {
exportFlashDocument(status);
}
});
_win.preview.addEventListener(MouseEvent.CLICK, function (..._) :void {
showPreviewWindow(_libraries.selectedItem.lib);
});
_importChooser =
new DirChooser(_settings, "IMPORT_ROOT", _win.importRoot, _win.browseImport);
_importChooser.changed.add(setImport);
setImport(_importChooser.dir);
_exportChooser =
new DirChooser(_settings, "EXPORT_ROOT", _win.exportRoot, _win.browseExport);
_exportChooser.changed.add(updateExportEnabled);
_win.addEventListener(Event.CLOSE, function (..._) :void { NA.exit(0); });
}
protected function setImport (root :File) :void {
_libraries.dataProvider.removeAll();
_errors.dataProvider.removeAll();
if (root == null) return;
_rootLen = root.nativePath.length + 1;
if (_docFinder != null) _docFinder.shutdownNow();
_docFinder = new Executor(2);
findFlashDocuments(root, _docFinder);
}
protected function showPreviewWindow (lib :XflLibrary) :void {
if (_previewController == null || _previewWindow.closed || _previewControls.closed) {
_previewWindow = new PreviewWindow();
_previewControls = new PreviewControlsWindow();
_previewWindow.started = function (container :Sprite) :void {
_previewController = new PreviewController(lib, container, _previewControls);
}
_previewWindow.open();
_previewControls.open();
preventWindowClose(_previewWindow.nativeWindow);
preventWindowClose(_previewControls.nativeWindow);
} else {
_previewController.lib = lib;
_previewWindow.nativeWindow.visible = true;
_previewControls.nativeWindow.visible = true;
}
}
// Causes a window to be hidden, rather than closed, when its close box is clicked
protected static function preventWindowClose (window :NativeWindow) :void {
window.addEventListener(Event.CLOSING, function (e :Event) :void {
e.preventDefault();
window.visible = false;
});
}
protected var _previewController :PreviewController;
protected var _previewWindow :PreviewWindow;
protected var _previewControls :PreviewControlsWindow;
protected function findFlashDocuments (base :File, exec :Executor) :void {
Files.list(base, exec).succeeded.add(function (files :Array) :void {
if (exec.isShutdown) return;
for each (var file :File in files) {
if (Files.hasExtension(file, "xfl")) {
addFlashDocument(file.parent);
return;
}
}
for each (file in files) {
if (file.isDirectory) findFlashDocuments(file, exec);
else if (Files.hasExtension(file, "fla")) addFlashDocument(file);
}
});
}
protected function addFlashDocument (file :File) :void {
const status :DocStatus = new DocStatus(file, _rootLen, Ternary.UNKNOWN, Ternary.UNKNOWN, null);
_libraries.dataProvider.addItem(status);
loadFlashDocument(status);
}
protected function exportFlashDocument (status :DocStatus) :void {
var stage :Stage = NA.activeWindow.stage;
var prevQuality :String = stage.quality;
stage.quality = StageQuality.BEST;
BetwixtPublisher.publish(status.lib, status.file,
DeviceSelection(_authoredResolution.selectedItem).type, _exportChooser.dir);
stage.quality = prevQuality;
status.updateModified(Ternary.FALSE);
}
protected function loadFlashDocument (status :DocStatus) :void {
if (Files.hasExtension(status.file, "xfl")) status.file = status.file.parent;
if (status.file.isDirectory) {
const name :String = status.file.nativePath
.substring(_rootLen).replace(File.separator, "/");
const load :Future = new XflLoader().load(name, status.file);
load.succeeded.add(function (lib :XflLibrary) :void {
// Don't blow up if the export directory hasn't been chosen
var isMod :Boolean = true;
if (_exportChooser.dir != null) {
var metadata :File = _exportChooser.dir.resolvePath(
lib.location + "/resources.xml");
isMod = BetwixtPublisher.modified(lib, metadata);
}
status.lib = lib;
status.updateModified(Ternary.of(isMod));
for each (var err :ParseError in lib.getErrors()) {
_errors.dataProvider.addItem(err);
trace(err);
}
status.updateValid(Ternary.of(lib.valid));
});
} else loadFla(status.file);
}
protected function loadFla (file :File) :void {
log.info("Loading fla", "path", file.nativePath);
Files.load(file).succeeded.add(function (file :File) :void {
const zip :FZip = new FZip();
zip.loadBytes(file.data);
const files :Array = [];
for (var ii :int = 0; ii < zip.getFileCount(); ii++) files.push(zip.getFileAt(ii));
const xmls :Array = F.filter(files, function (fz :FZipFile) :Boolean {
return StringUtil.endsWith(fz.filename, ".xml");
});
const movies :Array = F.filter(xmls, function (fz :FZipFile) :Boolean {
return StringUtil.startsWith(fz.filename, "LIBRARY/Animations/");
});
const textures :Array = F.filter(xmls, function (fz :FZipFile) :Boolean {
return StringUtil.startsWith(fz.filename, "LIBRARY/Textures/");
});
function toFn (fz :FZipFile) :String { return fz.filename };
log.info("Loaded", "bytes", file.data.length, "movies", F.map(movies, toFn),
"textures", F.map(textures, toFn));
for each (var fz :FZipFile in movies) {
new XflMovie(fz.filename, bytesToXML(fz.content), MD5.hashBytes(fz.content));
}
NA.exit(0);
});
}
protected var _rootLen :int;
protected var _docFinder :Executor;
protected var _win :ExporterWindow;
protected var _libraries :DataGrid;
protected var _errors :DataGrid;
protected var _exportChooser :DirChooser;
protected var _importChooser :DirChooser;
protected var _authoredResolution :DropDownList;
protected const _settings :SharedObject = SharedObject.getLocal("flump/Exporter");
private static const log :Log = Log.getLog(Exporter);
}
}
import flash.events.EventDispatcher;
import flash.filesystem.File;
import flump.export.DeviceType;
import flump.export.Ternary;
import flump.xfl.XflLibrary;
import mx.core.IPropertyChangeNotifier;
import mx.events.PropertyChangeEvent;
class DeviceSelection {
public var type :DeviceType;
public function DeviceSelection (type :DeviceType) {
this.type = type;
}
public function toString () :String {
return type.displayName + " (" + type.resWidth + "x" + type.resHeight + ")";
}
}
class DocStatus extends EventDispatcher implements IPropertyChangeNotifier {
public var path :String;
public var modified :String;
public var valid :String = QUESTION;
public var file :File;
public var lib :XflLibrary;
public function DocStatus (file :File, rootLen :int, modified :Ternary, valid :Ternary, lib :XflLibrary) {
this.file = file;
this.lib = lib;
path = file.nativePath.substring(rootLen);
_uid = path;
updateModified(modified);
updateValid(valid);
}
public function updateValid (newValid :Ternary) :void {
changeField("valid", function (..._) :void {
if (newValid == Ternary.TRUE) valid = CHECK;
else if (newValid == Ternary.FALSE) valid = FROWN;
else valid = QUESTION;
});
}
public function get isValid () :Boolean { return valid == CHECK; }
public function updateModified (newModified :Ternary) :void {
changeField("modified", function (..._) :void {
if (newModified == Ternary.TRUE) modified = CHECK;
else if (newModified == Ternary.FALSE) modified = " ";
else modified = QUESTION;
});
}
protected function changeField(fieldName :String, modifier :Function) :void {
const oldValue :Object = this[fieldName];
modifier();
const newValue :Object = this[fieldName];
dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, fieldName, oldValue, newValue));
}
public function get uid () :String { return _uid; }
public function set uid (uid :String) :void { _uid = uid; }
protected var _uid :String;
protected static const QUESTION :String = "?";
protected static const FROWN :String = "☹";
protected static const CHECK :String = "✓";
}
|
Use the best stage quality when publishing the atlases.
|
Use the best stage quality when publishing the atlases.
Once Flash 11.2 is out, we should use "16X16" as described at
http://blog.kaourantin.net/?p=152.
|
ActionScript
|
mit
|
mathieuanthoine/flump,funkypandagame/flump,funkypandagame/flump,tconkling/flump,tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump
|
a0946462dbc710c0c93759fd10da1c179d655c79
|
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);
Steamworks.addEventListener(SteamEvent.STEAM_RESPONSE, onSteamResponse);
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') );
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("activateGameOverlay('Friends') == " + Steamworks.activateGameOverlay("Friends"));
}
private function enumerateSubscribedFiles(e:Event = null):void {
if(!Steamworks.isReady) return;
log("enumerateUserSubscribedFiles(0) == " + Steamworks.enumerateUserSubscribedFiles(0));
}
private function onSteamResponse(e:SteamEvent):void{
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 result:SubscribedFilesResult = Steamworks.enumerateUserSubscribedFilesResult();
log("User subscribed files: " + result.resultsReturned + "/" + result.totalResults);
for(var i:int = 0; i < result.resultsReturned; i++)
log(i + ": " + result.publishedFileId[i] + " (" + result.timeSubscribed[i] + ")");
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;
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);
Steamworks.addEventListener(SteamEvent.STEAM_RESPONSE, onSteamResponse);
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') );
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 onSteamResponse(e:SteamEvent):void{
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 result:SubscribedFilesResult = Steamworks.enumerateUserSubscribedFilesResult();
log("User subscribed files: " + result.resultsReturned + "/" + result.totalResults);
for(var i:int = 0; i < result.resultsReturned; i++)
log(i + ": " + result.publishedFileId[i] + " (" + result.timeSubscribed[i] + ")");
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;
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 isOverlayEnabled
|
Add test for isOverlayEnabled
|
ActionScript
|
bsd-2-clause
|
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
|
dec934c97d67a5332d0e05beefbc16fc889f43ab
|
kdp3Lib/src/org/puremvc/as3/patterns/observer/Observer.as
|
kdp3Lib/src/org/puremvc/as3/patterns/observer/Observer.as
|
/*
PureMVC - Copyright(c) 2006-08 Futurescale, Inc., Some rights reserved.
Your reuse is governed by the Creative Commons Attribution 3.0 United States License
*/
package org.puremvc.as3.patterns.observer
{
import org.puremvc.as3.interfaces.*;
/**
* A base <code>IObserver</code> implementation.
*
* <P>
* An <code>Observer</code> is an object that encapsulates information
* about an interested object with a method that should
* be called when a particular <code>INotification</code> is broadcast. </P>
*
* <P>
* In PureMVC, the <code>Observer</code> class assumes these responsibilities:
* <UL>
* <LI>Encapsulate the notification (callback) method of the interested object.</LI>
* <LI>Encapsulate the notification context (this) of the interested object.</LI>
* <LI>Provide methods for setting the notification method and context.</LI>
* <LI>Provide a method for notifying the interested object.</LI>
* </UL>
*
* @see org.puremvc.as3.core.view.View View
* @see org.puremvc.as3.patterns.observer.Notification Notification
*/
public class Observer implements IObserver
{
private var notify:Function;
private var context:Object;
/**
* Constructor.
*
* <P>
* The notification method on the interested object should take
* one parameter of type <code>INotification</code></P>
*
* @param notifyMethod the notification method of the interested object
* @param notifyContext the notification context of the interested object
*/
public function Observer( notifyMethod:Function, notifyContext:Object )
{
setNotifyMethod( notifyMethod );
setNotifyContext( notifyContext );
}
/**
* Set the notification method.
*
* <P>
* The notification method should take one parameter of type <code>INotification</code>.</P>
*
* @param notifyMethod the notification (callback) method of the interested object.
*/
public function setNotifyMethod( notifyMethod:Function ):void
{
notify = notifyMethod;
}
/**
* Set the notification context.
*
* @param notifyContext the notification context (this) of the interested object.
*/
public function setNotifyContext( notifyContext:Object ):void
{
context = notifyContext;
}
/**
* Get the notification method.
*
* @return the notification (callback) method of the interested object.
*/
private function getNotifyMethod():Function
{
return notify;
}
/**
* Get the notification context.
*
* @return the notification context (<code>this</code>) of the interested object.
*/
private function getNotifyContext():Object
{
return context;
}
/**
* Notify the interested object.
*
* @param notification the <code>INotification</code> to pass to the interested object's notification method.
*/
public function notifyObserver( notification:INotification ):void
{
//If the handleNotification method fails internally, the notification needs to carry on being
//delivered to other listeners.
try
{
this.getNotifyMethod().apply(this.getNotifyContext(),[notification]);
}
catch(e : Error)
{
return;
}
}
/**
* Compare an object to the notification context.
*
* @param object the object to compare
* @return boolean indicating if the object and the notification context are the same
*/
public function compareNotifyContext( object:Object ):Boolean
{
return object === this.context;
}
}
}
|
/*
PureMVC - Copyright(c) 2006-08 Futurescale, Inc., Some rights reserved.
Your reuse is governed by the Creative Commons Attribution 3.0 United States License
*/
package org.puremvc.as3.patterns.observer
{
import com.kaltura.kdpfl.view.controls.KTrace;
import org.puremvc.as3.interfaces.*;
/**
* A base <code>IObserver</code> implementation.
*
* <P>
* An <code>Observer</code> is an object that encapsulates information
* about an interested object with a method that should
* be called when a particular <code>INotification</code> is broadcast. </P>
*
* <P>
* In PureMVC, the <code>Observer</code> class assumes these responsibilities:
* <UL>
* <LI>Encapsulate the notification (callback) method of the interested object.</LI>
* <LI>Encapsulate the notification context (this) of the interested object.</LI>
* <LI>Provide methods for setting the notification method and context.</LI>
* <LI>Provide a method for notifying the interested object.</LI>
* </UL>
*
* @see org.puremvc.as3.core.view.View View
* @see org.puremvc.as3.patterns.observer.Notification Notification
*/
public class Observer implements IObserver
{
private var notify:Function;
private var context:Object;
/**
* Constructor.
*
* <P>
* The notification method on the interested object should take
* one parameter of type <code>INotification</code></P>
*
* @param notifyMethod the notification method of the interested object
* @param notifyContext the notification context of the interested object
*/
public function Observer( notifyMethod:Function, notifyContext:Object )
{
setNotifyMethod( notifyMethod );
setNotifyContext( notifyContext );
}
/**
* Set the notification method.
*
* <P>
* The notification method should take one parameter of type <code>INotification</code>.</P>
*
* @param notifyMethod the notification (callback) method of the interested object.
*/
public function setNotifyMethod( notifyMethod:Function ):void
{
notify = notifyMethod;
}
/**
* Set the notification context.
*
* @param notifyContext the notification context (this) of the interested object.
*/
public function setNotifyContext( notifyContext:Object ):void
{
context = notifyContext;
}
/**
* Get the notification method.
*
* @return the notification (callback) method of the interested object.
*/
private function getNotifyMethod():Function
{
return notify;
}
/**
* Get the notification context.
*
* @return the notification context (<code>this</code>) of the interested object.
*/
private function getNotifyContext():Object
{
return context;
}
/**
* Notify the interested object.
*
* @param notification the <code>INotification</code> to pass to the interested object's notification method.
*/
public function notifyObserver( notification:INotification ):void
{
//If the handleNotification method fails internally, the notification needs to carry on being
//delivered to other listeners.
try
{
this.getNotifyMethod().apply(this.getNotifyContext(),[notification]);
}
catch(e : Error)
{
KTrace.getInstance().log("--Exception while notifying " + notification.getName() + ": " + e.message);
return;
}
}
/**
* Compare an object to the notification context.
*
* @param object the object to compare
* @return boolean indicating if the object and the notification context are the same
*/
public function compareNotifyContext( object:Object ):Boolean
{
return object === this.context;
}
}
}
|
add informative trace when sendNotification fails
|
add informative trace when sendNotification fails
|
ActionScript
|
agpl-3.0
|
kaltura/kdp,shvyrev/kdp,shvyrev/kdp,kaltura/kdp,kaltura/kdp,shvyrev/kdp
|
2fd020edbf7b8f90520e7df374b6fe52f35603e7
|
src/org/mangui/hls/demux/Nalu.as
|
src/org/mangui/hls/demux/Nalu.as
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls.demux {
import flash.utils.ByteArray;
CONFIG::LOGGING {
import org.mangui.hls.HLSSettings;
import org.mangui.hls.utils.Log;
}
/** Constants and utilities for the H264 video format. **/
public class Nalu {
private static var _audNalu : ByteArray;
// static initializer
{
_audNalu = new ByteArray();
_audNalu.length = 2;
_audNalu.writeByte(0x09);
_audNalu.writeByte(0xF0);
};
/** Return an array with NAL delimiter indexes. **/
public static function getNALU(nalu : ByteArray, position : uint) : Vector.<VideoFrame> {
var units : Vector.<VideoFrame> = new Vector.<VideoFrame>();
var unit_start : int;
var unit_type : int;
var unit_header : int;
var aud_found : Boolean = false;
// Loop through data to find NAL startcodes.
var window : uint = 0;
nalu.position = position;
while (nalu.bytesAvailable > 4) {
window = nalu.readUnsignedInt();
// Match four-byte startcodes
if ((window & 0xFFFFFFFF) == 0x01) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if (unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
unit_header = 4;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
if(unit_type ==9) {
aud_found = true;
}
/* if AUD already found and newly found unit is NDR or IDR,
stop parsing here and consider that this IDR/NDR is the last NAL unit
breaking the loop here is done for optimization purpose, as NAL parsing is time consuming ...
*/
if (aud_found && (unit_type == 1 || unit_type == 5)) {
break;
}
// Match three-byte startcodes
} else if ((window & 0xFFFFFF00) == 0x100) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if (unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
nalu.position--;
unit_header = 3;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
if(unit_type ==9) {
aud_found = true;
}
/* if AUD already found and newly found unit is NDR or IDR,
stop parsing here and consider that this IDR/NDR is the last NAL unit
breaking the loop here is done for optimization purpose, as NAL parsing is time consuming ...
*/
if (aud_found && (unit_type == 1 || unit_type == 5)) {
break;
}
} else {
nalu.position -= 3;
}
}
// Append the last NAL to the array.
if (unit_start) {
units.push(new VideoFrame(unit_header, nalu.length - unit_start, unit_start, unit_type));
}
// Reset position and return results.
CONFIG::LOGGING {
if (HLSSettings.logDebug2) {
/** H264 NAL unit names. **/
const NAMES : Array = ['Unspecified',// 0
'NDR', // 1
'Partition A', // 2
'Partition B', // 3
'Partition C', // 4
'IDR', // 5
'SEI', // 6
'SPS', // 7
'PPS', // 8
'AUD', // 9
'End of Sequence', // 10
'End of Stream', // 11
'Filler Data'// 12
];
if (units.length) {
var txt : String = "AVC: ";
for (var i : int = 0; i < units.length; i++) {
txt += NAMES[units[i].type] + ","; //+ ":" + units[i].length
}
Log.debug2(txt.substr(0, txt.length - 2) + " slices");
} else {
Log.debug2('AVC: no NALU slices found');
}
}
}
nalu.position = position;
return units;
};
public static function get AUD():ByteArray {
return _audNalu;
}
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls.demux {
import flash.utils.ByteArray;
CONFIG::LOGGING {
import org.mangui.hls.HLSSettings;
import org.mangui.hls.utils.Log;
}
/** Constants and utilities for the H264 video format. **/
public class Nalu {
private static var _audNalu : ByteArray;
// static initializer
{
_audNalu = new ByteArray();
_audNalu.length = 2;
_audNalu.writeByte(0x09);
_audNalu.writeByte(0xF0);
};
/** Return an array with NAL delimiter indexes. **/
public static function getNALU(nalu : ByteArray, position : uint) : Vector.<VideoFrame> {
var units : Vector.<VideoFrame> = new Vector.<VideoFrame>();
var unit_start : int;
var unit_type : int;
var unit_header : int;
var aud_found : Boolean = false;
// Loop through data to find NAL startcodes.
var window : uint = 0;
nalu.position = position;
while (nalu.bytesAvailable > 4) {
window = nalu.readUnsignedInt();
// Match four-byte startcodes
if ((window & 0xFFFFFFFF) == 0x01) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if (unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
unit_header = 4;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
if(unit_type ==9) {
aud_found = true;
}
/* if AUD already found and newly found unit is NDR or IDR,
stop parsing here and consider that this IDR/NDR is the last NAL unit
breaking the loop here is done for optimization purpose, as NAL parsing is time consuming ...
*/
if (aud_found && (unit_type == 1 || unit_type == 5)) {
break;
}
// Match three-byte startcodes
} else if ((window & 0xFFFFFF00) == 0x100) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if (unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
nalu.position--;
unit_header = 3;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
if(unit_type ==9) {
aud_found = true;
}
/* if AUD already found and newly found unit is NDR or IDR,
stop parsing here and consider that this IDR/NDR is the last NAL unit
breaking the loop here is done for optimization purpose, as NAL parsing is time consuming ...
*/
if (aud_found && (unit_type == 1 || unit_type == 5)) {
break;
}
} else {
nalu.position -= 3;
}
}
// Append the last NAL to the array.
if (unit_start) {
units.push(new VideoFrame(unit_header, nalu.length - unit_start, unit_start, unit_type));
}
// Reset position and return results.
CONFIG::LOGGING {
if (HLSSettings.logDebug2) {
/** H264 NAL unit names. **/
const NAMES : Array = ['Unspecified',// 0
'NDR', // 1
'Partition A', // 2
'Partition B', // 3
'Partition C', // 4
'IDR', // 5
'SEI', // 6
'SPS', // 7
'PPS', // 8
'AUD', // 9
'End of Sequence', // 10
'End of Stream', // 11
'Filler Data'// 12
];
if (units.length) {
var txt : String = "AVC: ";
for (var i : int = 0; i < units.length; i++) {
txt += NAMES[units[i].type] + ","; //+ ":" + units[i].length
}
Log.debug2(txt.substr(0,txt.length-1) + " slices");
} else {
Log.debug2('AVC: no NALU slices found');
}
}
}
nalu.position = position;
return units;
};
public static function get AUD():ByteArray {
return _audNalu;
}
}
}
|
fix truncated debug2 logs
|
fix truncated debug2 logs
|
ActionScript
|
mpl-2.0
|
tedconf/flashls,JulianPena/flashls,hola/flashls,hola/flashls,Corey600/flashls,NicolasSiver/flashls,codex-corp/flashls,JulianPena/flashls,tedconf/flashls,clappr/flashls,thdtjsdn/flashls,vidible/vdb-flashls,mangui/flashls,neilrackett/flashls,jlacivita/flashls,dighan/flashls,Boxie5/flashls,jlacivita/flashls,loungelogic/flashls,thdtjsdn/flashls,neilrackett/flashls,dighan/flashls,loungelogic/flashls,clappr/flashls,fixedmachine/flashls,fixedmachine/flashls,codex-corp/flashls,Corey600/flashls,NicolasSiver/flashls,vidible/vdb-flashls,Boxie5/flashls,mangui/flashls
|
8b52ec47560c6d4cfd3da996f5861a4f1696fe88
|
flash-src/com/gsolo/encryption/SHA1.as
|
flash-src/com/gsolo/encryption/SHA1.as
|
package com.gsolo.encryption {
public class SHA1 {
/*
* A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
* in FIPS PUB 180-1
* Version 2.1a Copyright Paul Johnston 2000 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for details.
*
* Converted to AS3 By Geoffrey Williams
*/
/*
* Configurable variables. You may need to tweak these to be compatible with
* the server-side, but the defaults work in most cases.
*/
public static const HEX_FORMAT_LOWERCASE:uint = 0;
public static const HEX_FORMAT_UPPERCASE:uint = 1;
public static const BASE64_PAD_CHARACTER_DEFAULT_COMPLIANCE:String = "";
public static const BASE64_PAD_CHARACTER_RFC_COMPLIANCE:String = "=";
public static const BITS_PER_CHAR_ASCII:uint = 8;
public static const BITS_PER_CHAR_UNICODE:uint = 8;
public static var hexcase:uint = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
public static var b64pad:String = ""; /* base-64 pad character. "=" for strict RFC compliance */
public static var chrsz:uint = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
public static function encrypt (string:String):String {
return hex_sha1 (string);
}
/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
public static function hex_sha1 (string:String):String {
return binb2hex (core_sha1( str2binb(string), string.length * chrsz));
}
public static function b64_sha1 (string:String):String {
return binb2b64 (core_sha1 (str2binb (string), string.length * chrsz));
}
public static function str_sha1 (string:String):String {
return binb2str (core_sha1 (str2binb (string), string.length * chrsz));
}
public static function hex_hmac_sha1 (key:String, data:String):String {
return binb2hex (core_hmac_sha1 (key, data));
}
public static function b64_hmac_sha1 (key:String, data:String):String {
return binb2b64 (core_hmac_sha1 (key, data));
}
public static function str_hmac_sha1 (key:String, data:String):String {
return binb2str (core_hmac_sha1 (key, data));
}
/*
* Perform a simple self-test to see if the VM is working
*/
public static function sha1_vm_test ():Boolean {
return hex_sha1 ("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d";
}
/*
* Calculate the SHA-1 of an array of big-endian words, and a bit length
*/
public static function core_sha1 (x:Array, len:Number):Array {
/* append padding */
x[len >> 5] |= 0x80 << (24 - len % 32);
x[((len + 64 >> 9) << 4) + 15] = len;
var w:Array = Array(80);
var a:Number = 1732584193;
var b:Number = -271733879;
var c:Number = -1732584194;
var d:Number = 271733878;
var e:Number = -1009589776;
for(var i:Number = 0; i < x.length; i += 16) {
var olda:Number = a;
var oldb:Number = b;
var oldc:Number = c;
var oldd:Number = d;
var olde:Number = e;
for(var j:Number = 0; j < 80; j++) {
if(j < 16) w[j] = x[i + j];
else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
var t:Number = safe_add (safe_add (rol (a, 5), sha1_ft (j, b, c, d)), safe_add (safe_add (e, w[j]), sha1_kt (j)));
e = d;
d = c;
c = rol(b, 30);
b = a;
a = t;
}
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
e = safe_add(e, olde);
}
return [a, b, c, d, e];
}
/*
* Perform the appropriate triplet combination function for the current
* iteration
*/
public static function sha1_ft (t:Number, b:Number, c:Number, d:Number):Number {
if(t < 20) return (b & c) | ((~b) & d);
if(t < 40) return b ^ c ^ d;
if(t < 60) return (b & c) | (b & d) | (c & d);
return b ^ c ^ d;
}
/*
* Determine the appropriate additive constant for the current iteration
*/
public static function sha1_kt (t:Number):Number {
return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514;
}
/*
* Calculate the HMAC-SHA1 of a key and some data
*/
public static function core_hmac_sha1 (key:String, data:String):Array {
var bkey:Array = str2binb (key);
if (bkey.length > 16) bkey = core_sha1 (bkey, key.length * chrsz);
var ipad:Array = Array(16), opad:Array = Array(16);
for(var i:Number = 0; i < 16; i++) {
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash:Array = core_sha1 (ipad.concat (str2binb(data)), 512 + data.length * chrsz);
return core_sha1 (opad.concat (hash), 512 + 160);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
public static function safe_add (x:Number, y:Number):Number {
var lsw:Number = (x & 0xFFFF) + (y & 0xFFFF);
var msw:Number = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
public static function rol (num:Number, cnt:Number):Number {
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* Convert an 8-bit or 16-bit string to an array of big-endian words
* In 8-bit function, characters >255 have their hi-byte silently ignored.
*/
public static function str2binb (str:String):Array {
var bin:Array = new Array ();
var mask:Number = (1 << chrsz) - 1;
for (var i:Number = 0; i < str.length * chrsz; i += chrsz) bin[i>>5] |= (str.charCodeAt (i / chrsz) & mask) << (32 - chrsz - i%32);
return bin;
}
/*
* Convert an array of big-endian words to a string
*/
public static function binb2str (bin:Array):String {
var str:String = "";
var mask:Number = (1 << chrsz) - 1;
for (var i:Number = 0; i < bin.length * 32; i += chrsz) str += String.fromCharCode((bin[i>>5] >>> (32 - chrsz - i%32)) & mask);
return str;
}
/*
* Convert an array of big-endian words to a hex string.
*/
public static function binb2hex (binarray:Array):String {
var hex_tab:String = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str:String = "";
for(var i:Number = 0; i < binarray.length * 4; i++) {
str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +
hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8 )) & 0xF);
}
return str;
}
/*
* Convert an array of big-endian words to a base-64 string
*/
public static function binb2b64 (binarray:Array):String {
var tab:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var str:String = "";
for(var i:Number = 0; i < binarray.length * 4; i += 3) {
var triplet:Number = (((binarray[i >> 2] >> 8 * (3 - i %4)) & 0xFF) << 16)
| (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 )
| ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF);
for(var j:Number = 0; j < 4; j++) {
if (i * 8 + j * 6 > binarray.length * 32) str += b64pad;
else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
}
}
return str;
}
}
}
|
package com.gsolo.encryption {
public class SHA1 {
/*
* A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
* in FIPS PUB 180-1
* Version 2.1a Copyright Paul Johnston 2000 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for details.
*
* Converted to AS3 By Geoffrey Williams
*/
/*
* Configurable variables. You may need to tweak these to be compatible with
* the server-side, but the defaults work in most cases.
*/
public static const HEX_FORMAT_LOWERCASE:uint = 0;
public static const HEX_FORMAT_UPPERCASE:uint = 1;
public static const BASE64_PAD_CHARACTER_DEFAULT_COMPLIANCE:String = "";
public static const BASE64_PAD_CHARACTER_RFC_COMPLIANCE:String = "=";
public static const BITS_PER_CHAR_ASCII:uint = 8;
public static const BITS_PER_CHAR_UNICODE:uint = 8;
public static var hexcase:uint = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
public static var b64pad:String = ""; /* base-64 pad character. "=" for strict RFC compliance */
public static var chrsz:uint = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
public static function encrypt (string:String):String {
return hex_sha1 (string);
}
/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
public static function hex_sha1 (string:String):String {
return binb2hex (core_sha1( str2binb(string), string.length * chrsz));
}
public static function b64_sha1 (string:String):String {
return binb2b64 (core_sha1 (str2binb (string), string.length * chrsz));
}
public static function str_sha1 (string:String):String {
return binb2str (core_sha1 (str2binb (string), string.length * chrsz));
}
public static function hex_hmac_sha1 (key:String, data:String):String {
return binb2hex (core_hmac_sha1 (key, data));
}
public static function b64_hmac_sha1 (key:String, data:String):String {
return binb2b64 (core_hmac_sha1 (key, data));
}
public static function str_hmac_sha1 (key:String, data:String):String {
return binb2str (core_hmac_sha1 (key, data));
}
/*
* Perform a simple self-test to see if the VM is working
*/
public static function sha1_vm_test ():Boolean {
return hex_sha1 ("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d";
}
/*
* Calculate the SHA-1 of an array of big-endian words, and a bit length
*/
public static function core_sha1 (x:Array, len:Number):Array {
/* append padding */
x[len >> 5] |= 0x80 << (24 - len % 32);
x[((len + 64 >> 9) << 4) + 15] = len;
var w:Array = new Array(80);
var a:Number = 1732584193;
var b:Number = -271733879;
var c:Number = -1732584194;
var d:Number = 271733878;
var e:Number = -1009589776;
for(var i:Number = 0; i < x.length; i += 16) {
var olda:Number = a;
var oldb:Number = b;
var oldc:Number = c;
var oldd:Number = d;
var olde:Number = e;
for(var j:Number = 0; j < 80; j++) {
if(j < 16) w[j] = x[i + j];
else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
var t:Number = safe_add (safe_add (rol (a, 5), sha1_ft (j, b, c, d)), safe_add (safe_add (e, w[j]), sha1_kt (j)));
e = d;
d = c;
c = rol(b, 30);
b = a;
a = t;
}
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
e = safe_add(e, olde);
}
return [a, b, c, d, e];
}
/*
* Perform the appropriate triplet combination function for the current
* iteration
*/
public static function sha1_ft (t:Number, b:Number, c:Number, d:Number):Number {
if(t < 20) return (b & c) | ((~b) & d);
if(t < 40) return b ^ c ^ d;
if(t < 60) return (b & c) | (b & d) | (c & d);
return b ^ c ^ d;
}
/*
* Determine the appropriate additive constant for the current iteration
*/
public static function sha1_kt (t:Number):Number {
return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514;
}
/*
* Calculate the HMAC-SHA1 of a key and some data
*/
public static function core_hmac_sha1 (key:String, data:String):Array {
var bkey:Array = str2binb (key);
if (bkey.length > 16) bkey = core_sha1 (bkey, key.length * chrsz);
var ipad:Array = new Array(16), opad:Array = new Array(16);
for(var i:Number = 0; i < 16; i++) {
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash:Array = core_sha1 (ipad.concat (str2binb(data)), 512 + data.length * chrsz);
return core_sha1 (opad.concat (hash), 512 + 160);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
public static function safe_add (x:Number, y:Number):Number {
var lsw:Number = (x & 0xFFFF) + (y & 0xFFFF);
var msw:Number = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
public static function rol (num:Number, cnt:Number):Number {
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* Convert an 8-bit or 16-bit string to an array of big-endian words
* In 8-bit function, characters >255 have their hi-byte silently ignored.
*/
public static function str2binb (str:String):Array {
var bin:Array = new Array ();
var mask:Number = (1 << chrsz) - 1;
for (var i:Number = 0; i < str.length * chrsz; i += chrsz) bin[i>>5] |= (str.charCodeAt (i / chrsz) & mask) << (32 - chrsz - i%32);
return bin;
}
/*
* Convert an array of big-endian words to a string
*/
public static function binb2str (bin:Array):String {
var str:String = "";
var mask:Number = (1 << chrsz) - 1;
for (var i:Number = 0; i < bin.length * 32; i += chrsz) str += String.fromCharCode((bin[i>>5] >>> (32 - chrsz - i%32)) & mask);
return str;
}
/*
* Convert an array of big-endian words to a hex string.
*/
public static function binb2hex (binarray:Array):String {
var hex_tab:String = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str:String = "";
for(var i:Number = 0; i < binarray.length * 4; i++) {
str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +
hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8 )) & 0xF);
}
return str;
}
/*
* Convert an array of big-endian words to a base-64 string
*/
public static function binb2b64 (binarray:Array):String {
var tab:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var str:String = "";
for(var i:Number = 0; i < binarray.length * 4; i += 3) {
var triplet:Number = (((binarray[i >> 2] >> 8 * (3 - i %4)) & 0xFF) << 16)
| (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 )
| ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF);
for(var j:Number = 0; j < 4; j++) {
if (i * 8 + j * 6 > binarray.length * 32) str += b64pad;
else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
}
}
return str;
}
}
}
|
stop compile warnings.
|
com/gsolo/encryption/SHA1.as: stop compile warnings.
|
ActionScript
|
bsd-3-clause
|
nitzo/web-socket-js,keiosweb/web-socket-js,hanicker/web-socket-js,hehuabing/web-socket-js,keiosweb/web-socket-js,hanicker/web-socket-js,zhangxingits/web-socket-js,hehuabing/web-socket-js,nitzo/web-socket-js,gimite/web-socket-js,gimite/web-socket-js,gimite/web-socket-js,keiosweb/web-socket-js,nitzo/web-socket-js,zhangxingits/web-socket-js,hanicker/web-socket-js,hehuabing/web-socket-js,zhangxingits/web-socket-js
|
199ec5ba1d8ac4604b30acf1616bac30e6a1d8f2
|
fp9/src/eDpLib/events/EventDispatcherProxy.as
|
fp9/src/eDpLib/events/EventDispatcherProxy.as
|
/*
as3isolib - An open-source ActionScript 3.0 Isometric Library developed to assist
in creating isometrically projected content (such as games and graphics)
targeted for the Flash player platform
http://code.google.com/p/as3isolib/
Copyright (c) 2006 - 2008 J.W.Opitz, All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package eDpLib.events
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.FocusEvent;
import flash.events.IEventDispatcher;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
/**
* EventDispatcherProxy provides a means for intercepting events on behalf of a target and redispatching them as the target of the event.
*/
public class EventDispatcherProxy implements IEventDispatcher, IEventDispatcherProxy
{
////////////////////////////////////////////////////////////////////////
// PROXY TARGET
////////////////////////////////////////////////////////////////////////
/**
* @private
*/
private var _proxyTarget:IEventDispatcher; //the item that we are intercepting and redispatching, this being the target, should be set in subclasses
/**
* @private
*/
public function get proxyTarget ():IEventDispatcher
{
return _proxyTarget;
}
/**
* @inheritDoc
*/
public function set proxyTarget (value:IEventDispatcher):void
{
if (_proxyTarget != value)
{
_proxyTarget = value;
updateProxyListeners();
}
}
////////////////////////////////////////////////////////////////////////
// PROXY
////////////////////////////////////////////////////////////////////////
/**
* @private
*/
private var _proxy:IEventDispatcher;
/**
* @private
*/
public function get proxy ():IEventDispatcher
{
return _proxy;
}
/**
* @inheritDoc
*/
public function set proxy (target:IEventDispatcher):void
{
if (_proxy != target)
{
_proxy = target;
eventDispatcher = new EventDispatcher(_proxy);
}
}
////////////////////////////////////////////////////////////////////////
// CONSTRUCTOR
////////////////////////////////////////////////////////////////////////
/**
* Constructor
*/
public function EventDispatcherProxy ()
{
proxy = this;
}
////////////////////////////////////////////////////////////////////////
// LISTENER HASH
////////////////////////////////////////////////////////////////////////
/**
* @private
*
* A hash table following a basic format:
*
* hash[eventType] = ListenerHash() - a collection of listener objects with some convenience methods.
*/
private var listenerHashTable:Object = {};
/**
* @private
*
* Adds a listener for a given event type.
*/
private function setListenerHashProperty (type:String, listener:Function):void
{
var hash:ListenerHash;
if (!listenerHashTable.hasOwnProperty(type))
{
hash = new ListenerHash();
hash.addListener(listener);
listenerHashTable[type] = hash;
}
else
{
hash = ListenerHash(listenerHashTable[type]);
hash.addListener(listener);
}
}
/**
* @private
*
* Checks to see if a particular event type has been set up within the hash table.
*/
private function hasListenerHashProperty (type:String):Boolean
{
return listenerHashTable.hasOwnProperty(type);
}
/**
* @private
*
* Returns an array of listeners for a given event type.
*/
private function getListenersForEventType (type:String):Array
{
if (listenerHashTable.hasOwnProperty(type))
return ListenerHash(listenerHashTable[type]).listeners;
else
return [];
}
/**
* @private
*
* Removes the listeners and the event type from the hash table.
*/
private function removeListenerHashProperty (type:String):Boolean
{
if (listenerHashTable.hasOwnProperty(type))
{
listenerHashTable[type] = null;
delete listenerHashTable[type];
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////
// MISC. PROXY METHODS
////////////////////////////////////////////////////////////////////////
/**
* @private
*
* An array of events to check against that could be dispatched from an interactive target.
*/
public var interceptedEventTypes:Array = generateEventTypes();
/**
* Creates an array of interactive object events to check against during event proxying.
* To add more event types to check for, subclasses should override this.
*
* @return Array An array of event types.
*/
protected function generateEventTypes ():Array
{
var evtTypes:Array = [];
evtTypes.push
(
//REGULAR EVENTS
Event.ADDED,
Event.ADDED_TO_STAGE,
Event.ENTER_FRAME,
Event.REMOVED,
Event.REMOVED_FROM_STAGE,
Event.RENDER,
Event.TAB_CHILDREN_CHANGE,
Event.TAB_ENABLED_CHANGE,
Event.TAB_INDEX_CHANGE,
//FOCUS EVENTS
FocusEvent.FOCUS_IN,
FocusEvent.FOCUS_OUT,
FocusEvent.KEY_FOCUS_CHANGE,
FocusEvent.MOUSE_FOCUS_CHANGE,
//MOUSE EVENTS
MouseEvent.CLICK,
MouseEvent.DOUBLE_CLICK,
MouseEvent.MOUSE_DOWN,
MouseEvent.MOUSE_MOVE,
MouseEvent.MOUSE_OUT,
MouseEvent.MOUSE_OVER,
MouseEvent.MOUSE_UP,
MouseEvent.MOUSE_WHEEL,
MouseEvent.ROLL_OUT,
MouseEvent.ROLL_OVER,
//KEYBOARD EVENTS
KeyboardEvent.KEY_DOWN,
KeyboardEvent.KEY_UP
);
return evtTypes;
}
/**
* @private
*
* For a given event type, check to see if it is intended for interception.
* InteractiveObject event types will return true since the non-visual class that proxies the proxyTarget needs to dispatch those events on the target's behalf.
*/
private function checkForInteceptedEventType (type:String):Boolean
{
var evtType:String;
for each (evtType in interceptedEventTypes)
{
if (type == evtType)
return true;
}
return false;
}
/**
* @private
*
* A generic event handler that stops event propogation of InteractiveObject event types.
* Once stopped, it checks for listeners for the given event type and triggers them.
*
* Depending on specific developer needs, this method can be overridden by subclasses.
*/
protected function eventDelegateFunction (evt:Event):void
{
evt.stopImmediatePropagation(); //prevent from further bubbling up thru display list
var pEvt:ProxyEvent = new ProxyEvent(proxy, evt);
pEvt.proxyTarget = proxyTarget;
var func:Function;
var listeners:Array;
if (hasListenerHashProperty(evt.type))
{
listeners = getListenersForEventType(evt.type);
for each (func in listeners)
func.call(this, pEvt);
}
}
/**
* A flag indicating if the queue is a one-time use, where other visual assets may not receive the same handlers.
*/
public var deleteQueueAfterUpdate:Boolean = true;
/**
* If a proxyTarget has not been set, then a queue of event handlers has been set up.
* Once the proxyTarget is created, it iterates through each queue item and assigns the listeners.
*/
protected function updateProxyListeners ():void
{
var queueItem:Object
for each (queueItem in _proxyTargetListenerQueue)
proxyTarget.addEventListener(queueItem.type, eventDelegateFunction, queueItem.useCapture, queueItem.priority, queueItem.useWeakReference);
if (deleteQueueAfterUpdate)
_proxyTargetListenerQueue = [];
}
////////////////////////////////////////////////////////////////////////
// EVENT DISPATCHER HOOKS
////////////////////////////////////////////////////////////////////////
/**
* @private
*
* A queue of events a proxy target will listen for and hand off to the proxy.
*/
private var _proxyTargetListenerQueue:Array = [];
/**
* @private
*/
private var eventDispatcher:EventDispatcher;
/**
* @inheritDoc
*/
public function hasEventListener (type:String):Boolean
{
if (checkForInteceptedEventType(type))
{
if (proxyTarget)
return proxyTarget.hasEventListener(type);
else
return false;
}
else
return eventDispatcher.hasEventListener(type);
}
/**
* @inheritDoc
*/
public function willTrigger (type:String):Boolean
{
if (checkForInteceptedEventType(type))
{
if (proxyTarget)
return proxyTarget.willTrigger(type);
else
return false;
}
else
return eventDispatcher.willTrigger(type);
}
/**
* @inheritDoc
*/
public function addEventListener (type:String, listener:Function, useCapture:Boolean = false, priority:int = 0.0, useWeakReference:Boolean = false):void
{
if (checkForInteceptedEventType(type))
{
setListenerHashProperty(type, listener);
if (proxyTarget)
proxyTarget.addEventListener(type, eventDelegateFunction, useCapture, priority, useWeakReference);
else
{
var queueItem:Object = {type:type, useCapture:useCapture, priority:priority, useWeakReference:useWeakReference};
_proxyTargetListenerQueue.push(queueItem);
}
}
else
eventDispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference);
}
/**
* @inheritDoc
*/
public function removeEventListener (type:String, listener:Function, useCapture:Boolean = false):void
{
if (checkForInteceptedEventType(type))
{
if (hasListenerHashProperty(type))
{
removeListenerHashProperty(type);
if (proxyTarget)
proxyTarget.removeEventListener(type ,eventDelegateFunction, useCapture);
else
{
var quequeItem:Object;
var i:uint;
var l:uint = _proxyTargetListenerQueue.length;
for (i; i < l; i++)
{
quequeItem = _proxyTargetListenerQueue[i];
if (quequeItem.type == type)
{
_proxyTargetListenerQueue.splice(i, 1);
return;
}
}
}
}
}
else
eventDispatcher.addEventListener(type, listener, useCapture);
}
/**
* @inheritDoc
*/
public function dispatchEvent (event:Event):Boolean
{
if (event.bubbles || checkForInteceptedEventType(event.type))
return proxyTarget.dispatchEvent(new ProxyEvent(this, event));
else
return eventDispatcher.dispatchEvent(event);
}
}
}
|
/*
as3isolib - An open-source ActionScript 3.0 Isometric Library developed to assist
in creating isometrically projected content (such as games and graphics)
targeted for the Flash player platform
http://code.google.com/p/as3isolib/
Copyright (c) 2006 - 2008 J.W.Opitz, All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package eDpLib.events
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.FocusEvent;
import flash.events.IEventDispatcher;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
/**
* EventDispatcherProxy provides a means for intercepting events on behalf of a target and redispatching them as the target of the event.
*/
public class EventDispatcherProxy implements IEventDispatcher, IEventDispatcherProxy
{
////////////////////////////////////////////////////////////////////////
// PROXY TARGET
////////////////////////////////////////////////////////////////////////
/**
* @private
*/
private var _proxyTarget:IEventDispatcher; //the item that we are intercepting and redispatching, this being the target, should be set in subclasses
/**
* @private
*/
public function get proxyTarget ():IEventDispatcher
{
return _proxyTarget;
}
/**
* @inheritDoc
*/
public function set proxyTarget (value:IEventDispatcher):void
{
if (_proxyTarget != value)
{
_proxyTarget = value;
updateProxyListeners();
}
}
////////////////////////////////////////////////////////////////////////
// PROXY
////////////////////////////////////////////////////////////////////////
/**
* @private
*/
private var _proxy:IEventDispatcher;
/**
* @private
*/
public function get proxy ():IEventDispatcher
{
return _proxy;
}
/**
* @inheritDoc
*/
public function set proxy (target:IEventDispatcher):void
{
if (_proxy != target)
{
_proxy = target;
eventDispatcher = new EventDispatcher(_proxy);
}
}
////////////////////////////////////////////////////////////////////////
// CONSTRUCTOR
////////////////////////////////////////////////////////////////////////
/**
* Constructor
*/
public function EventDispatcherProxy ()
{
proxy = this;
}
////////////////////////////////////////////////////////////////////////
// LISTENER HASH
////////////////////////////////////////////////////////////////////////
/**
* @private
*
* A hash table following a basic format:
*
* hash[eventType] = ListenerHash() - a collection of listener objects with some convenience methods.
*/
private var listenerHashTable:Object = {};
/**
* @private
*
* Adds a listener for a given event type.
*/
private function setListenerHashProperty (type:String, listener:Function):void
{
var hash:ListenerHash;
if (!listenerHashTable.hasOwnProperty(type))
{
hash = new ListenerHash();
hash.addListener(listener);
listenerHashTable[type] = hash;
}
else
{
hash = ListenerHash(listenerHashTable[type]);
hash.addListener(listener);
}
}
/**
* @private
*
* Checks to see if a particular event type has been set up within the hash table.
*/
private function hasListenerHashProperty (type:String):Boolean
{
return listenerHashTable.hasOwnProperty(type);
}
/**
* @private
*
* Returns an array of listeners for a given event type.
*/
private function getListenersForEventType (type:String):Array
{
if (listenerHashTable.hasOwnProperty(type))
return ListenerHash(listenerHashTable[type]).listeners;
else
return [];
}
/**
* @private
*
* Removes the listeners and the event type from the hash table.
*/
private function removeListenerHashProperty (type:String):Boolean
{
if (listenerHashTable.hasOwnProperty(type))
{
listenerHashTable[type] = null;
delete listenerHashTable[type];
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////
// MISC. PROXY METHODS
////////////////////////////////////////////////////////////////////////
/**
* @private
*
* An array of events to check against that could be dispatched from an interactive target.
*/
public var interceptedEventTypes:Array = generateEventTypes();
/**
* Creates an array of interactive object events to check against during event proxying.
* To add more event types to check for, subclasses should override this.
*
* @return Array An array of event types.
*/
protected function generateEventTypes ():Array
{
var evtTypes:Array = [];
evtTypes.push
(
//REGULAR EVENTS
Event.ADDED,
Event.ADDED_TO_STAGE,
Event.ENTER_FRAME,
Event.REMOVED,
Event.REMOVED_FROM_STAGE,
Event.RENDER,
Event.TAB_CHILDREN_CHANGE,
Event.TAB_ENABLED_CHANGE,
Event.TAB_INDEX_CHANGE,
//FOCUS EVENTS
FocusEvent.FOCUS_IN,
FocusEvent.FOCUS_OUT,
FocusEvent.KEY_FOCUS_CHANGE,
FocusEvent.MOUSE_FOCUS_CHANGE,
//MOUSE EVENTS
MouseEvent.CLICK,
MouseEvent.DOUBLE_CLICK,
MouseEvent.MOUSE_DOWN,
MouseEvent.MOUSE_MOVE,
MouseEvent.MOUSE_OUT,
MouseEvent.MOUSE_OVER,
MouseEvent.MOUSE_UP,
MouseEvent.MOUSE_WHEEL,
MouseEvent.ROLL_OUT,
MouseEvent.ROLL_OVER,
//KEYBOARD EVENTS
KeyboardEvent.KEY_DOWN,
KeyboardEvent.KEY_UP
);
return evtTypes;
}
/**
* @private
*
* For a given event type, check to see if it is intended for interception.
* InteractiveObject event types will return true since the non-visual class that proxies the proxyTarget needs to dispatch those events on the target's behalf.
*/
private function checkForInteceptedEventType (type:String):Boolean
{
var evtType:String;
for each (evtType in interceptedEventTypes)
{
if (type == evtType)
return true;
}
return false;
}
/**
* @private
*
* A generic event handler that stops event propogation of InteractiveObject event types.
* Once stopped, it checks for listeners for the given event type and triggers them.
*
* Depending on specific developer needs, this method can be overridden by subclasses.
*/
protected function eventDelegateFunction (evt:Event):void
{
evt.stopImmediatePropagation(); //prevent from further bubbling up thru display list
var pEvt:ProxyEvent = new ProxyEvent(proxy, evt);
pEvt.proxyTarget = proxyTarget;
var func:Function;
var listeners:Array;
if (hasListenerHashProperty(evt.type))
{
listeners = getListenersForEventType(evt.type);
for each (func in listeners)
func.call(this, pEvt);
}
}
/**
* A flag indicating if the queue is a one-time use, where other visual assets may not receive the same handlers.
*/
public var deleteQueueAfterUpdate:Boolean = true;
/**
* If a proxyTarget has not been set, then a queue of event handlers has been set up.
* Once the proxyTarget is created, it iterates through each queue item and assigns the listeners.
*/
protected function updateProxyListeners ():void
{
var queueItem:Object
for each (queueItem in _proxyTargetListenerQueue)
proxyTarget.addEventListener(queueItem.type, eventDelegateFunction, queueItem.useCapture, queueItem.priority, queueItem.useWeakReference);
if (deleteQueueAfterUpdate)
_proxyTargetListenerQueue = [];
}
////////////////////////////////////////////////////////////////////////
// EVENT DISPATCHER HOOKS
////////////////////////////////////////////////////////////////////////
/**
* @private
*
* A queue of events a proxy target will listen for and hand off to the proxy.
*/
private var _proxyTargetListenerQueue:Array = [];
/**
* @private
*/
private var eventDispatcher:EventDispatcher;
/**
* @inheritDoc
*/
public function hasEventListener (type:String):Boolean
{
if (checkForInteceptedEventType(type))
{
if (proxyTarget)
return proxyTarget.hasEventListener(type);
else
return false;
}
else
return eventDispatcher.hasEventListener(type);
}
/**
* @inheritDoc
*/
public function willTrigger (type:String):Boolean
{
if (checkForInteceptedEventType(type))
{
if (proxyTarget)
return proxyTarget.willTrigger(type);
else
return false;
}
else
return eventDispatcher.willTrigger(type);
}
/**
* @inheritDoc
*/
public function addEventListener (type:String, listener:Function, useCapture:Boolean = false, priority:int = 0.0, useWeakReference:Boolean = false):void
{
if (checkForInteceptedEventType(type))
{
setListenerHashProperty(type, listener);
if (proxyTarget)
proxyTarget.addEventListener(type, eventDelegateFunction, useCapture, priority, useWeakReference);
else
{
var queueItem:Object = {type:type, useCapture:useCapture, priority:priority, useWeakReference:useWeakReference};
_proxyTargetListenerQueue.push(queueItem);
}
}
else
eventDispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference);
}
/**
* @inheritDoc
*/
public function removeEventListener (type:String, listener:Function, useCapture:Boolean = false):void
{
if (checkForInteceptedEventType(type))
{
if (hasListenerHashProperty(type))
{
removeListenerHashProperty(type);
if (proxyTarget)
proxyTarget.removeEventListener(type ,eventDelegateFunction, useCapture);
else
{
var quequeItem:Object;
var i:uint;
var l:uint = _proxyTargetListenerQueue.length;
for (i; i < l; i++)
{
quequeItem = _proxyTargetListenerQueue[i];
if (quequeItem.type == type)
{
_proxyTargetListenerQueue.splice(i, 1);
return;
}
}
}
}
}
else
eventDispatcher.removeEventListener(type, listener, useCapture);
}
/**
* @inheritDoc
*/
public function dispatchEvent (event:Event):Boolean
{
if (event.bubbles || checkForInteceptedEventType(event.type))
return proxyTarget.dispatchEvent(new ProxyEvent(this, event));
else
return eventDispatcher.dispatchEvent(event);
}
}
}
|
fix for fp9 trunk
|
fix for fp9 trunk
|
ActionScript
|
mit
|
dreamsxin/as3isolib.v1,as3isolib/as3isolib.v1,liuju/as3isolib.v1,as3isolib/as3isolib.v1,dreamsxin/as3isolib.v1,liuju/as3isolib.v1
|
62fb546f2746037762554d0c010ed4e4ce4bb80d
|
src/as/com/threerings/util/Util.as
|
src/as/com/threerings/util/Util.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.utils.ByteArray;
import flash.utils.getQualifiedClassName;
public class Util
{
/**
* Initialize the target object with values present in the initProps object and the defaults
* object. Neither initProps nor defaults will be modified.
* @throws ReferenceError if a property cannot be set on the target object.
*
* @param target any object or class instance.
* @param initProps a plain Object hash containing names and properties to set on the target
* object.
* @param defaults a plain Object hash containing names and properties to set on the target
* object, only if the same property name does not exist in initProps.
* @param maskProps a plain Object hash containing names of properties to omit setting
* from the initProps object. This allows you to add custom properties to
* initProps without having to modify the value from your callers.
*/
public static function init (
target :Object, initProps :Object, defaults :Object = null, maskProps :Object = null) :void
{
var prop :String;
for (prop in initProps) {
if (maskProps == null || !(prop in maskProps)) {
target[prop] = initProps[prop];
}
}
if (defaults != null) {
for (prop in defaults) {
if (initProps == null || !(prop in initProps)) {
target[prop] = defaults[prop];
}
}
}
}
/**
* Returns true if the specified object is just a regular old associative hash.
*/
public static function isPlainObject (obj :Object) :Boolean
{
return getQualifiedClassName(obj) == "Object";
}
/**
* Is the specified object 'simple': one of the basic built-in flash types.
*/
public static function isSimple (obj :Object) :Boolean
{
var type :String = typeof(obj);
switch (type) {
case "number":
case "string":
case "boolean":
return true;
case "object":
return (obj is Date) || (obj is Array);
default:
return false;
}
}
/**
* Get an array containing the property keys of the specified object, in their
* natural iteration order.
*/
public static function keys (obj :Object) :Array
{
var arr :Array = [];
for (var k :* in obj) { // no "each": iterate over keys
arr.push(k);
}
return arr;
}
/**
* Get an array containing the property values of the specified object, in their
* natural iteration order.
*/
public static function values (obj :Object) :Array
{
var arr :Array = [];
for each (var v :* in obj) { // "each" iterates over values
arr.push(v);
}
return arr;
}
/**
* Parse the 'value' object into XML safely. This is equivalent to <code>new XML(value)</code>
* but offers protection from other code that may have changing the default settings
* used for parsing XML. Also, if you would like to use non-standard parsing settings
* this method will protect other code from being broken by you.
*
* @param value the value to parse into XML.
* @param settings an Object containing your desired XML settings, or null (or omitted) to
* use the default settings.
* @see XML#setSettings()
*/
public static function newXML (value :Object, settings :Object = null) :XML
{
return safeXMLOp(function () :* {
return new XML(value);
}, settings) as XML;
}
/**
* Call toString() on the specified XML object safely. This is equivalent to
* <code>xml.toString()</code> but offers protection from other code that may have changed
* the default settings used for stringing XML. Also, if you would like to use the
* non-standard printing settings this method will protect other code from being
* broken by you.
*
* @param xml the xml value to Stringify.
* @param settings an Object containing your desired XML settings, or null (or omitted) to
* use the default settings.
* @see XML#toString()
* @see XML#setSettings()
*/
public static function XMLtoString (xml :XML, settings :Object = null) :String
{
return safeXMLOp(function () :* {
return xml.toString();
}, settings) as String;
}
/**
* Call toXMLString() on the specified XML object safely. This is equivalent to
* <code>xml.toXMLString()</code> but offers protection from other code that may have changed
* the default settings used for stringing XML. Also, if you would like to use the
* non-standard printing settings this method will protect other code from being
* broken by you.
*
* @param xml the xml value to Stringify.
* @param settings an Object containing your desired XML settings, or null (or omitted) to
* use the default settings.
* @see XML#toXMLString()
* @see XML#setSettings()
*/
public static function XMLtoXMLString (xml :XML, settings :Object = null) :String
{
return safeXMLOp(function () :* {
return xml.toXMLString();
}, settings) as String;
}
/**
* Perform an operation on XML that takes place using the specified settings, and
* restores the XML settings to their previous values.
*
* @param fn a function to be called with no arguments.
* @param settings an Object containing your desired XML settings, or null (or omitted) to
* use the default settings.
*
* @return the return value of your function, if any.
* @see XML#setSettings()
* @see XML#settings()
*/
public static function safeXMLOp (fn :Function, settings :Object = null) :*
{
var oldSettings :Object = XML.settings();
try {
XML.setSettings(settings); // setting to null resets to all the defaults
return fn();
} finally {
XML.setSettings(oldSettings);
}
}
/**
* A nice utility method for testing equality in a better way.
* If the objects are Equalable, then that will be tested. Arrays
* and ByteArrays are also compared and are equal if they have
* elements that are equals (deeply).
*/
public static function equals (obj1 :Object, obj2 :Object) :Boolean
{
// catch various common cases (both primitive or null)
if (obj1 === obj2) {
return true;
} else if (obj1 is Equalable) {
// if obj1 is Equalable, then that decides it
return (obj1 as Equalable).equals(obj2);
} else if ((obj1 is Array) && (obj2 is Array)) {
return ArrayUtil.equals(obj1 as Array, obj2 as Array);
} else if ((obj1 is ByteArray) && (obj2 is ByteArray)) {
var ba1 :ByteArray = (obj1 as ByteArray);
var ba2 :ByteArray = (obj2 as ByteArray);
if (ba1.length != ba2.length) {
return false;
}
for (var ii :int = 0; ii < ba1.length; ii++) {
if (ba1[ii] != ba2[ii]) {
return false;
}
}
return true;
}
return false;
}
/**
* If you call a varargs method by passing it an array, the array
* will end up being arg 1.
*/
public static function unfuckVarargs (args :Array) :Array
{
return (args.length == 1 && (args[0] is Array)) ? (args[0] as Array)
: args;
}
}
}
|
//
// $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.utils.ByteArray;
import flash.utils.getQualifiedClassName;
public class Util
{
/**
* Initialize the target object with values present in the initProps object and the defaults
* object. Neither initProps nor defaults will be modified.
* @throws ReferenceError if a property cannot be set on the target object.
*
* @param target any object or class instance.
* @param initProps a plain Object hash containing names and properties to set on the target
* object.
* @param defaults a plain Object hash containing names and properties to set on the target
* object, only if the same property name does not exist in initProps.
* @param maskProps a plain Object hash containing names of properties to omit setting
* from the initProps object. This allows you to add custom properties to
* initProps without having to modify the value from your callers.
*/
public static function init (
target :Object, initProps :Object, defaults :Object = null, maskProps :Object = null) :void
{
var prop :String;
for (prop in initProps) {
if (maskProps == null || !(prop in maskProps)) {
target[prop] = initProps[prop];
}
}
if (defaults != null) {
for (prop in defaults) {
if (initProps == null || !(prop in initProps)) {
target[prop] = defaults[prop];
}
}
}
}
/**
* Return a var-args function that will attempt to pass only the arguments accepted by the
* passed-in function. Does not work if the passed-in function is varargs, and anyway
* then you don't need adapting, do you?
*/
public static function adapt (fn :Function) :Function
{
return function (... args) :* {
args.length = fn.length; // fit the args to the fn, filling in 'undefined' if growing
return fn.apply(null, args);
}
}
/**
* Returns true if the specified object is just a regular old associative hash.
*/
public static function isPlainObject (obj :Object) :Boolean
{
return getQualifiedClassName(obj) == "Object";
}
/**
* Is the specified object 'simple': one of the basic built-in flash types.
*/
public static function isSimple (obj :Object) :Boolean
{
var type :String = typeof(obj);
switch (type) {
case "number":
case "string":
case "boolean":
return true;
case "object":
return (obj is Date) || (obj is Array);
default:
return false;
}
}
/**
* Get an array containing the property keys of the specified object, in their
* natural iteration order.
*/
public static function keys (obj :Object) :Array
{
var arr :Array = [];
for (var k :* in obj) { // no "each": iterate over keys
arr.push(k);
}
return arr;
}
/**
* Get an array containing the property values of the specified object, in their
* natural iteration order.
*/
public static function values (obj :Object) :Array
{
var arr :Array = [];
for each (var v :* in obj) { // "each" iterates over values
arr.push(v);
}
return arr;
}
/**
* Parse the 'value' object into XML safely. This is equivalent to <code>new XML(value)</code>
* but offers protection from other code that may have changing the default settings
* used for parsing XML. Also, if you would like to use non-standard parsing settings
* this method will protect other code from being broken by you.
*
* @param value the value to parse into XML.
* @param settings an Object containing your desired XML settings, or null (or omitted) to
* use the default settings.
* @see XML#setSettings()
*/
public static function newXML (value :Object, settings :Object = null) :XML
{
return safeXMLOp(function () :* {
return new XML(value);
}, settings) as XML;
}
/**
* Call toString() on the specified XML object safely. This is equivalent to
* <code>xml.toString()</code> but offers protection from other code that may have changed
* the default settings used for stringing XML. Also, if you would like to use the
* non-standard printing settings this method will protect other code from being
* broken by you.
*
* @param xml the xml value to Stringify.
* @param settings an Object containing your desired XML settings, or null (or omitted) to
* use the default settings.
* @see XML#toString()
* @see XML#setSettings()
*/
public static function XMLtoString (xml :XML, settings :Object = null) :String
{
return safeXMLOp(function () :* {
return xml.toString();
}, settings) as String;
}
/**
* Call toXMLString() on the specified XML object safely. This is equivalent to
* <code>xml.toXMLString()</code> but offers protection from other code that may have changed
* the default settings used for stringing XML. Also, if you would like to use the
* non-standard printing settings this method will protect other code from being
* broken by you.
*
* @param xml the xml value to Stringify.
* @param settings an Object containing your desired XML settings, or null (or omitted) to
* use the default settings.
* @see XML#toXMLString()
* @see XML#setSettings()
*/
public static function XMLtoXMLString (xml :XML, settings :Object = null) :String
{
return safeXMLOp(function () :* {
return xml.toXMLString();
}, settings) as String;
}
/**
* Perform an operation on XML that takes place using the specified settings, and
* restores the XML settings to their previous values.
*
* @param fn a function to be called with no arguments.
* @param settings an Object containing your desired XML settings, or null (or omitted) to
* use the default settings.
*
* @return the return value of your function, if any.
* @see XML#setSettings()
* @see XML#settings()
*/
public static function safeXMLOp (fn :Function, settings :Object = null) :*
{
var oldSettings :Object = XML.settings();
try {
XML.setSettings(settings); // setting to null resets to all the defaults
return fn();
} finally {
XML.setSettings(oldSettings);
}
}
/**
* A nice utility method for testing equality in a better way.
* If the objects are Equalable, then that will be tested. Arrays
* and ByteArrays are also compared and are equal if they have
* elements that are equals (deeply).
*/
public static function equals (obj1 :Object, obj2 :Object) :Boolean
{
// catch various common cases (both primitive or null)
if (obj1 === obj2) {
return true;
} else if (obj1 is Equalable) {
// if obj1 is Equalable, then that decides it
return (obj1 as Equalable).equals(obj2);
} else if ((obj1 is Array) && (obj2 is Array)) {
return ArrayUtil.equals(obj1 as Array, obj2 as Array);
} else if ((obj1 is ByteArray) && (obj2 is ByteArray)) {
var ba1 :ByteArray = (obj1 as ByteArray);
var ba2 :ByteArray = (obj2 as ByteArray);
if (ba1.length != ba2.length) {
return false;
}
for (var ii :int = 0; ii < ba1.length; ii++) {
if (ba1[ii] != ba2[ii]) {
return false;
}
}
return true;
}
return false;
}
/**
* If you call a varargs method by passing it an array, the array
* will end up being arg 1.
*/
public static function unfuckVarargs (args :Array) :Array
{
return (args.length == 1 && (args[0] is Array)) ? (args[0] as Array)
: args;
}
}
}
|
Check this out. This little buddy rocks. I sorta want to make a new FunctionUtil so that I can use it with impunity everwhere without having to include the other crap in here.
|
Check this out. This little buddy rocks.
I sorta want to make a new FunctionUtil so that I can use it
with impunity everwhere without having to include the other crap in here.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5730 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
20f2117fef86e51bbe074f80441de3b39795b2ba
|
com/segonquart/menuIdiomes.as
|
com/segonquart/menuIdiomes.as
|
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
class menuIdiomes extends MovieClip
{
public var fr:MovieClip;
public function menuIdiomes ()
{
this.onRollOver = this.over;
this.onRollOut = this.out;
this.onRelease =this.over;
}
private function over ()
{
fr.colorTo ("#95C60D", 0.3, "easeOutCirc");
}
private function out ()
{
fr.colorTo ("#010101", 0.3, "easeInCirc");
}
}
|
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
class menuIdiomes extends MovieClip
{
public var fr:MovieClip;
public function menuIdiomes ()
{
this.onRollOver = this.over;
this.onRollOut = this.out;
this.onRelease =this.over;
}
private function over ()
{
fr.colorTo ("#95C60D", 0.3, "easeOutCirc");
}
private function out ()
{
fr.colorTo ("#010101", 0.3, "easeInCirc");
}
}
|
Update menuIdiomes.as
|
Update menuIdiomes.as
|
ActionScript
|
bsd-3-clause
|
delfiramirez/web-talking-wear,delfiramirez/web-talking-wear,delfiramirez/web-talking-wear
|
c3361d9768eda0a38479335a64cc3b9abc2ba3ff
|
source/ASConfigC.as
|
source/ASConfigC.as
|
/*
Copyright 2016 Bowler Hat LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package
{
import com.nextgenactionscript.asconfigc.ASConfigFields;
import com.nextgenactionscript.asconfigc.CompilerOptions;
import com.nextgenactionscript.asconfigc.CompilerOptionsParser;
import com.nextgenactionscript.asconfigc.ConfigName;
import com.nextgenactionscript.asconfigc.JSOutputType;
import com.nextgenactionscript.asconfigc.ProjectType;
import com.nextgenactionscript.flexjs.utils.ApacheFlexJSUtils;
import com.nextgenactionscript.utils.ActionScriptSDKUtils;
/**
* A command line utility to build a project defined with an asconfig.json
* file using the Apache FlexJS SDK.
*/
public class ASConfigC
{
private static const ASCONFIG_JSON:String = "asconfig.json";
private static const MXMLC_JARS:Vector.<String> = new <String>
[
"falcon-mxmlc.jar",
"mxmlc-cli.jar",
"mxmlc.jar",
];
private static const COMPC_JARS:Vector.<String> = new <String>
[
"falcon-compc.jar",
"compc-cli.jar",
"compc.jar",
];
public function ASConfigC()
{
this.parseArguments();
if(!this._javaExecutable)
{
this._javaExecutable = ApacheFlexJSUtils.findJava();
if(!this._javaExecutable)
{
console.error("Java not found. Cannot run compiler without Java.");
process.exit(1);
}
}
if(!this._configFilePath)
{
//try to find asconfig.json in the current working directory
var cwdConfigPath:String = path.resolve(process.cwd(), ASCONFIG_JSON);
if(fs.existsSync(cwdConfigPath))
{
this._configFilePath = cwdConfigPath;
}
else
{
//asconfig.json not found
this.printUsage();
process.exit(0);
}
}
process.chdir(path.dirname(this._configFilePath));
this.parseConfig();
//validate the SDK after knowing if we're building SWF or JS
//because JS has stricter SDK requirements
this.validateSDK();
this.compileProject();
}
private var _flexHome:String;
private var _javaExecutable:String;
private var _configFilePath:String;
private var _projectType:String;
private var _jsOutputType:String;
private var _isSWF:Boolean;
private var _args:Array;
private function printVersion():void
{
var packageJSONString:String = fs.readFileSync(path.join(__dirname, "..", "..", "package.json"), "utf8") as String;
var packageJSON:Object = JSON.parse(packageJSONString);
console.info("Version: " + packageJSON.version);
}
private function printUsage():void
{
this.printVersion();
console.info("Syntax: asconfigc [options]");
console.info();
console.info("Examples: asconfigc -p .");
console.info(" asconfigc -p path/to/project");
console.info();
console.info("Options:");
console.info(" -h, --help Print this help message.");
console.info(" -v, --version Print the version.");
console.info(" -p DIRECTORY, --project DIRECTORY Compile the asconfig.json project in the given directory. If omitted, will look for asconfig.json in current directory.");
console.info(" --flexHome DIRECTORY Specify the directory where Apache FlexJS is located. Defaults to checking FLEX_HOME and PATH environment variables.");
}
private function parseArguments():void
{
var args:Object = minimist(process.argv.slice(2),
{
alias:
{
h: ["help"],
p: ["project"],
v: ["version"]
}
});
for(var key:String in args)
{
switch(key)
{
case "h":
case "p":
case "v":
{
//ignore aliases
break;
}
case "_":
{
var value:String = args[key] as String;
if(value)
{
console.error("Unknown argument: " + value);
process.exit(1);
}
break;
}
case "help":
{
this.printUsage();
process.exit(0);
break;
}
case "flexHome":
{
this._flexHome = args[key] as String;
break;
}
case "project":
{
var projectDirectoryPath:String = args[key] as String;
projectDirectoryPath = path.resolve(process.cwd(), projectDirectoryPath);
if(!fs.existsSync(projectDirectoryPath))
{
console.error("Project directory not found: " + projectDirectoryPath);
process.exit(1);
}
if(!fs.statSync(projectDirectoryPath).isDirectory())
{
console.error("Project must be a directory: " + projectDirectoryPath);
process.exit(1);
}
var configFilePath:String = path.resolve(projectDirectoryPath, ASCONFIG_JSON);
if(!fs.existsSync(configFilePath))
{
console.error("asconfig.json not found in directory: " + projectDirectoryPath);
process.exit(1);
}
this._configFilePath = configFilePath;
break;
}
case "version":
{
this.printVersion();
process.exit(0);
}
default:
{
console.error("Unknown argument: " + key);
process.exit(1);
}
}
}
}
private function loadConfig():Object
{
var schemaFilePath:String = path.join(__dirname, "..", "..", "schemas", "asconfig.schema.json");
try
{
var schemaText:String = fs.readFileSync(schemaFilePath, "utf8") as String;
}
catch(error:Error)
{
console.error("Error: Cannot read schema file. " + schemaFilePath);
process.exit(1);
}
try
{
var schemaData:Object = JSON.parse(schemaText);
}
catch(error:Error)
{
console.error("Error: Invalid JSON in schema file. " + schemaFilePath);
console.error(error);
process.exit(1);
}
try
{
var validate:Function = jsen(schemaData);
}
catch(error:Error)
{
console.error("Error: Invalid schema. " + schemaFilePath);
console.error(error);
process.exit(1);
}
try
{
var configText:String = fs.readFileSync(this._configFilePath, "utf8") as String;
}
catch(error:Error)
{
console.error("Error: Cannot read file. " + this._configFilePath);
process.exit(1);
}
try
{
var configData:Object = JSON.parse(configText);
}
catch(error:Error)
{
console.error("Error: Invalid JSON in file. " + this._configFilePath);
console.error(error);
process.exit(1);
}
if(!validate(configData))
{
console.error("Error: Invalid asconfig.json file. " + this._configFilePath);
console.error(validate["errors"]);
process.exit(1);
}
return configData;
}
private function parseConfig():void
{
this._args = [];
var configData:Object = this.loadConfig();
this._projectType = this.readProjectType(configData);
if(ASConfigFields.CONFIG in configData)
{
var configName:String = configData[ASConfigFields.CONFIG] as String;
this.detectJavaScript(configName);
this._args.push("+configname=" + configName);
}
if(ASConfigFields.COMPILER_OPTIONS in configData)
{
var compilerOptions:Object = configData[ASConfigFields.COMPILER_OPTIONS];
this.readCompilerOptions(compilerOptions);
}
if(ASConfigFields.FILES in configData)
{
var files:Array = configData[ASConfigFields.FILES] as Array;
if(this._projectType === ProjectType.LIB)
{
CompilerOptionsParser.parse(
{
"include-sources": files
}, this._args);
}
else
{
var filesCount:int = files.length;
for(var i:int = 0; i < filesCount; i++)
{
var file:String = files[i];
this._args.push(file);
}
}
}
}
private function readProjectType(configData:Object):String
{
if(ASConfigFields.TYPE in configData)
{
//this was already validated
return configData[ASConfigFields.TYPE] as String;
}
//this field is optional, and this is the default
return ProjectType.APP;
}
private function readCompilerOptions(options:Object):void
{
try
{
CompilerOptionsParser.parse(options, this._args);
}
catch(error:Error)
{
console.error(error.message);
process.exit(1);
}
if(CompilerOptions.JS_OUTPUT_TYPE in options)
{
//if it is set explicitly, then clear the default
this._jsOutputType = null;
}
else if(this._jsOutputType)
{
this._args.push("--" + CompilerOptions.JS_OUTPUT_TYPE + "=" + this._jsOutputType);
}
}
private function detectJavaScript(configName:String):void
{
switch(configName)
{
case ConfigName.JS:
{
this._jsOutputType = JSOutputType.JSC;
this._isSWF = false;
break;
}
case ConfigName.NODE:
{
this._jsOutputType = JSOutputType.NODE;
this._isSWF = false;
break;
}
case ConfigName.FLEX:
case ConfigName.AIR:
case ConfigName.AIRMOBILE:
{
this._isSWF = true;
break;
}
default:
{
this._jsOutputType = null;
}
}
}
private function validateSDK():void
{
if(this._flexHome)
{
//the --flexHome argument was used, so check if it's valid
if(!ApacheFlexJSUtils.isValidSDK(this._flexHome))
{
if(!this._isSWF)
{
console.error("Path to Apache FlexJS SDK is not valid: " + this._flexHome);
process.exit(1);
}
else if(!ActionScriptSDKUtils.isValidSDK(this._flexHome))
{
console.error("Path to SDK is not valid: " + this._flexHome);
process.exit(1);
}
}
}
else
{
//the --flexHome argument wasn't passed in, so try to find an SDK
this._flexHome = ApacheFlexJSUtils.findSDK();
if(!this._flexHome && this._isSWF)
{
//if we're building a SWF, we don't necessarily need
//FlexJS, so try to find another compatible SDK
this._flexHome = ActionScriptSDKUtils.findSDK();
}
if(!this._flexHome)
{
console.error("SDK not found. Set FLEX_HOME, add to PATH, or use --flexHome option.");
process.exit(1);
}
}
}
private function findJarPath():String
{
var jarPath:String = null;
var jarNames:Vector.<String> = MXMLC_JARS;
if(this._projectType === ProjectType.LIB)
{
jarNames = COMPC_JARS;
}
var jarNamesCount:int = jarNames.length;
for(var i:int = 0; i < jarNamesCount; i++)
{
var jarName:String = jarNames[i];
if(this._isSWF)
{
jarPath = path.join(this._flexHome, "lib", jarName);
}
else
{
jarPath = path.join(this._flexHome, "js", "lib", jarName);
}
if(fs.existsSync(jarPath))
{
break;
}
jarPath = null;
}
return jarPath;
}
private function compileProject():void
{
var jarPath:String = this.findJarPath();
if(!jarPath)
{
console.error("Compiler not found in SDK. Expected: " + jarPath);
process.exit(1);
}
var frameworkPath:String = path.join(this._flexHome, "frameworks");
this._args.unshift("+flexlib=" + frameworkPath);
this._args.unshift(jarPath);
this._args.unshift("-jar");
this._args.unshift("-Dflexlib=" + frameworkPath);
this._args.unshift("-Dflexcompiler=" + this._flexHome);
try
{
var result:Object = child_process.execFileSync(this._javaExecutable, this._args,
{
encoding: "utf8"
});
console.info(result);
}
catch(error:Error)
{
process.exit(1);
}
}
}
}
|
/*
Copyright 2016 Bowler Hat LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package
{
import com.nextgenactionscript.asconfigc.ASConfigFields;
import com.nextgenactionscript.asconfigc.CompilerOptions;
import com.nextgenactionscript.asconfigc.CompilerOptionsParser;
import com.nextgenactionscript.asconfigc.ConfigName;
import com.nextgenactionscript.asconfigc.JSOutputType;
import com.nextgenactionscript.asconfigc.ProjectType;
import com.nextgenactionscript.flexjs.utils.ApacheFlexJSUtils;
import com.nextgenactionscript.utils.ActionScriptSDKUtils;
/**
* A command line utility to build a project defined with an asconfig.json
* file using the Apache FlexJS SDK.
*/
public class ASConfigC
{
private static const ASCONFIG_JSON:String = "asconfig.json";
private static const MXMLC_JARS:Vector.<String> = new <String>
[
"falcon-mxmlc.jar",
"mxmlc-cli.jar",
"mxmlc.jar",
];
private static const COMPC_JARS:Vector.<String> = new <String>
[
"falcon-compc.jar",
"compc-cli.jar",
"compc.jar",
];
public function ASConfigC()
{
this.parseArguments();
if(!this._javaExecutable)
{
this._javaExecutable = ApacheFlexJSUtils.findJava();
if(!this._javaExecutable)
{
console.error("Java not found. Cannot run compiler without Java.");
process.exit(1);
}
}
if(!this._configFilePath)
{
//try to find asconfig.json in the current working directory
var cwdConfigPath:String = path.resolve(process.cwd(), ASCONFIG_JSON);
if(fs.existsSync(cwdConfigPath))
{
this._configFilePath = cwdConfigPath;
}
else
{
//asconfig.json not found
this.printUsage();
process.exit(0);
}
}
process.chdir(path.dirname(this._configFilePath));
this.parseConfig();
//validate the SDK after knowing if we're building SWF or JS
//because JS has stricter SDK requirements
this.validateSDK();
this.compileProject();
}
private var _flexHome:String;
private var _javaExecutable:String;
private var _configFilePath:String;
private var _projectType:String;
private var _jsOutputType:String;
private var _isSWF:Boolean;
private var _args:Array;
private function printVersion():void
{
var packageJSONString:String = fs.readFileSync(path.join(__dirname, "..", "..", "package.json"), "utf8") as String;
var packageJSON:Object = JSON.parse(packageJSONString);
console.info("Version: " + packageJSON.version);
}
private function printUsage():void
{
this.printVersion();
console.info("Syntax: asconfigc [options]");
console.info();
console.info("Examples: asconfigc -p .");
console.info(" asconfigc -p path/to/project");
console.info();
console.info("Options:");
console.info(" -h, --help Print this help message.");
console.info(" -v, --version Print the version.");
console.info(" -p DIRECTORY, --project DIRECTORY Compile the asconfig.json project in the given directory. If omitted, will look for asconfig.json in current directory.");
console.info(" --flexHome DIRECTORY Specify the directory where Apache FlexJS is located. Defaults to checking FLEX_HOME and PATH environment variables.");
}
private function parseArguments():void
{
var args:Object = minimist(process.argv.slice(2),
{
alias:
{
h: ["help"],
p: ["project"],
v: ["version"]
}
});
for(var key:String in args)
{
switch(key)
{
case "h":
case "p":
case "v":
{
//ignore aliases
break;
}
case "_":
{
var value:String = args[key] as String;
if(value)
{
console.error("Unknown argument: " + value);
process.exit(1);
}
break;
}
case "help":
{
this.printUsage();
process.exit(0);
break;
}
case "flexHome":
{
this._flexHome = args[key] as String;
break;
}
case "project":
{
var projectDirectoryPath:String = args[key] as String;
projectDirectoryPath = path.resolve(process.cwd(), projectDirectoryPath);
if(!fs.existsSync(projectDirectoryPath))
{
console.error("Project directory not found: " + projectDirectoryPath);
process.exit(1);
}
if(!fs.statSync(projectDirectoryPath).isDirectory())
{
console.error("Project must be a directory: " + projectDirectoryPath);
process.exit(1);
}
var configFilePath:String = path.resolve(projectDirectoryPath, ASCONFIG_JSON);
if(!fs.existsSync(configFilePath))
{
console.error("asconfig.json not found in directory: " + projectDirectoryPath);
process.exit(1);
}
this._configFilePath = configFilePath;
break;
}
case "version":
{
this.printVersion();
process.exit(0);
}
default:
{
console.error("Unknown argument: " + key);
process.exit(1);
}
}
}
}
private function loadConfig():Object
{
var schemaFilePath:String = path.join(__dirname, "..", "..", "schemas", "asconfig.schema.json");
try
{
var schemaText:String = fs.readFileSync(schemaFilePath, "utf8") as String;
}
catch(error:Error)
{
console.error("Error: Cannot read schema file. " + schemaFilePath);
process.exit(1);
}
try
{
var schemaData:Object = JSON.parse(schemaText);
}
catch(error:Error)
{
console.error("Error: Invalid JSON in schema file. " + schemaFilePath);
console.error(error);
process.exit(1);
}
try
{
var validate:Function = jsen(schemaData);
}
catch(error:Error)
{
console.error("Error: Invalid schema. " + schemaFilePath);
console.error(error);
process.exit(1);
}
try
{
var configText:String = fs.readFileSync(this._configFilePath, "utf8") as String;
}
catch(error:Error)
{
console.error("Error: Cannot read file. " + this._configFilePath);
process.exit(1);
}
try
{
var configData:Object = JSON.parse(configText);
}
catch(error:Error)
{
console.error("Error: Invalid JSON in file. " + this._configFilePath);
console.error(error);
process.exit(1);
}
if(!validate(configData))
{
console.error("Error: Invalid asconfig.json file. " + this._configFilePath);
console.error(validate["errors"]);
process.exit(1);
}
return configData;
}
private function parseConfig():void
{
this._args = [];
var configData:Object = this.loadConfig();
this._projectType = this.readProjectType(configData);
if(ASConfigFields.CONFIG in configData)
{
var configName:String = configData[ASConfigFields.CONFIG] as String;
this.detectJavaScript(configName);
this._args.push("+configname=" + configName);
}
if(ASConfigFields.COMPILER_OPTIONS in configData)
{
var compilerOptions:Object = configData[ASConfigFields.COMPILER_OPTIONS];
this.readCompilerOptions(compilerOptions);
}
if(ASConfigFields.FILES in configData)
{
var files:Array = configData[ASConfigFields.FILES] as Array;
if(this._projectType === ProjectType.LIB)
{
CompilerOptionsParser.parse(
{
"include-sources": files
}, this._args);
}
else
{
var filesCount:int = files.length;
for(var i:int = 0; i < filesCount; i++)
{
var file:String = files[i];
this._args.push(file);
}
}
}
}
private function readProjectType(configData:Object):String
{
if(ASConfigFields.TYPE in configData)
{
//this was already validated
return configData[ASConfigFields.TYPE] as String;
}
//this field is optional, and this is the default
return ProjectType.APP;
}
private function readCompilerOptions(options:Object):void
{
try
{
CompilerOptionsParser.parse(options, this._args);
}
catch(error:Error)
{
console.error(error.message);
process.exit(1);
}
if(CompilerOptions.JS_OUTPUT_TYPE in options)
{
//if it is set explicitly, then clear the default
this._jsOutputType = null;
}
else if(this._jsOutputType)
{
this._args.push("--" + CompilerOptions.JS_OUTPUT_TYPE + "=" + this._jsOutputType);
}
}
private function detectJavaScript(configName:String):void
{
switch(configName)
{
case ConfigName.JS:
{
this._jsOutputType = JSOutputType.JSC;
this._isSWF = false;
break;
}
case ConfigName.NODE:
{
this._jsOutputType = JSOutputType.NODE;
this._isSWF = false;
break;
}
case ConfigName.FLEX:
case ConfigName.AIR:
case ConfigName.AIRMOBILE:
{
this._jsOutputType = null;
this._isSWF = true;
break;
}
default:
{
this._jsOutputType = null;
}
}
}
private function validateSDK():void
{
if(this._flexHome)
{
//the --flexHome argument was used, so check if it's valid
if(!ApacheFlexJSUtils.isValidSDK(this._flexHome))
{
if(!this._isSWF)
{
console.error("Path to Apache FlexJS SDK is not valid: " + this._flexHome);
process.exit(1);
}
else if(!ActionScriptSDKUtils.isValidSDK(this._flexHome))
{
console.error("Path to SDK is not valid: " + this._flexHome);
process.exit(1);
}
}
}
else
{
//the --flexHome argument wasn't passed in, so try to find an SDK
this._flexHome = ApacheFlexJSUtils.findSDK();
if(!this._flexHome && this._isSWF)
{
//if we're building a SWF, we don't necessarily need
//FlexJS, so try to find another compatible SDK
this._flexHome = ActionScriptSDKUtils.findSDK();
}
if(!this._flexHome)
{
console.error("SDK not found. Set FLEX_HOME, add to PATH, or use --flexHome option.");
process.exit(1);
}
}
}
private function findJarPath():String
{
var jarPath:String = null;
var jarNames:Vector.<String> = MXMLC_JARS;
if(this._projectType === ProjectType.LIB)
{
jarNames = COMPC_JARS;
}
var jarNamesCount:int = jarNames.length;
for(var i:int = 0; i < jarNamesCount; i++)
{
var jarName:String = jarNames[i];
if(this._isSWF)
{
jarPath = path.join(this._flexHome, "lib", jarName);
}
else
{
jarPath = path.join(this._flexHome, "js", "lib", jarName);
}
if(fs.existsSync(jarPath))
{
break;
}
jarPath = null;
}
return jarPath;
}
private function compileProject():void
{
var jarPath:String = this.findJarPath();
if(!jarPath)
{
console.error("Compiler not found in SDK. Expected: " + jarPath);
process.exit(1);
}
var frameworkPath:String = path.join(this._flexHome, "frameworks");
this._args.unshift("+flexlib=" + frameworkPath);
this._args.unshift(jarPath);
this._args.unshift("-jar");
this._args.unshift("-Dflexlib=" + frameworkPath);
this._args.unshift("-Dflexcompiler=" + this._flexHome);
try
{
var result:Object = child_process.execFileSync(this._javaExecutable, this._args,
{
encoding: "utf8"
});
console.info(result);
}
catch(error:Error)
{
process.exit(1);
}
}
}
}
|
clear js-output-type when compiling a SWF
|
clear js-output-type when compiling a SWF
|
ActionScript
|
apache-2.0
|
BowlerHatLLC/asconfigc
|
02c9a40838804f2e0cc2b935b00b944078d9d7cd
|
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.events.Event;
import flash.utils.setTimeout;
import FacilitatorSocket;
import events.FacilitatorSocketEvent;
import ProxyPair;
import RTMFPProxyPair;
import TCPProxyPair;
import rtmfp.CirrusSocket;
import rtmfp.events.CirrusSocketEvent;
public class swfcat extends Sprite
{
/* Adobe's Cirrus server for RTMFP connections.
The Cirrus key is defined at compile time by
reading from the CIRRUS_KEY environment var. */
private const DEFAULT_CIRRUS_ADDR:String = "rtmfp://p2p.rtmfp.net";
private const DEFAULT_CIRRUS_KEY:String = RTMFP::CIRRUS_KEY;
private const DEFAULT_FACILITATOR_ADDR:Object = {
host: "tor-facilitator.bamsoftware.com",
port: 9002
};
/* Default Tor client to use in case of RTMFP connection */
private const DEFAULT_TOR_CLIENT_ADDR:Object = {
host: "127.0.0.1",
port: 9002
};
// 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;
// Socket to Cirrus server
private var s_c:CirrusSocket;
// Socket to facilitator.
private var s_f:FacilitatorSocket;
// Handle local-remote traffic
private var p_p:ProxyPair;
private var client_id:String;
private var proxy_pair_factory:Function;
private var proxy_pairs:Array;
private var debug_mode:Boolean;
private var proxy_mode:Boolean;
/* TextField for debug output. */
private var output_text:TextField;
/* Badge for display */
private var badge:Badge;
private var fac_addr:Object;
private var relay_addr:Object;
public var rate_limit:RateLimit;
public function swfcat()
{
proxy_mode = false;
debug_mode = false;
// Absolute positioning.
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
if (RATE_LIMIT)
rate_limit = new BucketRateLimit(RATE_LIMIT * RATE_LIMIT_HISTORY, RATE_LIMIT_HISTORY);
else
rate_limit = new RateUnlimit();
// Wait until the query string parameters are loaded.
this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
}
public function puts(s:String):void
{
if (output_text != null) {
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
}
private function loaderinfo_complete(e:Event):void
{
var fac_spec:String;
var relay_spec:String;
debug_mode = (this.loaderInfo.parameters["debug"] != null)
proxy_mode = (this.loaderInfo.parameters["proxy"] != null);
if (proxy_mode && !debug_mode) {
badge = new Badge();
addChild(badge);
} else {
output_text = new TextField();
output_text.width = stage.stageWidth;
output_text.height = stage.stageHeight;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44cc44;
addChild(output_text);
}
puts("Starting: parameters loaded.");
/* TODO: use this to have multiple proxies going at once */
proxy_pairs = new Array();
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 (proxy_mode) {
establish_facilitator_connection();
} else {
establish_cirrus_connection();
}
}
private function establish_cirrus_connection():void
{
s_c = new CirrusSocket();
s_c.addEventListener(CirrusSocketEvent.CONNECT_SUCCESS, function (e:CirrusSocketEvent):void {
puts("Cirrus: connected with id " + s_c.id + ".");
if (proxy_mode) {
start_proxy_pair();
s_c.send_hello(client_id);
} else {
establish_facilitator_connection();
}
});
s_c.addEventListener(CirrusSocketEvent.CONNECT_FAILED, function (e:CirrusSocketEvent):void {
puts("Error: failed to connect to Cirrus.");
});
s_c.addEventListener(CirrusSocketEvent.CONNECT_CLOSED, function (e:CirrusSocketEvent):void {
puts("Cirrus: closed connection.");
});
s_c.addEventListener(CirrusSocketEvent.HELLO_RECEIVED, function (e:CirrusSocketEvent):void {
puts("Cirrus: received hello from peer " + e.peer);
/* don't bother if we already have a proxy going */
if (p_p != null && p_p.connected) {
return;
}
/* if we're in proxy mode, we should have already set
up a proxy pair */
if (!proxy_mode) {
relay_addr = DEFAULT_TOR_CLIENT_ADDR;
proxy_pair_factory = rtmfp_proxy_pair_factory;
start_proxy_pair();
s_c.send_hello(e.peer);
} else if (!debug_mode && badge != null) {
badge.proxy_begin();
}
p_p.client = {peer: e.peer, stream: e.stream};
});
s_c.connect(DEFAULT_CIRRUS_ADDR, DEFAULT_CIRRUS_KEY);
}
private function establish_facilitator_connection():void
{
s_f = new FacilitatorSocket(fac_addr.host, fac_addr.port);
s_f.addEventListener(FacilitatorSocketEvent.CONNECT_FAILED, function (e:Event):void {
puts("Facilitator: connect failed.");
setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL);
});
if (proxy_mode) {
s_f.addEventListener(FacilitatorSocketEvent.REGISTRATION_RECEIVED, function (e:FacilitatorSocketEvent):void {
var client_addr:Object = parse_addr_spec(e.client);
relay_addr = parse_addr_spec(e.relay);
if (client_addr == null) {
puts("Facilitator: got registration " + e.client);
proxy_pair_factory = rtmfp_proxy_pair_factory;
if (s_c == null || !s_c.connected) {
client_id = e.client;
establish_cirrus_connection();
} else {
start_proxy_pair();
s_c.send_hello(e.client);
}
} else {
proxy_pair_factory = tcp_proxy_pair_factory;
start_proxy_pair();
p_p.client = client_addr;
}
});
s_f.addEventListener(FacilitatorSocketEvent.REGISTRATIONS_EMPTY, function (e:Event):void {
puts("Facilitator: no registrations available.");
setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL);
});
puts("Facilitator: getting registration.");
s_f.get_registration();
} else {
s_f.addEventListener(FacilitatorSocketEvent.REGISTRATION_FAILED, function (e:Event):void {
puts("Facilitator: registration failed.");
setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL);
});
puts("Facilitator: posting registration.");
s_f.post_registration(s_c.id);
}
}
private function start_proxy_pair():void
{
p_p = proxy_pair_factory();
p_p.addEventListener(Event.CONNECT, function (e:Event):void {
puts("ProxyPair: connected!");
});
p_p.addEventListener(Event.CLOSE, function (e:Event):void {
puts("ProxyPair: connection closed.");
p_p = null;
if (proxy_mode && !debug_mode && badge != null) {
badge.proxy_end();
}
establish_facilitator_connection();
});
p_p.relay = relay_addr;
}
private function rtmfp_proxy_pair_factory():ProxyPair
{
return new RTMFPProxyPair(this, s_c, s_c.local_stream_name);
}
private function tcp_proxy_pair_factory():ProxyPair
{
return new TCPProxyPair(this);
}
/* 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.events.Event;
import flash.utils.setTimeout;
import FacilitatorSocket;
import events.FacilitatorSocketEvent;
import ProxyPair;
import RTMFPProxyPair;
import TCPProxyPair;
import rtmfp.CirrusSocket;
import rtmfp.events.CirrusSocketEvent;
public class swfcat extends Sprite
{
/* Adobe's Cirrus server for RTMFP connections.
The Cirrus key is defined at compile time by
reading from the CIRRUS_KEY environment var. */
private const DEFAULT_CIRRUS_ADDR:String = "rtmfp://p2p.rtmfp.net";
private const DEFAULT_CIRRUS_KEY:String = RTMFP::CIRRUS_KEY;
private const DEFAULT_FACILITATOR_ADDR:Object = {
host: "tor-facilitator.bamsoftware.com",
port: 9002
};
/* Default Tor client to use in case of RTMFP connection */
private const DEFAULT_TOR_CLIENT_ADDR:Object = {
host: "127.0.0.1",
port: 9002
};
// 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;
// Socket to Cirrus server
private var s_c:CirrusSocket;
// Socket to facilitator.
private var s_f:FacilitatorSocket;
// Handle local-remote traffic
private var p_p:ProxyPair;
private var client_id:String;
private var proxy_pair_factory:Function;
private var debug_mode:Boolean;
private var proxy_mode:Boolean;
/* TextField for debug output. */
private var output_text:TextField;
/* Badge for display */
private var badge:Badge;
private var fac_addr:Object;
private var relay_addr:Object;
public var rate_limit:RateLimit;
public function swfcat()
{
proxy_mode = false;
debug_mode = false;
// Absolute positioning.
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
if (RATE_LIMIT)
rate_limit = new BucketRateLimit(RATE_LIMIT * RATE_LIMIT_HISTORY, RATE_LIMIT_HISTORY);
else
rate_limit = new RateUnlimit();
// Wait until the query string parameters are loaded.
this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
}
public function puts(s:String):void
{
if (output_text != null) {
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
}
private function loaderinfo_complete(e:Event):void
{
var fac_spec:String;
var relay_spec:String;
debug_mode = (this.loaderInfo.parameters["debug"] != null)
proxy_mode = (this.loaderInfo.parameters["proxy"] != null);
if (proxy_mode && !debug_mode) {
badge = new Badge();
addChild(badge);
} else {
output_text = new TextField();
output_text.width = stage.stageWidth;
output_text.height = stage.stageHeight;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44cc44;
addChild(output_text);
}
puts("Starting: parameters loaded.");
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 (proxy_mode) {
establish_facilitator_connection();
} else {
establish_cirrus_connection();
}
}
private function establish_cirrus_connection():void
{
s_c = new CirrusSocket();
s_c.addEventListener(CirrusSocketEvent.CONNECT_SUCCESS, function (e:CirrusSocketEvent):void {
puts("Cirrus: connected with id " + s_c.id + ".");
if (proxy_mode) {
start_proxy_pair();
s_c.send_hello(client_id);
} else {
establish_facilitator_connection();
}
});
s_c.addEventListener(CirrusSocketEvent.CONNECT_FAILED, function (e:CirrusSocketEvent):void {
puts("Error: failed to connect to Cirrus.");
});
s_c.addEventListener(CirrusSocketEvent.CONNECT_CLOSED, function (e:CirrusSocketEvent):void {
puts("Cirrus: closed connection.");
});
s_c.addEventListener(CirrusSocketEvent.HELLO_RECEIVED, function (e:CirrusSocketEvent):void {
puts("Cirrus: received hello from peer " + e.peer);
/* don't bother if we already have a proxy going */
if (p_p != null && p_p.connected) {
return;
}
/* if we're in proxy mode, we should have already set
up a proxy pair */
if (!proxy_mode) {
relay_addr = DEFAULT_TOR_CLIENT_ADDR;
proxy_pair_factory = rtmfp_proxy_pair_factory;
start_proxy_pair();
s_c.send_hello(e.peer);
} else if (!debug_mode && badge != null) {
badge.proxy_begin();
}
p_p.client = {peer: e.peer, stream: e.stream};
});
s_c.connect(DEFAULT_CIRRUS_ADDR, DEFAULT_CIRRUS_KEY);
}
private function establish_facilitator_connection():void
{
s_f = new FacilitatorSocket(fac_addr.host, fac_addr.port);
s_f.addEventListener(FacilitatorSocketEvent.CONNECT_FAILED, function (e:Event):void {
puts("Facilitator: connect failed.");
setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL);
});
if (proxy_mode) {
s_f.addEventListener(FacilitatorSocketEvent.REGISTRATION_RECEIVED, function (e:FacilitatorSocketEvent):void {
var client_addr:Object = parse_addr_spec(e.client);
relay_addr = parse_addr_spec(e.relay);
if (client_addr == null) {
puts("Facilitator: got registration " + e.client);
proxy_pair_factory = rtmfp_proxy_pair_factory;
if (s_c == null || !s_c.connected) {
client_id = e.client;
establish_cirrus_connection();
} else {
start_proxy_pair();
s_c.send_hello(e.client);
}
} else {
proxy_pair_factory = tcp_proxy_pair_factory;
start_proxy_pair();
p_p.client = client_addr;
}
});
s_f.addEventListener(FacilitatorSocketEvent.REGISTRATIONS_EMPTY, function (e:Event):void {
puts("Facilitator: no registrations available.");
setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL);
});
puts("Facilitator: getting registration.");
s_f.get_registration();
} else {
s_f.addEventListener(FacilitatorSocketEvent.REGISTRATION_FAILED, function (e:Event):void {
puts("Facilitator: registration failed.");
setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL);
});
puts("Facilitator: posting registration.");
s_f.post_registration(s_c.id);
}
}
private function start_proxy_pair():void
{
p_p = proxy_pair_factory();
p_p.addEventListener(Event.CONNECT, function (e:Event):void {
puts("ProxyPair: connected!");
});
p_p.addEventListener(Event.CLOSE, function (e:Event):void {
puts("ProxyPair: connection closed.");
p_p = null;
if (proxy_mode && !debug_mode && badge != null) {
badge.proxy_end();
}
establish_facilitator_connection();
});
p_p.relay = relay_addr;
}
private function rtmfp_proxy_pair_factory():ProxyPair
{
return new RTMFPProxyPair(this, s_c, s_c.local_stream_name);
}
private function tcp_proxy_pair_factory():ProxyPair
{
return new TCPProxyPair(this);
}
/* 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;
}
}
|
Remove unused and unnecessary proxy_pairs local.
|
Remove unused and unnecessary proxy_pairs local.
|
ActionScript
|
mit
|
glamrock/flashproxy,glamrock/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,infinity0/flashproxy,infinity0/flashproxy
|
d15e94f246e212b5dbe9c8c51534dc1cc20415fc
|
src/com/kemsky/impl/Flex.as
|
src/com/kemsky/impl/Flex.as
|
package com.kemsky.impl
{
import flash.utils.getDefinitionByName;
public class Flex
{
private static const instance:Flex = new Flex();
protected var collection:Class;
protected var arrayList:Class;
protected var list:Class;
public var available:Boolean;
public function Flex()
{
try
{
this.collection = getDefinitionByName("mx.collections::ArrayCollection") as Class;
this.arrayList = getDefinitionByName("mx.collections::ArrayList") as Class;
this.list = getDefinitionByName("mx.collections::IList") as Class;
this.available = true;
}
catch (e:Error)
{
}
}
public static function get list():Class
{
return instance.list;
}
public static function get arrayList():Class
{
return instance.arrayList;
}
public static function get collection():Class
{
return instance.collection;
}
public static function get available():Boolean
{
return instance.available;
}
}
}
|
package com.kemsky.impl
{
import flash.utils.getDefinitionByName;
public class Flex
{
private static const instance:Flex = new Flex();
protected var collection:Class;
protected var list:Class;
public var available:Boolean;
public function Flex()
{
try
{
this.collection = getDefinitionByName("mx.collections::ArrayCollection") as Class;
this.list = getDefinitionByName("mx.collections::IList") as Class;
this.available = true;
}
catch (e:Error)
{
}
}
public static function get list():Class
{
return instance.list;
}
public static function get collection():Class
{
return instance.collection;
}
public static function get available():Boolean
{
return instance.available;
}
}
}
|
remove flex dependencies
|
remove flex dependencies
|
ActionScript
|
mit
|
kemsky/stream
|
f5407e43a59b60abd5a3a29414a3ee2d71d24d20
|
src/flash/display/Loader.as
|
src/flash/display/Loader.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.display {
import flash.errors.IllegalOperationError;
import flash.events.UncaughtErrorEvents;
import flash.net.URLRequest;
import flash.system.ApplicationDomain;
import flash.system.LoaderContext;
import flash.system.SecurityDomain;
import flash.utils.ByteArray;
[native(cls='LoaderClass')]
public class Loader extends DisplayObjectContainer {
public function Loader() {
}
public native function get content():DisplayObject;
public native function get contentLoaderInfo():LoaderInfo;
public function get uncaughtErrorEvents():UncaughtErrorEvents {
var events:UncaughtErrorEvents = _getUncaughtErrorEvents();
if (!events) {
events = new UncaughtErrorEvents();
_setUncaughtErrorEvents(events);
}
return events;
}
public override function addChild(child:DisplayObject):DisplayObject {
Error.throwError(IllegalOperationError, 2069);
return null;
}
public override function addChildAt(child:DisplayObject, index:int):DisplayObject {
Error.throwError(IllegalOperationError, 2069);
return null;
}
public override function removeChild(child:DisplayObject):DisplayObject {
Error.throwError(IllegalOperationError, 2069);
return null;
}
public override function removeChildAt(index:int):DisplayObject {
Error.throwError(IllegalOperationError, 2069);
return null;
}
public override function setChildIndex(child:DisplayObject, index:int):void
{
Error.throwError(IllegalOperationError, 2069);
}
public function load(request:URLRequest, context:LoaderContext = null):void {
context = sanitizeContext(context);
_load(request, context.checkPolicyFile, context.applicationDomain, context.securityDomain,
context.requestedContentParent, context.parameters,
_getJPEGLoaderContextdeblockingfilter(context), context.allowCodeImport,
context.imageDecodingPolicy);
}
private function sanitizeContext(context:LoaderContext):LoaderContext {
if (!context) {
context = new LoaderContext();
}
if (!context.applicationDomain) {
context.applicationDomain = new ApplicationDomain(ApplicationDomain.currentDomain);
}
context.parameters = cloneObject(context.parameters);
return context;
}
public function loadBytes(bytes:ByteArray, context:LoaderContext = null):void {
context = sanitizeContext(context);
_loadBytes(bytes, context.checkPolicyFile, context.applicationDomain, context.securityDomain,
context.requestedContentParent, context.parameters,
_getJPEGLoaderContextdeblockingfilter(context), context.allowCodeImport,
context.imageDecodingPolicy);
}
public function close():void {
_close();
}
public function unload():void {
_unload(false, false);
}
public function unloadAndStop(gc:Boolean = true):void {
_unload(true, gc);
}
private function cloneObject(obj:Object):Object {
if (!obj) {
return null;
}
var clone:Object = {};
for (var key:String in obj) {
clone[key] = obj[key];
}
return clone;
}
private native function _close():void;
private native function _unload(stopExecution:Boolean, gc:Boolean):void;
private native function _getJPEGLoaderContextdeblockingfilter(context:LoaderContext):Number;
private native function _getUncaughtErrorEvents():UncaughtErrorEvents;
private native function _setUncaughtErrorEvents(value:UncaughtErrorEvents):void;
private native function _load(request:URLRequest, checkPolicyFile:Boolean,
applicationDomain:ApplicationDomain, securityDomain:SecurityDomain,
requestedContentParent:DisplayObjectContainer, parameters:Object,
deblockingFilter:Number, allowCodeExecution:Boolean,
imageDecodingPolicy:String):void;
private native function _loadBytes(bytes:ByteArray, checkPolicyFile:Boolean,
applicationDomain:ApplicationDomain, securityDomain:SecurityDomain,
requestedContentParent:DisplayObjectContainer, parameters:Object,
deblockingFilter:Number, allowCodeExecution:Boolean,
imageDecodingPolicy:String):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.errors.IllegalOperationError;
import flash.events.UncaughtErrorEvents;
import flash.net.URLRequest;
import flash.system.ApplicationDomain;
import flash.system.LoaderContext;
import flash.system.SecurityDomain;
import flash.utils.ByteArray;
[native(cls='LoaderClass')]
public class Loader extends DisplayObjectContainer {
public native function Loader();
public native function get content():DisplayObject;
public native function get contentLoaderInfo():LoaderInfo;
public function get uncaughtErrorEvents():UncaughtErrorEvents {
var events:UncaughtErrorEvents = _getUncaughtErrorEvents();
if (!events) {
events = new UncaughtErrorEvents();
_setUncaughtErrorEvents(events);
}
return events;
}
public override function addChild(child:DisplayObject):DisplayObject {
Error.throwError(IllegalOperationError, 2069);
return null;
}
public override function addChildAt(child:DisplayObject, index:int):DisplayObject {
Error.throwError(IllegalOperationError, 2069);
return null;
}
public override function removeChild(child:DisplayObject):DisplayObject {
Error.throwError(IllegalOperationError, 2069);
return null;
}
public override function removeChildAt(index:int):DisplayObject {
Error.throwError(IllegalOperationError, 2069);
return null;
}
public override function setChildIndex(child:DisplayObject, index:int):void
{
Error.throwError(IllegalOperationError, 2069);
}
public function load(request:URLRequest, context:LoaderContext = null):void {
context = sanitizeContext(context);
_load(request, context.checkPolicyFile, context.applicationDomain, context.securityDomain,
context.requestedContentParent, context.parameters,
_getJPEGLoaderContextdeblockingfilter(context), context.allowCodeImport,
context.imageDecodingPolicy);
}
private function sanitizeContext(context:LoaderContext):LoaderContext {
if (!context) {
context = new LoaderContext();
}
if (!context.applicationDomain) {
context.applicationDomain = new ApplicationDomain(ApplicationDomain.currentDomain);
}
context.parameters = cloneObject(context.parameters);
return context;
}
public function loadBytes(bytes:ByteArray, context:LoaderContext = null):void {
context = sanitizeContext(context);
_loadBytes(bytes, context.checkPolicyFile, context.applicationDomain, context.securityDomain,
context.requestedContentParent, context.parameters,
_getJPEGLoaderContextdeblockingfilter(context), context.allowCodeImport,
context.imageDecodingPolicy);
}
public function close():void {
_close();
}
public function unload():void {
_unload(false, false);
}
public function unloadAndStop(gc:Boolean = true):void {
_unload(true, gc);
}
private function cloneObject(obj:Object):Object {
if (!obj) {
return null;
}
var clone:Object = {};
for (var key:String in obj) {
clone[key] = obj[key];
}
return clone;
}
private native function _close():void;
private native function _unload(stopExecution:Boolean, gc:Boolean):void;
private native function _getJPEGLoaderContextdeblockingfilter(context:LoaderContext):Number;
private native function _getUncaughtErrorEvents():UncaughtErrorEvents;
private native function _setUncaughtErrorEvents(value:UncaughtErrorEvents):void;
private native function _load(request:URLRequest, checkPolicyFile:Boolean,
applicationDomain:ApplicationDomain, securityDomain:SecurityDomain,
requestedContentParent:DisplayObjectContainer, parameters:Object,
deblockingFilter:Number, allowCodeExecution:Boolean,
imageDecodingPolicy:String):void;
private native function _loadBytes(bytes:ByteArray, checkPolicyFile:Boolean,
applicationDomain:ApplicationDomain, securityDomain:SecurityDomain,
requestedContentParent:DisplayObjectContainer, parameters:Object,
deblockingFilter:Number, allowCodeExecution:Boolean,
imageDecodingPolicy:String):void;
}
}
|
Make Loader constructor native
|
Make Loader constructor native
|
ActionScript
|
apache-2.0
|
yurydelendik/shumway,mbebenita/shumway,tschneidereit/shumway,mozilla/shumway,mozilla/shumway,yurydelendik/shumway,mozilla/shumway,yurydelendik/shumway,yurydelendik/shumway,tschneidereit/shumway,yurydelendik/shumway,mozilla/shumway,mozilla/shumway,yurydelendik/shumway,mozilla/shumway,mozilla/shumway,mbebenita/shumway,yurydelendik/shumway,tschneidereit/shumway,mbebenita/shumway,tschneidereit/shumway,tschneidereit/shumway,tschneidereit/shumway,yurydelendik/shumway,mbebenita/shumway,mbebenita/shumway,mbebenita/shumway,mbebenita/shumway,mozilla/shumway,tschneidereit/shumway,tschneidereit/shumway,mbebenita/shumway
|
fd4fc5e0b00b9c003e8c6f20b4c76493b47dc356
|
src/milkshape/media/flash/src/cc/milkshape/grid/GridModel.as
|
src/milkshape/media/flash/src/cc/milkshape/grid/GridModel.as
|
package cc.milkshape.grid
{
import cc.milkshape.framework.mvc.Model;
import cc.milkshape.grid.events.GridEvent;
import cc.milkshape.grid.events.GridFocusEvent;
import cc.milkshape.grid.events.GridLineEvent;
import cc.milkshape.grid.events.GridMoveEvent;
import cc.milkshape.grid.events.GridZoomEvent;
import cc.milkshape.grid.square.*;
import cc.milkshape.grid.square.events.SquareEvent;
import cc.milkshape.grid.square.events.SquareFormEvent;
public class GridModel extends Model
{
private var _issueSlug:String;
private var _issue:Object;
private var _minX:int;
private var _minY:int;
private var _maxX:int;
private var _maxY:int;
private var _lstPosition:Array;
private var _focusX:int;
private var _focusY:int;
private var _currentScale:int;
private var _minScale:int;
private var _maxScale:int;
private var _gridLineVisible:Boolean;
private var _posX:int;
private var _posY:int;
private var _isShowForm:Boolean;
public function GridModel(issueSlug:String)
{
_issueSlug = issueSlug;
}
public function get showDisableSquare():int
{
return _issue.show_disable_square;
}
public function set showDisableSquare(v:int):void
{
_issue.show_disable_square = v;
}
public function get gridLineVisible():Boolean
{
return _gridLineVisible;
}
public function get maxScale():int
{
return _maxScale;
}
public function set maxScale(v:int):void
{
_maxScale = v;
}
public function get minScale():int
{
return _minScale;
}
public function set minScale(v:int):void
{
_minScale = v;
}
public function get focusY():int
{
return _focusY;
}
public function get focusX():int
{
return _focusX;
}
public function get squareSize():int
{
return _issue.size;
}
public function set squareSize(v:int):void
{
_issue.size = v;
}
public function get posY():int
{
return _posY;
}
public function set posY(v:int):void
{
_posY = v;
}
public function get posX():int
{
return _posX;
}
public function set posX(v:int):void
{
_posX = v;
}
public function get currentScale():int
{
return _currentScale;
}
public function get issue():Object
{
return _issue;
}
public function set issue(issue:Object):void
{
_issue = issue;
_posX = 0;
_posY = 0;
_gridLineVisible = true;
dispatchEvent(new GridEvent(GridEvent.INFO_READY, _issue.steps, nbHSquare, nbVSquare, squareSize));
}
public function get issueSlug():String
{
return _issueSlug;
}
public function set issueSlug(v:String):void
{
_issueSlug = v;
}
public function setFocus(x:int, y:int):void {
focusX = y;
focusY = x;
}
public function initSquares(squares:Array, squaresOpen:Array):void
{
_lstPosition = new Array(nbHSquare);
for(var i:int = 0 ; i < nbHSquare ; ++i)
{
_lstPosition[i] = new Array(nbVSquare);
}
var square:Object;
for each(square in squares)
{
var squareObject:*;
// si status = false et pas de background alors c'est une booked
if(square.status || square.background_image != null && square.status){
squareObject = new SquareFull(square.pos_x + minX, square.pos_y + minY, square.background_image_path, squareSize);
squareObject.layers = square.layers;
squareObject.neighbors = square.neighbors_keys;
} else {
squareObject = new SquareBooked(square.pos_x + minX, square.pos_y + minY, squareSize);
}
_addPosition(squareObject);
}
for each(square in squaresOpen)
{
_addPosition(new SquareOpen(square.pos_x + minX, square.pos_y + minY, squareSize));
}
/*
if(showDisableSquare)
{
for(i = 0 ; i < nbVSquare ; ++i)
{
for(var j:int = 0 ; j < nbHSquare ; ++j)
{
if(_lstPosition[i][j] == null)
{
_addPosition(new SquareDisable(i, j, squareSize));;
}
}
}
}*/
dispatchEvent(new GridEvent(GridEvent.READY));
}
public function zoomTo(op:int):void
{
var futurScale:int = currentScale + op < minScale ? minScale : currentScale + op > maxScale ? maxScale : currentScale + op;
if(currentScale != futurScale)// Si le zoom change
{
if(_isShowForm)
{
_isShowForm = false;
dispatchEvent(new SquareFormEvent(SquareFormEvent.CLOSE));
}
currentScale = futurScale;
dispatchEvent(new GridZoomEvent(GridZoomEvent.ZOOM, futurScale));
moveTo();
}
}
public function moveTo():void
{
if(currentScale == maxScale)// Si on est au zoom maximal
{
trace('ok');
var square:Square = focusSquare;
if(square is SquareOpen)
{
_isShowForm = true;
dispatchEvent(new SquareFormEvent(SquareFormEvent.SHOW_OPEN));
}
else if(square is SquareBooked)
{
_isShowForm = true;
dispatchEvent(new SquareFormEvent(SquareFormEvent.SHOW_BOOKED));
}
else if(_isShowForm)
{
_isShowForm = false;
dispatchEvent(new SquareFormEvent(SquareFormEvent.CLOSE));
}
}
if(currentScale != minScale)// Si on n'est pas au zoom minimal
{
posX = focusX * _issue.steps[currentScale] + _issue.steps[currentScale] / 2;
posY = focusY * _issue.steps[currentScale] + _issue.steps[currentScale] / 2;
}
else
{
posX = nbVSquare * _issue.steps[currentScale] / 2;
posY = nbHSquare * _issue.steps[currentScale] / 2;
}
dispatchEvent(new GridMoveEvent(GridMoveEvent.MOVE, posX, posY));
}
private function _addPosition(square:Square):void
{
_lstPosition[square.X][square.Y] = SquareManager.length() - 1;
dispatchEvent(new SquareEvent(SquareEvent.CREATION, square));
}
public function set currentScale(scale:int):void {
_currentScale = scale;
dispatchEvent(new GridZoomEvent(GridZoomEvent.ZOOM, scale));
}
public function set focusX(x:int):void {
_focusX = x < 0 ? 0 : x >= nbVSquare ? nbVSquare - 1 : x;
dispatchEvent(new GridFocusEvent(GridFocusEvent.FOCUS));
}
public function set focusY(y:int):void {
_focusY = y < 0 ? 0 : y >= nbHSquare ? nbHSquare - 1 : y;
dispatchEvent(new GridFocusEvent(GridFocusEvent.FOCUS));
}
public function set gridLineVisible(b:Boolean):void
{
_gridLineVisible = b;
dispatchEvent(new GridLineEvent(b ? GridLineEvent.SHOW : GridLineEvent.HIDE));
}
public function get minX():int
{
return 0;
}
public function get minY():int
{
return 0;
}
public function get nbHSquare():int
{
return _issue.nb_case_x;
}
public function get nbVSquare():int
{
return issue.nb_case_y;
}
public function get focusSquare():Square {
return SquareManager.get(_lstPosition[_focusY][_focusX]);
}
public function get currentStep():int
{
return _issue.steps[_currentScale];
}
}
}
|
package cc.milkshape.grid
{
import cc.milkshape.framework.mvc.Model;
import cc.milkshape.grid.events.GridEvent;
import cc.milkshape.grid.events.GridFocusEvent;
import cc.milkshape.grid.events.GridLineEvent;
import cc.milkshape.grid.events.GridMoveEvent;
import cc.milkshape.grid.events.GridZoomEvent;
import cc.milkshape.grid.square.*;
import cc.milkshape.grid.square.events.SquareEvent;
import cc.milkshape.grid.square.events.SquareFormEvent;
public class GridModel extends Model
{
private var _issueSlug:String;
private var _issue:Object;
private var _minX:int;
private var _minY:int;
private var _maxX:int;
private var _maxY:int;
private var _lstPosition:Array;
private var _focusX:int;
private var _focusY:int;
private var _currentScale:int;
private var _minScale:int;
private var _maxScale:int;
private var _gridLineVisible:Boolean;
private var _posX:int;
private var _posY:int;
private var _isShowForm:Boolean;
public function GridModel(issueSlug:String)
{
_issueSlug = issueSlug;
}
public function get showDisableSquare():int
{
return _issue.show_disable_square;
}
public function set showDisableSquare(v:int):void
{
_issue.show_disable_square = v;
}
public function get gridLineVisible():Boolean
{
return _gridLineVisible;
}
public function get maxScale():int
{
return _maxScale;
}
public function set maxScale(v:int):void
{
_maxScale = v;
}
public function get minScale():int
{
return _minScale;
}
public function set minScale(v:int):void
{
_minScale = v;
}
public function get focusY():int
{
return _focusY;
}
public function get focusX():int
{
return _focusX;
}
public function get squareSize():int
{
return _issue.size;
}
public function set squareSize(v:int):void
{
_issue.size = v;
}
public function get posY():int
{
return _posY;
}
public function set posY(v:int):void
{
_posY = v;
}
public function get posX():int
{
return _posX;
}
public function set posX(v:int):void
{
_posX = v;
}
public function get currentScale():int
{
return _currentScale;
}
public function get issue():Object
{
return _issue;
}
public function set issue(issue:Object):void
{
_issue = issue;
_posX = 0;
_posY = 0;
_gridLineVisible = true;
dispatchEvent(new GridEvent(GridEvent.INFO_READY, _issue.steps, nbHSquare, nbVSquare, squareSize));
}
public function get issueSlug():String
{
return _issueSlug;
}
public function set issueSlug(v:String):void
{
_issueSlug = v;
}
public function setFocus(x:int, y:int):void {
focusX = y;
focusY = x;
}
public function initSquares(squares:Array, squaresOpen:Array):void
{
_lstPosition = new Array(nbHSquare);
for(var i:int = 0 ; i < nbHSquare ; ++i)
{
_lstPosition[i] = new Array(nbVSquare);
}
var square:Object;
for each(square in squares)
{
var squareObject:*;
// si status = false et pas de background alors c'est une booked
if(square.status || (square.background_image != null && !square.status)){
squareObject = new SquareFull(square.pos_x + minX, square.pos_y + minY, square.background_image_path, squareSize);
squareObject.layers = square.layers;
squareObject.neighbors = square.neighbors_keys;
} else {
squareObject = new SquareBooked(square.pos_x + minX, square.pos_y + minY, squareSize);
}
_addPosition(squareObject);
}
for each(square in squaresOpen)
{
_addPosition(new SquareOpen(square.pos_x + minX, square.pos_y + minY, squareSize));
}
/*
if(showDisableSquare)
{
for(i = 0 ; i < nbVSquare ; ++i)
{
for(var j:int = 0 ; j < nbHSquare ; ++j)
{
if(_lstPosition[i][j] == null)
{
_addPosition(new SquareDisable(i, j, squareSize));;
}
}
}
}*/
dispatchEvent(new GridEvent(GridEvent.READY));
}
public function zoomTo(op:int):void
{
var futurScale:int = currentScale + op < minScale ? minScale : currentScale + op > maxScale ? maxScale : currentScale + op;
if(currentScale != futurScale)// Si le zoom change
{
if(_isShowForm)
{
_isShowForm = false;
dispatchEvent(new SquareFormEvent(SquareFormEvent.CLOSE));
}
currentScale = futurScale;
dispatchEvent(new GridZoomEvent(GridZoomEvent.ZOOM, futurScale));
moveTo();
}
}
public function moveTo():void
{
if(currentScale == maxScale)// Si on est au zoom maximal
{
var square:Square = focusSquare;
if(square is SquareOpen)
{
_isShowForm = true;
dispatchEvent(new SquareFormEvent(SquareFormEvent.SHOW_OPEN));
}
else if(square is SquareBooked)
{
_isShowForm = true;
dispatchEvent(new SquareFormEvent(SquareFormEvent.SHOW_BOOKED));
}
else if(_isShowForm)
{
_isShowForm = false;
dispatchEvent(new SquareFormEvent(SquareFormEvent.CLOSE));
}
}
if(currentScale != minScale)// Si on n'est pas au zoom minimal
{
posX = focusX * _issue.steps[currentScale] + _issue.steps[currentScale] / 2;
posY = focusY * _issue.steps[currentScale] + _issue.steps[currentScale] / 2;
}
else
{
posX = nbVSquare * _issue.steps[currentScale] / 2;
posY = nbHSquare * _issue.steps[currentScale] / 2;
}
dispatchEvent(new GridMoveEvent(GridMoveEvent.MOVE, posX, posY));
}
private function _addPosition(square:Square):void
{
_lstPosition[square.X][square.Y] = SquareManager.length() - 1;
dispatchEvent(new SquareEvent(SquareEvent.CREATION, square));
}
public function set currentScale(scale:int):void {
_currentScale = scale;
dispatchEvent(new GridZoomEvent(GridZoomEvent.ZOOM, scale));
}
public function set focusX(x:int):void {
_focusX = x < 0 ? 0 : x >= nbVSquare ? nbVSquare - 1 : x;
dispatchEvent(new GridFocusEvent(GridFocusEvent.FOCUS));
}
public function set focusY(y:int):void {
_focusY = y < 0 ? 0 : y >= nbHSquare ? nbHSquare - 1 : y;
dispatchEvent(new GridFocusEvent(GridFocusEvent.FOCUS));
}
public function set gridLineVisible(b:Boolean):void
{
_gridLineVisible = b;
dispatchEvent(new GridLineEvent(b ? GridLineEvent.SHOW : GridLineEvent.HIDE));
}
public function get minX():int
{
return 0;
}
public function get minY():int
{
return 0;
}
public function get nbHSquare():int
{
return _issue.nb_case_x;
}
public function get nbVSquare():int
{
return issue.nb_case_y;
}
public function get focusSquare():Square {
return SquareManager.get(_lstPosition[_focusY][_focusX]);
}
public function get currentStep():int
{
return _issue.steps[_currentScale];
}
}
}
|
fix square process form
|
fix square process form
|
ActionScript
|
mit
|
thoas/i386,thoas/i386,thoas/i386,thoas/i386
|
5895cd34d3f86c3ab45f19084a54889f9b4a000e
|
src/aerys/minko/type/binding/DataBindings.as
|
src/aerys/minko/type/binding/DataBindings.as
|
package aerys.minko.type.binding
{
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.type.Signal;
import aerys.minko.type.enum.DataProviderUsage;
import flash.utils.Dictionary;
public final class DataBindings
{
private var _owner : ISceneNode;
private var _providers : Vector.<IDataProvider>;
private var _bindingNames : Vector.<String>;
private var _bindingNameToValue : Object;
private var _bindingNameToChangedSignal : Object;
private var _bindingNameToProvider : Object;
private var _providerToBindingNames : Dictionary;
private var _consumers : Vector.<IDataBindingsConsumer>;
public function get owner() : ISceneNode
{
return _owner;
}
public function get numProviders() : uint
{
return _providers.length;
}
public function get numProperties() : uint
{
return _bindingNames.length;
}
public function DataBindings(owner : ISceneNode)
{
_owner = owner;
_providers = new <IDataProvider>[];
_bindingNames = new <String>[];
_bindingNameToValue = {};
_bindingNameToChangedSignal = {};
_bindingNameToProvider = {};
_providerToBindingNames = new Dictionary(true);
_consumers = new <IDataBindingsConsumer>[];
}
public function contains(dataProvider : IDataProvider) : Boolean
{
return _providers.indexOf(dataProvider) != -1;
}
public function addProvider(provider : IDataProvider) : void
{
if (_providerToBindingNames[provider])
throw new Error('This provider is already bound.');
var dataDescriptor : Object = provider.dataDescriptor;
provider.propertyChanged.add(propertyChangedHandler);
if (provider is IDynamicDataProvider)
{
var dynamicProvider : IDynamicDataProvider = provider as IDynamicDataProvider;
dynamicProvider.propertyAdded.add(addBinding);
dynamicProvider.propertyRemoved.add(removeBinding);
}
_providerToBindingNames[provider] = new <String>[];
_providers.push(provider);
for (var propertyName : String in dataDescriptor)
addBinding(
provider,
propertyName,
dataDescriptor[propertyName],
provider[propertyName]
);
}
private function addBinding(provider : IDataProvider,
propertyName : String,
bindingName : String,
value : Object) : void
{
var providerBindingNames : Vector.<String> = _providerToBindingNames[provider];
if (_bindingNames.indexOf(bindingName) != -1)
throw new Error(
'Another data provider is already declaring the \'' + bindingName
+ '\' property.'
);
_bindingNameToProvider[bindingName] = provider;
_bindingNameToValue[bindingName] = value;
providerBindingNames.push(bindingName);
_bindingNames.push(bindingName);
var numConsumers : uint = _consumers.length;
for (var consumerId : uint = 0; consumerId < numConsumers; ++consumerId)
_consumers[consumerId].setProperty(bindingName, value);
if (_bindingNameToChangedSignal[bindingName])
_bindingNameToChangedSignal[bindingName].execute(this, bindingName, null, value);
}
public function removeProvider(provider : IDataProvider) : void
{
var providerBindingsNames : Vector.<String> = _providerToBindingNames[provider];
if (providerBindingsNames == null)
throw new ArgumentError('Unknown provider.');
var numProviders : uint = _providers.length - 1;
provider.propertyChanged.remove(propertyChangedHandler);
if (provider is IDynamicDataProvider)
{
var dynamicProvider : IDynamicDataProvider = provider as IDynamicDataProvider;
dynamicProvider.propertyAdded.remove(addBinding);
dynamicProvider.propertyRemoved.remove(removeBinding);
}
_providers[_providers.indexOf(provider)] = _providers[numProviders];
_providers.length = numProviders;
delete _providerToBindingNames[provider];
var dataDescriptor : Object = provider.dataDescriptor;
for (var propertyName : String in dataDescriptor)
removeBinding(
provider,
propertyName,
dataDescriptor[propertyName],
provider[propertyName]
);
}
public function removeBinding(provider : IDataProvider,
propertyName : String,
bindingName : String,
value : Object) : void
{
var numBindings : uint = _bindingNames.length - 1;
var changedSignal : Signal = _bindingNameToChangedSignal[bindingName] as Signal;
delete _bindingNameToValue[bindingName];
delete _bindingNameToProvider[bindingName];
_bindingNames[_bindingNames.indexOf(bindingName)] = _bindingNames[numBindings];
_bindingNames.length = numBindings;
var numConsumers : uint = _consumers.length;
for (var consumerId : uint = 0; consumerId < numConsumers; ++consumerId)
_consumers[consumerId].setProperty(bindingName, null);
if (changedSignal != null)
changedSignal.execute(this, bindingName, value, null);
}
public function removeAllProviders() : void
{
var numProviders : uint = this.numProviders;
for (var providerId : int = numProviders - 1; providerId >= 0; --providerId)
removeProvider(getProviderAt(providerId));
}
public function hasCallback(bindingName : String,
callback : Function) : Boolean
{
var signal : Signal = _bindingNameToChangedSignal[bindingName];
return signal != null && signal.hasCallback(callback);
}
public function addCallback(bindingName : String,
callback : Function) : void
{
_bindingNameToChangedSignal[bindingName] ||= new Signal(
'DataBindings.changed[' + bindingName + ']'
);
Signal(_bindingNameToChangedSignal[bindingName]).add(callback);
}
public function removeCallback(bindingName : String,
callback : Function) : void
{
var signal : Signal = _bindingNameToChangedSignal[bindingName];
if (!signal)
throw new ArgumentError('Unkown property \'' + bindingName + '\'.');
signal.remove(callback);
if (signal.numCallbacks == 0)
delete _bindingNameToChangedSignal[bindingName];
}
public function getProviderAt(index : uint) : IDataProvider
{
return _providers[index];
}
public function getProviderByBindingName(bindingName : String) : IDataProvider
{
if (_bindingNameToProvider[bindingName] == null)
throw new ArgumentError('Unkown property \'' + bindingName + '\'.');
return _bindingNameToProvider[bindingName];
}
public function propertyExists(bindingName : String) : Boolean
{
return _bindingNameToValue.hasOwnProperty(bindingName);
}
public function getProperty(bindingName : String) : *
{
if (_bindingNames.indexOf(bindingName) < 0)
throw new Error('The property \'' + bindingName + '\' does not exist.');
return _bindingNameToValue[bindingName];
}
public function getPropertyName(bindingIndex : uint) : String
{
if (bindingIndex > numProperties)
throw new ArgumentError('No such binding');
return _bindingNames[bindingIndex];
}
public function copySharedProvidersFrom(source : DataBindings) : void
{
var numProviders : uint = source._providers.length;
for (var providerId : uint = 0; providerId < numProviders; ++providerId)
{
var provider : IDataProvider = source._providers[providerId];
if (provider.usage == DataProviderUsage.SHARED)
addProvider(provider);
}
}
private function propertyChangedHandler(source : IDataProvider,
propertyName : String,
bindingName : String,
value : Object) : void
{
if (propertyName == null)
throw new Error('DataProviders must change only one property at a time.');
var oldValue : Object = _bindingNameToValue[bindingName];
_bindingNameToValue[bindingName] = value;
var numConsumers : uint = _consumers.length;
for (var consumerId : uint = 0; consumerId < numConsumers; ++consumerId)
_consumers[consumerId].setProperty(bindingName, value);
if (_bindingNameToChangedSignal[bindingName])
_bindingNameToChangedSignal[bindingName].execute(
this,
bindingName,
oldValue,
value
);
}
public function addConsumer(consumer : IDataBindingsConsumer) : void
{
_consumers.push(consumer);
var numProperties : uint = this.numProperties;
for (var propertyId : uint = 0; propertyId < numProperties; ++propertyId)
{
var bindingName : String = _bindingNames[propertyId];
consumer.setProperty(bindingName, _bindingNameToValue[bindingName]);
}
}
public function removeConsumer(consumer : IDataBindingsConsumer) : void
{
var numConsumers : uint = _consumers.length - 1;
var index : int = _consumers.indexOf(consumer);
if (index < 0)
throw new Error('This consumer does not exist.');
_consumers[index] = _consumers[numConsumers];
_consumers.length = numConsumers;
}
}
}
|
package aerys.minko.type.binding
{
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.type.Signal;
import aerys.minko.type.enum.DataProviderUsage;
import flash.utils.Dictionary;
public final class DataBindings
{
private var _owner : ISceneNode;
private var _providers : Vector.<IDataProvider>;
private var _bindingNames : Vector.<String>;
private var _bindingNameToValue : Object;
private var _bindingNameToChangedSignal : Object;
private var _bindingNameToProvider : Object;
private var _providerToBindingNames : Dictionary;
private var _consumers : Vector.<IDataBindingsConsumer>;
public function get owner() : ISceneNode
{
return _owner;
}
public function get numProviders() : uint
{
return _providers.length;
}
public function get numProperties() : uint
{
return _bindingNames.length;
}
public function DataBindings(owner : ISceneNode)
{
_owner = owner;
_providers = new <IDataProvider>[];
_bindingNames = new <String>[];
_bindingNameToValue = {};
_bindingNameToChangedSignal = {};
_bindingNameToProvider = {};
_providerToBindingNames = new Dictionary(true);
_consumers = new <IDataBindingsConsumer>[];
}
public function contains(dataProvider : IDataProvider) : Boolean
{
return _providers.indexOf(dataProvider) != -1;
}
public function addProvider(provider : IDataProvider) : void
{
if (_providerToBindingNames[provider])
throw new Error('This provider is already bound.');
var dataDescriptor : Object = provider.dataDescriptor;
provider.propertyChanged.add(propertyChangedHandler);
if (provider is IDynamicDataProvider)
{
var dynamicProvider : IDynamicDataProvider = provider as IDynamicDataProvider;
dynamicProvider.propertyAdded.add(addBinding);
dynamicProvider.propertyRemoved.add(removeBinding);
}
_providerToBindingNames[provider] = new <String>[];
_providers.push(provider);
for (var propertyName : String in dataDescriptor)
addBinding(
provider,
propertyName,
dataDescriptor[propertyName],
provider[propertyName]
);
}
private function addBinding(provider : IDataProvider,
propertyName : String,
bindingName : String,
value : Object) : void
{
var providerBindingNames : Vector.<String> = _providerToBindingNames[provider];
if (_bindingNames.indexOf(bindingName) != -1)
throw new Error(
'Another data provider is already declaring the \'' + bindingName
+ '\' property.'
);
_bindingNameToProvider[bindingName] = provider;
_bindingNameToValue[bindingName] = value;
providerBindingNames.push(bindingName);
_bindingNames.push(bindingName);
var numConsumers : uint = _consumers.length;
for (var consumerId : uint = 0; consumerId < numConsumers; ++consumerId)
_consumers[consumerId].setProperty(bindingName, value);
if (_bindingNameToChangedSignal[bindingName])
_bindingNameToChangedSignal[bindingName].execute(this, bindingName, null, value);
}
public function removeProvider(provider : IDataProvider) : void
{
var providerBindingsNames : Vector.<String> = _providerToBindingNames[provider];
if (providerBindingsNames == null)
throw new ArgumentError('Unknown provider.');
var numProviders : uint = _providers.length - 1;
provider.propertyChanged.remove(propertyChangedHandler);
if (provider is IDynamicDataProvider)
{
var dynamicProvider : IDynamicDataProvider = provider as IDynamicDataProvider;
dynamicProvider.propertyAdded.remove(addBinding);
dynamicProvider.propertyRemoved.remove(removeBinding);
}
_providers[_providers.indexOf(provider)] = _providers[numProviders];
_providers.length = numProviders;
delete _providerToBindingNames[provider];
var dataDescriptor : Object = provider.dataDescriptor;
for (var propertyName : String in dataDescriptor)
removeBinding(
provider,
propertyName,
dataDescriptor[propertyName],
provider[propertyName]
);
}
public function removeBinding(provider : IDataProvider,
propertyName : String,
bindingName : String,
value : Object) : void
{
var numBindings : uint = _bindingNames.length - 1;
var changedSignal : Signal = _bindingNameToChangedSignal[bindingName] as Signal;
delete _bindingNameToValue[bindingName];
delete _bindingNameToProvider[bindingName];
_bindingNames[_bindingNames.indexOf(bindingName)] = _bindingNames[numBindings];
_bindingNames.length = numBindings;
var numConsumers : uint = _consumers.length;
for (var consumerId : uint = 0; consumerId < numConsumers; ++consumerId)
_consumers[consumerId].setProperty(bindingName, null);
if (changedSignal != null)
changedSignal.execute(this, bindingName, value, null);
}
public function removeAllProviders() : void
{
var numProviders : uint = this.numProviders;
for (var providerId : int = numProviders - 1; providerId >= 0; --providerId)
removeProvider(getProviderAt(providerId));
}
public function hasCallback(bindingName : String,
callback : Function) : Boolean
{
var signal : Signal = _bindingNameToChangedSignal[bindingName];
return signal != null && signal.hasCallback(callback);
}
public function addCallback(bindingName : String,
callback : Function) : void
{
_bindingNameToChangedSignal[bindingName] ||= new Signal(
'DataBindings.changed[' + bindingName + ']'
);
Signal(_bindingNameToChangedSignal[bindingName]).add(callback);
}
public function removeCallback(bindingName : String,
callback : Function) : void
{
var signal : Signal = _bindingNameToChangedSignal[bindingName];
if (!signal)
throw new ArgumentError('Unkown property \'' + bindingName + '\'.');
signal.remove(callback);
if (signal.numCallbacks == 0)
delete _bindingNameToChangedSignal[bindingName];
}
public function getProviderAt(index : uint) : IDataProvider
{
return _providers[index];
}
public function getProviderByBindingName(bindingName : String) : IDataProvider
{
if (_bindingNameToProvider[bindingName] == null)
throw new ArgumentError('Unkown property \'' + bindingName + '\'.');
return _bindingNameToProvider[bindingName];
}
public function propertyExists(bindingName : String) : Boolean
{
return _bindingNameToValue.hasOwnProperty(bindingName);
}
public function getProperty(bindingName : String) : *
{
if (_bindingNames.indexOf(bindingName) < 0)
throw new Error('The property \'' + bindingName + '\' does not exist.');
return _bindingNameToValue[bindingName];
}
public function getPropertyName(bindingIndex : uint) : String
{
if (bindingIndex > numProperties)
throw new ArgumentError('No such binding');
return _bindingNames[bindingIndex];
}
public function copySharedProvidersFrom(source : DataBindings) : void
{
var numProviders : uint = source._providers.length;
for (var providerId : uint = 0; providerId < numProviders; ++providerId)
{
var provider : IDataProvider = source._providers[providerId];
if (provider.usage == DataProviderUsage.SHARED)
addProvider(provider);
}
}
public function hasProvider(provider : DataProvider) : Boolean
{
return provider in _providers;
}
private function propertyChangedHandler(source : IDataProvider,
propertyName : String,
bindingName : String,
value : Object) : void
{
if (propertyName == null)
throw new Error('DataProviders must change only one property at a time.');
var oldValue : Object = _bindingNameToValue[bindingName];
_bindingNameToValue[bindingName] = value;
var numConsumers : uint = _consumers.length;
for (var consumerId : uint = 0; consumerId < numConsumers; ++consumerId)
_consumers[consumerId].setProperty(bindingName, value);
if (_bindingNameToChangedSignal[bindingName])
_bindingNameToChangedSignal[bindingName].execute(
this,
bindingName,
oldValue,
value
);
}
public function addConsumer(consumer : IDataBindingsConsumer) : void
{
_consumers.push(consumer);
var numProperties : uint = this.numProperties;
for (var propertyId : uint = 0; propertyId < numProperties; ++propertyId)
{
var bindingName : String = _bindingNames[propertyId];
consumer.setProperty(bindingName, _bindingNameToValue[bindingName]);
}
}
public function removeConsumer(consumer : IDataBindingsConsumer) : void
{
var numConsumers : uint = _consumers.length - 1;
var index : int = _consumers.indexOf(consumer);
if (index < 0)
throw new Error('This consumer does not exist.');
_consumers[index] = _consumers[numConsumers];
_consumers.length = numConsumers;
}
}
}
|
add DataBindings.hasProvider()
|
add DataBindings.hasProvider()
|
ActionScript
|
mit
|
aerys/minko-as3
|
f71c2f9e81adabd209ffac2f009a2d7a1dc4a7b1
|
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.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;
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: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.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"
}
}
|
replace class Version by core.version
|
replace class Version by core.version
|
ActionScript
|
apache-2.0
|
nsdevaraj/gaforflash,minimedj/gaforflash,nsdevaraj/gaforflash,minimedj/gaforflash
|
23fb6fc6a4823ed21b74ed69afdf28c3cdac52ce
|
src/widgets/supportClasses/ResultAttributes.as
|
src/widgets/supportClasses/ResultAttributes.as
|
package widgets.supportClasses
{
import com.esri.ags.FeatureSet;
import com.esri.ags.Graphic;
import com.esri.ags.layers.FeatureLayer;
import com.esri.ags.layers.supportClasses.CodedValue;
import com.esri.ags.layers.supportClasses.CodedValueDomain;
import com.esri.ags.layers.supportClasses.FeatureType;
import com.esri.ags.layers.supportClasses.Field;
import com.esri.ags.layers.supportClasses.LayerDetails;
import mx.formatters.DateFormatter;
[Bindable]
public class ResultAttributes
{
public var attributes:Object;
public var title:String;
public var content:String;
public var link:String;
public var linkAlias:String;
public static function toResultAttributes(fields:XMLList,
textDirection:String = null,
graphic:Graphic = null,
featureSet:FeatureSet = null,
layer:FeatureLayer = null,
layerDetails:LayerDetails = null,
widgetTitle:String = null,
titleField:String = null,
linkField:String = null,
linkAlias:String = null):ResultAttributes
{
var resultAttributes:ResultAttributes = new ResultAttributes;
var value:String = "";
var title:String = "";
var content:String = "";
var link:String = "";
var linkAlias:String;
var fieldsXMLList:XMLList = fields ? fields.field : null;
if (fields && fields[0].@all[0] == "true")
{
if (layerDetails.fields)
{
for each (var field:Field in layerDetails.fields)
{
if (field.name in graphic.attributes)
{
displayFields(field.name, getFieldXML(field.name, fieldsXMLList), field);
}
}
}
else
{
for (var fieldName:String in graphic.attributes)
{
displayFields(fieldName, getFieldXML(fieldName, fieldsXMLList), null);
}
}
}
else
{
for each (var fieldXML:XML in fieldsXMLList) // display the fields in the same order as specified
{
if (fieldXML.@name[0] in graphic.attributes)
{
displayFields(fieldXML.@name[0], fieldXML, getField(layer, fieldXML.@name[0]));
}
}
}
resultAttributes.attributes = graphic.attributes;
resultAttributes.title = title ? title : widgetTitle;
resultAttributes.content = content;
resultAttributes.link = link ? link : null;
resultAttributes.linkAlias = linkAlias;
function displayFields(fieldName:String, fieldXML:XML, field:Field):void
{
value = graphic.attributes[fieldName] ? String(graphic.attributes[fieldName]) : "";
if (value)
{
var isDateField:Boolean;
var useUTC:Boolean;
var dateFormat:String;
if (fieldXML)
{
useUTC = fieldXML.format.@useutc[0] || fieldXML.@useutc[0] == "true";
dateFormat = fieldXML.format.@dateformat[0] || fieldXML.@dateformat[0];
if (dateFormat)
{
isDateField = true;
}
}
if (!isDateField && field)
{
isDateField = field.type == Field.TYPE_DATE;
}
if (isDateField)
{
var dateMS:Number = Number(value);
if (!isNaN(dateMS))
{
value = msToDate(dateMS, dateFormat, useUTC);
}
}
else
{
var typeID:String = layerDetails.typeIdField ? graphic.attributes[layerDetails.typeIdField] : null;
if (fieldName == layerDetails.typeIdField)
{
var featureType:FeatureType = getFeatureType(layer, typeID);
if (featureType && featureType.name)
{
value = featureType.name;
}
}
else
{
var codedValue:CodedValue = getCodedValue(layer, fieldName, value, typeID);
if (codedValue)
{
value = codedValue.name;
}
}
}
}
if (titleField && fieldName.toUpperCase() == titleField.toUpperCase())
{
title = value;
}
else if (linkField && fieldName.toUpperCase() == linkField.toUpperCase())
{
link = value;
linkAlias = linkAlias;
}
else if (fieldName.toUpperCase() != "SHAPE_LENGTH" && fieldName.toUpperCase() != "SHAPE_AREA")
{
var fieldLabel:String;
if (fieldXML && fieldXML.@alias[0])
{
fieldLabel = fieldXML.@alias[0];
}
else
{
fieldLabel = featureSet.fieldAliases[fieldName];
}
if (textDirection && textDirection == "rtl")
{
content += value + " :" + fieldLabel + "\n";
}
else
{
content += fieldLabel + ": " + value + "\n";
}
}
}
return resultAttributes;
}
private static function getFieldXML(fieldName:String, fields:XMLList):XML
{
var result:XML;
for each (var fieldXML:XML in fields)
{
if (fieldName == fieldXML.@name[0])
{
result = fieldXML;
break;
}
}
return result;
}
private static function getField(layer:FeatureLayer, fieldName:String):Field
{
var result:Field;
if (layer)
{
for each (var field:Field in layer.layerDetails.fields)
{
if (fieldName == field.name)
{
result = field;
break;
}
}
}
return result;
}
private static function getFeatureType(layer:FeatureLayer, typeID:String):FeatureType
{
var result:FeatureType;
if (layer)
{
for each (var featureType:FeatureType in layer.layerDetails.types)
{
if (typeID == featureType.id)
{
result = featureType;
break;
}
}
}
return result;
}
private static function msToDate(ms:Number, dateFormat:String, useUTC:Boolean):String
{
var date:Date = new Date(ms);
if (date.milliseconds == 999) // workaround for REST bug
{
date.milliseconds++;
}
if (useUTC)
{
date.minutes += date.timezoneOffset;
}
if (dateFormat)
{
var dateFormatter:DateFormatter = new DateFormatter();
dateFormatter.formatString = dateFormat;
var result:String = dateFormatter.format(date);
if (result)
{
return result;
}
else
{
return dateFormatter.error;
}
}
else
{
return date.toLocaleString();
}
}
private static function getCodedValue(layer:FeatureLayer, fieldName:String, fieldValue:String, typeID:String):CodedValue
{
var result:CodedValue;
var codedValueDomain:CodedValueDomain;
if (typeID)
{
var featureType:FeatureType = getFeatureType(layer, typeID);
if (featureType)
{
codedValueDomain = featureType.domains[fieldName] as CodedValueDomain;
}
}
else
{
var field:Field = getField(layer, fieldName);
if (field)
{
codedValueDomain = field.domain as CodedValueDomain;
}
}
if (codedValueDomain)
{
for each (var codedValue:CodedValue in codedValueDomain.codedValues)
{
if (fieldValue == codedValue.code)
{
result = codedValue;
break;
}
}
}
return result;
}
}
}
|
package widgets.supportClasses
{
import com.esri.ags.FeatureSet;
import com.esri.ags.Graphic;
import com.esri.ags.layers.FeatureLayer;
import com.esri.ags.layers.supportClasses.CodedValue;
import com.esri.ags.layers.supportClasses.CodedValueDomain;
import com.esri.ags.layers.supportClasses.FeatureType;
import com.esri.ags.layers.supportClasses.Field;
import com.esri.ags.layers.supportClasses.LayerDetails;
import mx.formatters.DateFormatter;
[Bindable]
public class ResultAttributes
{
public var attributes:Object;
public var title:String;
public var content:String;
public var link:String;
public var linkAlias:String;
public static function toResultAttributes(fields:XMLList,
textDirection:String = null,
graphic:Graphic = null,
featureSet:FeatureSet = null,
layer:FeatureLayer = null,
layerDetails:LayerDetails = null,
widgetTitle:String = null,
titleField:String = null,
linkField:String = null,
linkAlias:String = null):ResultAttributes
{
var resultAttributes:ResultAttributes = new ResultAttributes;
var value:String = "";
var title:String = "";
var content:String = "";
var link:String = "";
var linkAlias:String;
var fieldsXMLList:XMLList = fields ? fields.field : null;
if (fields && fields[0].@all[0] == "true")
{
if (layerDetails.fields)
{
for each (var field:Field in layerDetails.fields)
{
if (field.name in graphic.attributes)
{
displayFields(field.name, getFieldXML(field.name, fieldsXMLList), field);
}
}
}
else
{
for (var fieldName:String in graphic.attributes)
{
displayFields(fieldName, getFieldXML(fieldName, fieldsXMLList), null);
}
}
}
else
{
for each (var fieldXML:XML in fieldsXMLList) // display the fields in the same order as specified
{
if (fieldXML.@name[0] in graphic.attributes)
{
displayFields(fieldXML.@name[0], fieldXML, getField(layer, fieldXML.@name[0]));
}
}
}
resultAttributes.attributes = graphic.attributes;
resultAttributes.title = title ? title : widgetTitle;
resultAttributes.content = content;
resultAttributes.link = link ? link : null;
resultAttributes.linkAlias = linkAlias;
function displayFields(fieldName:String, fieldXML:XML, field:Field):void
{
var fieldNameTextValue:String = graphic.attributes[fieldName];
value = fieldNameTextValue ? fieldNameTextValue : "";
if (value)
{
var isDateField:Boolean;
var useUTC:Boolean;
var dateFormat:String;
if (fieldXML)
{
useUTC = fieldXML.format.@useutc[0] || fieldXML.@useutc[0] == "true";
dateFormat = fieldXML.format.@dateformat[0] || fieldXML.@dateformat[0];
if (dateFormat)
{
isDateField = true;
}
}
if (!isDateField && field)
{
isDateField = field.type == Field.TYPE_DATE;
}
if (isDateField)
{
var dateMS:Number = Number(value);
if (!isNaN(dateMS))
{
value = msToDate(dateMS, dateFormat, useUTC);
}
}
else
{
var typeID:String = layerDetails.typeIdField ? graphic.attributes[layerDetails.typeIdField] : null;
if (fieldName == layerDetails.typeIdField)
{
var featureType:FeatureType = getFeatureType(layer, typeID);
if (featureType && featureType.name)
{
value = featureType.name;
}
}
else
{
var codedValue:CodedValue = getCodedValue(layer, fieldName, value, typeID);
if (codedValue)
{
value = codedValue.name;
}
}
}
}
if (titleField && fieldName.toUpperCase() == titleField.toUpperCase())
{
title = value;
}
else if (linkField && fieldName.toUpperCase() == linkField.toUpperCase())
{
link = value;
linkAlias = linkAlias;
}
else if (fieldName.toUpperCase() != "SHAPE_LENGTH" && fieldName.toUpperCase() != "SHAPE_AREA")
{
var fieldLabel:String;
if (fieldXML && fieldXML.@alias[0])
{
fieldLabel = fieldXML.@alias[0];
}
else
{
fieldLabel = featureSet.fieldAliases[fieldName];
}
if (textDirection && textDirection == "rtl")
{
content += value + " :" + fieldLabel + "\n";
}
else
{
content += fieldLabel + ": " + value + "\n";
}
}
}
return resultAttributes;
}
private static function getFieldXML(fieldName:String, fields:XMLList):XML
{
var result:XML;
for each (var fieldXML:XML in fields)
{
if (fieldName == fieldXML.@name[0])
{
result = fieldXML;
break;
}
}
return result;
}
private static function getField(layer:FeatureLayer, fieldName:String):Field
{
var result:Field;
if (layer)
{
for each (var field:Field in layer.layerDetails.fields)
{
if (fieldName == field.name)
{
result = field;
break;
}
}
}
return result;
}
private static function getFeatureType(layer:FeatureLayer, typeID:String):FeatureType
{
var result:FeatureType;
if (layer)
{
for each (var featureType:FeatureType in layer.layerDetails.types)
{
if (typeID == featureType.id)
{
result = featureType;
break;
}
}
}
return result;
}
private static function msToDate(ms:Number, dateFormat:String, useUTC:Boolean):String
{
var date:Date = new Date(ms);
if (date.milliseconds == 999) // workaround for REST bug
{
date.milliseconds++;
}
if (useUTC)
{
date.minutes += date.timezoneOffset;
}
if (dateFormat)
{
var dateFormatter:DateFormatter = new DateFormatter();
dateFormatter.formatString = dateFormat;
var result:String = dateFormatter.format(date);
if (result)
{
return result;
}
else
{
return dateFormatter.error;
}
}
else
{
return date.toLocaleString();
}
}
private static function getCodedValue(layer:FeatureLayer, fieldName:String, fieldValue:String, typeID:String):CodedValue
{
var result:CodedValue;
var codedValueDomain:CodedValueDomain;
if (typeID)
{
var featureType:FeatureType = getFeatureType(layer, typeID);
if (featureType)
{
codedValueDomain = featureType.domains[fieldName] as CodedValueDomain;
}
}
else
{
var field:Field = getField(layer, fieldName);
if (field)
{
codedValueDomain = field.domain as CodedValueDomain;
}
}
if (codedValueDomain)
{
for each (var codedValue:CodedValue in codedValueDomain.codedValues)
{
if (fieldValue == codedValue.code)
{
result = codedValue;
break;
}
}
}
return result;
}
}
}
|
Improve ResultAttribute#toResultAttributes field value handling.
|
Improve ResultAttribute#toResultAttributes field value handling.
|
ActionScript
|
apache-2.0
|
CanterburyRegionalCouncil/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex,Esri/arcgis-viewer-flex,Esri/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex
|
072ac2a13e50ac7b0af4f6636fe4d2a338d5ff9f
|
generator/sources/as3/com/kaltura/delegates/WebDelegateBase.as
|
generator/sources/as3/com/kaltura/delegates/WebDelegateBase.as
|
// ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2011 Kaltura Inc.
//
// 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/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.delegates {
import com.kaltura.config.IKalturaConfig;
import com.kaltura.config.KalturaConfig;
import com.kaltura.core.KClassFactory;
import com.kaltura.encryption.MD5;
import com.kaltura.errors.KalturaError;
import com.kaltura.events.KalturaEvent;
import com.kaltura.net.KalturaCall;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.events.TimerEvent;
import flash.net.FileReference;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.utils.Timer;
import flash.utils.getDefinitionByName;
public class WebDelegateBase extends EventDispatcher implements IKalturaCallDelegate {
public static var CONNECT_TIME:int = 60000; //60 secs
public static var LOAD_TIME:int = 120000; //120 secs
protected var connectTimer:Timer;
protected var loadTimer:Timer;
protected var _call:KalturaCall;
protected var _config:KalturaConfig;
protected var loader:URLLoader;
protected var fileRef:FileReference;
//Setters & getters
public function get call():KalturaCall {
return _call;
}
public function set call(newVal:KalturaCall):void {
_call = newVal;
}
public function get config():IKalturaConfig {
return _config;
}
public function set config(newVal:IKalturaConfig):void {
_config = newVal as KalturaConfig;
}
public function WebDelegateBase(call:KalturaCall = null, config:KalturaConfig = null) {
this.call = call;
this.config = config;
if (!call)
return; //maybe a multi request
if (call.useTimeout) {
connectTimer = new Timer(CONNECT_TIME, 1);
connectTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onConnectTimeout);
loadTimer = new Timer(LOAD_TIME, 1);
loadTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onLoadTimeOut);
}
execute();
}
public function close():void {
try {
loader.close();
}
catch (e:*) {
}
if (call.useTimeout) {
connectTimer.stop();
loadTimer.stop();
}
}
protected function onConnectTimeout(event:TimerEvent):void {
var kError:KalturaError = new KalturaError();
kError.errorCode = "CONNECTION_TIMEOUT";
kError.errorMsg = "Connection Timeout: " + CONNECT_TIME / 1000 + " sec with no post command from kaltura client.";
_call.handleError(kError);
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
loadTimer.stop();
close();
}
protected function onLoadTimeOut(event:TimerEvent):void {
connectTimer.stop();
close();
var kError:KalturaError = new KalturaError();
kError.errorCode = "POST_TIMEOUT";
kError.errorMsg = "Post Timeout: " + LOAD_TIME / 1000 + " sec with no post result.";
_call.handleError(kError);
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
}
protected function execute():void {
if (call == null) {
throw new Error('No call defined.');
}
post(); //post the call
}
/**
* Helper function for sending the call straight to the server
*/
protected function post():void {
addOptionalArguments();
formatRequest();
sendRequest();
if (call.useTimeout) {
connectTimer.start();
}
}
protected function formatRequest():void {
//The configuration is stronger then the args
if (_config.partnerId != null && _call.args["partnerId"] == -1)
_call.setRequestArgument("partnerId", _config.partnerId);
if (_config.ks != null)
_call.setRequestArgument("ks", _config.ks);
if (_config.clientTag != null)
_call.setRequestArgument("clientTag", _config.clientTag);
_call.setRequestArgument("ignoreNull", _config.ignoreNull);
//Create signature hash.
//call.setRequestArgument("kalsig", getMD5Checksum(call));
}
protected function getMD5Checksum(call:KalturaCall):String {
var props:Array = new Array();
for each (var prop:String in call.args)
props.push(prop);
props.push("service");
props.push("action");
props.sort();
var s:String;
for each (prop in props) {
s += prop;
if (prop == "service")
s += call.service;
else if (prop == "action")
s += call.action;
else
s += call.args[prop];
}
return MD5.encrypt(s);
}
protected function sendRequest():void {
//construct the loader
createURLLoader();
//Create signature hash.
var kalsig:String = getMD5Checksum(call);
//create the service request for normal calls
var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action + "&kalsig=" + kalsig;;
if (_call.method == URLRequestMethod.GET)
url += "&";
var req:URLRequest = new URLRequest(url);
req.contentType = "application/x-www-form-urlencoded";
req.method = call.method;
req.data = call.args;
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.load(req);
}
protected function createURLLoader():void {
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onDataComplete);
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);
loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
loader.addEventListener(Event.OPEN, onOpen);
}
protected function onHTTPStatus(event:HTTPStatusEvent):void {
}
protected function onOpen(event:Event):void {
if (call.useTimeout) {
connectTimer.stop();
loadTimer.start();
}
}
protected function addOptionalArguments():void {
//add optional args here
}
// Event Handlers
/**
* try to process received data.
* if procesing failed, let call handle the processing error
* @param event load complete event
*/
protected function onDataComplete(event:Event):void {
try {
handleResult(XML(event.target.data));
}
catch (e:Error) {
var kErr:KalturaError = new KalturaError();
kErr.errorCode = String(e.errorID);
kErr.errorMsg = e.message;
_call.handleError(kErr);
}
}
/**
* handle io or security error events from the loader.
* create relevant KalturaError, let the call process it.
* @param event
*/
protected function onError(event:ErrorEvent):void {
clean();
var kError:KalturaError = createKalturaError(event, loader.data);
if (!kError) {
kError = new KalturaError();
kError.errorMsg = event.text;
//kError.errorCode;
}
call.handleError(kError);
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
}
/**
* parse the server's response and let the call process it.
* @param result server's response
*/
protected function handleResult(result:XML):void {
clean();
var error:KalturaError = validateKalturaResponse(result);
if (error == null) {
var digestedResult:Object = parse(result);
call.handleResult(digestedResult);
}
else {
call.handleError(error);
}
}
/**
* stop timers and clean event listeners
*/
protected function clean():void {
if (call.useTimeout) {
connectTimer.stop();
loadTimer.stop();
}
if (loader == null) {
return;
}
loader.removeEventListener(Event.COMPLETE, onDataComplete);
loader.removeEventListener(IOErrorEvent.IO_ERROR, onError);
loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
loader.removeEventListener(Event.OPEN, onOpen);
}
/**
* create the correct object and populate it with the given values. if the needed class is not found
* in the file, a generic object is created with attributes matching the XML attributes.
* Override this parssing function in the specific delegate to create the correct object.
* @param result instance attributes
* @return an instance of the class declared by the given XML.
* */
public function parse(result:XML):* {
//by defualt create the response object
var cls:Class;
try {
cls = getDefinitionByName('com.kaltura.vo.' + result.result.objectType) as Class;
}
catch (e:Error) {
cls = Object;
}
var obj:* = (new KClassFactory(cls)).newInstanceFromXML(result.result);
return obj;
}
/**
* If the result string holds an error, return a KalturaError object with
* relevant values. <br/>
* Overide this to create validation object and fill it.
* @param result the string returned from the server.
* @return matching error object
*/
protected function validateKalturaResponse(result:String):KalturaError {
var kError:KalturaError = null;
var xml:XML = XML(result);
if (xml.result.hasOwnProperty('error')
&& xml.result.error.hasOwnProperty('code')
&& xml.result.error.hasOwnProperty('message')) {
kError = new KalturaError();
kError.errorCode = String(xml.result.error.code);
kError.errorMsg = xml.result.error.message;
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
}
return kError;
}
/**
* create error object and fill it with relevant details
* @param event
* @param loaderData
* @return detailed KalturaError to be processed
*/
protected function createKalturaError(event:ErrorEvent, loaderData:*):KalturaError {
var ke:KalturaError = new KalturaError();
ke.errorMsg = event.text;
return ke;
}
/**
* create the url that is used for serve actions
* @param call the KalturaCall that defines the required parameters
* @return URLRequest with relevant parameters
* */
public function getServeUrl(call:KalturaCall):URLRequest {
var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action;
for (var key:String in call.args) {
url += "&" + key + "=" + call.args[key];
}
var req:URLRequest = new URLRequest(url);
req.contentType = "application/x-www-form-urlencoded";
req.method = call.method;
// req.data = call.args;
return req;
}
}
}
|
// ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2011 Kaltura Inc.
//
// 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/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.delegates {
import com.kaltura.config.IKalturaConfig;
import com.kaltura.config.KalturaConfig;
import com.kaltura.core.KClassFactory;
import com.kaltura.encryption.MD5;
import com.kaltura.errors.KalturaError;
import com.kaltura.events.KalturaEvent;
import com.kaltura.net.KalturaCall;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.events.TimerEvent;
import flash.net.FileReference;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.utils.Timer;
import flash.utils.getDefinitionByName;
public class WebDelegateBase extends EventDispatcher implements IKalturaCallDelegate {
public static var CONNECT_TIME:int = 120000; //120 secs
public static var LOAD_TIME:int = 120000; //120 secs
protected var connectTimer:Timer;
protected var loadTimer:Timer;
protected var _call:KalturaCall;
protected var _config:KalturaConfig;
protected var loader:URLLoader;
protected var fileRef:FileReference;
//Setters & getters
public function get call():KalturaCall {
return _call;
}
public function set call(newVal:KalturaCall):void {
_call = newVal;
}
public function get config():IKalturaConfig {
return _config;
}
public function set config(newVal:IKalturaConfig):void {
_config = newVal as KalturaConfig;
}
public function WebDelegateBase(call:KalturaCall = null, config:KalturaConfig = null) {
this.call = call;
this.config = config;
if (!call)
return; //maybe a multi request
if (call.useTimeout) {
connectTimer = new Timer(CONNECT_TIME, 1);
connectTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onConnectTimeout);
loadTimer = new Timer(LOAD_TIME, 1);
loadTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onLoadTimeOut);
}
execute();
}
public function close():void {
try {
loader.close();
}
catch (e:*) {
}
if (call.useTimeout) {
connectTimer.stop();
loadTimer.stop();
}
}
protected function onConnectTimeout(event:TimerEvent):void {
var kError:KalturaError = new KalturaError();
kError.errorCode = "CONNECTION_TIMEOUT";
kError.errorMsg = "Connection Timeout: " + CONNECT_TIME / 1000 + " sec with no post command from kaltura client.";
_call.handleError(kError);
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
loadTimer.stop();
close();
}
protected function onLoadTimeOut(event:TimerEvent):void {
connectTimer.stop();
close();
var kError:KalturaError = new KalturaError();
kError.errorCode = "POST_TIMEOUT";
kError.errorMsg = "Post Timeout: " + LOAD_TIME / 1000 + " sec with no post result.";
_call.handleError(kError);
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
}
protected function execute():void {
if (call == null) {
throw new Error('No call defined.');
}
post(); //post the call
}
/**
* Helper function for sending the call straight to the server
*/
protected function post():void {
addOptionalArguments();
formatRequest();
sendRequest();
if (call.useTimeout) {
connectTimer.start();
}
}
protected function formatRequest():void {
//The configuration is stronger then the args
if (_config.partnerId != null && _call.args["partnerId"] == -1)
_call.setRequestArgument("partnerId", _config.partnerId);
if (_config.ks != null)
_call.setRequestArgument("ks", _config.ks);
if (_config.clientTag != null)
_call.setRequestArgument("clientTag", _config.clientTag);
_call.setRequestArgument("ignoreNull", _config.ignoreNull);
//Create signature hash.
//call.setRequestArgument("kalsig", getMD5Checksum(call));
}
protected function getMD5Checksum(call:KalturaCall):String {
var props:Array = new Array();
for each (var prop:String in call.args)
props.push(prop);
props.push("service");
props.push("action");
props.sort();
var s:String;
for each (prop in props) {
s += prop;
if (prop == "service")
s += call.service;
else if (prop == "action")
s += call.action;
else
s += call.args[prop];
}
return MD5.encrypt(s);
}
protected function sendRequest():void {
//construct the loader
createURLLoader();
//Create signature hash.
var kalsig:String = getMD5Checksum(call);
//create the service request for normal calls
var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action + "&kalsig=" + kalsig;;
if (_call.method == URLRequestMethod.GET)
url += "&";
var req:URLRequest = new URLRequest(url);
req.contentType = "application/x-www-form-urlencoded";
req.method = call.method;
req.data = call.args;
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.load(req);
}
protected function createURLLoader():void {
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onDataComplete);
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);
loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
loader.addEventListener(Event.OPEN, onOpen);
}
protected function onHTTPStatus(event:HTTPStatusEvent):void {
}
protected function onOpen(event:Event):void {
if (call.useTimeout) {
connectTimer.stop();
loadTimer.start();
}
}
protected function addOptionalArguments():void {
//add optional args here
}
// Event Handlers
/**
* try to process received data.
* if procesing failed, let call handle the processing error
* @param event load complete event
*/
protected function onDataComplete(event:Event):void {
try {
handleResult(XML(event.target.data));
}
catch (e:Error) {
var kErr:KalturaError = new KalturaError();
kErr.errorCode = String(e.errorID);
kErr.errorMsg = e.message;
_call.handleError(kErr);
}
}
/**
* handle io or security error events from the loader.
* create relevant KalturaError, let the call process it.
* @param event
*/
protected function onError(event:ErrorEvent):void {
clean();
var kError:KalturaError = createKalturaError(event, loader.data);
if (!kError) {
kError = new KalturaError();
kError.errorMsg = event.text;
//kError.errorCode;
}
call.handleError(kError);
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
}
/**
* parse the server's response and let the call process it.
* @param result server's response
*/
protected function handleResult(result:XML):void {
clean();
var error:KalturaError = validateKalturaResponse(result);
if (error == null) {
var digestedResult:Object = parse(result);
call.handleResult(digestedResult);
}
else {
call.handleError(error);
}
}
/**
* stop timers and clean event listeners
*/
protected function clean():void {
if (call.useTimeout) {
connectTimer.stop();
loadTimer.stop();
}
if (loader == null) {
return;
}
loader.removeEventListener(Event.COMPLETE, onDataComplete);
loader.removeEventListener(IOErrorEvent.IO_ERROR, onError);
loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
loader.removeEventListener(Event.OPEN, onOpen);
}
/**
* create the correct object and populate it with the given values. if the needed class is not found
* in the file, a generic object is created with attributes matching the XML attributes.
* Override this parssing function in the specific delegate to create the correct object.
* @param result instance attributes
* @return an instance of the class declared by the given XML.
* */
public function parse(result:XML):* {
//by defualt create the response object
var cls:Class;
try {
cls = getDefinitionByName('com.kaltura.vo.' + result.result.objectType) as Class;
}
catch (e:Error) {
cls = Object;
}
var obj:* = (new KClassFactory(cls)).newInstanceFromXML(result.result);
return obj;
}
/**
* If the result string holds an error, return a KalturaError object with
* relevant values. <br/>
* Overide this to create validation object and fill it.
* @param result the string returned from the server.
* @return matching error object
*/
protected function validateKalturaResponse(result:String):KalturaError {
var kError:KalturaError = null;
var xml:XML = XML(result);
if (xml.result.hasOwnProperty('error')
&& xml.result.error.hasOwnProperty('code')
&& xml.result.error.hasOwnProperty('message')) {
kError = new KalturaError();
kError.errorCode = String(xml.result.error.code);
kError.errorMsg = xml.result.error.message;
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
}
return kError;
}
/**
* create error object and fill it with relevant details
* @param event
* @param loaderData
* @return detailed KalturaError to be processed
*/
protected function createKalturaError(event:ErrorEvent, loaderData:*):KalturaError {
var ke:KalturaError = new KalturaError();
ke.errorMsg = event.text;
return ke;
}
/**
* create the url that is used for serve actions
* @param call the KalturaCall that defines the required parameters
* @return URLRequest with relevant parameters
* */
public function getServeUrl(call:KalturaCall):URLRequest {
var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action;
for (var key:String in call.args) {
url += "&" + key + "=" + call.args[key];
}
var req:URLRequest = new URLRequest(url);
req.contentType = "application/x-www-form-urlencoded";
req.method = call.method;
// req.data = call.args;
return req;
}
}
}
|
increase connect timeout to 120 secs
|
fwr: increase connect timeout to 120 secs
git-svn-id: 8a2ccb88241e16c78017770bc38d91d6d5396a5a@94136 6b8eccd3-e8c5-4e7d-8186-e12b5326b719
|
ActionScript
|
agpl-3.0
|
matsuu/server,gale320/server,DBezemer/server,ratliff/server,DBezemer/server,gale320/server,gale320/server,ivesbai/server,doubleshot/server,ivesbai/server,jorgevbo/server,ivesbai/server,DBezemer/server,jorgevbo/server,matsuu/server,ratliff/server,gale320/server,doubleshot/server,matsuu/server,matsuu/server,DBezemer/server,ivesbai/server,ratliff/server,ratliff/server,jorgevbo/server,jorgevbo/server,ivesbai/server,doubleshot/server,ivesbai/server,matsuu/server,doubleshot/server,ivesbai/server,jorgevbo/server,ratliff/server,gale320/server,kaltura/server,doubleshot/server,ivesbai/server,ratliff/server,doubleshot/server,matsuu/server,gale320/server,DBezemer/server,DBezemer/server,jorgevbo/server,jorgevbo/server,kaltura/server,DBezemer/server,gale320/server,kaltura/server,matsuu/server,DBezemer/server,ratliff/server,gale320/server,kaltura/server,jorgevbo/server,kaltura/server,kaltura/server,ratliff/server,doubleshot/server,matsuu/server,doubleshot/server
|
2e8818e3b5fb87394a756f70d1fb2d04d51d8323
|
src/as/com/threerings/cast/CharacterManager.as
|
src/as/com/threerings/cast/CharacterManager.as
|
//
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/nenya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.cast {
import flash.geom.Point;
import com.threerings.util.Hashable;
import com.threerings.util.Log;
import com.threerings.util.Map;
import com.threerings.util.StringUtil;
import com.threerings.util.Maps;
import com.threerings.util.maps.LRMap;
/**
* The character manager provides facilities for constructing sprites that
* are used to represent characters in a scene. It also handles the
* compositing and caching of composited character animations.
*/
public class CharacterManager
{
private static var log :Log = Log.getLog(CharacterManager);
/**
* Constructs the character manager.
*/
public function CharacterManager (crepo :ComponentRepository)
{
// keep this around
_crepo = crepo;
for each (var action :ActionSequence in crepo.getActionSequences()) {
_actions.put(action.name, action);
}
}
/**
* Returns a {@link CharacterSprite} representing the character
* described by the given {@link CharacterDescriptor}, or
* <code>null</code> if an error occurs.
*
* @param desc the character descriptor.
*/
public function getCharacter (desc :CharacterDescriptor,
charClass :Class = null) :CharacterSprite
{
if (charClass == null) {
charClass = _charClass;
}
try {
var sprite :CharacterSprite = new charClass();
sprite.init(desc, this);
return sprite;
} catch (e :Error) {
log.warning("Failed to instantiate character sprite.", e);
return null;
}
return getCharacter(desc, charClass);
}
public function getActionSequence (action :String) :ActionSequence
{
return _actions.get(action);
}
public function getActionFrames (descrip :CharacterDescriptor, action :String) :ActionFrames
{
if (!isLoaded(descrip)) {
return null;
}
var key :FrameKey = new FrameKey(descrip, action);
var frames :ActionFrames = _actionFrames.get(key);
if (frames == null) {
// this doesn't actually composite the images, but prepares an
// object to be able to do so
frames = createCompositeFrames(descrip, action);
_actionFrames.put(key, frames);
}
return frames;
}
/**
* Returns whether all the components are loaded and ready to go.
*/
protected function isLoaded (descrip :CharacterDescriptor) :Boolean
{
var cids :Array = descrip.getComponentIds();
var ccount :int = cids.length;
for (var ii :int = 0; ii < ccount; ii++) {
var ccomp :CharacterComponent = _crepo.getComponent(cids[ii]);
if (!ccomp.isLoaded()) {
return false;
}
}
return true;
}
public function load (descrip :CharacterDescriptor, notify :Function) :void
{
_crepo.load(descrip.getComponentIds(), notify);
}
protected function createCompositeFrames (descrip :CharacterDescriptor,
action :String) :ActionFrames
{
var cids :Array = descrip.getComponentIds();
var ccount :int = cids.length;
var zations :Array = descrip.getColorizations();
var xlations :Array = descrip.getTranslations();
log.debug("Compositing action [action=" + action +
", descrip=" + descrip + "].");
// this will be used to construct any shadow layers
var shadows :Map = null; /* of String, Array<TranslatedComponent> */
// maps components by class name for masks
var ccomps :Map = Maps.newMapOf(String); /* of String, ArrayList<TranslatedComponent> */
// create colorized versions of all of the source action frames
var sources :Array = [];
for (var ii :int = 0; ii < ccount; ii++) {
var cframes :ComponentFrames = new ComponentFrames();
sources.push(cframes);
var ccomp :CharacterComponent = cframes.ccomp = _crepo.getComponent(cids[ii]);
// load up the main component images
var source :ActionFrames = ccomp.getFrames(action, null);
if (source == null) {
var errmsg :String = "Cannot composite action frames; no such " +
"action for component [action=" + action +
", desc=" + descrip + ", comp=" + ccomp + "]";
throw new Error(errmsg);
}
source = (zations == null || zations[ii] == null) ?
source : source.cloneColorized(zations[ii]);
var xlation :Point = (xlations == null) ? null : xlations[ii];
cframes.frames = (xlation == null) ?
source : source.cloneTranslated(xlation.x, xlation.y);
// store the component with its translation under its class for masking
var tcomp :TranslatedComponent = new TranslatedComponent(ccomp, xlation);
var tcomps :Array = ccomps.get(ccomp.componentClass.name);
if (tcomps == null) {
ccomps.put(ccomp.componentClass.name, tcomps = []);
}
tcomps.push(tcomp);
// if this component has a shadow, make a note of it
if (ccomp.componentClass.isShadowed()) {
if (shadows == null) {
shadows = Maps.newMapOf(String);
}
var shadlist :Array = shadows.get(ccomp.componentClass.shadow);
if (shadlist == null) {
shadows.put(ccomp.componentClass.shadow, shadlist = []);
}
shadlist.push(tcomp);
}
}
/* TODO - Implement shadows & masks - I don't actually know if/where we use these, though.
// now create any necessary shadow layers
if (shadows != null) {
for (Map.Entry<String, ArrayList<TranslatedComponent>> entry : shadows.entrySet()) {
ComponentFrames scf = compositeShadow(action, entry.getKey(), entry.getValue());
if (scf != null) {
sources.add(scf);
}
}
}
// add any necessary masks
for (ComponentFrames cframes : sources) {
ArrayList<TranslatedComponent> mcomps = ccomps.get(cframes.ccomp.componentClass.mask);
if (mcomps != null) {
cframes.frames = compositeMask(action, cframes.ccomp, cframes.frames, mcomps);
}
}
*/
// use those to create an entity that will lazily composite things
// together as they are needed
return new CompositedActionFrames(_frameCache, _actions.get(action), sources);
}
protected var _crepo :ComponentRepository;
protected var _actions :Map = Maps.newMapOf(String);
protected var _actionFrames :Map = Maps.newMapOf(FrameKey);
protected var _frameCache :LRMap = new LRMap(Maps.newMapOf(CompositedFramesKey), MAX_FRAMES);
protected var _charClass :Class;
protected static const MAX_FRAMES :int = 1000;
}
}
import com.threerings.util.Hashable;
import com.threerings.util.StringUtil;
import com.threerings.cast.CharacterDescriptor;
class FrameKey
implements Hashable
{
public var desc :CharacterDescriptor;
public var action :String;
public function FrameKey (desc :CharacterDescriptor, action :String)
{
this.desc = desc;
this.action = action;
}
public function hashCode () :int
{
return desc.hashCode() ^ StringUtil.hashCode(action);
}
public function equals (other :Object) :Boolean
{
if (other is FrameKey) {
var okey :FrameKey = FrameKey(other);
return okey.desc.equals(desc) && okey.action == action;
} else {
return false;
}
}
}
import flash.geom.Point;
import com.threerings.cast.ActionFrames;
import com.threerings.cast.CharacterComponent;
class TranslatedComponent
{
public var ccomp :CharacterComponent;
public var xlation :Point;
public function TranslatedComponent (ccomp :CharacterComponent, xlation :Point)
{
this.ccomp = ccomp;
this.xlation = xlation;
}
public function getFrames (action :String, type :String) :ActionFrames
{
var frames :ActionFrames = ccomp.getFrames(action, type);
return (frames == null || xlation == null) ?
frames : frames.cloneTranslated(xlation.x, xlation.y);
}
}
|
//
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/nenya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.cast {
import flash.geom.Point;
import com.threerings.util.Hashable;
import com.threerings.util.Log;
import com.threerings.util.Map;
import com.threerings.util.StringUtil;
import com.threerings.util.Maps;
import com.threerings.util.maps.LRMap;
/**
* The character manager provides facilities for constructing sprites that
* are used to represent characters in a scene. It also handles the
* compositing and caching of composited character animations.
*/
public class CharacterManager
{
private static var log :Log = Log.getLog(CharacterManager);
/**
* Constructs the character manager.
*/
public function CharacterManager (crepo :ComponentRepository)
{
// keep this around
_crepo = crepo;
for each (var action :ActionSequence in crepo.getActionSequences()) {
_actions.put(action.name, action);
}
}
/**
* Returns a {@link CharacterSprite} representing the character
* described by the given {@link CharacterDescriptor}, or
* <code>null</code> if an error occurs.
*
* @param desc the character descriptor.
*/
public function getCharacter (desc :CharacterDescriptor,
charClass :Class = null) :CharacterSprite
{
if (charClass == null) {
charClass = _charClass;
}
try {
var sprite :CharacterSprite = new charClass();
sprite.init(desc, this);
return sprite;
} catch (e :Error) {
log.warning("Failed to instantiate character sprite.", e);
return null;
}
return getCharacter(desc, charClass);
}
public function getActionSequence (action :String) :ActionSequence
{
return _actions.get(action);
}
public function getComponent (compId :int) :CharacterComponent
{
return _crepo.getComponent(compId);
}
public function getActionFrames (descrip :CharacterDescriptor, action :String) :ActionFrames
{
if (!isLoaded(descrip)) {
return null;
}
var key :FrameKey = new FrameKey(descrip, action);
var frames :ActionFrames = _actionFrames.get(key);
if (frames == null) {
// this doesn't actually composite the images, but prepares an
// object to be able to do so
frames = createCompositeFrames(descrip, action);
_actionFrames.put(key, frames);
}
return frames;
}
/**
* Returns whether all the components are loaded and ready to go.
*/
protected function isLoaded (descrip :CharacterDescriptor) :Boolean
{
var cids :Array = descrip.getComponentIds();
var ccount :int = cids.length;
for (var ii :int = 0; ii < ccount; ii++) {
var ccomp :CharacterComponent = _crepo.getComponent(cids[ii]);
if (!ccomp.isLoaded()) {
return false;
}
}
return true;
}
public function load (descrip :CharacterDescriptor, notify :Function) :void
{
_crepo.load(descrip.getComponentIds(), notify);
}
protected function createCompositeFrames (descrip :CharacterDescriptor,
action :String) :ActionFrames
{
var cids :Array = descrip.getComponentIds();
var ccount :int = cids.length;
var zations :Array = descrip.getColorizations();
var xlations :Array = descrip.getTranslations();
log.debug("Compositing action [action=" + action +
", descrip=" + descrip + "].");
// this will be used to construct any shadow layers
var shadows :Map = null; /* of String, Array<TranslatedComponent> */
// maps components by class name for masks
var ccomps :Map = Maps.newMapOf(String); /* of String, ArrayList<TranslatedComponent> */
// create colorized versions of all of the source action frames
var sources :Array = [];
for (var ii :int = 0; ii < ccount; ii++) {
var cframes :ComponentFrames = new ComponentFrames();
sources.push(cframes);
var ccomp :CharacterComponent = cframes.ccomp = _crepo.getComponent(cids[ii]);
// load up the main component images
var source :ActionFrames = ccomp.getFrames(action, null);
if (source == null) {
var errmsg :String = "Cannot composite action frames; no such " +
"action for component [action=" + action +
", desc=" + descrip + ", comp=" + ccomp + "]";
throw new Error(errmsg);
}
source = (zations == null || zations[ii] == null) ?
source : source.cloneColorized(zations[ii]);
var xlation :Point = (xlations == null) ? null : xlations[ii];
cframes.frames = (xlation == null) ?
source : source.cloneTranslated(xlation.x, xlation.y);
// store the component with its translation under its class for masking
var tcomp :TranslatedComponent = new TranslatedComponent(ccomp, xlation);
var tcomps :Array = ccomps.get(ccomp.componentClass.name);
if (tcomps == null) {
ccomps.put(ccomp.componentClass.name, tcomps = []);
}
tcomps.push(tcomp);
// if this component has a shadow, make a note of it
if (ccomp.componentClass.isShadowed()) {
if (shadows == null) {
shadows = Maps.newMapOf(String);
}
var shadlist :Array = shadows.get(ccomp.componentClass.shadow);
if (shadlist == null) {
shadows.put(ccomp.componentClass.shadow, shadlist = []);
}
shadlist.push(tcomp);
}
}
/* TODO - Implement shadows & masks - I don't actually know if/where we use these, though.
// now create any necessary shadow layers
if (shadows != null) {
for (Map.Entry<String, ArrayList<TranslatedComponent>> entry : shadows.entrySet()) {
ComponentFrames scf = compositeShadow(action, entry.getKey(), entry.getValue());
if (scf != null) {
sources.add(scf);
}
}
}
// add any necessary masks
for (ComponentFrames cframes : sources) {
ArrayList<TranslatedComponent> mcomps = ccomps.get(cframes.ccomp.componentClass.mask);
if (mcomps != null) {
cframes.frames = compositeMask(action, cframes.ccomp, cframes.frames, mcomps);
}
}
*/
// use those to create an entity that will lazily composite things
// together as they are needed
return new CompositedActionFrames(_frameCache, _actions.get(action), sources);
}
protected var _crepo :ComponentRepository;
protected var _actions :Map = Maps.newMapOf(String);
protected var _actionFrames :Map = Maps.newMapOf(FrameKey);
protected var _frameCache :LRMap = new LRMap(Maps.newMapOf(CompositedFramesKey), MAX_FRAMES);
protected var _charClass :Class;
protected static const MAX_FRAMES :int = 1000;
}
}
import com.threerings.util.Hashable;
import com.threerings.util.StringUtil;
import com.threerings.cast.CharacterDescriptor;
class FrameKey
implements Hashable
{
public var desc :CharacterDescriptor;
public var action :String;
public function FrameKey (desc :CharacterDescriptor, action :String)
{
this.desc = desc;
this.action = action;
}
public function hashCode () :int
{
return desc.hashCode() ^ StringUtil.hashCode(action);
}
public function equals (other :Object) :Boolean
{
if (other is FrameKey) {
var okey :FrameKey = FrameKey(other);
return okey.desc.equals(desc) && okey.action == action;
} else {
return false;
}
}
}
import flash.geom.Point;
import com.threerings.cast.ActionFrames;
import com.threerings.cast.CharacterComponent;
class TranslatedComponent
{
public var ccomp :CharacterComponent;
public var xlation :Point;
public function TranslatedComponent (ccomp :CharacterComponent, xlation :Point)
{
this.ccomp = ccomp;
this.xlation = xlation;
}
public function getFrames (action :String, type :String) :ActionFrames
{
var frames :ActionFrames = ccomp.getFrames(action, type);
return (frames == null || xlation == null) ?
frames : frames.cloneTranslated(xlation.x, xlation.y);
}
}
|
Allow access to getComponent through the character manager rather than having to go through the repository.
|
Allow access to getComponent through the character manager rather than having to go through the repository.
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@994 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
7cb9da4e20a6e8eac37f0c77115332db2a896e9c
|
generator/sources/as3/com/kaltura/delegates/WebDelegateBase.as
|
generator/sources/as3/com/kaltura/delegates/WebDelegateBase.as
|
// ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2011 Kaltura Inc.
//
// 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/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.delegates {
import com.kaltura.config.IKalturaConfig;
import com.kaltura.config.KalturaConfig;
import com.kaltura.core.KClassFactory;
import com.kaltura.errors.KalturaError;
import com.kaltura.events.KalturaEvent;
import com.kaltura.net.KalturaCall;
import com.kaltura.encryption.MD5;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.events.TimerEvent;
import flash.net.FileReference;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.utils.Timer;
import flash.utils.getDefinitionByName;
public class WebDelegateBase extends EventDispatcher implements IKalturaCallDelegate {
public static var CONNECT_TIME:int = 60000; //60 secs
public static var LOAD_TIME:int = 120000; //120 secs
protected var connectTimer:Timer;
protected var loadTimer:Timer;
protected var _call:KalturaCall;
protected var _config:KalturaConfig;
protected var loader:URLLoader;
protected var fileRef:FileReference;
//Setters & getters
public function get call():KalturaCall {
return _call;
}
public function set call(newVal:KalturaCall):void {
_call = newVal;
}
public function get config():IKalturaConfig {
return _config;
}
public function set config(newVal:IKalturaConfig):void {
_config = newVal as KalturaConfig;
}
public function WebDelegateBase(call:KalturaCall = null, config:KalturaConfig = null) {
this.call = call;
this.config = config;
if (!call)
return; //maybe a multi request
if (call.useTimeout) {
connectTimer = new Timer(CONNECT_TIME, 1);
connectTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onConnectTimeout);
loadTimer = new Timer(LOAD_TIME, 1);
loadTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onLoadTimeOut);
}
execute();
}
public function close():void {
try {
loader.close();
}
catch (e:*) {
}
if (call.useTimeout) {
connectTimer.stop();
loadTimer.stop();
}
}
protected function onConnectTimeout(event:TimerEvent):void {
var kError:KalturaError = new KalturaError();
kError.errorCode = "KMC_CONNECTION_TIMEOUT";
kError.errorMsg = "Connection Timeout: " + CONNECT_TIME / 1000 + " sec with no post command from kaltura client.";
_call.handleError(kError);
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
loadTimer.stop();
close();
}
protected function onLoadTimeOut(event:TimerEvent):void {
connectTimer.stop();
close();
var kError:KalturaError = new KalturaError();
kError.errorCode = "KMC_POST_TIMEOUT";
kError.errorMsg = "Post Timeout: " + LOAD_TIME / 1000 + " sec with no post result.";
_call.handleError(kError);
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
}
protected function execute():void {
if (call == null) {
throw new Error('No call defined.');
}
post(); //post the call
}
/**
* Helper function for sending the call straight to the server
*/
protected function post():void {
addOptionalArguments();
formatRequest();
sendRequest();
if (call.useTimeout) {
connectTimer.start();
}
}
protected function formatRequest():void {
//The configuration is stronger then the args
if (_config.partnerId != null && _call.args["partnerId"] == -1)
_call.setRequestArgument("partnerId", _config.partnerId);
if (_config.ks != null)
_call.setRequestArgument("ks", _config.ks);
if (_config.clientTag != null)
_call.setRequestArgument("clientTag", _config.clientTag);
_call.setRequestArgument("ignoreNull", _config.ignoreNull);
//Create signature hash.
//call.setRequestArgument("kalsig", getMD5Checksum(call));
}
protected function getMD5Checksum(call:KalturaCall):String {
var props:Array = new Array();
for each (var prop:String in call.args)
props.push(prop);
props.push("service");
props.push("action");
props.sort();
var s:String;
for each (prop in props) {
s += prop;
if (prop == "service")
s += call.service;
else if (prop == "action")
s += call.action;
else
s += call.args[prop];
}
return MD5.encrypt(s);
}
protected function sendRequest():void {
//construct the loader
createURLLoader();
//Create signature hash.
var kalsig:String = getMD5Checksum(call);
//create the service request for normal calls
var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action + "&kalsig=" + kalsig;;
if (_call.method == URLRequestMethod.GET)
url += "&";
var req:URLRequest = new URLRequest(url);
req.contentType = "application/x-www-form-urlencoded";
req.method = call.method;
req.data = call.args;
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.load(req);
}
protected function createURLLoader():void {
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onDataComplete);
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);
loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
loader.addEventListener(Event.OPEN, onOpen);
}
protected function onHTTPStatus(event:HTTPStatusEvent):void {
}
protected function onOpen(event:Event):void {
if (call.useTimeout) {
connectTimer.stop();
loadTimer.start();
}
}
protected function addOptionalArguments():void {
//add optional args here
}
// Event Handlers
protected function onDataComplete(event:Event):void {
try {
handleResult(XML(event.target.data));
}
catch (e:Error) {
var kErr:KalturaError = new KalturaError();
kErr.errorCode = String(e.errorID);
kErr.errorMsg = e.message;
_call.handleError(kErr);
}
}
protected function onError(event:ErrorEvent):void {
clean();
var kError:KalturaError = createKalturaError(event, loader.data);
if (!kError) {
kError.errorMsg = event.text;
//kError.errorCode;
}
call.handleError(kError);
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
}
/**
* parse the server's response and let the call process it.
* @param result server's response
*/
protected function handleResult(result:XML):void {
clean();
var error:KalturaError = validateKalturaResponse(result);
if (error == null) {
var digestedResult:Object = parse(result);
call.handleResult(digestedResult);
}
else {
call.handleError(error);
}
}
/**
* stop timers and clean event listeners
*/
protected function clean():void {
if (call.useTimeout) {
connectTimer.stop();
loadTimer.stop();
}
if (loader == null) {
return;
}
loader.removeEventListener(Event.COMPLETE, onDataComplete);
loader.removeEventListener(IOErrorEvent.IO_ERROR, onError);
loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
loader.removeEventListener(Event.OPEN, onOpen);
}
/**
* create the correct object and populate it with the given values. if the needed class is not found
* in the file, a generic object is created with attributes matching the XML attributes.
* Override this parssing function in the specific delegate to create the correct object.
* @param result instance attributes
* @return an instance of the class declared by the given XML.
* */
public function parse(result:XML):* {
//by defualt create the response object
var cls:Class;
try {
cls = getDefinitionByName('com.kaltura.vo.' + result.result.objectType) as Class;
}
catch (e:Error) {
cls = Object;
}
var obj:* = (new KClassFactory(cls)).newInstanceFromXML(result.result);
return obj;
}
/**
* If the result string holds an error, return a KalturaError object with
* relevant values. <br/>
* Overide this to create validation object and fill it.
* @param result the string returned from the server.
* @return matching error object
*/
protected function validateKalturaResponse(result:String):KalturaError {
var kError:KalturaError = null;
var xml:XML = XML(result);
if (xml.result.hasOwnProperty('error')) {
kError = new KalturaError();
kError.errorCode = String(xml.result.error.code);
kError.errorMsg = xml.result.error.message;
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
}
return kError;
}
//Overide this to create error object and fill it
protected function createKalturaError(event:ErrorEvent, loaderData:*):KalturaError {
var ke:KalturaError = new KalturaError();
return ke;
}
/**
* create the url that is used for serve actions
* @param call the KalturaCall that defines the required parameters
* @return URLRequest with relevant parameters
* */
public function getServeUrl(call:KalturaCall):URLRequest {
var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action;
for (var key:String in call.args) {
url += "&" + key + "=" + call.args[key];
}
var req:URLRequest = new URLRequest(url);
req.contentType = "application/x-www-form-urlencoded";
req.method = call.method;
// req.data = call.args;
return req;
}
}
}
|
// ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2011 Kaltura Inc.
//
// 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/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.delegates {
import com.kaltura.config.IKalturaConfig;
import com.kaltura.config.KalturaConfig;
import com.kaltura.core.KClassFactory;
import com.kaltura.errors.KalturaError;
import com.kaltura.events.KalturaEvent;
import com.kaltura.net.KalturaCall;
import com.kaltura.encryption.MD5;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.events.TimerEvent;
import flash.net.FileReference;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.utils.Timer;
import flash.utils.getDefinitionByName;
public class WebDelegateBase extends EventDispatcher implements IKalturaCallDelegate {
public static var CONNECT_TIME:int = 60000; //60 secs
public static var LOAD_TIME:int = 120000; //120 secs
protected var connectTimer:Timer;
protected var loadTimer:Timer;
protected var _call:KalturaCall;
protected var _config:KalturaConfig;
protected var loader:URLLoader;
protected var fileRef:FileReference;
//Setters & getters
public function get call():KalturaCall {
return _call;
}
public function set call(newVal:KalturaCall):void {
_call = newVal;
}
public function get config():IKalturaConfig {
return _config;
}
public function set config(newVal:IKalturaConfig):void {
_config = newVal as KalturaConfig;
}
public function WebDelegateBase(call:KalturaCall = null, config:KalturaConfig = null) {
this.call = call;
this.config = config;
if (!call)
return; //maybe a multi request
if (call.useTimeout) {
connectTimer = new Timer(CONNECT_TIME, 1);
connectTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onConnectTimeout);
loadTimer = new Timer(LOAD_TIME, 1);
loadTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onLoadTimeOut);
}
execute();
}
public function close():void {
try {
loader.close();
}
catch (e:*) {
}
if (call.useTimeout) {
connectTimer.stop();
loadTimer.stop();
}
}
protected function onConnectTimeout(event:TimerEvent):void {
var kError:KalturaError = new KalturaError();
kError.errorCode = "CONNECTION_TIMEOUT";
kError.errorMsg = "Connection Timeout: " + CONNECT_TIME / 1000 + " sec with no post command from kaltura client.";
_call.handleError(kError);
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
loadTimer.stop();
close();
}
protected function onLoadTimeOut(event:TimerEvent):void {
connectTimer.stop();
close();
var kError:KalturaError = new KalturaError();
kError.errorCode = "POST_TIMEOUT";
kError.errorMsg = "Post Timeout: " + LOAD_TIME / 1000 + " sec with no post result.";
_call.handleError(kError);
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
}
protected function execute():void {
if (call == null) {
throw new Error('No call defined.');
}
post(); //post the call
}
/**
* Helper function for sending the call straight to the server
*/
protected function post():void {
addOptionalArguments();
formatRequest();
sendRequest();
if (call.useTimeout) {
connectTimer.start();
}
}
protected function formatRequest():void {
//The configuration is stronger then the args
if (_config.partnerId != null && _call.args["partnerId"] == -1)
_call.setRequestArgument("partnerId", _config.partnerId);
if (_config.ks != null)
_call.setRequestArgument("ks", _config.ks);
if (_config.clientTag != null)
_call.setRequestArgument("clientTag", _config.clientTag);
_call.setRequestArgument("ignoreNull", _config.ignoreNull);
//Create signature hash.
//call.setRequestArgument("kalsig", getMD5Checksum(call));
}
protected function getMD5Checksum(call:KalturaCall):String {
var props:Array = new Array();
for each (var prop:String in call.args)
props.push(prop);
props.push("service");
props.push("action");
props.sort();
var s:String;
for each (prop in props) {
s += prop;
if (prop == "service")
s += call.service;
else if (prop == "action")
s += call.action;
else
s += call.args[prop];
}
return MD5.encrypt(s);
}
protected function sendRequest():void {
//construct the loader
createURLLoader();
//Create signature hash.
var kalsig:String = getMD5Checksum(call);
//create the service request for normal calls
var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action + "&kalsig=" + kalsig;;
if (_call.method == URLRequestMethod.GET)
url += "&";
var req:URLRequest = new URLRequest(url);
req.contentType = "application/x-www-form-urlencoded";
req.method = call.method;
req.data = call.args;
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.load(req);
}
protected function createURLLoader():void {
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onDataComplete);
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);
loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
loader.addEventListener(Event.OPEN, onOpen);
}
protected function onHTTPStatus(event:HTTPStatusEvent):void {
}
protected function onOpen(event:Event):void {
if (call.useTimeout) {
connectTimer.stop();
loadTimer.start();
}
}
protected function addOptionalArguments():void {
//add optional args here
}
// Event Handlers
protected function onDataComplete(event:Event):void {
try {
handleResult(XML(event.target.data));
}
catch (e:Error) {
var kErr:KalturaError = new KalturaError();
kErr.errorCode = String(e.errorID);
kErr.errorMsg = e.message;
_call.handleError(kErr);
}
}
protected function onError(event:ErrorEvent):void {
clean();
var kError:KalturaError = createKalturaError(event, loader.data);
if (!kError) {
kError.errorMsg = event.text;
//kError.errorCode;
}
call.handleError(kError);
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
}
/**
* parse the server's response and let the call process it.
* @param result server's response
*/
protected function handleResult(result:XML):void {
clean();
var error:KalturaError = validateKalturaResponse(result);
if (error == null) {
var digestedResult:Object = parse(result);
call.handleResult(digestedResult);
}
else {
call.handleError(error);
}
}
/**
* stop timers and clean event listeners
*/
protected function clean():void {
if (call.useTimeout) {
connectTimer.stop();
loadTimer.stop();
}
if (loader == null) {
return;
}
loader.removeEventListener(Event.COMPLETE, onDataComplete);
loader.removeEventListener(IOErrorEvent.IO_ERROR, onError);
loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
loader.removeEventListener(Event.OPEN, onOpen);
}
/**
* create the correct object and populate it with the given values. if the needed class is not found
* in the file, a generic object is created with attributes matching the XML attributes.
* Override this parssing function in the specific delegate to create the correct object.
* @param result instance attributes
* @return an instance of the class declared by the given XML.
* */
public function parse(result:XML):* {
//by defualt create the response object
var cls:Class;
try {
cls = getDefinitionByName('com.kaltura.vo.' + result.result.objectType) as Class;
}
catch (e:Error) {
cls = Object;
}
var obj:* = (new KClassFactory(cls)).newInstanceFromXML(result.result);
return obj;
}
/**
* If the result string holds an error, return a KalturaError object with
* relevant values. <br/>
* Overide this to create validation object and fill it.
* @param result the string returned from the server.
* @return matching error object
*/
protected function validateKalturaResponse(result:String):KalturaError {
var kError:KalturaError = null;
var xml:XML = XML(result);
if (xml.result.hasOwnProperty('error')) {
kError = new KalturaError();
kError.errorCode = String(xml.result.error.code);
kError.errorMsg = xml.result.error.message;
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
}
return kError;
}
//Overide this to create error object and fill it
protected function createKalturaError(event:ErrorEvent, loaderData:*):KalturaError {
var ke:KalturaError = new KalturaError();
return ke;
}
/**
* create the url that is used for serve actions
* @param call the KalturaCall that defines the required parameters
* @return URLRequest with relevant parameters
* */
public function getServeUrl(call:KalturaCall):URLRequest {
var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action;
for (var key:String in call.args) {
url += "&" + key + "=" + call.args[key];
}
var req:URLRequest = new URLRequest(url);
req.contentType = "application/x-www-form-urlencoded";
req.method = call.method;
// req.data = call.args;
return req;
}
}
}
|
change error code (no "KMC")
|
qnd: change error code (no "KMC")
git-svn-id: 8a2ccb88241e16c78017770bc38d91d6d5396a5a@86268 6b8eccd3-e8c5-4e7d-8186-e12b5326b719
|
ActionScript
|
agpl-3.0
|
doubleshot/server,matsuu/server,ivesbai/server,gale320/server,ratliff/server,kaltura/server,gale320/server,kaltura/server,matsuu/server,ivesbai/server,gale320/server,ratliff/server,ratliff/server,DBezemer/server,jorgevbo/server,ratliff/server,gale320/server,ivesbai/server,doubleshot/server,ivesbai/server,matsuu/server,matsuu/server,ivesbai/server,doubleshot/server,doubleshot/server,gale320/server,DBezemer/server,jorgevbo/server,DBezemer/server,doubleshot/server,ratliff/server,gale320/server,kaltura/server,gale320/server,ratliff/server,kaltura/server,DBezemer/server,ivesbai/server,jorgevbo/server,matsuu/server,jorgevbo/server,ivesbai/server,doubleshot/server,ratliff/server,matsuu/server,doubleshot/server,gale320/server,jorgevbo/server,jorgevbo/server,matsuu/server,ratliff/server,DBezemer/server,jorgevbo/server,DBezemer/server,ivesbai/server,DBezemer/server,DBezemer/server,jorgevbo/server,kaltura/server,kaltura/server,matsuu/server,doubleshot/server
|
666e2bc4f8b67dfb63ed6887148fc62fdbe11e58
|
src/com/ryanberdeen/echonest/api/v3/ApiSupport.as
|
src/com/ryanberdeen/echonest/api/v3/ApiSupport.as
|
/*
* Copyright 2009 Ryan Berdeen. All rights reserved.
* Distributed under the terms of the MIT License.
* See accompanying file LICENSE.txt
*/
package com.ryanberdeen.echonest.api.v3 {
import flash.events.Event;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.net.URLVariables;
/**
* Base class for Echo Nest API classes.
*/
public class ApiSupport {
public static const API_VERSION:int = 3;
/**
* @private
*/
protected var _baseUrl:String = 'http://developer.echonest.com/api/';
/**
* @private
*/
protected var _apiKey:String;
/**
* The API key to use for Echo Nest API requests.
*/
public function set apiKey(apiKey:String):void {
_apiKey = apiKey;
}
/**
* Creates a request for an Echo Nest API method call with a set of
* parameters.
*
* @param method The method to call.
* @param parameters The parameters to include in the request.
*
* @return The request to use to call the method.
*/
public function createRequest(method:String, parameters:Object):URLRequest {
var variables:URLVariables = new URLVariables;
variables.api_key = _apiKey;
variables.version = API_VERSION;
for (var name:String in parameters) {
variables[name] = parameters[name];
}
var request:URLRequest = new URLRequest();
request.url = _baseUrl + method;
request.data = variables;
request.requestHeaders = new Array(new URLRequestHeader('X-User-Agent', 'echo-nest-flash-api'));
return request;
}
/**
* Creates a loader with event listeners.
*
* <p>The following options are supported:</p>
*
* <table><thead><tr><th>Option</th><th>Event</th></tr></thead><tbody>
* <tr>
* <td>onComplete</td>
* <td><code>Event.COMPLETE</code></td>
* </tr>
* <tr>
* <td>onResponse</td>
* <td>Called with the processed response.</td>
* </tr>
* <tr>
* <td>onEchoNestError</td>
* <td>Called with an <code>EchoNestError</code> if the status code is nonzero</td>
* </tr>
* <tr>
* <td>onProgress</td>
* <td><code>ProgressEvent.PROGRESS</code></td>
* </tr>
* <tr>
* <td>onSecurityError</td>
* <td><code>SecurityErrorEvent.SECURITY_ERROR</code></td>
* </tr>
* <tr>
* <td>onIoError</td>
* <td><code>IOErrorEvent.IO_ERROR</code></td>
* </tr>
* <tr>
* <td>onError</td>
* <td><code>IOErrorEvent.IO_ERROR</code><br/> <code>SecurityErrorEvent.SECURITY_ERROR</code></td>
* </tr>
* <tr>
* <td>onHttpStatus</td>
* <td><code>HTTPStatusEvent.HTTP_STATUS</code></td>
* </tr>
* </tbody></table>
*
* @param options The event listener options.
* @param responseProcessor The function that processes the XML response.
*/
public function createLoader(options:Object, responseProcessor:Function = null, ...responseProcessorArgs):URLLoader {
var loader:URLLoader = new URLLoader();
if (options.onComplete) {
loader.addEventListener(Event.COMPLETE, options.onComplete);
}
if (responseProcessor != null && options.onResponse) {
loader.addEventListener(Event.COMPLETE, function(e:Event):void {
try {
var responseXml:XML = new XML(loader.data);
checkStatus(responseXml);
responseProcessorArgs.push(responseXml);
var response:Object = responseProcessor.apply(responseProcessor, responseProcessorArgs);
options.onResponse(response);
}
catch (e:EchoNestError) {
if (options.onEchoNestError) {
options.onEchoNestError(e);
}
}
});
}
if (options.onProgress) {
loader.addEventListener(ProgressEvent.PROGRESS, options.onProgress);
}
if (options.onSecurityError) {
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, options.onSecurityError);
}
if (options.onIoError) {
loader.addEventListener(IOErrorEvent.IO_ERROR, options.onIoError);
}
if (options.onError) {
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, options.onError);
loader.addEventListener(IOErrorEvent.IO_ERROR, options.onError);
}
if (options.onHttpStatus) {
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, options.onHttpStatus);
}
return loader;
}
/**
* Throws an <code>EchoNestError</code> if the status indicates an error.
*
* @param The XML result of an Echo Nest API call.
*
* @throws EchoNestError When the status code is nonzero.
*/
public function checkStatus(response:XML):void {
if (response.status.code != 0) {
throw new EchoNestError(response.status.code, response.status.message);
}
}
}
}
|
/*
* Copyright 2009 Ryan Berdeen. All rights reserved.
* Distributed under the terms of the MIT License.
* See accompanying file LICENSE.txt
*/
package com.ryanberdeen.echonest.api.v3 {
import flash.events.Event;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.net.URLVariables;
/**
* Base class for Echo Nest API classes.
*/
public class ApiSupport {
public static const API_VERSION:int = 3;
/**
* @private
*/
protected var _baseUrl:String = 'http://developer.echonest.com/api/';
/**
* @private
*/
protected var _apiKey:String;
/**
* The API key to use for Echo Nest API requests.
*/
public function set apiKey(apiKey:String):void {
_apiKey = apiKey;
}
/**
* Creates a request for an Echo Nest API method call with a set of
* parameters.
*
* @param method The method to call.
* @param parameters The parameters to include in the request.
*
* @return The request to use to call the method.
*/
public function createRequest(method:String, parameters:Object):URLRequest {
var variables:URLVariables = new URLVariables;
variables.api_key = _apiKey;
variables.version = API_VERSION;
for (var name:String in parameters) {
variables[name] = parameters[name];
}
var request:URLRequest = new URLRequest();
request.url = _baseUrl + method;
request.data = variables;
return request;
}
/**
* Creates a loader with event listeners.
*
* <p>The following options are supported:</p>
*
* <table><thead><tr><th>Option</th><th>Event</th></tr></thead><tbody>
* <tr>
* <td>onComplete</td>
* <td><code>Event.COMPLETE</code></td>
* </tr>
* <tr>
* <td>onResponse</td>
* <td>Called with the processed response.</td>
* </tr>
* <tr>
* <td>onEchoNestError</td>
* <td>Called with an <code>EchoNestError</code> if the status code is nonzero</td>
* </tr>
* <tr>
* <td>onProgress</td>
* <td><code>ProgressEvent.PROGRESS</code></td>
* </tr>
* <tr>
* <td>onSecurityError</td>
* <td><code>SecurityErrorEvent.SECURITY_ERROR</code></td>
* </tr>
* <tr>
* <td>onIoError</td>
* <td><code>IOErrorEvent.IO_ERROR</code></td>
* </tr>
* <tr>
* <td>onError</td>
* <td><code>IOErrorEvent.IO_ERROR</code><br/> <code>SecurityErrorEvent.SECURITY_ERROR</code></td>
* </tr>
* <tr>
* <td>onHttpStatus</td>
* <td><code>HTTPStatusEvent.HTTP_STATUS</code></td>
* </tr>
* </tbody></table>
*
* @param options The event listener options.
* @param responseProcessor The function that processes the XML response.
*/
public function createLoader(options:Object, responseProcessor:Function = null, ...responseProcessorArgs):URLLoader {
var loader:URLLoader = new URLLoader();
if (options.onComplete) {
loader.addEventListener(Event.COMPLETE, options.onComplete);
}
if (responseProcessor != null && options.onResponse) {
loader.addEventListener(Event.COMPLETE, function(e:Event):void {
try {
var responseXml:XML = new XML(loader.data);
checkStatus(responseXml);
responseProcessorArgs.push(responseXml);
var response:Object = responseProcessor.apply(responseProcessor, responseProcessorArgs);
options.onResponse(response);
}
catch (e:EchoNestError) {
if (options.onEchoNestError) {
options.onEchoNestError(e);
}
}
});
}
if (options.onProgress) {
loader.addEventListener(ProgressEvent.PROGRESS, options.onProgress);
}
if (options.onSecurityError) {
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, options.onSecurityError);
}
if (options.onIoError) {
loader.addEventListener(IOErrorEvent.IO_ERROR, options.onIoError);
}
if (options.onError) {
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, options.onError);
loader.addEventListener(IOErrorEvent.IO_ERROR, options.onError);
}
if (options.onHttpStatus) {
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, options.onHttpStatus);
}
return loader;
}
/**
* Throws an <code>EchoNestError</code> if the status indicates an error.
*
* @param The XML result of an Echo Nest API call.
*
* @throws EchoNestError When the status code is nonzero.
*/
public function checkStatus(response:XML):void {
if (response.status.code != 0) {
throw new EchoNestError(response.status.code, response.status.message);
}
}
}
}
|
remove request header
|
remove request header
|
ActionScript
|
mit
|
also/echo-nest-flash-api
|
e9ec904342f2361df19f04e9d209fe1d8ed7ce2f
|
dolly-framework/src/test/resources/dolly/data/CompositeCloneableClass.as
|
dolly-framework/src/test/resources/dolly/data/CompositeCloneableClass.as
|
package dolly.data {
import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
[Cloneable]
public class CompositeCloneableClass {
public var cloneable:CloneableClass = new CloneableClass();
public var array:Array = [0, 1, 2, 3, 4];
public var arrayList:ArrayList = new ArrayList([0, 1, 2, 3, 4]);
public var arrayCollection:ArrayCollection = new ArrayCollection([0, 1, 2, 3, 4]);
public function CompositeCloneableClass() {
}
}
}
|
package dolly.data {
import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
[Cloneable]
public class CompositeCloneableClass {
public var cloneable:CloneableClass;
public var array:Array = [0, 1, 2, 3, 4];
public var arrayList:ArrayList = new ArrayList([0, 1, 2, 3, 4]);
public var arrayCollection:ArrayCollection = new ArrayCollection([0, 1, 2, 3, 4]);
public function CompositeCloneableClass() {
}
}
}
|
Remove default instantiation of CompositeCloneableClass.cloneable field.
|
Remove default instantiation of CompositeCloneableClass.cloneable field.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
a87286b2215fc2b7b2cd0644459b5e53c842c93e
|
WEB-INF/lps/lfc/kernel/swf/LzMakeLoadSprite.as
|
WEB-INF/lps/lfc/kernel/swf/LzMakeLoadSprite.as
|
/**
* LzMakeLoadSprite.as
*
* @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic AS2
*/
/**
* @access private
*/
function LzMakeLoadSprite( ){
}
LzMakeLoadSprite.transformerID = 0;
/**
* Makes the given view able to load a remote resource
*/
LzMakeLoadSprite.transform = function ( v , src , cache, headers, filetype ){
//super.transform( v );
for ( var k in this){
if (typeof v[k] == 'function' && this[k]) {
// replace old method with _methodname to support super
//Debug.write('replacing _' + k + ' with ' + k + ' in ' + v);
v[ '___' + k ] = v[k];
v[k] = this[k];
} else {
//Debug.write('adding ' + k + ' to ' + v);
v[k] = this[k];
}
}
// Debug.trace(v, 'setHeight');
// Debug.trace(v, 'setWidth');
// Debug.monitor(v, 'resourcewidth')
// Debug.monitor(v, 'resourceheight')
// Debug.monitor(v, '_xscale')
// Debug.monitor(v, '_yscale')
v.firstsrc = src;
v.firstcache = cache;
v.firstheaders = headers;
v.firstfiletype = filetype;
if ( v.__LZmovieClipRef == null ){
v.makeContainerResource();
}
if (v.__LZhaser ){
v.createLoader();
} else {
//the view doesn't have the empty resource. We need to try and replace
//it
v.makeContainerResource();
if (! this.loader) v.createLoader();
}
// var mc = v.__LZmovieClipRef;
// Debug.debug(mc, '_width', mc._width);
// Debug.debug(mc, '_height', mc._height);
// Debug.debug(mc, '_xscale', mc._xscale);
// Debug.debug(mc, '_yscale', mc._yscale);
}
/**
* @access private
*/
LzMakeLoadSprite.doReplaceResource = function (){
//this gets called when a view applies the load transformer but it
//already had a resource
// use shadowed doReplaceResource()
this.___doReplaceResource( );
if (this._newrescname.indexOf('http:') == 0 || this._newrescname.indexOf('https:') == 0){
this.createLoader();
}
}
/**
* @access private
*/
LzMakeLoadSprite.createLoader = function (){
this.loader = new LzMediaLoader( this , {} );
this.updateDel = new LzDelegate( this , "updateAfterLoad" );
this.updateDel.register( this.loader , "onloaddone" );
this.errorDel = new LzDelegate( this , "__LZsendError" );
this.errorDel.register( this.loader , "onerror" );
this.timeoutDel = new LzDelegate( this , "__LZsendTimeout" );
this.timeoutDel.register( this.loader , "ontimeout" );
//Debug.write('LzMakeLoadSprite.createLoader', this.firstsrc)
if ( this.firstsrc != null ){
this.setSource( this.firstsrc , this.firstcache, this.firstheaders, this.firstfiletype );
}
}
/**
* @access private
* @param String newSrc: The url from which to load the resource for this view.
* @param String cache: If set, controls caching behavior. Choices are
* "none" , "clientonly" , "serveronly" , "both" -- where both is the default.
* @param String headers: Headers to send with the request (if any.)
* @param String filetype: Filetype, e.g. 'mp3' or 'jpg'. If not specified, it will be derived from the URL.
*/
LzMakeLoadSprite.setSource = function ( newSrc , cache , headers , filetype ){
if (this.loader.mc.loading == true) {
LzLoadQueue.unloadRequest(this.loader.mc);
}
//Debug.write('setSource', newSrc);
if (newSrc == '' || newSrc == ' ' || newSrc == null) {
Debug.error('setSource called with an empty url');
return;
}
this.stopTrackPlay();
this.isloaded = false;
if ( this.queuedplayaction == null ){
this.queuePlayAction( "checkPlayStatus" );
}
this.resource = newSrc;
//this.owner.resource = newSrc;
//if (this.owner.onresource) this.owner.onresource.sendEvent( newSrc );
this.owner.__LZvizLoad = false;
this.owner.__LZupdateShown();
this.loader.request( newSrc , cache , headers, filetype );
}
/**
* This method keeps the behavior of setResource consistent between
* load-transformed views and those that aren't
* @access private
*/
LzMakeLoadSprite.setResource = function ( nresc ){
// unload anything currently loading...
if (this.loader.mc.loading == true) {
LzLoadQueue.unloadRequest(this.loader.mc);
}
if ( nresc == "empty" ){
// call shadowed setResource()
this.___setResource( nresc );
} else {
if ( nresc.indexOf('http:') == 0 || nresc.indexOf('https:') == 0){
this.setSource( nresc );
return;
}
this.loader.attachLoadMovie( nresc );
if ( this.queuedplayaction == null ){
this.queuePlayAction( "checkPlayStatus" );
}
//this.updateAfterLoad();
}
// var mc = this.__LZmovieClipRef;
// Debug.debug(mc, '_width', mc._width);
// Debug.debug(mc, '_height', mc._height);
// Debug.debug(mc, '_xscale', mc._xscale);
// Debug.debug(mc, '_yscale', mc._yscale);
}
//handle error
/**
* Updates movieclip properties after the resource has loaded
* @access private
*/
LzMakeLoadSprite.updateAfterLoad = function (ignore){
this.isloaded = true;
var mc = this.getMCRef();
this.resourcewidth = mc._width;
this.resourceheight = mc._height;
this.currentframe = mc._currentframe;
var tfchg = this.totalframes != mc._totalframes;
if ( tfchg ){
this.totalframes = mc._totalframes;
this.owner.resourceevent('totalframes', this.totalframes);
}
if ( this.totalframes > 1 ){
this.checkPlayStatus();
}
this.setHeight(this.hassetheight?this.height:null);
this.setWidth(this.hassetwidth?this.width:null);
if (this.__contextmenu) {
this.setContextMenu(this.__contextmenu);
}
this.owner.__LZvizLoad = true;
this.owner.__LZupdateShown();
this.owner.resourceload({width: this.resourcewidth, height: this.resourceheight, resource: this.resource, skiponload: false});
this.owner.reevaluateSize( );
//if (this.owner.onload) this.owner.onload.sendEvent( this.loader.mc );
//Debug.write('Sprite.updateAfterLoad', mc, this.resourcewidth, this.resourceheight, this.resource, this.owner.resource, this.owner, this.x);
//Debug.warn('Sprite.updateAfterLoad');
}
/**
* Unloads the media
* @access private
*/
LzMakeLoadSprite.unload = function () {
this.loader.unload( this.loader.mc );
}
/**
* Get a reference to the control mc
* @access private
*/
LzMakeLoadSprite.getMCRef = function () {
//return null if not loaded
if (this.loader.isaudio) return this.loader.mc;
return this.isloaded ? this.loader.getLoadMC() : null;
}
/**
* Get the number of bytes loaded so far
* @return: A number that is the maximum offset for this resource
*/
LzMakeLoadSprite.getLoadBytes = function (){
return this.getMCRef().getBytesLoaded();
}
/**
* Get the total number of bytes for the attached resource
* @return: A number that is the maximum offset for this resource
*/
LzMakeLoadSprite.getMaxBytes = function (){
return this.getMCRef().getBytesTotal();
}
/**
* @access private
*/
LzMakeLoadSprite.__LZsendError = function ( e ){
this.resourcewidth = 0;
this.resourceheight = 0;
if (this.owner) this.owner.resourceloaderror( e )
}
/**
* @access private
*/
LzMakeLoadSprite.__LZsendTimeout = function ( e ){
this.resourcewidth = 0;
this.resourceheight = 0;
if (this.owner) this.owner.resourceloadtimeout( e )
}
/**
* @access private
*/
LzMakeLoadSprite.destroy = function () {
if ('updateDel' in this)
this.updateDel.unregisterAll();
if ('errorDel' in this)
this.errorDel.unregisterAll();
if ('timeoutDel' in this)
this.timeoutDel.unregisterAll();
this.loader.unload( this.loader.mc );
// call shadowed destroy()
this.___destroy();
}
|
/**
* LzMakeLoadSprite.as
*
* @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic AS2
*/
/**
* @access private
*/
var LzMakeLoadSprite = {};
/**
* Makes the given view able to load a remote resource
*/
LzMakeLoadSprite.transform = function (v, src, cache, headers, filetype) {
for (var k in this) {
if (k != "transform") {
if (typeof v[k] == 'function') {
// replace old method with _methodname to support super
v[ '___' + k ] = v[k];
}
v[k] = this[k];
}
}
if (v.__LZmovieClipRef == null || ! v.__LZhaser) {
//the view doesn't have the empty resource. We need to try and replace it
v.makeContainerResource();
}
v.createLoader(src, cache, headers, filetype);
}
/**
* @access private
*/
LzMakeLoadSprite.createLoader = function (src, cache, headers, filetype) {
this.loader = new LzMediaLoader(this, {});
this.updateDel = new LzDelegate(this, "updateAfterLoad", this.loader, "onloaddone");
this.errorDel = new LzDelegate(this, "__LZsendError", this.loader, "onerror");
this.timeoutDel = new LzDelegate(this, "__LZsendTimeout", this.loader, "ontimeout");
if (src != null) {
this.setSource(src, cache, headers, filetype);
}
}
/**
* @access private
* @param String src: The url from which to load the resource for this view.
* @param String cache: If set, controls caching behavior. Choices are
* "none" , "clientonly" , "serveronly" , "both" -- where both is the default.
* @param String headers: Headers to send with the request (if any.)
* @param String filetype: Filetype, e.g. 'mp3' or 'jpg'. If not specified, it will be derived from the URL.
*/
LzMakeLoadSprite.setSource = function (src, cache, header, filetype) {
if (this.loader.mc.loading == true) {
LzLoadQueue.unloadRequest(this.loader.mc);
}
if (src == '' || src == ' ' || src == null) {
if ($debug) Debug.error('setSource called with an empty url');
return;
}
this.stopTrackPlay();
this.isloaded = false;
if (this.queuedplayaction == null) {
this.queuePlayAction("checkPlayStatus");
}
this.resource = src;
//this.owner.resource = src;
//if (this.owner.onresource) this.owner.onresource.sendEvent( src );
this.owner.__LZvizLoad = false;
this.owner.__LZupdateShown();
this.loader.request(src, cache, headers, filetype);
}
/**
* This method keeps the behavior of setResource consistent between
* load-transformed views and those that aren't
* @access private
*/
LzMakeLoadSprite.setResource = function (nresc) {
// unload anything currently loading...
if (this.loader.mc.loading == true) {
LzLoadQueue.unloadRequest(this.loader.mc);
}
if (nresc == "empty") {
// call shadowed setResource()
this.___setResource(nresc);
} else if (nresc.indexOf('http:') == 0 || nresc.indexOf('https:') == 0) {
this.setSource(nresc);
} else {
this.loader.attachLoadMovie(nresc);
if (this.queuedplayaction == null) {
this.queuePlayAction("checkPlayStatus");
}
//this.updateAfterLoad();
}
}
/**
* Updates movieclip properties after the resource has loaded
* @access private
*/
LzMakeLoadSprite.updateAfterLoad = function (ignore) {
this.isloaded = true;
var mc = this.getMCRef();
this.resourcewidth = mc._width;
this.resourceheight = mc._height;
this.currentframe = mc._currentframe;
var tfchg = this.totalframes != mc._totalframes;
if (tfchg) {
this.totalframes = mc._totalframes;
this.owner.resourceevent('totalframes', this.totalframes);
}
if (this.totalframes > 1) {
this.checkPlayStatus();
}
this.setHeight(this.hassetheight ? this.height : null);
this.setWidth(this.hassetwidth ? this.width : null);
if (this.__contextmenu) {
this.setContextMenu(this.__contextmenu);
}
this.owner.__LZvizLoad = true;
this.owner.__LZupdateShown();
this.owner.resourceload({width: this.resourcewidth, height: this.resourceheight, resource: this.resource, skiponload: false});
this.owner.reevaluateSize();
//if (this.owner.onload) this.owner.onload.sendEvent( this.loader.mc );
}
/**
* Unloads the media
* @access private
*/
LzMakeLoadSprite.unload = function () {
this.loader.unload(this.loader.mc);
}
/**
* Get a reference to the control mc
* @access private
*/
LzMakeLoadSprite.getMCRef = function () {
//return null if not loaded
if (this.loader.isaudio) return this.loader.mc;
return this.isloaded ? this.loader.getLoadMC() : null;
}
/**
* Get the number of bytes loaded so far
* @return: A number that is the maximum offset for this resource
*/
LzMakeLoadSprite.getLoadBytes = function () {
return this.getMCRef().getBytesLoaded();
}
/**
* Get the total number of bytes for the attached resource
* @return: A number that is the maximum offset for this resource
*/
LzMakeLoadSprite.getMaxBytes = function () {
return this.getMCRef().getBytesTotal();
}
/**
* @access private
*/
LzMakeLoadSprite.__LZsendError = function (e) {
this.resourcewidth = 0;
this.resourceheight = 0;
if (this.owner) this.owner.resourceloaderror(e)
}
/**
* @access private
*/
LzMakeLoadSprite.__LZsendTimeout = function (e) {
this.resourcewidth = 0;
this.resourceheight = 0;
if (this.owner) this.owner.resourceloadtimeout(e)
}
/**
* @access private
*/
LzMakeLoadSprite.destroy = function () {
if ('updateDel' in this)
this.updateDel.unregisterAll();
if ('errorDel' in this)
this.errorDel.unregisterAll();
if ('timeoutDel' in this)
this.timeoutDel.unregisterAll();
this.loader.unload(this.loader.mc);
// call shadowed destroy()
this.___destroy();
}
|
Change 20080902-bargull-2wD by bargull@dell--p4--2-53 on 2008-09-02 21:31:23 in /home/Admin/src/svn/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk
|
Change 20080902-bargull-2wD by bargull@dell--p4--2-53 on 2008-09-02 21:31:23
in /home/Admin/src/svn/openlaszlo/trunk
for http://svn.openlaszlo.org/openlaszlo/trunk
Summary: LzMakeLoadSprite cleanup
New Features:
Bugs Fixed: LPP-5551 (part 1 - cleanup)
Technical Reviewer: max
QA Reviewer: (pending)
Doc Reviewer: (pending)
Documentation:
Release Notes:
Details:
As part of LPP-5551, I like to do some code cleanup.
LzMakeLoadSprite:
- consistent code-formatting
- changed LzMakeLoadSprite from function to object
- removed out commented debug-code
- removed first* properties, instead call "createLoader" directly
- removed override of "doReplaceResource" because it was superfluous as "_newrescname" was never defined
- removed "if (! this.loader)"-check in LzMakeLoadSprite.transform, because it always yield true as there is no "loader"-field defined in LzMakeLoadSprite
- removed "transformerID", no where referenced in the lfc
Tests:
git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@10856 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
|
ActionScript
|
epl-1.0
|
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
|
65f45f8e869ef075216754b30f1a27b6d0eca387
|
src/aerys/minko/type/Signal.as
|
src/aerys/minko/type/Signal.as
|
package aerys.minko.type
{
public final class Signal
{
private var _name : String;
private var _enabled : Boolean;
private var _disableWhenNoCallbacks : Boolean;
private var _callbacks : Vector.<Function>;
private var _numCallbacks : uint;
private var _executed : Boolean;
private var _numAdded : uint;
private var _toAdd : Vector.<Function>;
private var _numRemoved : uint;
private var _toRemove : Vector.<Function>;
public function get enabled() : Boolean
{
return _enabled;
}
public function set enabled(value : Boolean) : void
{
_enabled = value;
}
public function get numCallbacks() : uint
{
return _numCallbacks;
}
public function Signal(name : String,
enabled : Boolean = true,
disableWhenNoCallbacks : Boolean = false)
{
_name = name;
_enabled = enabled;
_disableWhenNoCallbacks = disableWhenNoCallbacks;
}
public function add(callback : Function) : void
{
if (_callbacks && _callbacks.indexOf(callback) >= 0)
{
var removeIndex : int = _toRemove ? _toRemove.indexOf(callback) : -1;
// if that callback is in the temp. remove list, we simply remove it from this list
// instead of removing/adding it all over again
if (removeIndex >= 0)
{
--_numRemoved;
_toRemove[removeIndex] = _toRemove[_numRemoved];
_toRemove.length = _numRemoved;
return;
}
else
throw new Error('The same callback cannot be added twice.');
}
if (_executed)
{
if (_toAdd)
_toAdd.push(callback);
else
_toAdd = new <Function>[callback];
++_numAdded;
return ;
}
if (_callbacks) _callbacks[_numCallbacks] = callback;
else _callbacks = new <Function>[callback];
++_numCallbacks;
if (_numCallbacks == 1 && _disableWhenNoCallbacks)
_enabled = true;
}
public function remove(callback : Function) : void
{
var index : int = (_callbacks ? _callbacks.indexOf(callback) : -1);
if (index < 0)
{
var addIndex : int = _toAdd ? _toAdd.indexOf(callback) : -1;
// if that callback is in the temp. add list, we simply remove it from this list
// instead of adding/removing it all over again
if (addIndex >= 0)
{
--_numAdded;
_toAdd[addIndex] = _toAdd[_numAdded];
_toAdd.length = _numAdded;
}
else
throw new Error('This callback does not exist.');
}
if (_executed)
{
if (_toRemove)
_toRemove.push(callback);
else
_toRemove = new <Function>[callback];
++_numRemoved;
return ;
}
--_numCallbacks;
_callbacks[index] = _callbacks[_numCallbacks];
_callbacks.length = _numCallbacks;
if (!_numCallbacks && _disableWhenNoCallbacks)
_enabled = false;
}
public function hasCallback(callback : Function) : Boolean
{
return _callbacks && _callbacks.indexOf(callback) >= 0;
}
public function execute(...params) : void
{
if (_numCallbacks && _enabled)
{
_executed = true;
for (var i : uint = 0; i < _numCallbacks; ++i)
_callbacks[i].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;
private var _enabled : Boolean;
private var _disableWhenNoCallbacks : Boolean;
private var _callbacks : Vector.<Function>;
private var _numCallbacks : uint;
private var _executed : Boolean;
private var _numAdded : uint;
private var _toAdd : Vector.<Function>;
private var _numRemoved : uint;
private var _toRemove : Vector.<Function>;
public function get enabled() : Boolean
{
return _enabled;
}
public function set enabled(value : Boolean) : void
{
_enabled = value;
}
public function get numCallbacks() : uint
{
return _numCallbacks;
}
public function Signal(name : String,
enabled : Boolean = true,
disableWhenNoCallbacks : Boolean = false)
{
_name = name;
_enabled = enabled;
_disableWhenNoCallbacks = disableWhenNoCallbacks;
}
public function add(callback : Function) : void
{
if (_callbacks && _callbacks.indexOf(callback) >= 0)
{
var removeIndex : int = _toRemove ? _toRemove.indexOf(callback) : -1;
// if that callback is in the temp. remove list, we simply remove it from this list
// instead of removing/adding it all over again
if (removeIndex >= 0)
{
--_numRemoved;
_toRemove[removeIndex] = _toRemove[_numRemoved];
_toRemove.length = _numRemoved;
return;
}
else
throw new Error('The same callback cannot be added twice.');
}
if (_executed)
{
if (_toAdd)
_toAdd.push(callback);
else
_toAdd = new <Function>[callback];
++_numAdded;
return ;
}
if (_callbacks)
_callbacks[_numCallbacks] = callback;
else
_callbacks = new <Function>[callback];
++_numCallbacks;
if (_numCallbacks == 1 && _disableWhenNoCallbacks)
_enabled = true;
}
public function remove(callback : Function) : void
{
var index : int = (_callbacks ? _callbacks.indexOf(callback) : -1);
if (index < 0)
{
var addIndex : int = _toAdd ? _toAdd.indexOf(callback) : -1;
// if that callback is in the temp. add list, we simply remove it from this list
// instead of adding/removing it all over again
if (addIndex >= 0)
{
--_numAdded;
_toAdd[addIndex] = _toAdd[_numAdded];
_toAdd.length = _numAdded;
}
else
throw new Error('This callback does not exist.');
}
if (_executed)
{
if (_toRemove)
_toRemove.push(callback);
else
_toRemove = new <Function>[callback];
++_numRemoved;
return ;
}
--_numCallbacks;
_callbacks[index] = _callbacks[_numCallbacks];
_callbacks.length = _numCallbacks;
if (!_numCallbacks && _disableWhenNoCallbacks)
_enabled = false;
}
public function hasCallback(callback : Function) : Boolean
{
return _callbacks && _callbacks.indexOf(callback) >= 0;
}
public function execute(...params) : void
{
if (_numCallbacks && _enabled)
{
_executed = true;
for (var i : uint = 0; i < _numCallbacks; ++i)
_callbacks[i].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;
}
}
}
}
|
Update Signal.as
|
Update Signal.as
|
ActionScript
|
mit
|
aerys/minko-as3
|
9414b50c94a9f84328b9a9d6d6a2dad3a5039e6b
|
WeaveJS/src/weavejs/data/CSVParser.as
|
WeaveJS/src/weavejs/data/CSVParser.as
|
/* ***** BEGIN LICENSE BLOCK *****
*
* This file is part of Weave.
*
* The Initial Developer of Weave is the Institute for Visualization
* and Perception Research at the University of Massachusetts Lowell.
* Portions created by the Initial Developer are Copyright (C) 2008-2015
* the Initial Developer. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* ***** END LICENSE BLOCK ***** */
package weavejs.data
{
import weavejs.WeaveAPI;
import weavejs.api.core.ILinkableObject;
import weavejs.api.data.ICSVParser;
import weavejs.util.JS;
/**
* Parses and generates CSV-encoded data.
*/
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';
private static const flascc:Object = null;
/**
* Creates a CSVParser.
* @param asyncMode If this is set to true, parseCSV() will work asynchronously
* and trigger callbacks when it finishes.
* If this is set to false, no callback collection will be generated
* for this instance of CSVParser as a result of calling its methods.
* Note that if asyncMode is enabled, you can only parse one CSV string at a time.
* @param delimiter A single character for the delimiter
* @param quote A single character for the quote
*/
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 = '"';
private var removeBlankLines:Boolean = true;
private var parseTokens:Boolean = true;
// async state
private var csvData:String;
private var csvDataArray:Array;
/**
* @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):Array
{
if (asyncMode)
{
this.csvData = csvData;
this.csvDataArray = [];
// high priority because preparing data is often the first thing we need to do
WeaveAPI.Scheduler.startTask(this, parseIterate, WeaveAPI.TASK_PRIORITY_HIGH, parseDone);
}
else
{
csvDataArray = flascc.parseCSV(csvData, delimiter, quote, removeBlankLines, parseTokens);
}
return csvDataArray;
}
private function parseIterate(stopTime:int):Number
{
// This isn't actually asynchronous at the moment, but moving the code to
// FlasCC made it so much faster that it won't matter most of the time.
// The async code structure is kept in case we want to make it asynchronous again in the future.
flascc.parseCSV(csvData, delimiter, quote, removeBlankLines, parseTokens, csvDataArray);
csvData = null;
return 1;
}
private function parseDone():void
{
if (asyncMode)
Weave.getCallbacks(this).triggerCallbacks();
}
/**
* @inheritDoc
*/
public function parseCSVRow(csvData:String):Array
{
if (csvData == null)
return null;
var rows:Array = flascc.parseCSV(csvData, delimiter, quote, removeBlankLines, parseTokens);
if (rows.length == 0)
return rows;
if (rows.length == 1)
return rows[0];
// flatten
return [].concat.apply(null, rows);
}
/**
* @inheritDoc
*/
public function createCSV(rows:Array):String
{
return flascc.createCSV(rows, delimiter, quote);
}
/**
* @inheritDoc
*/
public function createCSVRow(row:Array):String
{
return row ? flascc.createCSV([row], delimiter, quote) : null;
}
/**
* @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.sort();
}
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);
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);
JS.log(_);
}
}
}
|
/*
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 weavejs.data
{
import weavejs.WeaveAPI;
import weavejs.api.core.ILinkableObject;
import weavejs.api.data.ICSVParser;
import weavejs.util.AsyncSort;
import weavejs.util.JS;
import weavejs.util.StandardLib;
/**
* 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 = '"';
private var parseTokens:Boolean = true;
// async state
private var csvData:String;
private var csvDataArray:Array;
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):Array
{
// initialization
this.csvData = csvData;
this.csvDataArray = [];
this.i = 0;
this.row = 0;
this.col = 0;
this.escaped = false;
if (asyncMode)
{
// high priority because preparing data is often the first thing we need to do
WeaveAPI.Scheduler.startTask(this, parseIterate, WeaveAPI.TASK_PRIORITY_HIGH, parseDone);
}
else
{
parseIterate(Number.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 (JS.now() < 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)
Weave.getCallbacks(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):Array
{
if (csvData == null)
return null;
var rows:Array = parseCSV(csvData);
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 == StandardLib.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);
JS.log(_);
}
}
}
|
copy old CSVParser from commit 7a0c543a1b4dcc0d3587d14f261b252f20c88af9
|
copy old CSVParser from commit 7a0c543a1b4dcc0d3587d14f261b252f20c88af9
|
ActionScript
|
mpl-2.0
|
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
|
17b2ad22f88645b0711eb51fa20cb7bf26ed6cd5
|
build-aux/children.as
|
build-aux/children.as
|
# -*- shell-script -*-
##
## children.as: This file is part of build-aux.
## Copyright (C) Gostai S.A.S., 2006-2008.
##
## This software is provided "as is" without warranty of any kind,
## either expressed or implied, including but not limited to the
## implied warranties of fitness for a particular purpose.
##
## See the LICENSE file for more information.
## For comments, bug reports and feedback: http://www.urbiforge.com
##
m4_defun([URBI_CHILDREN_PREPARE],
[
# run TITLE COMMAND...
# --------------------
# Run the COMMAND... (which may use its stdin) and output detailed
# logs about the execution.
#
# Leave un $run_prefix.{cmd, out, sta, err, val} the command, standard
# output, exit status, standard error, and instrumentation output.
run_counter=0
run_prefix=
run ()
{
local title=$[1]
run_prefix=$run_counter-$(echo $[1] |
sed -e 's/[[^a-zA-Z0-9][^a-zA-Z0-9]]*/-/g;s/-$//')
run_counter=$(($run_counter + 1))
shift
echo "$[@]"> $run_prefix.cmd
# Beware of set -e.
local sta
if "$[@]" >$run_prefix.out 2>$run_prefix.err; then
sta=0
else
sta=$?
title="$title FAIL ($sta)"
fi
echo $sta >$run_prefix.sta
rst_subsection "$me: $title"
rst_run_report "$title" "$run_prefix"
return $sta
}
## ------------------------------------------------- ##
## PID sets -- Lower layer for children management. ##
## ------------------------------------------------- ##
# pids_alive PIDS
# ---------------
# Return whether some of the PIDs point to alive processes,
# i.e., return 1 iff there are no children alive.
pids_alive ()
{
local pid
for pid
do
# Using "ps PID" to test whether a processus is alive is,
# unfortunately, non portable. OS X Tiger always return 0, and
# outputs the ps-banner and the line of the processus (if there is
# none, it outputs just the banner). On Cygwin, "ps PID" outputs
# everything, and "ps -p PID" outputs the banner, and the process
# line if alive. In both cases it exits with success.
#
# We once used grep to check the result:
#
# ps -p $pid | grep ["^[ ]*$pid[^0-9]"]
#
# Unfortunately sometimes there are flags displayed before the
# process number. Since we never saw a "ps -p PID" that does not
# display the title line, we expect two lines.
case $(ps -p $pid | wc -l | sed -e '[s/^[ ]*//]') in
1) # process is dead.
;;
2) # Process is live.
return 0;;
*) error SOFTWARE "unexpected ps output:" "$(ps -p $pid)" ;;
esac
done
return 1
}
# pids_kill PIDS
# --------------
# Kill all the PIDS. This function can be called twice: once
# before cleaning the components, and once when exiting, so it's
# robust to children no longer in the process table.
pids_kill ()
{
local pid
for pid
do
if pids_alive $pid; then
local name
name=$(cat $pid.name)
echo "Killing $name (kill -ALRM $pid)"
kill -ALRM $pid 2>&1 || true
fi
done
}
# pids_wait TIMEOUT PIDS
# ----------------------
pids_wait ()
{
local timeout=$[1]
shift
if $INSTRUMENT; then
timeout=$(($timeout * 5))
fi
while pids_alive "$[@]"; do
if test $timeout -le 0; then
pids_kill "$[@]"
break
fi
sleep 1
timeout=$(($timeout - 1))
done
}
## ---------- ##
## Children. ##
## ---------- ##
# rst_run_report $TITLE $FILE-PREFIX
# ----------------------------------
# Report the input and output for $FILE-PREFIX.
rst_run_report ()
{
local title=$[1]
case $title in
?*) title="$title ";;
esac
rst_pre "${title}Command" $[2].cmd
rst_pre "${title}Pid" $[2].pid
rst_pre "${title}Status" $[2].sta
rst_pre "${title}Input" $[2].in
rst_pre "${title}Output" $[2].out
rst_pre "${title}Error" $[2].err
rst_pre "${title}Valgrind" $[2].val
}
# children_alive [CHILDREN]
# -------------------------
# Return whether there are still some children running,
# i.e., return 1 iff there are no children alive.
children_alive ()
{
local pid
local pids
pids=$(children_pid "$@")
for pid in $pids
do
# Using "ps PID" to test whether a processus is alive is,
# unfortunately, non portable. OS X Tiger always return 0, and
# outputs the ps-banner and the line of the processus (if there is
# none, it outputs just the banner). On Cygwin, "ps PID" outputs
# everything, and "ps -p PID" outputs the banner, and the process
# line if alive. In both cases it exits with success.
#
# We once used grep to check the result:
#
# ps -p $pid | grep ["^[ ]*$pid[^0-9]"]
#
# Unfortunately sometimes there are flags displayed before the
# process number. Since we never saw a "ps -p PID" that does not
# display the title line, we expect two lines.
case $(ps -p $pid | wc -l | sed -e '[s/^[ ]*//]') in
1) # process is dead.
;;
2) # Process is live.
return 0;;
*) error SOFTWARE "unexpected ps output:" "$(ps -p $pid)" ;;
esac
done
return 1
}
# children_clean [CHILDREN]
# --------------------------
# Remove the children files.
children_clean ()
{
test $[#] -ne 0 ||
{ set x $children; shift; }
local i
for i
do
rm -f $i.{cmd,pid,sta,in,out,err,val}
done
}
# children_pid [CHILDREN]
# -----------------------
# Return the PIDs of the CHILDREN (whether alive or not).
children_pid ()
{
test $[#] -ne 0 ||
{ set x $children; shift; }
local i
for i
do
test -f $i.pid ||
error SOFTWARE "children_pid: cannot find $i.pid."
cat $i.pid
done
}
# children_register NAME
# ----------------------
# It is very important that we do not leave some random exit status
# from some previous runs. Standard output etc. are not a problem:
# they *are* created during the run, while *.sta is created *only* if
# it does not already exists (this is because you can call "wait" only
# once per processus, so to enable calling children_harvest multiple
# times, we create *.sta only if it does not exist).
#
# Creates NAME.pid which contains the PID, and PID.name which contains
# the name.
children_register ()
{
test $[#] -eq 1
rm -f $[1].sta
children="$children $[1]"
echo $! >$[1].pid
echo $[1] >$!.name
}
# children_report [CHILDREN]
# --------------------------
# Produce an RST report for the CHILDREN.
children_report ()
{
test $[#] -ne 0 ||
{ set x $children; shift; }
local i
for i
do
rst_run_report "$i" "$i"
done
}
# children_kill [CHILDREN]
# ------------------------
# Kill all the children. This function can be called twice: once
# before cleaning the components, and once when exiting, so it's
# robust to children no longer in the process table.
children_kill ()
{
local pids
pids=$(children_pid "$[@]")
pids_kill "$pids"
}
# children_harvest [CHILDREN]
# ---------------------------
# Report the exit status of the children. Can be run several times.
# You might want to call it once in the regular control flow to fetch
# some exit status, but also in a trap, if you were interrupted. So
# it is meant to be callable multiple times, which might be a danger
# wrt *.sta (cf., children_register).
children_harvest ()
{
# Harvest exit status.
test $[#] -ne 0 ||
{ set x $children; shift; }
local i
for i
do
# Don't wait for children we already waited for.
if ! test -e $i.sta; then
local pid
pid=$(children_pid $i)
# Beware of set -e.
local sta
if wait $pid 2>&1; then
sta=$?
else
sta=$?
fi
echo "$sta$(ex_to_string $sta)" >$i.sta
fi
done
}
# children_status [CHILDREN]
# --------------------------
# Return the exit status of CHILD. Must be run after harvesting.
# If several CHILD are given, return the highest exit status.
children_status ()
{
test $[#] -ne 0 ||
{ set x $children; shift; }
local res=0
local i
for i
do
# We need to have waited for these children.
test -f $i.sta ||
error SOFTWARE "children_status: cannot find $i.sta." \
"Was children_harvest called?" \
"Maybe children_cleanup was already called..."
local sta=$(sed -n '1{s/^\([[0-9][0-9]]*\).*/\1/;p;q;}' <$i.sta)
if test $res -lt $sta; then
res=$sta
fi
done
echo $res
}
# children_wait TIMEOUT [CHILDREN]
# --------------------------------
# Wait for the registered children, and passed TIMEOUT, kill the remaining
# ones. TIMEOUT is increased by 5 if instrumenting.
children_wait ()
{
local timeout=$[1]
shift
local pids
pids=$(children_pid "$[@]")
pids_wait $timeout $pids
}
])
|
# -*- shell-script -*-
##
## children.as: This file is part of build-aux.
## Copyright (C) Gostai S.A.S., 2006-2008.
##
## This software is provided "as is" without warranty of any kind,
## either expressed or implied, including but not limited to the
## implied warranties of fitness for a particular purpose.
##
## See the LICENSE file for more information.
## For comments, bug reports and feedback: http://www.urbiforge.com
##
m4_defun([URBI_CHILDREN_PREPARE],
[
# run TITLE COMMAND...
# --------------------
# Run the COMMAND... (which may use its stdin) and output detailed
# logs about the execution.
#
# Leave un $run_prefix.{cmd, out, sta, err, val} the command, standard
# output, exit status, standard error, and instrumentation output.
run_counter=0
run_prefix=
run ()
{
local title=$[1]
run_prefix=$run_counter-$(echo $[1] |
sed -e 's/[[^a-zA-Z0-9][^a-zA-Z0-9]]*/-/g;s/-$//')
run_counter=$(($run_counter + 1))
shift
echo "$[@]"> $run_prefix.cmd
# Beware of set -e.
local sta
if "$[@]" >$run_prefix.out 2>$run_prefix.err; then
sta=0
else
sta=$?
title="$title FAIL ($sta)"
fi
echo $sta >$run_prefix.sta
rst_subsection "$me: $title"
rst_run_report "$title" "$run_prefix"
return $sta
}
## ------------------------------------------------- ##
## PID sets -- Lower layer for children management. ##
## ------------------------------------------------- ##
# pids_alive PIDS
# ---------------
# Return whether some of the PIDs point to alive processes,
# i.e., return 1 iff there are no children alive.
pids_alive ()
{
local pid
for pid
do
# Using "ps PID" to test whether a processus is alive is,
# unfortunately, non portable. OS X Tiger always return 0, and
# outputs the ps-banner and the line of the processus (if there is
# none, it outputs just the banner). On Cygwin, "ps PID" outputs
# everything, and "ps -p PID" outputs the banner, and the process
# line if alive. In both cases it exits with success.
#
# We once used grep to check the result:
#
# ps -p $pid | grep ["^[ ]*$pid[^0-9]"]
#
# Unfortunately sometimes there are flags displayed before the
# process number. Since we never saw a "ps -p PID" that does not
# display the title line, we expect two lines.
case $(ps -p $pid | wc -l | sed -e '[s/^[ ]*//]') in
1) # process is dead.
;;
2) # Process is live.
return 0;;
*) error SOFTWARE "unexpected ps output:" "$(ps -p $pid)" ;;
esac
done
return 1
}
# pids_kill PIDS
# --------------
# Kill all the PIDS. This function can be called twice: once
# before cleaning the components, and once when exiting, so it's
# robust to children no longer in the process table.
pids_kill ()
{
local pid
for pid
do
if pids_alive $pid; then
local name
name=$(cat $pid.name)
echo "Killing $name (kill -ALRM $pid)"
kill -ALRM $pid 2>&1 || true
fi
done
}
# pids_wait TIMEOUT PIDS
# ----------------------
pids_wait ()
{
local timeout=$[1]
shift
if $INSTRUMENT; then
timeout=$(($timeout * 5))
fi
while pids_alive "$[@]"; do
if test $timeout -le 0; then
pids_kill "$[@]"
break
fi
sleep 1
timeout=$(($timeout - 1))
done
}
## ---------- ##
## Children. ##
## ---------- ##
# rst_run_report $TITLE $FILE-PREFIX
# ----------------------------------
# Report the input and output for $FILE-PREFIX.
rst_run_report ()
{
local title=$[1]
case $title in
?*) title="$title ";;
esac
rst_pre "${title}Command" $[2].cmd
rst_pre "${title}Pid" $[2].pid
rst_pre "${title}Status" $[2].sta
rst_pre "${title}Input" $[2].in
rst_pre "${title}Output" $[2].out
rst_pre "${title}Error" $[2].err
rst_pre "${title}Valgrind" $[2].val
}
# children_alive [CHILDREN]
# -------------------------
# Return whether there are still some children running,
# i.e., return 1 iff there are no children alive.
children_alive ()
{
local pid
local pids
pids=$(children_pid "$[@]")
for pid in $pids
do
# Using "ps PID" to test whether a processus is alive is,
# unfortunately, non portable. OS X Tiger always return 0, and
# outputs the ps-banner and the line of the processus (if there is
# none, it outputs just the banner). On Cygwin, "ps PID" outputs
# everything, and "ps -p PID" outputs the banner, and the process
# line if alive. In both cases it exits with success.
#
# We once used grep to check the result:
#
# ps -p $pid | grep ["^[ ]*$pid[^0-9]"]
#
# Unfortunately sometimes there are flags displayed before the
# process number. Since we never saw a "ps -p PID" that does not
# display the title line, we expect two lines.
case $(ps -p $pid | wc -l | sed -e '[s/^[ ]*//]') in
1) # process is dead.
;;
2) # Process is live.
return 0;;
*) error SOFTWARE "unexpected ps output:" "$(ps -p $pid)" ;;
esac
done
return 1
}
# children_clean [CHILDREN]
# --------------------------
# Remove the children files.
children_clean ()
{
test $[#] -ne 0 ||
{ set x $children; shift; }
local i
for i
do
rm -f $i.{cmd,pid,sta,in,out,err,val}
done
}
# children_pid [CHILDREN]
# -----------------------
# Return the PIDs of the CHILDREN (whether alive or not).
children_pid ()
{
test $[#] -ne 0 ||
{ set x $children; shift; }
local i
for i
do
test -f $i.pid ||
error SOFTWARE "children_pid: cannot find $i.pid."
cat $i.pid
done
}
# children_register NAME
# ----------------------
# It is very important that we do not leave some random exit status
# from some previous runs. Standard output etc. are not a problem:
# they *are* created during the run, while *.sta is created *only* if
# it does not already exists (this is because you can call "wait" only
# once per processus, so to enable calling children_harvest multiple
# times, we create *.sta only if it does not exist).
#
# Creates NAME.pid which contains the PID, and PID.name which contains
# the name.
children_register ()
{
test $[#] -eq 1
rm -f $[1].sta
children="$children $[1]"
echo $! >$[1].pid
echo $[1] >$!.name
}
# children_report [CHILDREN]
# --------------------------
# Produce an RST report for the CHILDREN.
children_report ()
{
test $[#] -ne 0 ||
{ set x $children; shift; }
local i
for i
do
rst_run_report "$i" "$i"
done
}
# children_kill [CHILDREN]
# ------------------------
# Kill all the children. This function can be called twice: once
# before cleaning the components, and once when exiting, so it's
# robust to children no longer in the process table.
children_kill ()
{
local pids
pids=$(children_pid "$[@]")
pids_kill "$pids"
}
# children_harvest [CHILDREN]
# ---------------------------
# Report the exit status of the children. Can be run several times.
# You might want to call it once in the regular control flow to fetch
# some exit status, but also in a trap, if you were interrupted. So
# it is meant to be callable multiple times, which might be a danger
# wrt *.sta (cf., children_register).
children_harvest ()
{
# Harvest exit status.
test $[#] -ne 0 ||
{ set x $children; shift; }
local i
for i
do
# Don't wait for children we already waited for.
if ! test -e $i.sta; then
local pid
pid=$(children_pid $i)
# Beware of set -e.
local sta
if wait $pid 2>&1; then
sta=$?
else
sta=$?
fi
echo "$sta$(ex_to_string $sta)" >$i.sta
fi
done
}
# children_status [CHILDREN]
# --------------------------
# Return the exit status of CHILD. Must be run after harvesting.
# If several CHILD are given, return the highest exit status.
children_status ()
{
test $[#] -ne 0 ||
{ set x $children; shift; }
local res=0
local i
for i
do
# We need to have waited for these children.
test -f $i.sta ||
error SOFTWARE "children_status: cannot find $i.sta." \
"Was children_harvest called?" \
"Maybe children_cleanup was already called..."
local sta=$(sed -n '1{s/^\([[0-9][0-9]]*\).*/\1/;p;q;}' <$i.sta)
if test $res -lt $sta; then
res=$sta
fi
done
echo $res
}
# children_wait TIMEOUT [CHILDREN]
# --------------------------------
# Wait for the registered children, and passed TIMEOUT, kill the remaining
# ones. TIMEOUT is increased by 5 if instrumenting.
children_wait ()
{
local timeout=$[1]
shift
local pids
pids=$(children_pid "$[@]")
pids_wait $timeout $pids
}
])
|
Fix quotation error.
|
Fix quotation error.
* build-aux/children.as (children_alive): Fix m4 quotation.
|
ActionScript
|
bsd-3-clause
|
aldebaran/libport,aldebaran/libport,aldebaran/libport,aldebaran/libport,aldebaran/libport
|
6890890e26bf1c4e5959f9eb741f129fdac81c89
|
src/aerys/minko/render/material/phong/PhongMaterial.as
|
src/aerys/minko/render/material/phong/PhongMaterial.as
|
package aerys.minko.render.material.phong
{
import aerys.minko.render.Effect;
import aerys.minko.render.material.basic.BasicMaterial;
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.binding.IDataProvider;
import aerys.minko.type.math.Vector4;
import flash.utils.Dictionary;
public class PhongMaterial extends BasicMaterial
{
public static const DEFAULT_NAME : String = 'PhongMaterial';
private static const EFFECTS : Dictionary = new Dictionary(true);
public function get receptionMask() : uint
{
return getProperty(PhongProperties.RECEPTION_MASK) as uint;
}
public function set receptionMask(value : uint) : void
{
setProperty(PhongProperties.RECEPTION_MASK, value);
}
public function get lightmap() : TextureResource
{
return getProperty(PhongProperties.LIGHT_MAP) as TextureResource;
}
public function set lightmap(value : TextureResource) : void
{
setProperty(PhongProperties.LIGHT_MAP, value);
}
public function get specularMap() : TextureResource
{
return getProperty(PhongProperties.SPECULAR_MAP) as TextureResource;
}
public function set specularMap(value : TextureResource) : void
{
setProperty(PhongProperties.SPECULAR_MAP, value);
}
public function get lightmapMultiplier() : Number
{
return getProperty(PhongProperties.LIGHTMAP_MULTIPLIER) as Number;
}
public function set lightmapMultiplier(value : Number) : void
{
setProperty(PhongProperties.LIGHTMAP_MULTIPLIER, value);
}
public function get ambientMultiplier() : Number
{
return getProperty(PhongProperties.AMBIENT_MULTIPLIER) as Number;
}
public function set ambientMultiplier(value : Number) : void
{
setProperty(PhongProperties.AMBIENT_MULTIPLIER, value);
}
public function get diffuseMultiplier() : Number
{
return getProperty(PhongProperties.DIFFUSE_MULTIPLIER) as Number;
}
public function set diffuseMultiplier(value : Number) : void
{
setProperty(PhongProperties.DIFFUSE_MULTIPLIER, value);
}
public function get specular() : Vector4
{
return getProperty(PhongProperties.SPECULAR) as Vector4;
}
public function set specular(value : Vector4) : void
{
setProperty(PhongProperties.SPECULAR, value);
}
public function get shininess() : Number
{
return getProperty(PhongProperties.SHININESS) as Number;
}
public function set shininess(value : Number) : void
{
setProperty(PhongProperties.SHININESS, value);
}
public function get normalMappingType() : uint
{
return getProperty(PhongProperties.NORMAL_MAPPING_TYPE) as uint;
}
public function set normalMappingType(value : uint) : void
{
setProperty(PhongProperties.NORMAL_MAPPING_TYPE, value);
}
public function get normalMap() : TextureResource
{
return getProperty(PhongProperties.NORMAL_MAP) as TextureResource;
}
public function set normalMap(value : TextureResource) : void
{
setProperty(PhongProperties.NORMAL_MAP, value);
}
public function get heightMap() : TextureResource
{
return getProperty(PhongProperties.HEIGHT_MAP) as TextureResource;
}
public function set heightMap(value : TextureResource) : void
{
setProperty(PhongProperties.HEIGHT_MAP, value);
}
public function get numParallaxMappingSteps() : uint
{
return getProperty(PhongProperties.PARALLAX_MAPPING_NBSTEPS) as uint;
}
public function set numParallaxMappingSteps(value : uint) : void
{
setProperty(PhongProperties.PARALLAX_MAPPING_NBSTEPS, value);
}
public function get parallaxMappingBumpScale() : Number
{
return getProperty(PhongProperties.PARALLAX_MAPPING_BUMP_SCALE) as Number;
}
public function set parallaxMappingBumpScale(value : Number) : void
{
setProperty(PhongProperties.PARALLAX_MAPPING_BUMP_SCALE, value);
}
public function get shadowBias() : Number
{
return getProperty(PhongProperties.SHADOW_BIAS) as Number;
}
public function set shadowBias(value : Number) : void
{
setProperty(PhongProperties.SHADOW_BIAS, value);
}
public function get castShadows() : Boolean
{
return getProperty(PhongProperties.CAST_SHADOWS) as Boolean;
}
public function set castShadows(value : Boolean) : void
{
setProperty(PhongProperties.CAST_SHADOWS, value);
}
public function get receiveShadows() : Boolean
{
return getProperty(PhongProperties.RECEIVE_SHADOWS) as Boolean;
}
public function set receiveShadows(value : Boolean) : void
{
setProperty(PhongProperties.RECEIVE_SHADOWS, value);
}
public function PhongMaterial(scene : Scene,
properties : Object = null,
effect : Effect = null,
name : String = DEFAULT_NAME)
{
super(
properties,
effect || (EFFECTS[scene] || (EFFECTS[scene] = new PhongEffect(scene))),
name
);
}
override public function clone() : IDataProvider
{
return new PhongMaterial((effect as PhongEffect).scene, this, effect, name);
}
}
}
|
package aerys.minko.render.material.phong
{
import aerys.minko.render.Effect;
import aerys.minko.render.material.basic.BasicMaterial;
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.binding.IDataProvider;
import aerys.minko.type.math.Vector4;
import flash.utils.Dictionary;
public class PhongMaterial extends BasicMaterial
{
public static const DEFAULT_NAME : String = 'PhongMaterial';
private static const EFFECTS : Dictionary = new Dictionary(true);
public function get receptionMask() : uint
{
return getProperty(PhongProperties.RECEPTION_MASK) as uint;
}
public function set receptionMask(value : uint) : void
{
setProperty(PhongProperties.RECEPTION_MASK, value);
}
public function get lightmap() : TextureResource
{
return getProperty(PhongProperties.LIGHT_MAP) as TextureResource;
}
public function set lightmap(value : TextureResource) : void
{
setProperty(PhongProperties.LIGHT_MAP, value);
}
public function get specularMap() : TextureResource
{
return getProperty(PhongProperties.SPECULAR_MAP) as TextureResource;
}
public function set specularMap(value : TextureResource) : void
{
setProperty(PhongProperties.SPECULAR_MAP, value);
}
public function get lightmapMultiplier() : Number
{
return getProperty(PhongProperties.LIGHTMAP_MULTIPLIER) as Number;
}
public function set lightmapMultiplier(value : Number) : void
{
setProperty(PhongProperties.LIGHTMAP_MULTIPLIER, value);
}
public function get ambientMultiplier() : Number
{
return getProperty(PhongProperties.AMBIENT_MULTIPLIER) as Number;
}
public function set ambientMultiplier(value : Number) : void
{
setProperty(PhongProperties.AMBIENT_MULTIPLIER, value);
}
public function get diffuseMultiplier() : Number
{
return getProperty(PhongProperties.DIFFUSE_MULTIPLIER) as Number;
}
public function set diffuseMultiplier(value : Number) : void
{
setProperty(PhongProperties.DIFFUSE_MULTIPLIER, value);
}
public function get specular() : Vector4
{
return getProperty(PhongProperties.SPECULAR) as Vector4;
}
public function set specular(value : Vector4) : void
{
setProperty(PhongProperties.SPECULAR, value);
}
public function get shininess() : Number
{
return getProperty(PhongProperties.SHININESS) as Number;
}
public function set shininess(value : Number) : void
{
setProperty(PhongProperties.SHININESS, value);
}
public function get normalMappingType() : uint
{
return getProperty(PhongProperties.NORMAL_MAPPING_TYPE) as uint;
}
public function set normalMappingType(value : uint) : void
{
setProperty(PhongProperties.NORMAL_MAPPING_TYPE, value);
}
public function get normalMap() : TextureResource
{
return getProperty(PhongProperties.NORMAL_MAP) as TextureResource;
}
public function set normalMap(value : TextureResource) : void
{
setProperty(PhongProperties.NORMAL_MAP, value);
}
public function get normalMapFiltering() : uint
{
return getProperty(PhongProperties.NORMAL_MAP_FILTERING);
}
public function set normalMapFiltering(value : uint) : void
{
setProperty(PhongProperties.NORMAL_MAP_FILTERING, value);
}
public function get normalMapMipMapping() : uint
{
return getProperty(PhongProperties.NORMAL_MAP_MIPMAPPING);
}
public function set normalMapMipMapping(value : uint) : void
{
setProperty(PhongProperties.NORMAL_MAP_MIPMAPPING, value);
}
public function get normalMapFormat() : uint
{
return getProperty(PhongProperties.NORMAL_MAP_FORMAT);
}
public function set normalMapFormat(value : uint) : void
{
setProperty(PhongProperties.NORMAL_MAP_FORMAT, value);
}
public function get heightMap() : TextureResource
{
return getProperty(PhongProperties.HEIGHT_MAP) as TextureResource;
}
public function set heightMap(value : TextureResource) : void
{
setProperty(PhongProperties.HEIGHT_MAP, value);
}
public function get numParallaxMappingSteps() : uint
{
return getProperty(PhongProperties.PARALLAX_MAPPING_NBSTEPS) as uint;
}
public function set numParallaxMappingSteps(value : uint) : void
{
setProperty(PhongProperties.PARALLAX_MAPPING_NBSTEPS, value);
}
public function get parallaxMappingBumpScale() : Number
{
return getProperty(PhongProperties.PARALLAX_MAPPING_BUMP_SCALE) as Number;
}
public function set parallaxMappingBumpScale(value : Number) : void
{
setProperty(PhongProperties.PARALLAX_MAPPING_BUMP_SCALE, value);
}
public function get shadowBias() : Number
{
return getProperty(PhongProperties.SHADOW_BIAS) as Number;
}
public function set shadowBias(value : Number) : void
{
setProperty(PhongProperties.SHADOW_BIAS, value);
}
public function get castShadows() : Boolean
{
return getProperty(PhongProperties.CAST_SHADOWS) as Boolean;
}
public function set castShadows(value : Boolean) : void
{
setProperty(PhongProperties.CAST_SHADOWS, value);
}
public function get receiveShadows() : Boolean
{
return getProperty(PhongProperties.RECEIVE_SHADOWS) as Boolean;
}
public function set receiveShadows(value : Boolean) : void
{
setProperty(PhongProperties.RECEIVE_SHADOWS, value);
}
public function PhongMaterial(scene : Scene,
properties : Object = null,
effect : Effect = null,
name : String = DEFAULT_NAME)
{
super(
properties,
effect || (EFFECTS[scene] || (EFFECTS[scene] = new PhongEffect(scene))),
name
);
}
override public function clone() : IDataProvider
{
return new PhongMaterial((effect as PhongEffect).scene, this, effect, name);
}
}
}
|
add public properties normalMapFiltering, normalMapMipMapping and normalMapFormat to PhongMaterial
|
add public properties normalMapFiltering, normalMapMipMapping and normalMapFormat to PhongMaterial
|
ActionScript
|
mit
|
aerys/minko-as3
|
fd9a50fd5584ab10cdf0a5b1c37223fbd663a65d
|
src/as/com/threerings/util/StringUtil.as
|
src/as/com/threerings/util/StringUtil.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.utils.ByteArray;
import flash.utils.describeType; // function import
import mx.utils.*;
public class StringUtil
{
/**
* Get a reasonable hash code for the specified String.
*/
public static function hashCode (str :String) :int
{
var code :int = 0;
if (str != null) {
// sample at most 8 chars
var lastChar :int = Math.min(8, str.length);
for (var ii :int = 0; ii < lastChar; ii++) {
code = code * 31 + str.charCodeAt(ii);
}
}
return code;
}
public static function isBlank (str :String) :Boolean
{
return (str == null) || (str.search("\\S") == -1);
}
/**
* Does the specified string end with the specified substring.
*/
public static function endsWith (str :String, substr :String) :Boolean
{
var startDex :int = str.length - substr.length;
return (startDex >= 0) && (str.indexOf(substr, startDex) >= 0);
}
/**
* Does the specified string start with the specified substring.
*/
public static function startsWith (str :String, substr :String) :Boolean
{
// just check once if it's at the beginning
return (str.lastIndexOf(substr, 0) == 0);
}
/**
* Return true iff the first character is a lower-case character.
*/
public static function isLowerCase (str :String) :Boolean
{
var firstChar :String = str.charAt(0);
return (firstChar.toUpperCase() != firstChar) &&
(firstChar.toLowerCase() == firstChar);
}
/**
* Return true iff the first character is an upper-case character.
*/
public static function isUpperCase (str :String) :Boolean
{
var firstChar :String = str.charAt(0);
return (firstChar.toUpperCase() == firstChar) &&
(firstChar.toLowerCase() != firstChar);
}
/**
* Parse an integer more anally than the built-in parseInt() function,
* throwing an ArgumentError if there are any invalid characters.
*
* The built-in parseInt() will ignore trailing non-integer characters.
*
* @param str The string to parse.
* @param radix The radix to use, from 2 to 16. If not specified the radix will be 10,
* unless the String begins with "0x" in which case it will be 16,
* or the String begins with "0" in which case it will be 8.
*/
public static function parseInteger (str :String, radix :uint = 0) :int
{
if (str == null) {
throw new ArgumentError("Cannot parseInt(null)");
}
if (radix == 0) {
if (startsWith(str, "0x")) {
str = str.substring(2);
radix = 16;
} else if (startsWith(str, "0")) {
str = str.substring(1);
radix = 8;
} else {
radix = 10;
}
} else if (radix == 16 && startsWith(str, "0x")) {
str = str.substring(2);
} else if (radix < 2 || radix > 16) {
throw new ArgumentError("Radix out of range: " + radix);
}
// now verify that str only contains valid chars for the radix
for (var ii :int = 0; ii < str.length; ii++) {
var dex :int = HEX.indexOf(str.charAt(ii).toLowerCase());
if (dex == -1 || dex >= radix) {
throw new ArgumentError("Invalid characters in String parseInt='" + arguments[0] +
"', radix=" + radix);
}
}
var result :Number = parseInt(str, radix);
if (isNaN(result)) {
// this shouldn't happen..
throw new ArgumentError("Could not parseInt=" + arguments[0]);
}
return int(result);
}
/**
* Append 0 or more copies of the padChar String to the input String
* until it is at least the specified length.
*/
public static function pad (
str :String, length :int, padChar :String = " ") :String
{
while (str.length < length) {
str += padChar;
}
return str;
}
/**
* Prepend 0 or more copies of the padChar String to the input String
* until it is at least the specified length.
*/
public static function prepad (
str :String, length :int, padChar :String = " ") :String
{
while (str.length < length) {
str = padChar + str;
}
return str;
}
/**
* Substitute "{n}" tokens for the corresponding passed-in arguments.
*/
public static function substitute (str :String, ... args) :String
{
// holy christ the varargs insanity
args = Util.unfuckVarargs(args);
args.unshift(str);
return mx.utils.StringUtil.substitute.apply(null, args);
}
/**
* Utility function that strips whitespace from the ends of a String.
*/
public static function trim (str :String) :String
{
return mx.utils.StringUtil.trim(str);
}
public static function toString (obj :Object) :String
{
if (obj is Array) {
var arr :Array = (obj as Array);
var s :String = "Array(";
for (var ii :int = 0; ii < arr.length; ii++) {
if (ii > 0) {
s += ", ";
}
s += (ii + ": " + toString(arr[ii]));
}
return s + ")";
}
return String(obj);
}
/**
* Return a string containing all the public fields of the object
*/
public static function fieldsToString (buf :StringBuilder, obj :Object) :void
{
var desc :XML = describeType(obj);
var appended :Boolean = false;
for each (var varName :String in desc..variable.@name) {
if (appended) {
buf.append(", ");
}
buf.append(varName, "=", obj[varName]);
appended = true;
}
}
/**
* Return a pretty basic toString of the supplied Object.
*/
public static function simpleToString (obj :Object) :String
{
var buf :StringBuilder = new StringBuilder("[");
buf.append(ClassUtil.tinyClassName(obj));
buf.append("(");
fieldsToString(buf, obj);
return buf.append(")]").toString();
}
/**
* Truncate the specified String if it is longer than maxLength.
* The string will be truncated at a position such that it is
* maxLength chars long after the addition of the 'append' String.
*
* @param append a String to add to the truncated String only after
* truncation.
*/
public static function truncate (
s :String, maxLength :int, append :String = "") :String
{
if ((s == null) || (s.length <= maxLength)) {
return s;
} else {
return s.substring(0, maxLength - append.length) + append;
}
}
/**
* Locate URLs in a string, return an array in which even elements
* are plain text, odd elements are urls (as Strings). Any even element
* may be an empty string.
*/
public static function parseURLs (s :String) :Array
{
var array :Array = [];
while (true) {
var result :Object = URL_REGEXP.exec(s);
if (result == null) {
break;
}
var index :int = int(result.index);
var url :String = String(result[0]);
array.push(s.substring(0, index), url);
s = s.substring(index + url.length);
}
// just the string is left
array.push(s);
return array;
}
/**
* Turn the specified byte array, containing only ascii characters, into a String.
*/
public static function fromBytes (bytes :ByteArray) :String
{
var s :String = "";
if (bytes != null) {
for (var ii :int = 0; ii < bytes.length; ii++) {
s += String.fromCharCode(bytes[ii]);
}
}
return s;
}
/**
* Turn the specified String, containing only ascii characters, into a ByteArray.
*/
public static function toBytes (s :String) :ByteArray
{
if (s == null) {
return null;
}
var ba :ByteArray = new ByteArray();
for (var ii :int = 0; ii < s.length; ii++) {
ba[ii] = int(s.charCodeAt(ii)) & 0xFF;
}
return ba;
}
/**
* Generates a string from the supplied bytes that is the hex encoded
* representation of those byts. Returns the empty String for a
* <code>null</code> or empty byte array.
*/
public static function hexlate (bytes :ByteArray) :String
{
var str :String = "";
if (bytes != null) {
for (var ii :int = 0; ii < bytes.length; ii++) {
var b :int = bytes[ii];
str += HEX[b >> 4] + HEX[b & 0xF];
}
}
return str;
}
/**
* Turn a hexlated String back into a ByteArray.
*/
public static function unhexlate (hex :String) :ByteArray
{
if (hex == null || (hex.length % 2 != 0)) {
return null;
}
hex = hex.toLowerCase();
var data :ByteArray = new ByteArray();
for (var ii :int = 0; ii < hex.length; ii += 2) {
var value :int = HEX.indexOf(hex.charAt(ii)) << 4;
value += HEX.indexOf(hex.charAt(ii + 1));
// TODO: verify
// values over 127 are wrapped around, restoring negative bytes
data[ii / 2] = value;
}
return data;
}
/** Hexidecimal digits. */
protected static const HEX :Array = [ "0", "1", "2", "3", "4",
"5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" ];
/** A regular expression that finds URLs. */
protected static const URL_REGEXP :RegExp =
new RegExp("(http|https|ftp)://\\S+", "i");
}
}
|
//
// $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.utils.ByteArray;
import flash.utils.describeType; // function import
import mx.utils.*;
public class StringUtil
{
/**
* Get a reasonable hash code for the specified String.
*/
public static function hashCode (str :String) :int
{
var code :int = 0;
if (str != null) {
// sample at most 8 chars
var lastChar :int = Math.min(8, str.length);
for (var ii :int = 0; ii < lastChar; ii++) {
code = code * 31 + str.charCodeAt(ii);
}
}
return code;
}
public static function isBlank (str :String) :Boolean
{
return (str == null) || (str.search("\\S") == -1);
}
/**
* Does the specified string end with the specified substring.
*/
public static function endsWith (str :String, substr :String) :Boolean
{
var startDex :int = str.length - substr.length;
return (startDex >= 0) && (str.indexOf(substr, startDex) >= 0);
}
/**
* Does the specified string start with the specified substring.
*/
public static function startsWith (str :String, substr :String) :Boolean
{
// just check once if it's at the beginning
return (str.lastIndexOf(substr, 0) == 0);
}
/**
* Return true iff the first character is a lower-case character.
*/
public static function isLowerCase (str :String) :Boolean
{
var firstChar :String = str.charAt(0);
return (firstChar.toUpperCase() != firstChar) &&
(firstChar.toLowerCase() == firstChar);
}
/**
* Return true iff the first character is an upper-case character.
*/
public static function isUpperCase (str :String) :Boolean
{
var firstChar :String = str.charAt(0);
return (firstChar.toUpperCase() == firstChar) &&
(firstChar.toLowerCase() != firstChar);
}
/**
* Parse an integer more anally than the built-in parseInt() function,
* throwing an ArgumentError if there are any invalid characters.
*
* The built-in parseInt() will ignore trailing non-integer characters.
*
* @param str The string to parse.
* @param radix The radix to use, from 2 to 16. If not specified the radix will be 10,
* unless the String begins with "0x" in which case it will be 16,
* or the String begins with "0" in which case it will be 8.
*/
public static function parseInteger (str :String, radix :uint = 0) :int
{
if (str == null) {
throw new ArgumentError("Cannot parseInt(null)");
}
if (radix == 0) {
if (startsWith(str, "0x")) {
str = str.substring(2);
radix = 16;
} else if (startsWith(str, "0")) {
str = str.substring(1);
radix = 8;
} else {
radix = 10;
}
} else if (radix == 16 && startsWith(str, "0x")) {
str = str.substring(2);
} else if (radix < 2 || radix > 16) {
throw new ArgumentError("Radix out of range: " + radix);
}
// now verify that str only contains valid chars for the radix
for (var ii :int = 0; ii < str.length; ii++) {
var dex :int = HEX.indexOf(str.charAt(ii).toLowerCase());
if (dex == -1 || dex >= radix) {
throw new ArgumentError("Invalid characters in String parseInt='" + arguments[0] +
"', radix=" + radix);
}
}
var result :Number = parseInt(str, radix);
if (isNaN(result)) {
// this shouldn't happen..
throw new ArgumentError("Could not parseInt=" + arguments[0]);
}
return int(result);
}
/**
* Append 0 or more copies of the padChar String to the input String
* until it is at least the specified length.
*/
public static function pad (
str :String, length :int, padChar :String = " ") :String
{
while (str.length < length) {
str += padChar;
}
return str;
}
/**
* Prepend 0 or more copies of the padChar String to the input String
* until it is at least the specified length.
*/
public static function prepad (
str :String, length :int, padChar :String = " ") :String
{
while (str.length < length) {
str = padChar + str;
}
return str;
}
/**
* Substitute "{n}" tokens for the corresponding passed-in arguments.
*/
public static function substitute (str :String, ... args) :String
{
// holy christ the varargs insanity
args = Util.unfuckVarargs(args);
args.unshift(str);
return mx.utils.StringUtil.substitute.apply(null, args);
}
/**
* Utility function that strips whitespace from the ends of a String.
*/
public static function trim (str :String) :String
{
return mx.utils.StringUtil.trim(str);
}
public static function toString (obj :*) :String
{
if (obj is Array) {
var arr :Array = (obj as Array);
var s :String = "Array(";
for (var ii :int = 0; ii < arr.length; ii++) {
if (ii > 0) {
s += ", ";
}
s += (ii + ": " + toString(arr[ii]));
}
return s + ")";
}
return String(obj);
}
/**
* Return a string containing all the public fields of the object
*/
public static function fieldsToString (buf :StringBuilder, obj :Object) :void
{
var desc :XML = describeType(obj);
var appended :Boolean = false;
for each (var varName :String in desc..variable.@name) {
if (appended) {
buf.append(", ");
}
buf.append(varName, "=", obj[varName]);
appended = true;
}
}
/**
* Return a pretty basic toString of the supplied Object.
*/
public static function simpleToString (obj :Object) :String
{
var buf :StringBuilder = new StringBuilder("[");
buf.append(ClassUtil.tinyClassName(obj));
buf.append("(");
fieldsToString(buf, obj);
return buf.append(")]").toString();
}
/**
* Truncate the specified String if it is longer than maxLength.
* The string will be truncated at a position such that it is
* maxLength chars long after the addition of the 'append' String.
*
* @param append a String to add to the truncated String only after
* truncation.
*/
public static function truncate (
s :String, maxLength :int, append :String = "") :String
{
if ((s == null) || (s.length <= maxLength)) {
return s;
} else {
return s.substring(0, maxLength - append.length) + append;
}
}
/**
* Locate URLs in a string, return an array in which even elements
* are plain text, odd elements are urls (as Strings). Any even element
* may be an empty string.
*/
public static function parseURLs (s :String) :Array
{
var array :Array = [];
while (true) {
var result :Object = URL_REGEXP.exec(s);
if (result == null) {
break;
}
var index :int = int(result.index);
var url :String = String(result[0]);
array.push(s.substring(0, index), url);
s = s.substring(index + url.length);
}
// just the string is left
array.push(s);
return array;
}
/**
* Turn the specified byte array, containing only ascii characters, into a String.
*/
public static function fromBytes (bytes :ByteArray) :String
{
var s :String = "";
if (bytes != null) {
for (var ii :int = 0; ii < bytes.length; ii++) {
s += String.fromCharCode(bytes[ii]);
}
}
return s;
}
/**
* Turn the specified String, containing only ascii characters, into a ByteArray.
*/
public static function toBytes (s :String) :ByteArray
{
if (s == null) {
return null;
}
var ba :ByteArray = new ByteArray();
for (var ii :int = 0; ii < s.length; ii++) {
ba[ii] = int(s.charCodeAt(ii)) & 0xFF;
}
return ba;
}
/**
* Generates a string from the supplied bytes that is the hex encoded
* representation of those byts. Returns the empty String for a
* <code>null</code> or empty byte array.
*/
public static function hexlate (bytes :ByteArray) :String
{
var str :String = "";
if (bytes != null) {
for (var ii :int = 0; ii < bytes.length; ii++) {
var b :int = bytes[ii];
str += HEX[b >> 4] + HEX[b & 0xF];
}
}
return str;
}
/**
* Turn a hexlated String back into a ByteArray.
*/
public static function unhexlate (hex :String) :ByteArray
{
if (hex == null || (hex.length % 2 != 0)) {
return null;
}
hex = hex.toLowerCase();
var data :ByteArray = new ByteArray();
for (var ii :int = 0; ii < hex.length; ii += 2) {
var value :int = HEX.indexOf(hex.charAt(ii)) << 4;
value += HEX.indexOf(hex.charAt(ii + 1));
// TODO: verify
// values over 127 are wrapped around, restoring negative bytes
data[ii / 2] = value;
}
return data;
}
/** Hexidecimal digits. */
protected static const HEX :Array = [ "0", "1", "2", "3", "4",
"5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" ];
/** A regular expression that finds URLs. */
protected static const URL_REGEXP :RegExp =
new RegExp("(http|https|ftp)://\\S+", "i");
}
}
|
Allow undefined array elements to print as "undefined" rather than "null".
|
Allow undefined array elements to print as "undefined" rather than "null".
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4749 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.