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
|
---|---|---|---|---|---|---|---|---|---|
37bee06024be52a1afe0d1adf733c391e8891888
|
src/sample/Act203.as
|
src/sample/Act203.as
|
package sample
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.text.TextField;
public class Act203 extends Sprite
{
public function Act203()
{
super();
addEventListener(Event.ADDED_TO_STAGE,init);
}
private function init(event:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE,init);
var url:String = 'http://192.168.24.24/php/api.ph';
// var url:String = 'http://192.168.24.24/php/api.php';
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE,onLoaded);
loader.addEventListener(IOErrorEvent.IO_ERROR,onLoadError);
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.load(new URLRequest(url));
}
private function onLoaded(event:Event):void
{
var loader:URLLoader = event.currentTarget as URLLoader;
var text:String = loader.data as String;
trace('API retun ' + text);
showText(text);
}
private function onLoadError(event:IOErrorEvent):void
{
showText('an error occured.');
}
private function showText(message:String):void
{
var text:TextField = new TextField();
text.text = message;
text.width = 200;
text.x = (stage.stageWidth - text.width) / 2;
text.y = (stage.stageHeight - text.height) / 2;
addChild(text);
}
}
}
|
package sample
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.text.TextField;
public class Act203 extends Sprite
{
public function Act203()
{
super();
addEventListener(Event.ADDED_TO_STAGE,init);
}
private function init(event:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE,init);
var url:String = 'http://192.168.24.24/php/api.ph';
// var url:String = 'http://192.168.24.24/php/api.php';
var loader:URLLoader = new URLLoader();
//↓これは使わない方がいい。対象のファイルが無い時にTryCatchが効かない
// loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE,onLoaded);
loader.addEventListener(IOErrorEvent.IO_ERROR,onLoadError);
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.load(new URLRequest(url));
}
private function onLoaded(event:Event):void
{
var loader:URLLoader = event.currentTarget as URLLoader;
var text:String = loader.data as String;
trace('API retun ' + text);
showText(text);
}
private function onLoadError(event:IOErrorEvent):void
{
showText('an error occured.');
}
private function showText(message:String):void
{
var text:TextField = new TextField();
text.text = message;
text.width = 200;
text.x = (stage.stageWidth - text.width) / 2;
text.y = (stage.stageHeight - text.height) / 2;
addChild(text);
}
}
}
|
Update Act203.as
|
Update Act203.as
コメント追加
|
ActionScript
|
mit
|
z-ohnami/asWork,z-ohnami/asWork
|
fcf091b5c149f7229b47c10ed223654cb8d19768
|
src/as/com/threerings/flex/ChatControl.as
|
src/as/com/threerings/flex/ChatControl.as
|
//
// $Id$
package com.threerings.flex {
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import flash.events.FocusEvent;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.events.TextEvent;
import flash.ui.Keyboard;
import mx.containers.HBox;
import mx.core.Application;
import mx.controls.TextInput;
import mx.events.FlexEvent;
import com.threerings.util.ArrayUtil;
import com.threerings.util.StringUtil;
import com.threerings.flex.CommandButton;
import com.threerings.flex.CommandMenu;
import com.threerings.crowd.chat.client.ChatDirector;
import com.threerings.crowd.chat.data.ChatCodes;
import com.threerings.crowd.util.CrowdContext;
/**
* The chat control widget.
*/
public class ChatControl extends HBox
{
/**
* Request focus for the oldest ChatControl.
*/
public static function grabFocus () :void
{
if (_controls.length > 0) {
(_controls[0] as ChatControl).setFocus();
}
}
public function ChatControl (
ctx :CrowdContext, sendButtonLabel :String = "send",
height :Number = NaN, controlHeight :Number = NaN)
{
_ctx = ctx;
_chatDtr = _ctx.getChatDirector();
this.height = height;
styleName = "chatControl";
addChild(_txt = new ChatInput());
_txt.addEventListener(FlexEvent.ENTER, sendChat, false, 0, true);
_but = new CommandButton(sendButtonLabel, sendChat);
addChild(_but);
if (!isNaN(controlHeight)) {
_txt.height = controlHeight;
_but.height = controlHeight;
}
addEventListener(Event.ADDED_TO_STAGE, handleAddRemove);
addEventListener(Event.REMOVED_FROM_STAGE, handleAddRemove);
}
/**
* Provides access to the text field we use to accept chat.
*/
public function get chatInput () :ChatInput
{
return _txt;
}
/**
* Provides access to the send button.
*/
public function get sendButton () :CommandButton
{
return _but;
}
/**
* Request focus to this chat control.
*/
override public function setFocus () :void
{
_txt.setFocus();
}
/**
* Enables or disables our chat input.
*/
public function setEnabled (enabled :Boolean) :void
{
_txt.enabled = enabled;
_but.enabled = enabled;
}
/**
* Configures the chat director to which we should send our chat. Pass null to restore our
* default chat director.
*/
public function setChatDirector (chatDtr :ChatDirector) :void
{
_chatDtr = (chatDtr == null) ? _ctx.getChatDirector() : chatDtr;
}
/**
* Configures the background color of the text entry area.
*/
public function setChatColor (color :int) :void
{
_txt.setStyle("backgroundColor", color);
}
/**
* Handles FlexEvent.ENTER and the action from the send button.
*/
protected function sendChat (... ignored) :void
{
var message :String = StringUtil.trim(_txt.text);
if ("" == message) {
return;
}
var result :String = _chatDtr.requestChat(null, message, true);
if (result != ChatCodes.SUCCESS) {
_chatDtr.displayFeedback(null, result);
return;
}
// if there was no error, clear the entry area in prep for the next entry event
_txt.text = "";
}
/**
* Handles Event.ADDED_TO_STAGE and Event.REMOVED_FROM_STAGE.
*/
protected function handleAddRemove (event :Event) :void
{
if (event.type == Event.ADDED_TO_STAGE) {
// set up any already-configured text
_txt.text = _curLine;
// request focus
callLater(_txt.setFocus);
_controls.push(this);
} else {
_curLine = _txt.text;
ArrayUtil.removeAll(_controls, this);
}
}
/** Our client-side context. */
protected var _ctx :CrowdContext;
/** The director to which we are sending chat requests. */
protected var _chatDtr :ChatDirector;
/** The place where the user may enter chat. */
protected var _txt :ChatInput;
/** The button for sending chat. */
protected var _but :CommandButton;
/** An array of the currently shown-controls. */
protected static var _controls :Array = [];
/** The preserved current line of text when traversing history or carried between instances of
* ChatControl. */
protected static var _curLine :String;
}
}
|
//
// $Id$
package com.threerings.flex {
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import flash.events.FocusEvent;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.events.TextEvent;
import flash.ui.Keyboard;
import mx.containers.HBox;
import mx.core.Application;
import mx.controls.TextInput;
import mx.events.FlexEvent;
import com.threerings.util.ArrayUtil;
import com.threerings.util.StringUtil;
import com.threerings.flex.CommandButton;
import com.threerings.flex.CommandMenu;
import com.threerings.crowd.chat.client.ChatDirector;
import com.threerings.crowd.chat.data.ChatCodes;
import com.threerings.crowd.util.CrowdContext;
/**
* The chat control widget.
*/
public class ChatControl extends HBox
{
/**
* Request focus for the oldest ChatControl.
*/
public static function grabFocus () :void
{
if (_controls.length > 0) {
(_controls[0] as ChatControl).setFocus();
}
}
public function ChatControl (
ctx :CrowdContext, sendButtonLabel :String = "send",
height :Number = NaN, controlHeight :Number = NaN)
{
_ctx = ctx;
_chatDtr = _ctx.getChatDirector();
this.height = height;
styleName = "chatControl";
addChild(_txt = new ChatInput());
_txt.addEventListener(FlexEvent.ENTER, sendChat, false, 0, true);
_txt.addEventListener(KeyboardEvent.KEY_UP, handleKeyUp);
_but = new CommandButton(sendButtonLabel, sendChat);
addChild(_but);
if (!isNaN(controlHeight)) {
_txt.height = controlHeight;
_but.height = controlHeight;
}
addEventListener(Event.ADDED_TO_STAGE, handleAddRemove);
addEventListener(Event.REMOVED_FROM_STAGE, handleAddRemove);
}
/**
* Provides access to the text field we use to accept chat.
*/
public function get chatInput () :ChatInput
{
return _txt;
}
/**
* Provides access to the send button.
*/
public function get sendButton () :CommandButton
{
return _but;
}
/**
* Request focus to this chat control.
*/
override public function setFocus () :void
{
_txt.setFocus();
}
/**
* Enables or disables our chat input.
*/
public function setEnabled (enabled :Boolean) :void
{
_txt.enabled = enabled;
_but.enabled = enabled;
}
/**
* Configures the chat director to which we should send our chat. Pass null to restore our
* default chat director.
*/
public function setChatDirector (chatDtr :ChatDirector) :void
{
_chatDtr = (chatDtr == null) ? _ctx.getChatDirector() : chatDtr;
}
/**
* Configures the background color of the text entry area.
*/
public function setChatColor (color :int) :void
{
_txt.setStyle("backgroundColor", color);
}
/**
* Handles FlexEvent.ENTER and the action from the send button.
*/
protected function sendChat (... ignored) :void
{
var message :String = StringUtil.trim(_txt.text);
if ("" == message) {
return;
}
var result :String = _chatDtr.requestChat(null, message, true);
if (result != ChatCodes.SUCCESS) {
_chatDtr.displayFeedback(null, result);
return;
}
// if there was no error, clear the entry area in prep for the next entry event
_txt.text = "";
_histidx = -1;
}
protected function scrollHistory (next :Boolean) :void
{
var size :int = _chatDtr.getCommandHistorySize();
if ((_histidx == -1) || (_histidx == size)) {
_curLine = _txt.text;
_histidx = size;
}
_histidx = (next) ? Math.min(_histidx + 1, size)
: Math.max(_histidx - 1, 0);
var text :String = (_histidx == size) ? _curLine : _chatDtr.getCommandHistory(_histidx);
_txt.text = text;
_txt.setSelection(text.length, text.length);
}
/**
* Handles Event.ADDED_TO_STAGE and Event.REMOVED_FROM_STAGE.
*/
protected function handleAddRemove (event :Event) :void
{
if (event.type == Event.ADDED_TO_STAGE) {
// set up any already-configured text
_txt.text = _curLine;
_histidx = -1;
// request focus
callLater(_txt.setFocus);
_controls.push(this);
} else {
_curLine = _txt.text;
ArrayUtil.removeAll(_controls, this);
}
}
protected function handleKeyUp (event :KeyboardEvent) :void
{
switch (event.keyCode) {
case Keyboard.UP: scrollHistory(false); break;
case Keyboard.DOWN: scrollHistory(true); break;
}
}
/** Our client-side context. */
protected var _ctx :CrowdContext;
/** The director to which we are sending chat requests. */
protected var _chatDtr :ChatDirector;
/** The place where the user may enter chat. */
protected var _txt :ChatInput;
/** The current index in the chat command history. */
protected var _histidx :int = -1;
/** The button for sending chat. */
protected var _but :CommandButton;
/** An array of the currently shown-controls. */
protected static var _controls :Array = [];
/** The preserved current line of text when traversing history or carried between instances of
* ChatControl. */
protected static var _curLine :String;
}
}
|
Allow the up and down arrow keys to traverse the command history, like we do in Java.
|
Allow the up and down arrow keys to traverse the command history, like we do in Java.
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@667 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
c96fb7bd2304bec2b3f84ab32d619a9794fc13b5
|
src/com/merlinds/miracle_tool/viewer/ViewerView.as
|
src/com/merlinds/miracle_tool/viewer/ViewerView.as
|
/**
* User: MerlinDS
* Date: 18.07.2014
* Time: 17:42
*/
package com.merlinds.miracle_tool.viewer {
import com.bit101.components.List;
import com.bit101.components.Window;
import com.merlinds.debug.log;
import com.merlinds.miracle.Miracle;
import com.merlinds.miracle.animations.AnimationHelper;
import com.merlinds.miracle.display.MiracleDisplayObject;
import com.merlinds.miracle.utils.Asset;
import com.merlinds.miracle.utils.MafReader;
import com.merlinds.miracle_tool.models.AppModel;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.html.script.Package;
import flash.utils.ByteArray;
[SWF(backgroundColor="0x333333", frameRate=60)]
public class ViewerView extends Sprite {
private var _model:AppModel;
private var _assets:Vector.<Asset>;
private var _window:Window;
private var _name:String;
private var _current:MiracleDisplayObject;
public function ViewerView(model:AppModel = null) {
super();
_model = model;
if(_model == null){
_model = new AppModel();
}
this.addEventListener(Event.ADDED_TO_STAGE, this.initialize);
}
//==============================================================================
//{region PUBLIC METHODS
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
private function initialize(event:Event):void {
this.removeEventListener(event.type, this.initialize);
this.stage.scaleMode = StageScaleMode.NO_SCALE;
this.stage.align = StageAlign.TOP_LEFT;
Miracle.start(this.stage, this.createHandler, true);
}
private function choseAnimation():void {
//find animation asset and add all of animations to chose list
var n:int = _assets.length;
for(var i:int = 0; i < n; i++){
var asset:Asset = _assets[i];
if(asset.type == Asset.TIMELINE_TYPE){
//parse output
_window = new Window(this, 0, 0, "Chose animation");
var list:List = new List(_window, 0, 0, this.getAnimations(asset.output));
_window.x = this.stage.stageWidth - _window.width;
list.addEventListener(Event.SELECT, this.selectAnimationHandler);
}
}
var w2:Window = new Window(this, _window.x, _window.y + _window.height + 10, "FPS");
list = new List(w2, 0, 0, [1, 5, 16, 24, 30, 35, 40, 60]);
w2.height = 120;
list.addEventListener(Event.SELECT, this.selectFpsHandler);
}
[Inline]
private function getAnimations(bytes:ByteArray):Array {
var result:Array = [];
var reader:MafReader = new MafReader();
reader.execute(bytes);
var animations:Vector.<AnimationHelper> = reader.animations;
for each(var animation:AnimationHelper in animations){
result.push(animation.name);
}
return result;
}
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
private function createHandler(animation:Boolean = false):void {
//TODO: Show view if it exit
if(animation || _model.viewerInput == null){
_model.viewerInput = _model.lastFileDirection;
_model.viewerInput.addEventListener(Event.SELECT, this.selectFileHandler);
_model.viewerInput.browseForOpen("Open " + animation ? "Animation" : "Sprite"
+ "file that you want to view");
}
}
private function selectFileHandler(event:Event):void {
_model.viewerInput.removeEventListener(event.type, this.selectFileHandler);
_model.lastFileDirection = _model.viewerInput.parent;
var byteArray:ByteArray = new ByteArray();
var stream:FileStream = new FileStream();
stream.open(_model.viewerInput, FileMode.READ);
stream.readBytes(byteArray);
stream.close();
//parse
if(_assets == null)_assets = new <Asset>[];
var asset:Asset = new Asset(_model.viewerInput.name, byteArray);
if(asset.type == Asset.TIMELINE_TYPE){
_name = asset.name;
}
_assets.push(asset);
if(_assets.length > 1){
this.choseAnimation();
Miracle.createScene(_assets, 1);
Miracle.resume();
}else{
this.createHandler(true);
}
}
private function selectAnimationHandler(event:Event):void {
var list:List = event.target as List;
//add animation to miracle
var animation:String = list.selectedItem.toString();
log(this, "selectAnimationHandler", animation);
Miracle.currentScene.createAnimation(_name, _name + "." + animation, 60)
.addEventListener(Event.ADDED_TO_STAGE, this.imageAddedToStage);
}
private function imageAddedToStage(event:Event):void {
var target:MiracleDisplayObject = event.target as MiracleDisplayObject;
target.moveTO(
500,300 /*this.stage.stageWidth - target.width >> 1,
this.stage.stageHeight - target.height >> 1*/
);
_current = target;
_current.currentFrame = 0;
// _current.stop();
}
private function selectFpsHandler(event:Event):void {
var list:List = event.target as List;
//add animation to miracle
if(_current != null){
_current.fps = int(list.selectedItem);
}
}
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
|
/**
* User: MerlinDS
* Date: 18.07.2014
* Time: 17:42
*/
package com.merlinds.miracle_tool.viewer {
import com.bit101.components.List;
import com.bit101.components.Window;
import com.merlinds.debug.log;
import com.merlinds.miracle.Miracle;
import com.merlinds.miracle.animations.AnimationHelper;
import com.merlinds.miracle.display.MiracleDisplayObject;
import com.merlinds.miracle.utils.Asset;
import com.merlinds.miracle.utils.MafReader;
import com.merlinds.miracle_tool.models.AppModel;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.utils.ByteArray;
[SWF(backgroundColor="0x333333", frameRate=60)]
public class ViewerView extends Sprite {
private var _model:AppModel;
private var _assets:Vector.<Asset>;
private var _window:Window;
private var _name:String;
private var _current:MiracleDisplayObject;
public function ViewerView(model:AppModel = null) {
super();
_model = model;
if(_model == null){
_model = new AppModel();
}
this.addEventListener(Event.ADDED_TO_STAGE, this.initialize);
}
//==============================================================================
//{region PUBLIC METHODS
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
private function initialize(event:Event):void {
this.removeEventListener(event.type, this.initialize);
this.stage.scaleMode = StageScaleMode.NO_SCALE;
this.stage.align = StageAlign.TOP_LEFT;
Miracle.start(this.stage, this.createHandler, true);
}
private function choseAnimation():void {
//find animation asset and add all of animations to chose list
var n:int = _assets.length;
for(var i:int = 0; i < n; i++){
var asset:Asset = _assets[i];
if(asset.type == Asset.TIMELINE_TYPE){
//parse output
_window = new Window(this, 0, 0, "Chose animation");
var list:List = new List(_window, 0, 0, this.getAnimations(asset.output));
_window.x = this.stage.stageWidth - _window.width;
list.addEventListener(Event.SELECT, this.selectAnimationHandler);
}
}
var w2:Window = new Window(this, _window.x, _window.y + _window.height + 10, "FPS");
list = new List(w2, 0, 0, [1, 5, 16, 24, 30, 35, 40, 60]);
w2.height = 120;
list.addEventListener(Event.SELECT, this.selectFpsHandler);
}
[Inline]
private function getAnimations(bytes:ByteArray):Array {
var result:Array = [];
var reader:MafReader = new MafReader();
reader.execute(bytes);
var animations:Vector.<AnimationHelper> = reader.animations;
for each(var animation:AnimationHelper in animations){
result.push(animation.name);
}
return result;
}
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
private function createHandler(animation:Boolean = false):void {
//TODO: Show view if it exit
if(animation || _model.viewerInput == null){
_model.viewerInput = _model.lastFileDirection;
_model.viewerInput.addEventListener(Event.SELECT, this.selectFileHandler);
_model.viewerInput.browseForOpen("Open " + animation ? "Animation" : "Sprite"
+ "file that you want to view");
}
}
private function selectFileHandler(event:Event):void {
_model.viewerInput.removeEventListener(event.type, this.selectFileHandler);
_model.lastFileDirection = _model.viewerInput.parent;
var byteArray:ByteArray = new ByteArray();
var stream:FileStream = new FileStream();
stream.open(_model.viewerInput, FileMode.READ);
stream.readBytes(byteArray);
stream.close();
//parse
if(_assets == null)_assets = new <Asset>[];
var asset:Asset = new Asset(_model.viewerInput.name, byteArray);
if(asset.type == Asset.TIMELINE_TYPE){
_name = asset.name;
}
_assets.push(asset);
if(_assets.length > 1){
this.choseAnimation();
Miracle.createScene(_assets, 1);
Miracle.resume();
}else{
this.createHandler(true);
}
}
private function selectAnimationHandler(event:Event):void {
var list:List = event.target as List;
//add animation to miracle
var animation:String = list.selectedItem.toString();
log(this, "selectAnimationHandler", animation);
if(_current == null){
_current = Miracle.currentScene.createAnimation(_name, _name + "." + animation, 60);
_current.addEventListener(Event.ADDED_TO_STAGE, this.imageAddedToStage);
}else{
_current.animation = _name + "." + animation;
}
}
private function imageAddedToStage(event:Event):void {
_current.moveTO(
this.stage.stageWidth - _current.width >> 1,
this.stage.stageHeight - _current.height >> 1
);
}
private function selectFpsHandler(event:Event):void {
var list:List = event.target as List;
//add animation to miracle
if(_current != null){
_current.fps = int(list.selectedItem);
}
}
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
|
add change animation ability
|
add change animation ability
|
ActionScript
|
mit
|
MerlinDS/miracle_tool
|
3d0e78a651fa627967bfa6f98f80824e0caae598
|
WeaveData/src/weave/data/AttributeColumns/ReferencedColumn.as
|
WeaveData/src/weave/data/AttributeColumns/ReferencedColumn.as
|
/*
Weave (Web-based Analysis and Visualization Environment)
Copyright (C) 2008-2011 University of Massachusetts Lowell
This file is a part of Weave.
Weave is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License, Version 3,
as published by the Free Software Foundation.
Weave is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Weave. If not, see <http://www.gnu.org/licenses/>.
*/
package weave.data.AttributeColumns
{
import flash.utils.getQualifiedClassName;
import weave.api.WeaveAPI;
import weave.api.core.ILinkableObject;
import weave.api.data.IAttributeColumn;
import weave.api.data.IColumnReference;
import weave.api.data.IColumnWrapper;
import weave.api.data.IQualifiedKey;
import weave.api.detectLinkableObjectChange;
import weave.api.registerLinkableChild;
import weave.api.setSessionState;
import weave.core.CallbackCollection;
import weave.core.LinkableDynamicObject;
import weave.core.SessionManager;
import weave.utils.ColumnUtils;
/**
* This provides a wrapper for a referenced column.
*
* @author adufilie
*/
public class ReferencedColumn extends CallbackCollection implements IColumnWrapper
{
/**
* This is a reference to another column.
*/
public const dynamicColumnReference:LinkableDynamicObject = registerLinkableChild(this, new LinkableDynamicObject(IColumnReference));
/**
* The trigger counter value at the last time the internal column was retrieved.
*/
private var _dynamicRefTriggerCounter:uint = 0;
/**
* the internal referenced column
*/
protected var _internalColumn:IAttributeColumn = null;
/**
* This is the actual IColumnReference object inside dynamicColumnReference.
*/
public function get internalColumnReference():IColumnReference
{
return dynamicColumnReference.internalObject as IColumnReference;
}
/**
* @inheritDoc
*/
public function getInternalColumn():IAttributeColumn
{
if (_dynamicRefTriggerCounter != dynamicColumnReference.triggerCounter)
{
_dynamicRefTriggerCounter = dynamicColumnReference.triggerCounter;
var newColumn:IAttributeColumn = WeaveAPI.AttributeColumnCache.getColumn(internalColumnReference);
// do nothing if this is the same column
if (_internalColumn != newColumn)
{
if (_internalColumn)
_internalColumn.removeCallback(triggerCallbacks);
_internalColumn = newColumn;
if (_internalColumn)
_internalColumn.addImmediateCallback(this, triggerCallbacks, false, true);
}
}
return _internalColumn;
}
/************************************
* Begin IAttributeColumn interface
************************************/
public function getMetadata(attributeName:String):String
{
return getInternalColumn() ? _internalColumn.getMetadata(attributeName) : null;
}
/**
* @return the keys associated with this column.
*/
public function get keys():Array
{
return getInternalColumn() ? _internalColumn.keys : [];
}
/**
* @param key A key to test.
* @return true if the key exists in this IKeySet.
*/
public function containsKey(key:IQualifiedKey):Boolean
{
return getInternalColumn() && _internalColumn.containsKey(key);
}
/**
* getValueFromKey
* @param key A key of the type specified by keyType.
* @return The value associated with the given key.
*/
public function getValueFromKey(key:IQualifiedKey, dataType:Class = null):*
{
if (getInternalColumn())
return _internalColumn.getValueFromKey(key, dataType);
return undefined;
}
public function toString():String
{
return debugId(this) + '(' + ColumnUtils.getTitle(this) + ')';
}
// backwards compatibility
[Deprecated(replacement="dynamicColumnReference")] public function set columnReference(value:Object):void
{
setSessionState(dynamicColumnReference, value);
}
}
}
|
/*
Weave (Web-based Analysis and Visualization Environment)
Copyright (C) 2008-2011 University of Massachusetts Lowell
This file is a part of Weave.
Weave is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License, Version 3,
as published by the Free Software Foundation.
Weave is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Weave. If not, see <http://www.gnu.org/licenses/>.
*/
package weave.data.AttributeColumns
{
import flash.utils.getQualifiedClassName;
import weave.api.WeaveAPI;
import weave.api.core.ILinkableObject;
import weave.api.data.IAttributeColumn;
import weave.api.data.IColumnReference;
import weave.api.data.IColumnWrapper;
import weave.api.data.IQualifiedKey;
import weave.api.detectLinkableObjectChange;
import weave.api.registerLinkableChild;
import weave.api.setSessionState;
import weave.core.CallbackCollection;
import weave.core.LinkableDynamicObject;
import weave.core.SessionManager;
import weave.utils.ColumnUtils;
/**
* This provides a wrapper for a referenced column.
*
* @author adufilie
*/
public class ReferencedColumn extends CallbackCollection implements IColumnWrapper
{
/**
* This is a reference to another column.
*/
public const dynamicColumnReference:LinkableDynamicObject = registerLinkableChild(this, new LinkableDynamicObject(IColumnReference));
/**
* The trigger counter value at the last time the internal column was retrieved.
*/
private var _dynamicRefTriggerCounter:uint = 0;
/**
* the internal referenced column
*/
protected var _internalColumn:IAttributeColumn = null;
/**
* This is the actual IColumnReference object inside dynamicColumnReference.
*/
public function get internalColumnReference():IColumnReference
{
return dynamicColumnReference.internalObject as IColumnReference;
}
/**
* @inheritDoc
*/
public function getInternalColumn():IAttributeColumn
{
if (_dynamicRefTriggerCounter != dynamicColumnReference.triggerCounter)
{
_dynamicRefTriggerCounter = dynamicColumnReference.triggerCounter;
var newColumn:IAttributeColumn = WeaveAPI.AttributeColumnCache.getColumn(internalColumnReference);
// do nothing if this is the same column
if (_internalColumn != newColumn)
{
if (_internalColumn != null)
(WeaveAPI.SessionManager as SessionManager).unregisterLinkableChild(this, _internalColumn);
_internalColumn = newColumn;
if (_internalColumn != null)
registerLinkableChild(this, _internalColumn);
}
}
return _internalColumn;
}
/************************************
* Begin IAttributeColumn interface
************************************/
public function getMetadata(attributeName:String):String
{
return getInternalColumn() ? _internalColumn.getMetadata(attributeName) : null;
}
/**
* @return the keys associated with this column.
*/
public function get keys():Array
{
return getInternalColumn() ? _internalColumn.keys : [];
}
/**
* @param key A key to test.
* @return true if the key exists in this IKeySet.
*/
public function containsKey(key:IQualifiedKey):Boolean
{
return getInternalColumn() && _internalColumn.containsKey(key);
}
/**
* getValueFromKey
* @param key A key of the type specified by keyType.
* @return The value associated with the given key.
*/
public function getValueFromKey(key:IQualifiedKey, dataType:Class = null):*
{
if (getInternalColumn())
return _internalColumn.getValueFromKey(key, dataType);
return undefined;
}
public function toString():String
{
return debugId(this) + '(' + ColumnUtils.getTitle(this) + ')';
}
// backwards compatibility
[Deprecated(replacement="dynamicColumnReference")] public function set columnReference(value:Object):void
{
setSessionState(dynamicColumnReference, value);
}
}
}
|
undo recent change
|
undo recent change
Change-Id: I2b39cb43581c9bb84546b6e99c9164f8d1b23b0f
|
ActionScript
|
mpl-2.0
|
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
|
7fe72d2db1fc0e92367880fa5dd7f94dfc575fcc
|
src/com/esri/builder/controllers/supportClasses/WidgetTypeLoader.as
|
src/com/esri/builder/controllers/supportClasses/WidgetTypeLoader.as
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////////
package com.esri.builder.controllers.supportClasses
{
import com.esri.builder.model.Model;
import com.esri.builder.model.WidgetType;
import com.esri.builder.model.WidgetTypeRegistryModel;
import com.esri.builder.supportClasses.LogUtil;
import com.esri.builder.views.BuilderAlert;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.system.ApplicationDomain;
import modules.IBuilderModule;
import modules.supportClasses.CustomXMLModule;
import mx.core.FlexGlobals;
import mx.events.ModuleEvent;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.modules.IModuleInfo;
import mx.modules.ModuleManager;
import mx.resources.ResourceManager;
public class WidgetTypeLoader extends EventDispatcher
{
private static const LOG:ILogger = LogUtil.createLogger(WidgetTypeLoader);
private var _moduleInfoArr:Array = [];
private var _widgetTypeArr:Array = [];
public function loadWidgetTypes():void
{
if (Log.isInfo())
{
LOG.info('Loading modules...');
}
const modulesDirectory:File = WellKnownDirectories.getInstance().bundledModules;
loadCustomWidgetTypes(WellKnownDirectories.getInstance().customModules);
// Find all swf files under the modules folder.
const swfList:Array = [];
if (modulesDirectory.isDirectory)
{
getSWFList(modulesDirectory, swfList);
}
// Load the found modules.
swfList.forEach(function(file:File, index:int, source:Array):void
{
if (Log.isDebug())
{
LOG.debug('loading module {0}', file.url);
}
const moduleInfo:IModuleInfo = ModuleManager.getModule(file.url);
_moduleInfoArr.push(moduleInfo);
moduleInfo.addEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
moduleInfo.addEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
moduleInfo.load(ApplicationDomain.currentDomain, null, null, FlexGlobals.topLevelApplication.moduleFactory);
});
checkIfNoMoreModuleInfosLeft();
}
private function loadCustomWidgetTypes(modulesDirectory:File):void
{
var moduleDirectoryContents:Array = modulesDirectory.getDirectoryListing();
for each (var fileOrFolder:File in moduleDirectoryContents)
{
loadCustomWidgetTypeConfig(fileOrFolder);
}
}
public function loadCustomWidgetTypeConfig(configFile:File):void
{
const customModuleFileName:RegExp = /^.*Module\.xml$/;
if (!configFile.isDirectory && customModuleFileName.test(configFile.name))
{
var customModule:IBuilderModule = createCustomModuleFromConfig(configFile);
if (customModule)
{
WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.addWidgetType(new WidgetType(customModule));
}
}
}
private function createCustomModuleFromConfig(configFile:File):IBuilderModule
{
var fileStream:FileStream = new FileStream();
var customModule:CustomXMLModule;
try
{
fileStream.open(configFile, FileMode.READ);
const configXML:XML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
customModule = parseCustomModule(configXML);
}
catch (e:Error)
{
if (Log.isWarn())
{
LOG.warn('Error creating custom module {0}', configFile.nativePath);
}
}
finally
{
fileStream.close();
}
return customModule;
}
private function parseCustomModule(configXML:XML):CustomXMLModule
{
var customModule:CustomXMLModule = new CustomXMLModule();
customModule.widgetName = configXML.name;
customModule.isOpenByDefault = (configXML.openbydefault == 'true');
var widgetLabel:String = configXML.label[0];
var widgetDescription:String = configXML.description[0];
var widgetHelpURL:String = configXML.helpurl[0];
var widgetConfiguration:String = configXML.configuration[0];
var widgetVersion:String = configXML.widgetversion[0];
customModule.widgetIconLocation = createWidgetIconPath(configXML.icon[0], customModule.widgetName);
customModule.widgetLabel = widgetLabel ? widgetLabel : customModule.widgetName;
customModule.widgetVersion = widgetVersion;
customModule.widgetDescription = widgetDescription ? widgetDescription : "";
customModule.widgetHelpURL = widgetHelpURL ? widgetHelpURL : "";
customModule.configXML = widgetConfiguration ? widgetConfiguration : "<configuration></configuration>";
return customModule;
}
private function createWidgetIconPath(iconPath:String, widgetName:String):String
{
var widgetIconPath:String;
if (iconPath)
{
widgetIconPath = "widgets/" + widgetName + "/" + iconPath;
}
else
{
widgetIconPath = "assets/images/i_widget.png";
}
return widgetIconPath;
}
/**
* This will go through all sub folders in 'modules' looking for .swf files.
*/
private function getSWFList(parentFile:File, arr:Array):void
{
const moduleFileName:RegExp = /^.*Module\.swf$/;
const list:Array = parentFile.getDirectoryListing();
list.forEach(function(file:File, index:int, source:Array):void
{
if (file.isDirectory)
{
getSWFList(file, arr);
}
else if (moduleFileName.test(file.name))
{
arr.push(file);
}
}
);
}
private function moduleInfo_readyHandler(event:ModuleEvent):void
{
var moduleInfo:IModuleInfo = event.currentTarget as IModuleInfo;
moduleInfo.removeEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
const builderModule:IBuilderModule = event.module.factory.create() as IBuilderModule;
if (builderModule)
{
const widgetType:WidgetType = new WidgetType(builderModule);
_widgetTypeArr.push(widgetType);
// Resolve the object
// FlexGlobals.topLevelApplication.registry.resolve(builderModule, ApplicationDomain.currentDomain);
if (Log.isDebug())
{
LOG.debug('Module {0} is resolved', widgetType.name);
}
removeModuleInfo(event.module);
}
}
private function removeModuleInfo(moduleInfo:IModuleInfo):void
{
const index:int = _moduleInfoArr.indexOf(moduleInfo);
if (index > -1)
{
_moduleInfoArr.splice(index, 1);
checkIfNoMoreModuleInfosLeft();
}
}
private function checkIfNoMoreModuleInfosLeft():void
{
if (_moduleInfoArr.length === 0)
{
sortAndAssignWidgetTypes();
}
}
private function sortAndAssignWidgetTypes():void
{
if (Log.isInfo())
{
LOG.info('All modules resolved');
}
_widgetTypeArr.sort(compareWidgetTypes);
var widgetTypes:Array = _widgetTypeArr.filter(widgetTypeFilter);
for each (var widgetType:WidgetType in widgetTypes)
{
WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.addWidgetType(widgetType);
}
var layoutWidgetTypes:Array = _widgetTypeArr.filter(layoutWidgetTypeFilter);
for each (var layoutWidgetType:WidgetType in layoutWidgetTypes)
{
WidgetTypeRegistryModel.getInstance().layoutWidgetTypeRegistry.addWidgetType(layoutWidgetType);
}
function widgetTypeFilter(item:WidgetType, index:int, source:Array):Boolean
{
return item.isManaged;
}
function layoutWidgetTypeFilter(item:WidgetType, index:int, source:Array):Boolean
{
return !item.isManaged;
}
dispatchEvent(new Event(Event.COMPLETE));
}
private function compareWidgetTypes(lhs:WidgetType, rhs:WidgetType):int
{
const lhsLabel:String = lhs.label.toLowerCase();
const rhsLabel:String = rhs.label.toLowerCase();
if (lhsLabel < rhsLabel)
{
return -1;
}
if (lhsLabel > rhsLabel)
{
return 1;
}
return 0;
}
private function moduleInfo_errorHandler(event:ModuleEvent):void
{
if (Log.isWarn())
{
LOG.warn('Module error: {0}', event.errorText);
}
var moduleInfo:IModuleInfo = event.currentTarget as IModuleInfo;
moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
moduleInfo.removeEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
removeModuleInfo(event.module);
Model.instance.status = event.errorText;
BuilderAlert.show(event.errorText,
ResourceManager.getInstance().getString('BuilderStrings', 'error'));
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////////
package com.esri.builder.controllers.supportClasses
{
import com.esri.builder.model.Model;
import com.esri.builder.model.WidgetType;
import com.esri.builder.model.WidgetTypeRegistryModel;
import com.esri.builder.supportClasses.LogUtil;
import com.esri.builder.views.BuilderAlert;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.system.ApplicationDomain;
import flash.utils.ByteArray;
import modules.IBuilderModule;
import modules.supportClasses.CustomXMLModule;
import mx.core.FlexGlobals;
import mx.events.ModuleEvent;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.modules.IModuleInfo;
import mx.modules.ModuleManager;
import mx.resources.ResourceManager;
public class WidgetTypeLoader extends EventDispatcher
{
private static const LOG:ILogger = LogUtil.createLogger(WidgetTypeLoader);
private var _moduleInfoArr:Array = [];
private var _widgetTypeArr:Array = [];
public function loadWidgetTypes():void
{
if (Log.isInfo())
{
LOG.info('Loading modules...');
}
const modulesDirectory:File = WellKnownDirectories.getInstance().bundledModules;
loadCustomWidgetTypes(WellKnownDirectories.getInstance().customModules);
// Find all swf files under the modules folder.
const swfList:Array = [];
if (modulesDirectory.isDirectory)
{
getSWFList(modulesDirectory, swfList);
}
// Load the found modules.
swfList.forEach(function(file:File, index:int, source:Array):void
{
if (Log.isDebug())
{
LOG.debug('loading module {0}', file.url);
}
var fileBytes:ByteArray = new ByteArray();
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
fileStream.readBytes(fileBytes);
fileStream.close();
const moduleInfo:IModuleInfo = ModuleManager.getModule(file.url);
_moduleInfoArr.push(moduleInfo);
moduleInfo.addEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
moduleInfo.addEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
moduleInfo.load(ApplicationDomain.currentDomain, null, fileBytes, FlexGlobals.topLevelApplication.moduleFactory);
});
checkIfNoMoreModuleInfosLeft();
}
private function loadCustomWidgetTypes(modulesDirectory:File):void
{
var moduleDirectoryContents:Array = modulesDirectory.getDirectoryListing();
for each (var fileOrFolder:File in moduleDirectoryContents)
{
loadCustomWidgetTypeConfig(fileOrFolder);
}
}
public function loadCustomWidgetTypeConfig(configFile:File):void
{
const customModuleFileName:RegExp = /^.*Module\.xml$/;
if (!configFile.isDirectory && customModuleFileName.test(configFile.name))
{
var customModule:IBuilderModule = createCustomModuleFromConfig(configFile);
if (customModule)
{
WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.addWidgetType(new WidgetType(customModule));
}
}
}
private function createCustomModuleFromConfig(configFile:File):IBuilderModule
{
var fileStream:FileStream = new FileStream();
var customModule:CustomXMLModule;
try
{
fileStream.open(configFile, FileMode.READ);
const configXML:XML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
customModule = parseCustomModule(configXML);
}
catch (e:Error)
{
if (Log.isWarn())
{
LOG.warn('Error creating custom module {0}', configFile.nativePath);
}
}
finally
{
fileStream.close();
}
return customModule;
}
private function parseCustomModule(configXML:XML):CustomXMLModule
{
var customModule:CustomXMLModule = new CustomXMLModule();
customModule.widgetName = configXML.name;
customModule.isOpenByDefault = (configXML.openbydefault == 'true');
var widgetLabel:String = configXML.label[0];
var widgetDescription:String = configXML.description[0];
var widgetHelpURL:String = configXML.helpurl[0];
var widgetConfiguration:String = configXML.configuration[0];
var widgetVersion:String = configXML.widgetversion[0];
customModule.widgetIconLocation = createWidgetIconPath(configXML.icon[0], customModule.widgetName);
customModule.widgetLabel = widgetLabel ? widgetLabel : customModule.widgetName;
customModule.widgetVersion = widgetVersion;
customModule.widgetDescription = widgetDescription ? widgetDescription : "";
customModule.widgetHelpURL = widgetHelpURL ? widgetHelpURL : "";
customModule.configXML = widgetConfiguration ? widgetConfiguration : "<configuration></configuration>";
return customModule;
}
private function createWidgetIconPath(iconPath:String, widgetName:String):String
{
var widgetIconPath:String;
if (iconPath)
{
widgetIconPath = "widgets/" + widgetName + "/" + iconPath;
}
else
{
widgetIconPath = "assets/images/i_widget.png";
}
return widgetIconPath;
}
/**
* This will go through all sub folders in 'modules' looking for .swf files.
*/
private function getSWFList(parentFile:File, arr:Array):void
{
const moduleFileName:RegExp = /^.*Module\.swf$/;
const list:Array = parentFile.getDirectoryListing();
list.forEach(function(file:File, index:int, source:Array):void
{
if (file.isDirectory)
{
getSWFList(file, arr);
}
else if (moduleFileName.test(file.name))
{
arr.push(file);
}
}
);
}
private function moduleInfo_readyHandler(event:ModuleEvent):void
{
var moduleInfo:IModuleInfo = event.currentTarget as IModuleInfo;
moduleInfo.removeEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
const builderModule:IBuilderModule = event.module.factory.create() as IBuilderModule;
if (builderModule)
{
const widgetType:WidgetType = new WidgetType(builderModule);
_widgetTypeArr.push(widgetType);
// Resolve the object
// FlexGlobals.topLevelApplication.registry.resolve(builderModule, ApplicationDomain.currentDomain);
if (Log.isDebug())
{
LOG.debug('Module {0} is resolved', widgetType.name);
}
removeModuleInfo(event.module);
}
}
private function removeModuleInfo(moduleInfo:IModuleInfo):void
{
const index:int = _moduleInfoArr.indexOf(moduleInfo);
if (index > -1)
{
_moduleInfoArr.splice(index, 1);
checkIfNoMoreModuleInfosLeft();
}
}
private function checkIfNoMoreModuleInfosLeft():void
{
if (_moduleInfoArr.length === 0)
{
sortAndAssignWidgetTypes();
}
}
private function sortAndAssignWidgetTypes():void
{
if (Log.isInfo())
{
LOG.info('All modules resolved');
}
_widgetTypeArr.sort(compareWidgetTypes);
var widgetTypes:Array = _widgetTypeArr.filter(widgetTypeFilter);
for each (var widgetType:WidgetType in widgetTypes)
{
WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.addWidgetType(widgetType);
}
var layoutWidgetTypes:Array = _widgetTypeArr.filter(layoutWidgetTypeFilter);
for each (var layoutWidgetType:WidgetType in layoutWidgetTypes)
{
WidgetTypeRegistryModel.getInstance().layoutWidgetTypeRegistry.addWidgetType(layoutWidgetType);
}
function widgetTypeFilter(item:WidgetType, index:int, source:Array):Boolean
{
return item.isManaged;
}
function layoutWidgetTypeFilter(item:WidgetType, index:int, source:Array):Boolean
{
return !item.isManaged;
}
dispatchEvent(new Event(Event.COMPLETE));
}
private function compareWidgetTypes(lhs:WidgetType, rhs:WidgetType):int
{
const lhsLabel:String = lhs.label.toLowerCase();
const rhsLabel:String = rhs.label.toLowerCase();
if (lhsLabel < rhsLabel)
{
return -1;
}
if (lhsLabel > rhsLabel)
{
return 1;
}
return 0;
}
private function moduleInfo_errorHandler(event:ModuleEvent):void
{
if (Log.isWarn())
{
LOG.warn('Module error: {0}', event.errorText);
}
var moduleInfo:IModuleInfo = event.currentTarget as IModuleInfo;
moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
moduleInfo.removeEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
removeModuleInfo(event.module);
Model.instance.status = event.errorText;
BuilderAlert.show(event.errorText,
ResourceManager.getInstance().getString('BuilderStrings', 'error'));
}
}
}
|
Load modules from SWF bytes.
|
Load modules from SWF bytes.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
0a8dc5890dfed54894705d758237ee7136448860
|
krew-framework/krewfw/core/KrewScene.as
|
krew-framework/krewfw/core/KrewScene.as
|
package krewfw.core {
import starling.display.DisplayObject;
import starling.events.EnterFrameEvent;
import starling.events.Event;
import krewfw.core_internal.SceneServantActor;
import krewfw.core_internal.StageLayer;
import krewfw.core_internal.StuntAction;
import krewfw.utils.as3.KrewTimeKeeper;
//------------------------------------------------------------
public class KrewScene extends KrewGameObject {
private var _newActorPool:Array = new Array();
private var _servantActor:SceneServantActor; // to use multi tasker and so on
private var _isTimeToExit:Boolean = false;
private var _nextScene:KrewScene = null;
private var _hasDisposed:Boolean = false;
//------------------------------------------------------------
public function KrewScene() {
touchable = true;
addEventListener(Event.ENTER_FRAME, _onEnterFrame);
}
public override function dispose():void {
if (_hasDisposed) { return; }
_hasDisposed = true;
removeEventListener(Event.ENTER_FRAME, _onEnterFrame);
sharedObj.layerManager.dispose();
sharedObj.collisionSystem.removeAllGroups();
sharedObj.resourceManager.purgeSceneScopeResources();
_newActorPool = [];
onDispose();
super.dispose();
}
//------------------------------------------------------------
// To compose your game scene, implements these handlers.
//------------------------------------------------------------
/**
* 「ゲーム全体で常に保持しておきたいアセット」に追加するファイル名群を指定.
* これは起動時に 1 回だけ呼ばれる起動処理専用の Scene で指定されることを想定している。
* 現時点では、これによってグローバルに保持したアセットを解放するインタフェースは用意していない。
*
* Scene の getAdditionalGlobalAssets がオーバライドされていた場合、
* Scene は遷移時に Global のアセット読み込みを先に行ってから
* Scene スコープのアセット読み込みを行う。
*
* @see getRequiredAssets
*/
public function getAdditionalGlobalAssets():Array {
return [];
}
/**
* このシーンで必要なアセットのファイルパス一覧を指定.
* ここで指定したアセットによって確保されたリソースは、
* シーン遷移時に自動的に解放される
* @return Example:
* <pre>
* [
* "image/atlas_1.png",
* "image/atlas_1.xml",
* "bgm/bgm_1.mp3",
* "bmp_font/gothic.png",
* "bmp_font/gothic.fnt",
* "level_data/stage_1.json"
* ]
* </pre>
*/
public function getRequiredAssets():Array {
return [];
}
/**
* ローディング画面を構成するための init.
* この時点では KrewGameDirector で指定した大域リソースしか使えないので、
* ここでセットする Actor はグローバルに保持しているリソースを使う必要がある
*/
public function initLoadingView():void {
krew.fwlog(' - default initLoadingView called.');
}
/**
* getAdditionalGlobalAssets で指定したアセット群のロード中に呼ばれる。
* アセットの指定があれば最低 1 回は呼ばれ、最後の呼び出しでは loadRatio = 1 となる
*/
public function onLoadProgressGlobal(loadRatio:Number):void {
krew.fwlog(' - - default onLoadProgressGlobal called: ' + loadRatio);
}
/**
* getAdditionalGlobalAssets で指定したアセット群のロード完了時に呼ばれる。
* (これの直後に getRequiredAssets で指定したアセットの読み込みが始まる)
*/
public function onLoadCompleteGlobal():void {
krew.fwlog(' - - - default onLoadCompleteGlobal called.');
}
/**
* getRequiredAssets で指定したアセット群のロード中に呼ばれる。
* アセットの指定があれば最低 1 回は呼ばれ、最後の呼び出しでは loadRatio = 1 となる
*/
public function onLoadProgress(loadRatio:Number):void {
krew.fwlog(' - - - - default onLoadProgress called: ' + loadRatio);
}
/**
* getRequiredAssets で指定したアセット群のロード完了時に呼ばれる。
* (これの直後に initAfterLoad が呼ばれる)
*/
public function onLoadComplete():void {
krew.fwlog(' - - - - - default onLoadComplete called.');
}
/**
* 全てのアセットのロード完了後の本命のシーン初期化処理
* ここから requiredAssets で指定したアセットが使える
*/
public function initAfterLoad():void {
krew.fwlog(' - - - - - - default initAfterLoad called.');
}
/**
* exit() が呼ばれた際に遷移する次のシーンを返すよう override してほしい.
* なお exit(specificScene) と引数にシーンを渡した場合はそのシーンが遷移先となり、
* この関数は無視される
*/
public function getDefaultNextScene():KrewScene {
return null;
}
/**
* レイヤー構造の定義
* @return Example: ['back', 'front', 'ui']
*/
public function getLayerList():Array {
return ['l-back', 'l-front', 'l-ui'];
}
/**
* 衝突判定を行うグループの定義
* @return Example: Array of Array such as
* <pre>
* [
* ['myship' , ['enemy', 'en-shot', 'item']],
* ['myshot' , ['enemy']],
* ['enemy' , []],
* ['en-shot', []],
* ['item' , []]
* ]
* </pre>
* こう書くと「c-myship と c-enemy グループ間」、
* 「c-myship と c-item グループ間」などでヒットテストが行われるといった次第
*/
public function getCollisionGroups():Array {
return [];
}
//------------------------------------------------------------
// Automatically called by framework
//------------------------------------------------------------
/** @private */
public function startInitSceneSequence():void {
sharedObj.layerManager.setUpLayers(this, getLayerList());
sharedObj.collisionSystem.setUpGroups(getCollisionGroups());
_setUpServantActor();
initLoadingView();
// load global assets, load local assets, and call scene init.
_loadGlobalAssets(function():void {
_loadSceneScopeAssets(function():void {
initAfterLoad();
});
});
}
private function _loadGlobalAssets(doneCallback:Function):void {
// hook onLoadCompleteGlobal
var _onLoadComplete:Function = function():void {
_servantActor.sendMessage(KrewSystemEventType.COMPLETE_GLOBAL_ASSET_LOAD);
onLoadCompleteGlobal();
doneCallback();
};
if (getAdditionalGlobalAssets().length == 0) {
_onLoadComplete();
return;
}
// hook onLoadProgressGlobal
var _onLoadProgressGlobal:Function = function(loadRatio:Number):void {
_servantActor.sendMessage(
KrewSystemEventType.PROGRESS_GLOBAL_ASSET_LOAD, {loadRatio: loadRatio}
);
onLoadProgressGlobal(loadRatio);
};
// start loading assets
sharedObj.resourceManager.loadGlobalResources(
getAdditionalGlobalAssets(), _onLoadProgressGlobal, _onLoadComplete
);
}
private function _loadSceneScopeAssets(doneCallback:Function):void {
// hook onLoadComplete
var _onLoadComplete:Function = function():void {
_servantActor.sendMessage(KrewSystemEventType.COMPLETE_ASSET_LOAD);
onLoadComplete();
doneCallback();
};
if (getRequiredAssets().length == 0) {
_onLoadComplete();
return;
}
// hook onLoadProgress
var _onLoadProgress:Function = function(loadRatio:Number):void {
_servantActor.sendMessage(
KrewSystemEventType.PROGRESS_ASSET_LOAD, {loadRatio: loadRatio}
);
onLoadProgress(loadRatio);
};
// start loading assets
sharedObj.resourceManager.loadResources(
getRequiredAssets(), _onLoadProgress, _onLoadComplete
);
}
private function _setUpServantActor():void {
_servantActor = new SceneServantActor();
setUpActor('_system_', _servantActor);
}
/**
* @private
* 新しい Actor を足してもらうよう Scene に頼む。
* この関数は KrewActor によって呼ばれる。
* 新しい Actor 達は既存の Actor 達の update の後に layer に足される。
*
* layer に足される前に新しい Actor が sharedObject などにアクセスできるように
* するため、KrewActor.setUp() はこの段階で呼ばれる。
*/
public function applyForNewActor(newActor:KrewActor, layerName:String=null):void {
_newActorPool.push({
actor: newActor,
layer: layerName
});
newActor.setUp(
sharedObj, applyForNewActor,
getLayer(layerName), layerName
);
}
private function _recruitNewActors():void {
var count:int = 0;
for each (var info:Object in _newActorPool) {
++count;
setUpActor(info.layer, info.actor);
}
if (count > 0) {
_newActorPool = [];
//krew.fwlog(count + ' new actor joined');
}
}
/** @private */
public function addLayer(layer:StageLayer):void {
layer.sharedObj = this.sharedObj;
layer.applyForNewActor = this.applyForNewActor;
addChild(layer);
}
/** @private */
protected function addActor(layerName:String, actor:KrewActor,
putOnDisplayList:Boolean=true):void {
sharedObj.layerManager.addActor(layerName, actor, putOnDisplayList);
}
/** @private */
protected function addChildToLayer(layerName:String, displayObj:DisplayObject):void {
sharedObj.layerManager.addChild(layerName, displayObj);
}
/** @private */
public function getNextScene():KrewScene {
if (_nextScene != null) {
return _nextScene;
}
return getDefaultNextScene();
}
//------------------------------------------------------------
/**
* Entry point of the game loop
*/
private function _onEnterFrame(event:EnterFrameEvent):void {
if (_hasDisposed) { return; }
var passedTime:Number = KrewTimeKeeper.getReasonablePassedTime(event.passedTime);
mainLoop(passedTime);
}
/**
* Process one frame of game main loop.
* It is called automatically by framework, but you can
* manually call it for unit test of Actor's messaging.
*/
public function mainLoop(passedTime:Number=1/60):void {
if (_servantActor.isSystemActivated) {
// update actors
onUpdate(passedTime);
sharedObj.layerManager.onUpdate(passedTime);
_recruitNewActors();
// collision detection
sharedObj.collisionSystem.hitTest();
}
// broadcast messages
sharedObj.notificationService.broadcastMessage();
if (_isTimeToExit) {
dispatchEvent(new Event(KrewSystemEventType.EXIT_SCENE));
}
}
//------------------------------------------------------------
// Your tools
//------------------------------------------------------------
protected function exit(nextScene:KrewScene=null):void {
_isTimeToExit = true;
_nextScene = nextScene;
}
protected function act(action:StuntAction=null):StuntAction {
return _servantActor.act(action);
}
protected function react():void {
_servantActor.react();
}
public function addScheduledTask(timeout:Number, task:Function):void {
_servantActor.addScheduledTask(timeout, task);
}
public function delay(timeout:Number, task:Function):void {
_servantActor.addScheduledTask(timeout, task);
}
public function addPeriodicTask(interval:Number, task:Function):void {
_servantActor.addPeriodicTask(interval, task);
}
public function cyclic(interval:Number, task:Function):void {
_servantActor.addPeriodicTask(interval, task);
}
public function setUpActor(layerName:String, actor:KrewActor,
putOnDisplayList:Boolean=true):void
{
if (layerName == null) { layerName = 'l-front'; }
addActor(layerName, actor, putOnDisplayList);
}
}
}
|
package krewfw.core {
import starling.display.DisplayObject;
import starling.events.EnterFrameEvent;
import starling.events.Event;
import krewfw.core_internal.SceneServantActor;
import krewfw.core_internal.StageLayer;
import krewfw.core_internal.StuntAction;
import krewfw.utils.as3.KrewTimeKeeper;
//------------------------------------------------------------
public class KrewScene extends KrewGameObject {
private var _newActorPool:Array = new Array();
private var _servantActor:SceneServantActor; // to use multi tasker and so on
private var _isTimeToExit:Boolean = false;
private var _nextScene:KrewScene = null;
private var _hasDisposed:Boolean = false;
//------------------------------------------------------------
public function KrewScene() {
touchable = true;
addEventListener(Event.ENTER_FRAME, _onEnterFrame);
}
public override function dispose():void {
if (_hasDisposed) { return; }
_hasDisposed = true;
removeEventListener(Event.ENTER_FRAME, _onEnterFrame);
sharedObj.layerManager.dispose();
sharedObj.collisionSystem.removeAllGroups();
sharedObj.resourceManager.purgeSceneScopeResources();
_newActorPool = [];
onDispose();
super.dispose();
}
//------------------------------------------------------------
// To compose your game scene, implements these handlers.
//------------------------------------------------------------
/**
* 「ゲーム全体で常に保持しておきたいアセット」に追加するファイル名群を指定.
* これは起動時に 1 回だけ呼ばれる起動処理専用の Scene で指定されることを想定している。
* 現時点では、これによってグローバルに保持したアセットを解放するインタフェースは用意していない。
*
* Scene の getAdditionalGlobalAssets がオーバライドされていた場合、
* Scene は遷移時に Global のアセット読み込みを先に行ってから
* Scene スコープのアセット読み込みを行う。
*
* @see getRequiredAssets
*/
public function getAdditionalGlobalAssets():Array {
return [];
}
/**
* このシーンで必要なアセットのファイルパス一覧を指定.
* ここで指定したアセットによって確保されたリソースは、
* シーン遷移時に自動的に解放される
* @return Example:
* <pre>
* [
* "image/atlas_1.png",
* "image/atlas_1.xml",
* "bgm/bgm_1.mp3",
* "bmp_font/gothic.png",
* "bmp_font/gothic.fnt",
* "level_data/stage_1.json"
* ]
* </pre>
*/
public function getRequiredAssets():Array {
return [];
}
/**
* ローディング画面を構成するための init.
* この時点では KrewGameDirector で指定した大域リソースしか使えないので、
* ここでセットする Actor はグローバルに保持しているリソースを使う必要がある
*/
public function initLoadingView():void {
krew.fwlog(' - default initLoadingView called.');
}
/**
* getAdditionalGlobalAssets で指定したアセット群のロード中に呼ばれる。
* アセットの指定があれば最低 1 回は呼ばれ、最後の呼び出しでは loadRatio = 1 となる
*/
public function onLoadProgressGlobal(loadRatio:Number):void {
krew.fwlog(' - - default onLoadProgressGlobal called: ' + loadRatio);
}
/**
* getAdditionalGlobalAssets で指定したアセット群のロード完了時に呼ばれる。
* (これの直後に getRequiredAssets で指定したアセットの読み込みが始まる)
*/
public function onLoadCompleteGlobal():void {
krew.fwlog(' - - - default onLoadCompleteGlobal called.');
}
/**
* getRequiredAssets で指定したアセット群のロード中に呼ばれる。
* アセットの指定があれば最低 1 回は呼ばれ、最後の呼び出しでは loadRatio = 1 となる
*/
public function onLoadProgress(loadRatio:Number):void {
krew.fwlog(' - - - - default onLoadProgress called: ' + loadRatio);
}
/**
* getRequiredAssets で指定したアセット群のロード完了時に呼ばれる。
* (これの直後に initAfterLoad が呼ばれる)
*/
public function onLoadComplete():void {
krew.fwlog(' - - - - - default onLoadComplete called.');
}
/**
* 全てのアセットのロード完了後の本命のシーン初期化処理
* ここから requiredAssets で指定したアセットが使える
*/
public function initAfterLoad():void {
krew.fwlog(' - - - - - - default initAfterLoad called.');
}
/**
* exit() が呼ばれた際に遷移する次のシーンを返すよう override してほしい.
* なお exit(specificScene) と引数にシーンを渡した場合はそのシーンが遷移先となり、
* この関数は無視される
*/
public function getDefaultNextScene():KrewScene {
return null;
}
/**
* レイヤー構造の定義
* @return Example: ['back', 'front', 'ui']
*/
public function getLayerList():Array {
return ['l-back', 'l-front', 'l-ui'];
}
/**
* 衝突判定を行うグループの定義
* @return Example: Array of Array such as
* <pre>
* [
* ['myship' , ['enemy', 'en-shot', 'item']],
* ['myshot' , ['enemy']],
* ['enemy' , []],
* ['en-shot', []],
* ['item' , []]
* ]
* </pre>
* こう書くと「c-myship と c-enemy グループ間」、
* 「c-myship と c-item グループ間」などでヒットテストが行われるといった次第
*/
public function getCollisionGroups():Array {
return [];
}
//------------------------------------------------------------
// Automatically called by framework
//------------------------------------------------------------
/** @private */
public function startInitSceneSequence():void {
sharedObj.layerManager.setUpLayers(this, getLayerList());
sharedObj.collisionSystem.setUpGroups(getCollisionGroups());
_setUpServantActor();
initLoadingView();
// load global assets, load local assets, and call scene init.
_loadGlobalAssets(function():void {
_loadSceneScopeAssets(function():void {
initAfterLoad();
});
});
}
private function _loadGlobalAssets(doneCallback:Function):void {
// hook onLoadCompleteGlobal
var _onLoadComplete:Function = function():void {
_servantActor.sendMessage(KrewSystemEventType.COMPLETE_GLOBAL_ASSET_LOAD);
onLoadCompleteGlobal();
doneCallback();
};
if (getAdditionalGlobalAssets().length == 0) {
_onLoadComplete();
return;
}
// hook onLoadProgressGlobal
var _onLoadProgressGlobal:Function = function(loadRatio:Number):void {
_servantActor.sendMessage(
KrewSystemEventType.PROGRESS_GLOBAL_ASSET_LOAD, {loadRatio: loadRatio}
);
onLoadProgressGlobal(loadRatio);
};
// start loading assets
sharedObj.resourceManager.loadGlobalResources(
getAdditionalGlobalAssets(), _onLoadProgressGlobal, _onLoadComplete
);
}
private function _loadSceneScopeAssets(doneCallback:Function):void {
// hook onLoadComplete
var _onLoadComplete:Function = function():void {
_servantActor.sendMessage(KrewSystemEventType.COMPLETE_ASSET_LOAD);
onLoadComplete();
doneCallback();
};
if (getRequiredAssets().length == 0) {
_onLoadComplete();
return;
}
// hook onLoadProgress
var _onLoadProgress:Function = function(loadRatio:Number):void {
_servantActor.sendMessage(
KrewSystemEventType.PROGRESS_ASSET_LOAD, {loadRatio: loadRatio}
);
onLoadProgress(loadRatio);
};
// start loading assets
sharedObj.resourceManager.loadResources(
getRequiredAssets(), _onLoadProgress, _onLoadComplete
);
}
private function _setUpServantActor():void {
_servantActor = new SceneServantActor();
setUpActor('_system_', _servantActor);
}
/**
* @private
* 新しい Actor を足してもらうよう Scene に頼む。
* この関数は KrewActor によって呼ばれる。
* 新しい Actor 達は既存の Actor 達の update の後に layer に足される。
*
* layer に足される前に新しい Actor が sharedObject などにアクセスできるように
* するため、KrewActor.setUp() はこの段階で呼ばれる。
*/
public function applyForNewActor(newActor:KrewActor, layerName:String=null):void {
_newActorPool.push({
actor: newActor,
layer: layerName
});
newActor.setUp(
sharedObj, applyForNewActor,
getLayer(layerName), layerName
);
}
private function _recruitNewActors():void {
var count:int = 0;
for each (var info:Object in _newActorPool) {
++count;
setUpActor(info.layer, info.actor);
}
if (count > 0) {
_newActorPool = [];
//krew.fwlog(count + ' new actor joined');
}
}
/** @private */
public function addLayer(layer:StageLayer):void {
layer.sharedObj = this.sharedObj;
layer.applyForNewActor = this.applyForNewActor;
addChild(layer);
}
/** @private */
protected function addActor(layerName:String, actor:KrewActor,
putOnDisplayList:Boolean=true):void {
sharedObj.layerManager.addActor(layerName, actor, putOnDisplayList);
}
/** @private */
protected function addChildToLayer(layerName:String, displayObj:DisplayObject):void {
sharedObj.layerManager.addChild(layerName, displayObj);
}
/** @private */
public function getNextScene():KrewScene {
if (_nextScene != null) {
return _nextScene;
}
return getDefaultNextScene();
}
//------------------------------------------------------------
/**
* Entry point of the game loop
*/
private function _onEnterFrame(event:EnterFrameEvent):void {
if (_hasDisposed) { return; }
var passedTime:Number = KrewTimeKeeper.getReasonablePassedTime(event.passedTime);
mainLoop(passedTime);
}
/**
* Process one frame of game main loop.
* It is called automatically by framework, but you can
* manually call it for unit test of Actor's messaging.
*/
public function mainLoop(passedTime:Number=1/60):void {
if (_servantActor.isSystemActivated) {
// update actors
onUpdate(passedTime);
sharedObj.layerManager.onUpdate(passedTime);
_recruitNewActors();
// collision detection
sharedObj.collisionSystem.hitTest();
}
// broadcast messages
sharedObj.notificationService.broadcastMessage();
if (_isTimeToExit) {
dispatchEvent(new Event(KrewSystemEventType.EXIT_SCENE));
}
}
//------------------------------------------------------------
// Your tools
//------------------------------------------------------------
protected function exit(nextScene:KrewScene=null):void {
_isTimeToExit = true;
_nextScene = nextScene;
}
protected function act(action:StuntAction=null):StuntAction {
return _servantActor.act(action);
}
protected function react():void {
_servantActor.react();
}
public function addScheduledTask(timeout:Number, task:Function):void {
_servantActor.addScheduledTask(timeout, task);
}
public function delayed(timeout:Number, task:Function):void {
_servantActor.addScheduledTask(timeout, task);
}
public function addPeriodicTask(interval:Number, task:Function):void {
_servantActor.addPeriodicTask(interval, task);
}
public function cyclic(interval:Number, task:Function):void {
_servantActor.addPeriodicTask(interval, task);
}
public function setUpActor(layerName:String, actor:KrewActor,
putOnDisplayList:Boolean=true):void
{
if (layerName == null) { layerName = 'l-front'; }
addActor(layerName, actor, putOnDisplayList);
}
}
}
|
Rename delay to delayed
|
Rename delay to delayed
|
ActionScript
|
mit
|
tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework
|
d2f7c821a63b8162781720ece642429ba14f9e23
|
src/com/google/analytics/API.as
|
src/com/google/analytics/API.as
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
*/
package com.google.analytics
{
import com.google.analytics.utils.Version;
public class API
{
/**
* version of Google Analytics AS3 API
*
* note:
* each components share the same code base and so the same version
*/
public static var version:Version = new Version();
include "version.properties"
version.revision = "$Rev$ ".split( " " )[1];
}
}
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
*/
package com.google.analytics
{
import core.version;
public class API
{
/**
* version of Google Analytics AS3 API
*
* note:
* each components share the same code base and so the same version
*/
public static var version:core.version = new core.version();
include "version.properties"
version.revision = "$Rev$ ".split( " " )[1];
}
}
|
replace utils Version class by uri.version class
|
replace utils Version class by uri.version class
|
ActionScript
|
apache-2.0
|
minimedj/gaforflash,nsdevaraj/gaforflash,nsdevaraj/gaforflash,minimedj/gaforflash
|
6dd1c3407dcfe6bc53976e4f673f7e1e84ac9ab2
|
flash-src/WebSocket.as
|
flash-src/WebSocket.as
|
// Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
// License: New BSD License
// Reference: http://dev.w3.org/html5/websockets/
// Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-31
package {
import flash.display.*;
import flash.events.*;
import flash.external.*;
import flash.net.*;
import flash.system.*;
import flash.utils.*;
import mx.core.*;
import mx.controls.*;
import mx.events.*;
import mx.utils.*;
import com.adobe.net.proxies.RFC2817Socket;
import com.gsolo.encryption.MD5;
[Event(name="message", type="WebSocketMessageEvent")]
[Event(name="open", type="flash.events.Event")]
[Event(name="close", type="flash.events.Event")]
[Event(name="error", type="flash.events.Event")]
[Event(name="stateChange", type="WebSocketStateEvent")]
public class WebSocket extends EventDispatcher {
private static var CONNECTING:int = 0;
private static var OPEN:int = 1;
private static var CLOSING:int = 2;
private static var CLOSED:int = 3;
private var socket:RFC2817Socket;
private var main:WebSocketMain;
private var url:String;
private var scheme:String;
private var host:String;
private var port:uint;
private var path:String;
private var origin:String;
private var protocol:String;
private var buffer:ByteArray = new ByteArray();
private var headerState:int = 0;
private var readyState:int = CONNECTING;
private var bufferedAmount:int = 0;
private var headers:String;
private var noiseChars:Array;
private var expectedDigest:String;
public function WebSocket(
main:WebSocketMain, url:String, protocol:String,
proxyHost:String = null, proxyPort:int = 0,
headers:String = null) {
this.main = main;
initNoiseChars();
this.url = url;
var m:Array = url.match(/^(\w+):\/\/([^\/:]+)(:(\d+))?(\/.*)?$/);
if (!m) main.fatal("SYNTAX_ERR: invalid url: " + url);
this.scheme = m[1];
this.host = m[2];
this.port = parseInt(m[4] || "80");
this.path = m[5] || "/";
this.origin = main.getOrigin();
this.protocol = protocol;
// if present and not the empty string, headers MUST end with \r\n
// headers should be zero or more complete lines, for example
// "Header1: xxx\r\nHeader2: yyyy\r\n"
this.headers = headers;
socket = new RFC2817Socket();
// if no proxy information is supplied, it acts like a normal Socket
// @see RFC2817Socket::connect
if (proxyHost != null && proxyPort != 0){
socket.setProxyInfo(proxyHost, proxyPort);
}
socket.addEventListener(Event.CLOSE, onSocketClose);
socket.addEventListener(Event.CONNECT, onSocketConnect);
socket.addEventListener(IOErrorEvent.IO_ERROR, onSocketIoError);
socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSocketSecurityError);
socket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData);
socket.connect(host, port);
}
public function send(data:String):int {
if (readyState == OPEN) {
socket.writeByte(0x00);
socket.writeUTFBytes(decodeURIComponent(data));
socket.writeByte(0xff);
socket.flush();
main.log("sent: " + data);
return -1;
} else if (readyState == CLOSED) {
var bytes:ByteArray = new ByteArray();
bytes.writeUTFBytes(decodeURIComponent(data));
bufferedAmount += bytes.length; // not sure whether it should include \x00 and \xff
// We use return value to let caller know bufferedAmount because we cannot fire
// stateChange event here which causes weird error:
// > You are trying to call recursively into the Flash Player which is not allowed.
return bufferedAmount;
} else {
main.fatal("INVALID_STATE_ERR: invalid state");
return 0;
}
}
public function close():void {
main.log("close");
try {
socket.close();
} catch (ex:Error) { }
readyState = CLOSED;
// We don't fire any events here because it causes weird error:
// > You are trying to call recursively into the Flash Player which is not allowed.
// We do something equivalent in JavaScript WebSocket#close instead.
}
public function getReadyState():int {
return readyState;
}
public function getBufferedAmount():int {
return bufferedAmount;
}
private function onSocketConnect(event:Event):void {
main.log("connected");
var hostValue:String = host + (port == 80 ? "" : ":" + port);
var cookie:String = "";
if (main.getCallerHost() == host) {
cookie = ExternalInterface.call("function(){return document.cookie}");
}
var key1:String = generateKey();
var key2:String = generateKey();
var key3:String = generateKey3();
expectedDigest = getSecurityDigest(key1, key2, key3);
var opt:String = "";
if (protocol) opt += "WebSocket-Protocol: " + protocol + "\r\n";
// if caller passes additional headers they must end with "\r\n"
if (headers) opt += headers;
var req:String = StringUtil.substitute(
"GET {0} HTTP/1.1\r\n" +
"Upgrade: WebSocket\r\n" +
"Connection: Upgrade\r\n" +
"Host: {1}\r\n" +
"Origin: {2}\r\n" +
"Cookie: {3}\r\n" +
"Sec-WebSocket-Key1: {4}\r\n" +
"Sec-WebSocket-Key2: {5}\r\n" +
"{6}" +
"\r\n",
path, hostValue, origin, cookie, key1, key2, opt);
main.log("request header:\n" + req);
socket.writeUTFBytes(req);
main.log("sent key3: " + key3);
main.log("expected digest: " + expectedDigest);
writeBytes(key3);
socket.flush();
}
private function onSocketClose(event:Event):void {
main.log("closed");
readyState = CLOSED;
notifyStateChange();
dispatchEvent(new Event("close"));
}
private function onSocketIoError(event:IOErrorEvent):void {
var message:String;
if (readyState == CONNECTING) {
message = "cannot connect to Web Socket server at " + url + " (IoError)";
} else {
message = "error communicating with Web Socket server at " + url + " (IoError)";
}
onError(message);
}
private function onSocketSecurityError(event:SecurityErrorEvent):void {
var message:String;
if (readyState == CONNECTING) {
message =
"cannot connect to Web Socket server at " + url + " (SecurityError)\n" +
"make sure the server is running and Flash socket policy file is correctly placed";
} else {
message = "error communicating with Web Socket server at " + url + " (SecurityError)";
}
onError(message);
}
private function onError(message:String):void {
var state:int = readyState;
if (state == CLOSED) return;
main.error(message);
close();
notifyStateChange();
dispatchEvent(new Event(state == CONNECTING ? "close" : "error"));
}
private function onSocketData(event:ProgressEvent):void {
var pos:int = buffer.length;
socket.readBytes(buffer, pos);
for (; pos < buffer.length; ++pos) {
if (headerState < 4) {
// try to find "\r\n\r\n"
if ((headerState == 0 || headerState == 2) && buffer[pos] == 0x0d) {
++headerState;
} else if ((headerState == 1 || headerState == 3) && buffer[pos] == 0x0a) {
++headerState;
} else {
headerState = 0;
}
if (headerState == 4) {
var headerStr:String = buffer.readUTFBytes(pos + 1);
main.log("response header:\n" + headerStr);
if (!validateHeader(headerStr)) return;
makeBufferCompact();
pos = -1;
}
} else if (headerState == 4) {
var replyDigest:String = readBytes(buffer, 16);
main.log("reply digest: " + replyDigest);
if (replyDigest != expectedDigest) {
onError("digest doesn't match: " + replyDigest + " != " + expectedDigest);
return;
}
headerState = 5;
makeBufferCompact();
pos = -1;
readyState = OPEN;
notifyStateChange();
dispatchEvent(new Event("open"));
} else {
if (buffer[pos] == 0xff) {
if (buffer.readByte() != 0x00) {
onError("data must start with \\x00");
return;
}
var data:String = buffer.readUTFBytes(pos - 1);
main.log("received: " + data);
dispatchEvent(new WebSocketMessageEvent("message", encodeURIComponent(data)));
buffer.readByte();
makeBufferCompact();
pos = -1;
}
}
}
}
private function validateHeader(headerStr:String):Boolean {
var lines:Array = headerStr.split(/\r\n/);
if (!lines[0].match(/^HTTP\/1.1 101 /)) {
onError("bad response: " + lines[0]);
return false;
}
var header:Object = {};
for (var i:int = 1; i < lines.length; ++i) {
if (lines[i].length == 0) continue;
var m:Array = lines[i].match(/^(\S+): (.*)$/);
if (!m) {
onError("failed to parse response header line: " + lines[i]);
return false;
}
header[m[1]] = m[2];
}
if (header["Upgrade"] != "WebSocket") {
onError("invalid Upgrade: " + header["Upgrade"]);
return false;
}
if (header["Connection"] != "Upgrade") {
onError("invalid Connection: " + header["Connection"]);
return false;
}
var resOrigin:String = header["Sec-WebSocket-Origin"].toLowerCase();
if (resOrigin != origin) {
onError("origin doesn't match: '" + resOrigin + "' != '" + origin + "'");
return false;
}
if (protocol && header["Sec-WebSocket-Protocol"] != protocol) {
onError("protocol doesn't match: '" +
header["WebSocket-Protocol"] + "' != '" + protocol + "'");
return false;
}
return true;
}
private function makeBufferCompact():void {
if (buffer.position == 0) return;
var nextBuffer:ByteArray = new ByteArray();
buffer.readBytes(nextBuffer);
buffer = nextBuffer;
}
private function notifyStateChange():void {
dispatchEvent(new WebSocketStateEvent("stateChange", readyState, bufferedAmount));
}
private function initNoiseChars():void {
noiseChars = new Array();
for (var i:int = 0x21; i <= 0x2f; ++i) {
noiseChars.push(String.fromCharCode(i));
}
for (var j:int = 0x3a; j <= 0x7a; ++j) {
noiseChars.push(String.fromCharCode(j));
}
}
private function generateKey():String {
var spaces:uint = randomInt(1, 12);
var max:uint = uint.MAX_VALUE / spaces;
var number:uint = randomInt(0, max);
var key:String = (number * spaces).toString();
var noises:int = randomInt(1, 12);
var pos:int;
for (var i:int = 0; i < noises; ++i) {
var char:String = noiseChars[randomInt(0, noiseChars.length - 1)];
pos = randomInt(0, key.length);
key = key.substr(0, pos) + char + key.substr(pos);
}
for (var j:int = 0; j < spaces; ++j) {
pos = randomInt(1, key.length - 1);
key = key.substr(0, pos) + " " + key.substr(pos);
}
return key;
}
private function generateKey3():String {
var key3:String = "";
for (var i:int = 0; i < 8; ++i) {
key3 += String.fromCharCode(randomInt(0, 255));
}
return key3;
}
private function getSecurityDigest(key1:String, key2:String, key3:String):String {
var bytes1:String = keyToBytes(key1);
var bytes2:String = keyToBytes(key2);
return MD5.rstr_md5(bytes1 + bytes2 + key3);
}
private function keyToBytes(key:String):String {
var keyNum:uint = parseInt(key.replace(/[^\d]/g, ""));
var spaces:uint = 0;
for (var i:int = 0; i < key.length; ++i) {
if (key.charAt(i) == " ") ++spaces;
}
var resultNum:uint = keyNum / spaces;
var bytes:String = "";
for (var j:int = 3; j >= 0; --j) {
bytes += String.fromCharCode((resultNum >> (j * 8)) & 0xff);
}
return bytes;
}
private function writeBytes(bytes:String):void {
for (var i:int = 0; i < bytes.length; ++i) {
socket.writeByte(bytes.charCodeAt(i));
}
}
private function readBytes(buffer:ByteArray, numBytes:int):String {
var bytes:String = "";
for (var i:int = 0; i < numBytes; ++i) {
// & 0xff is to make \x80-\xff positive number.
bytes += String.fromCharCode(buffer.readByte() & 0xff);
}
return bytes;
}
private function randomInt(min:uint, max:uint):uint {
return min + Math.floor(Math.random() * (Number(max) - min + 1));
}
// for debug
private function dumpBytes(bytes:String):void {
var output:String = "";
for (var i:int = 0; i < bytes.length; ++i) {
output += bytes.charCodeAt(i).toString() + ", ";
}
main.log(output);
}
}
}
|
// Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
// License: New BSD License
// Reference: http://dev.w3.org/html5/websockets/
// Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-31
package {
import flash.display.*;
import flash.events.*;
import flash.external.*;
import flash.net.*;
import flash.system.*;
import flash.utils.*;
import mx.core.*;
import mx.controls.*;
import mx.events.*;
import mx.utils.*;
import com.adobe.net.proxies.RFC2817Socket;
import com.hurlant.crypto.tls.TLSSocket;
import com.hurlant.crypto.tls.TLSConfig;
import com.hurlant.crypto.tls.TLSEngine;
import com.hurlant.crypto.tls.TLSSecurityParameters;
import com.gsolo.encryption.MD5;
[Event(name="message", type="WebSocketMessageEvent")]
[Event(name="open", type="flash.events.Event")]
[Event(name="close", type="flash.events.Event")]
[Event(name="error", type="flash.events.Event")]
[Event(name="stateChange", type="WebSocketStateEvent")]
public class WebSocket extends EventDispatcher {
private static var CONNECTING:int = 0;
private static var OPEN:int = 1;
private static var CLOSING:int = 2;
private static var CLOSED:int = 3;
//private var rawSocket:RFC2817Socket;
private var rawSocket:Socket;
private var tlsSocket:TLSSocket;
private var tlsConfig:TLSConfig;
private var socket:Socket;
private var main:WebSocketMain;
private var url:String;
private var scheme:String;
private var host:String;
private var port:uint;
private var path:String;
private var origin:String;
private var protocol:String;
private var buffer:ByteArray = new ByteArray();
private var headerState:int = 0;
private var readyState:int = CONNECTING;
private var bufferedAmount:int = 0;
private var headers:String;
private var noiseChars:Array;
private var expectedDigest:String;
public function WebSocket(
main:WebSocketMain, url:String, protocol:String,
proxyHost:String = null, proxyPort:int = 0,
headers:String = null) {
this.main = main;
initNoiseChars();
this.url = url;
var m:Array = url.match(/^(\w+):\/\/([^\/:]+)(:(\d+))?(\/.*)?$/);
if (!m) main.fatal("SYNTAX_ERR: invalid url: " + url);
this.scheme = m[1];
this.host = m[2];
this.port = parseInt(m[4] || "80");
this.path = m[5] || "/";
this.origin = main.getOrigin();
this.protocol = protocol;
// if present and not the empty string, headers MUST end with \r\n
// headers should be zero or more complete lines, for example
// "Header1: xxx\r\nHeader2: yyyy\r\n"
this.headers = headers;
/*
socket = new RFC2817Socket();
// if no proxy information is supplied, it acts like a normal Socket
// @see RFC2817Socket::connect
if (proxyHost != null && proxyPort != 0){
socket.setProxyInfo(proxyHost, proxyPort);
}
*/
ExternalInterface.call("console.log", "[WebSocket] scheme: " + scheme);
rawSocket = new Socket();
rawSocket.addEventListener(Event.CLOSE, onSocketClose);
rawSocket.addEventListener(Event.CONNECT, onSocketConnect);
rawSocket.addEventListener(IOErrorEvent.IO_ERROR, onSocketIoError);
rawSocket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSocketSecurityError);
if (scheme == "wss") {
tlsConfig= new TLSConfig(TLSEngine.CLIENT,
null, null, null, null, null,
TLSSecurityParameters.PROTOCOL_VERSION);
tlsConfig.trustSelfSignedCertificates = true;
tlsConfig.ignoreCommonNameMismatch = true;
tlsSocket = new TLSSocket();
tlsSocket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData);
socket = (tlsSocket as Socket);
} else {
rawSocket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData);
socket = (rawSocket as Socket);
}
rawSocket.connect(host, port);
}
public function send(data:String):int {
if (readyState == OPEN) {
socket.writeByte(0x00);
socket.writeUTFBytes(decodeURIComponent(data));
socket.writeByte(0xff);
socket.flush();
main.log("sent: " + data);
return -1;
} else if (readyState == CLOSED) {
var bytes:ByteArray = new ByteArray();
bytes.writeUTFBytes(decodeURIComponent(data));
bufferedAmount += bytes.length; // not sure whether it should include \x00 and \xff
// We use return value to let caller know bufferedAmount because we cannot fire
// stateChange event here which causes weird error:
// > You are trying to call recursively into the Flash Player which is not allowed.
return bufferedAmount;
} else {
main.fatal("INVALID_STATE_ERR: invalid state");
return 0;
}
}
public function close():void {
main.log("close");
try {
socket.close();
} catch (ex:Error) { }
readyState = CLOSED;
// We don't fire any events here because it causes weird error:
// > You are trying to call recursively into the Flash Player which is not allowed.
// We do something equivalent in JavaScript WebSocket#close instead.
}
public function getReadyState():int {
return readyState;
}
public function getBufferedAmount():int {
return bufferedAmount;
}
private function onSocketConnect(event:Event):void {
main.log("connected");
if (scheme == "wss") {
ExternalInterface.call("console.log", "[WebSocket] starting SSL/TLS");
tlsSocket.startTLS(rawSocket, host, tlsConfig);
}
var hostValue:String = host + (port == 80 ? "" : ":" + port);
var cookie:String = "";
if (main.getCallerHost() == host) {
cookie = ExternalInterface.call("function(){return document.cookie}");
}
var key1:String = generateKey();
var key2:String = generateKey();
var key3:String = generateKey3();
expectedDigest = getSecurityDigest(key1, key2, key3);
var opt:String = "";
if (protocol) opt += "WebSocket-Protocol: " + protocol + "\r\n";
// if caller passes additional headers they must end with "\r\n"
if (headers) opt += headers;
var req:String = StringUtil.substitute(
"GET {0} HTTP/1.1\r\n" +
"Upgrade: WebSocket\r\n" +
"Connection: Upgrade\r\n" +
"Host: {1}\r\n" +
"Origin: {2}\r\n" +
"Cookie: {3}\r\n" +
"Sec-WebSocket-Key1: {4}\r\n" +
"Sec-WebSocket-Key2: {5}\r\n" +
"{6}" +
"\r\n",
path, hostValue, origin, cookie, key1, key2, opt);
main.log("request header:\n" + req);
socket.writeUTFBytes(req);
main.log("sent key3: " + key3);
main.log("expected digest: " + expectedDigest);
writeBytes(key3);
socket.flush();
}
private function onSocketClose(event:Event):void {
main.log("closed");
readyState = CLOSED;
notifyStateChange();
dispatchEvent(new Event("close"));
}
private function onSocketIoError(event:IOErrorEvent):void {
var message:String;
if (readyState == CONNECTING) {
message = "cannot connect to Web Socket server at " + url + " (IoError)";
} else {
message = "error communicating with Web Socket server at " + url + " (IoError)";
}
onError(message);
}
private function onSocketSecurityError(event:SecurityErrorEvent):void {
var message:String;
if (readyState == CONNECTING) {
message =
"cannot connect to Web Socket server at " + url + " (SecurityError)\n" +
"make sure the server is running and Flash socket policy file is correctly placed";
} else {
message = "error communicating with Web Socket server at " + url + " (SecurityError)";
}
onError(message);
}
private function onError(message:String):void {
var state:int = readyState;
if (state == CLOSED) return;
main.error(message);
close();
notifyStateChange();
dispatchEvent(new Event(state == CONNECTING ? "close" : "error"));
}
private function onSocketData(event:ProgressEvent):void {
var pos:int = buffer.length;
socket.readBytes(buffer, pos);
for (; pos < buffer.length; ++pos) {
if (headerState < 4) {
// try to find "\r\n\r\n"
if ((headerState == 0 || headerState == 2) && buffer[pos] == 0x0d) {
++headerState;
} else if ((headerState == 1 || headerState == 3) && buffer[pos] == 0x0a) {
++headerState;
} else {
headerState = 0;
}
if (headerState == 4) {
var headerStr:String = buffer.readUTFBytes(pos + 1);
main.log("response header:\n" + headerStr);
if (!validateHeader(headerStr)) return;
makeBufferCompact();
pos = -1;
}
} else if (headerState == 4) {
var replyDigest:String = readBytes(buffer, 16);
main.log("reply digest: " + replyDigest);
if (replyDigest != expectedDigest) {
onError("digest doesn't match: " + replyDigest + " != " + expectedDigest);
return;
}
headerState = 5;
makeBufferCompact();
pos = -1;
readyState = OPEN;
notifyStateChange();
dispatchEvent(new Event("open"));
} else {
if (buffer[pos] == 0xff) {
if (buffer.readByte() != 0x00) {
onError("data must start with \\x00");
return;
}
var data:String = buffer.readUTFBytes(pos - 1);
main.log("received: " + data);
dispatchEvent(new WebSocketMessageEvent("message", encodeURIComponent(data)));
buffer.readByte();
makeBufferCompact();
pos = -1;
}
}
}
}
private function validateHeader(headerStr:String):Boolean {
var lines:Array = headerStr.split(/\r\n/);
if (!lines[0].match(/^HTTP\/1.1 101 /)) {
onError("bad response: " + lines[0]);
return false;
}
var header:Object = {};
for (var i:int = 1; i < lines.length; ++i) {
if (lines[i].length == 0) continue;
var m:Array = lines[i].match(/^(\S+): (.*)$/);
if (!m) {
onError("failed to parse response header line: " + lines[i]);
return false;
}
header[m[1]] = m[2];
}
if (header["Upgrade"] != "WebSocket") {
onError("invalid Upgrade: " + header["Upgrade"]);
return false;
}
if (header["Connection"] != "Upgrade") {
onError("invalid Connection: " + header["Connection"]);
return false;
}
var resOrigin:String = header["Sec-WebSocket-Origin"].toLowerCase();
if (resOrigin != origin) {
onError("origin doesn't match: '" + resOrigin + "' != '" + origin + "'");
return false;
}
if (protocol && header["Sec-WebSocket-Protocol"] != protocol) {
onError("protocol doesn't match: '" +
header["WebSocket-Protocol"] + "' != '" + protocol + "'");
return false;
}
return true;
}
private function makeBufferCompact():void {
if (buffer.position == 0) return;
var nextBuffer:ByteArray = new ByteArray();
buffer.readBytes(nextBuffer);
buffer = nextBuffer;
}
private function notifyStateChange():void {
dispatchEvent(new WebSocketStateEvent("stateChange", readyState, bufferedAmount));
}
private function initNoiseChars():void {
noiseChars = new Array();
for (var i:int = 0x21; i <= 0x2f; ++i) {
noiseChars.push(String.fromCharCode(i));
}
for (var j:int = 0x3a; j <= 0x7a; ++j) {
noiseChars.push(String.fromCharCode(j));
}
}
private function generateKey():String {
var spaces:uint = randomInt(1, 12);
var max:uint = uint.MAX_VALUE / spaces;
var number:uint = randomInt(0, max);
var key:String = (number * spaces).toString();
var noises:int = randomInt(1, 12);
var pos:int;
for (var i:int = 0; i < noises; ++i) {
var char:String = noiseChars[randomInt(0, noiseChars.length - 1)];
pos = randomInt(0, key.length);
key = key.substr(0, pos) + char + key.substr(pos);
}
for (var j:int = 0; j < spaces; ++j) {
pos = randomInt(1, key.length - 1);
key = key.substr(0, pos) + " " + key.substr(pos);
}
return key;
}
private function generateKey3():String {
var key3:String = "";
for (var i:int = 0; i < 8; ++i) {
key3 += String.fromCharCode(randomInt(0, 255));
}
return key3;
}
private function getSecurityDigest(key1:String, key2:String, key3:String):String {
var bytes1:String = keyToBytes(key1);
var bytes2:String = keyToBytes(key2);
return MD5.rstr_md5(bytes1 + bytes2 + key3);
}
private function keyToBytes(key:String):String {
var keyNum:uint = parseInt(key.replace(/[^\d]/g, ""));
var spaces:uint = 0;
for (var i:int = 0; i < key.length; ++i) {
if (key.charAt(i) == " ") ++spaces;
}
var resultNum:uint = keyNum / spaces;
var bytes:String = "";
for (var j:int = 3; j >= 0; --j) {
bytes += String.fromCharCode((resultNum >> (j * 8)) & 0xff);
}
return bytes;
}
private function writeBytes(bytes:String):void {
for (var i:int = 0; i < bytes.length; ++i) {
socket.writeByte(bytes.charCodeAt(i));
}
}
private function readBytes(buffer:ByteArray, numBytes:int):String {
var bytes:String = "";
for (var i:int = 0; i < numBytes; ++i) {
// & 0xff is to make \x80-\xff positive number.
bytes += String.fromCharCode(buffer.readByte() & 0xff);
}
return bytes;
}
private function randomInt(min:uint, max:uint):uint {
return min + Math.floor(Math.random() * (Number(max) - min + 1));
}
// for debug
private function dumpBytes(bytes:String):void {
var output:String = "";
for (var i:int = 0; i < bytes.length; ++i) {
output += bytes.charCodeAt(i).toString() + ", ";
}
main.log(output);
}
}
}
|
Add wss:// (SSL/TLS) support using as3crypto_patched.
|
Add wss:// (SSL/TLS) support using as3crypto_patched.
Warning: RFC2817 proxy support interferes with the SSL Socket
(hurlant) so I've disabled RFC2817 proxy support.
|
ActionScript
|
bsd-3-clause
|
keiosweb/web-socket-js,zhangxingits/web-socket-js,keiosweb/web-socket-js,hanicker/web-socket-js,gimite/web-socket-js,hanicker/web-socket-js,nitzo/web-socket-js,zhangxingits/web-socket-js,zhangxingits/web-socket-js,nitzo/web-socket-js,hehuabing/web-socket-js,gimite/web-socket-js,hehuabing/web-socket-js,gimite/web-socket-js,hanicker/web-socket-js,hehuabing/web-socket-js,nitzo/web-socket-js,keiosweb/web-socket-js
|
e57f32fca7c44e4d55f7ca34813c560f3350ba9c
|
src/flash/geom/Rectangle.as
|
src/flash/geom/Rectangle.as
|
package flash.geom
{
import flash.geom.Point;
public class Rectangle
{
public var x:Number;
public var y:Number;
public var width:Number;
public var height:Number;
public function Rectangle(x:Number = 0, y:Number = 0, width:Number = 0, height:Number = 0) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public function get left():Number {
return x;
}
public function set left(value:Number):void {
width += x - value
x = value;
}
public function get right():Number {
return x + width;
}
public function set right(value:Number):void {
width = value - x;
}
public function get top():Number {
return y;
}
public function set top(value:Number):void {
height += y - value;
y = value;
}
public function get bottom():Number {
return y + height;
}
public function set bottom(value:Number):void {
height = value - y;
}
public function get topLeft():Point {
return new Point(left, top);
}
public function set topLeft(value:Point):void {
top = value.y;
left = value.x;
}
public function get bottomRight():Point {
return new Point(right, bottom);
}
public function set bottomRight(value:Point):void {
bottom = value.y;
right = value.x;
}
public function get size():Point {
return new Point(width, height);
}
public function set size(value:Point):void {
width = value.x;
height = value.y;
}
public function clone():Rectangle {
return new Rectangle(x, y, width, height);
}
public function isEmpty():Boolean {
return width <= 0 || height <= 0;
}
public function setEmpty():void {
x = 0;
y = 0;
width = 0;
height = 0;
}
public function inflate(dx:Number, dy:Number):void {
x -= dx;
y -= dy;
width += (dx * 2);
height += (dy * 2);
}
public function inflatePoint(point:Point):void {
inflate(point.x, point.y);
}
public function offset(dx:Number, dy:Number):void {
x += dx;
y += dy;
}
public function offsetPoint(point:Point):void {
offset(point.x, point.y);
}
public function contains(x:Number, y:Number):Boolean {
return this.x <= x && x <= this.right && this.y <= y && y <= this.bottom;
}
public function containsPoint(point:Point):Boolean {
return contains(point.x, point.y);
}
public function containsRect(rect:Rectangle):Boolean {
return containsPoint(rect.topLeft) && containsPoint(rect.bottomRight);
}
public function intersection(toIntersect:Rectangle):Rectangle {
var l:Number = Math.max(x, toIntersect.x);
var r:Number = Math.min(right, toIntersect.right);
if (l <= r) {
var t:Number = Math.max(y, toIntersect.y);
var b:Number = Math.min(bottom, toIntersect.bottom);
if (t <= b) {
return new Rectangle(l, t, r - l, b - t);
}
}
return new Rectangle();
}
public function intersects(toIntersect:Rectangle):Boolean {
return Math.max(x, toIntersect.x) <= Math.min(right, toIntersect.right)
&& Math.max(y, toIntersect.y) <= Math.min(bottom, toIntersect.bottom);
}
public function union(toUnion:Rectangle):Rectangle {
if (toUnion.width == 0 || toUnion.height == 0) {
return clone();
}
if (width == 0 || height == 0) {
return toUnion.clone();
}
var l:Number = Math.min(x, toUnion.x);
var t:Number = Math.min(y, toUnion.y);
return new Rectangle(l,
t,
Math.max(right, toUnion.right) - l,
Math.max(bottom, toUnion.bottom) - t);
}
public function equals(toCompare:Rectangle):Boolean {
return x == toCompare.x
&& y == toCompare.y
&& width == toCompare.width
&& height == toCompare.height;
}
public function copyFrom(sourceRect:Rectangle):void {
x = sourceRect.x;
y = sourceRect.y;
width = sourceRect.width;
height = sourceRect.height;
}
public function setTo(xa:Number, ya:Number, widtha:Number, heighta:Number):void {
x = xa;
y = ya;
width = widtha;
height = heighta;
}
public function toString():String {
return "(x=" + x + ", y=" + y + ", w=" + width + ", h=" + height + ")";
}
}
}
|
/*
* 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.geom
{
import flash.geom.Point;
public class Rectangle
{
public var x:Number;
public var y:Number;
public var width:Number;
public var height:Number;
public function Rectangle(x:Number = 0, y:Number = 0, width:Number = 0, height:Number = 0) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public function get left():Number {
return x;
}
public function set left(value:Number):void {
width += x - value
x = value;
}
public function get right():Number {
return x + width;
}
public function set right(value:Number):void {
width = value - x;
}
public function get top():Number {
return y;
}
public function set top(value:Number):void {
height += y - value;
y = value;
}
public function get bottom():Number {
return y + height;
}
public function set bottom(value:Number):void {
height = value - y;
}
public function get topLeft():Point {
return new Point(left, top);
}
public function set topLeft(value:Point):void {
top = value.y;
left = value.x;
}
public function get bottomRight():Point {
return new Point(right, bottom);
}
public function set bottomRight(value:Point):void {
bottom = value.y;
right = value.x;
}
public function get size():Point {
return new Point(width, height);
}
public function set size(value:Point):void {
width = value.x;
height = value.y;
}
public function clone():Rectangle {
return new Rectangle(x, y, width, height);
}
public function isEmpty():Boolean {
return width <= 0 || height <= 0;
}
public function setEmpty():void {
x = 0;
y = 0;
width = 0;
height = 0;
}
public function inflate(dx:Number, dy:Number):void {
x -= dx;
y -= dy;
width += (dx * 2);
height += (dy * 2);
}
public function inflatePoint(point:Point):void {
inflate(point.x, point.y);
}
public function offset(dx:Number, dy:Number):void {
x += dx;
y += dy;
}
public function offsetPoint(point:Point):void {
offset(point.x, point.y);
}
public function contains(x:Number, y:Number):Boolean {
return this.x <= x && x <= this.right && this.y <= y && y <= this.bottom;
}
public function containsPoint(point:Point):Boolean {
return contains(point.x, point.y);
}
public function containsRect(rect:Rectangle):Boolean {
return containsPoint(rect.topLeft) && containsPoint(rect.bottomRight);
}
public function intersection(toIntersect:Rectangle):Rectangle {
var l:Number = Math.max(x, toIntersect.x);
var r:Number = Math.min(right, toIntersect.right);
if (l <= r) {
var t:Number = Math.max(y, toIntersect.y);
var b:Number = Math.min(bottom, toIntersect.bottom);
if (t <= b) {
return new Rectangle(l, t, r - l, b - t);
}
}
return new Rectangle();
}
public function intersects(toIntersect:Rectangle):Boolean {
return Math.max(x, toIntersect.x) <= Math.min(right, toIntersect.right)
&& Math.max(y, toIntersect.y) <= Math.min(bottom, toIntersect.bottom);
}
public function union(toUnion:Rectangle):Rectangle {
if (toUnion.width == 0 || toUnion.height == 0) {
return clone();
}
if (width == 0 || height == 0) {
return toUnion.clone();
}
var l:Number = Math.min(x, toUnion.x);
var t:Number = Math.min(y, toUnion.y);
return new Rectangle(l,
t,
Math.max(right, toUnion.right) - l,
Math.max(bottom, toUnion.bottom) - t);
}
public function equals(toCompare:Rectangle):Boolean {
return x == toCompare.x
&& y == toCompare.y
&& width == toCompare.width
&& height == toCompare.height;
}
public function copyFrom(sourceRect:Rectangle):void {
x = sourceRect.x;
y = sourceRect.y;
width = sourceRect.width;
height = sourceRect.height;
}
public function setTo(xa:Number, ya:Number, widtha:Number, heighta:Number):void {
x = xa;
y = ya;
width = widtha;
height = heighta;
}
public function toString():String {
return "(x=" + x + ", y=" + y + ", w=" + width + ", h=" + height + ")";
}
}
}
|
add copyright notice
|
add copyright notice
|
ActionScript
|
apache-2.0
|
tschneidereit/shumway,tschneidereit/shumway,tschneidereit/shumway,tschneidereit/shumway,yurydelendik/shumway,mbebenita/shumway,mbebenita/shumway,yurydelendik/shumway,mbebenita/shumway,mbebenita/shumway,yurydelendik/shumway,mozilla/shumway,mbebenita/shumway,mozilla/shumway,yurydelendik/shumway,mbebenita/shumway,yurydelendik/shumway,mozilla/shumway,mozilla/shumway,mozilla/shumway,mozilla/shumway,mbebenita/shumway,tschneidereit/shumway,tschneidereit/shumway,yurydelendik/shumway,yurydelendik/shumway,tschneidereit/shumway,tschneidereit/shumway,mbebenita/shumway,mozilla/shumway,yurydelendik/shumway,mozilla/shumway
|
70e675654fdd15da1ae5358c30ac02e00c098e44
|
src/aerys/minko/render/geometry/stream/iterator/TriangleReference.as
|
src/aerys/minko/render/geometry/stream/iterator/TriangleReference.as
|
package aerys.minko.render.geometry.stream.iterator
{
import aerys.minko.ns.minko_stream;
import aerys.minko.render.geometry.stream.IVertexStream;
import aerys.minko.render.geometry.stream.IndexStream;
import aerys.minko.type.Factory;
import aerys.minko.type.math.Plane;
import aerys.minko.type.math.Vector4;
public final class TriangleReference
{
use namespace minko_stream;
private static const DUMMY_INDICES : Vector.<uint> = new <uint>[0, 1, 2];
minko_stream static const UPDATE_NONE : uint = 0;
minko_stream static const UPDATE_NORMAL : uint = 1;
minko_stream static const UPDATE_PLANE : uint = 2;
minko_stream static const UPDATE_CENTER : uint = 4;
minko_stream static const UPDATE_ALL : uint = 1 | 2 | 4;
minko_stream var _index : uint = 0;
minko_stream var _update : uint = UPDATE_ALL;
private var _indexStream : IndexStream = null;
private var _v0 : VertexReference = null;
private var _v1 : VertexReference = null;
private var _v2 : VertexReference = null;
private var _i0 : uint = 0;
private var _i1 : uint = 0;
private var _i2 : uint = 0;
public function get index() : int
{
return _index;
}
public function get v0() : VertexReference
{
return _v0;
}
public function get v1() : VertexReference
{
return _v1;
}
public function get v2() : VertexReference
{
return _v2;
}
public function get i0() : int
{
return _indexStream._data[int(_index * 3)];
}
public function set i0(value : int) : void
{
_indexStream._data[int(_index * 3)] = value;
_indexStream.invalidate();
_v0._index = value;
_update |= UPDATE_ALL;
}
public function get i1() : int
{
return _indexStream._data[int(_index * 3 + 1)];
}
public function set i1(value : int) : void
{
_indexStream._data[int(_index * 3 + 1)] = value;
_indexStream.invalidate();
_v1._index = value;
_update |= UPDATE_ALL;
}
public function get i2() : int
{
return _indexStream._data[int(_index * 3 + 2)];
}
public function set i2(value : int) : void
{
_indexStream._data[int(_index * 3 + 2)] = value;
_indexStream.invalidate();
_v2._index = value;
_update |= UPDATE_ALL;
}
public function TriangleReference(vertexStream : IVertexStream,
indexStream : IndexStream,
index : uint)
{
_indexStream = indexStream;
_index = index;
initialize(vertexStream);
}
private function initialize(vertexStream : IVertexStream) : void
{
var ii : uint = _index * 3;
// create a new triangle if it does not exist
if (ii >= _indexStream.length)
_indexStream.push(DUMMY_INDICES);
_v0 = new VertexReference(vertexStream, _indexStream.get(ii));
_v1 = new VertexReference(vertexStream, _indexStream.get(ii + 1));
_v2 = new VertexReference(vertexStream, _indexStream.get(ii + 2));
}
public function invertWinding() : void
{
_update = UPDATE_ALL;
var tmp : int = _i0;
_v0._index = _i0 = _i1;
_v1._index = tmp;
i0 = _i1;
i1 = tmp;
}
}
}
|
package aerys.minko.render.geometry.stream.iterator
{
import aerys.minko.ns.minko_stream;
import aerys.minko.render.geometry.stream.IVertexStream;
import aerys.minko.render.geometry.stream.IndexStream;
import aerys.minko.type.Factory;
import aerys.minko.type.math.Plane;
import aerys.minko.type.math.Vector4;
public final class TriangleReference
{
use namespace minko_stream;
private static const DUMMY_INDICES : Vector.<uint> = new <uint>[0, 1, 2];
minko_stream static const UPDATE_NONE : uint = 0;
minko_stream static const UPDATE_NORMAL : uint = 1;
minko_stream static const UPDATE_PLANE : uint = 2;
minko_stream static const UPDATE_CENTER : uint = 4;
minko_stream static const UPDATE_ALL : uint = 1 | 2 | 4;
minko_stream var _index : uint = 0;
minko_stream var _update : uint = UPDATE_ALL;
private var _indexStream : IndexStream = null;
private var _v0 : VertexReference = null;
private var _v1 : VertexReference = null;
private var _v2 : VertexReference = null;
private var _i0 : uint = 0;
private var _i1 : uint = 0;
private var _i2 : uint = 0;
public function get index() : int
{
return _index;
}
public function get v0() : VertexReference
{
return _v0;
}
public function get v1() : VertexReference
{
return _v1;
}
public function get v2() : VertexReference
{
return _v2;
}
public function get i0() : int
{
return _indexStream._data[int(_index * 3)];
}
public function set i0(value : int) : void
{
_indexStream._data[int(_index * 3)] = value;
_indexStream.invalidate();
_v0._index = value;
_update |= UPDATE_ALL;
}
public function get i1() : int
{
return _indexStream._data[int(_index * 3 + 1)];
}
public function set i1(value : int) : void
{
_indexStream._data[int(_index * 3 + 1)] = value;
_indexStream.invalidate();
_v1._index = value;
_update |= UPDATE_ALL;
}
public function get i2() : int
{
return _indexStream._data[int(_index * 3 + 2)];
}
public function set i2(value : int) : void
{
_indexStream._data[int(_index * 3 + 2)] = value;
_indexStream.invalidate();
_v2._index = value;
_update |= UPDATE_ALL;
}
public function TriangleReference(vertexStream : IVertexStream,
indexStream : IndexStream,
index : uint)
{
_indexStream = indexStream;
_index = index;
initialize(vertexStream);
}
private function initialize(vertexStream : IVertexStream) : void
{
var ii : uint = _index * 3;
// create a new triangle if it does not exist
if (ii >= _indexStream.length)
_indexStream.pushVector(DUMMY_INDICES);
_v0 = new VertexReference(vertexStream, _indexStream.get(ii));
_v1 = new VertexReference(vertexStream, _indexStream.get(ii + 1));
_v2 = new VertexReference(vertexStream, _indexStream.get(ii + 2));
}
public function invertWinding() : void
{
_update = UPDATE_ALL;
var tmp : int = _i0;
_v0._index = _i0 = _i1;
_v1._index = tmp;
i0 = _i1;
i1 = tmp;
}
}
}
|
fix TriangleReference to use IndexStream.pushVector() instead of TriangleReference.push()
|
fix TriangleReference to use IndexStream.pushVector() instead of TriangleReference.push()
|
ActionScript
|
mit
|
aerys/minko-as3
|
265857c4418c0c2021816e0f8e3845da8ae9d431
|
src/ageofai/unit/utils/VillagerAI.as
|
src/ageofai/unit/utils/VillagerAI.as
|
package ageofai.unit.utils
{
import ageofai.home.vo.HomeVO;
import ageofai.home.vo.MapNodeVO;
import ageofai.map.constant.CMapNodeType;
import ageofai.map.geom.IntPoint;
import ageofai.map.model.IMapModel;
import ageofai.map.model.MapNode;
import ageofai.unit.base.IUnitView;
import ageofai.villager.constant.CVillagerStatus;
import ageofai.villager.model.IVillagerModel;
import ageofai.villager.vo.VillagerVO;
import flash.geom.Point;
/**
* ...
* @author
*/
public class VillagerAI implements IUnitAI
{
private var sightOffset:Array = [[ -2, -2 ], [ -2, -1 ], [ -2, 0 ], [ -2, 1 ], [ -2, 2 ],
[ -1, -2 ], [ -1, -1 ], /*[ -1, 0 ],*/ [ -1, 1 ], [ -1, 2 ],
[ 0, -2 ], /*[ 0, -1 ], [ 0, 1 ],*/ [ 0, 2 ],
[ 1, -2 ], [ 1, -1 ], /*[ 1, 0 ],*/ [ 1, 1 ], [ 1, 2 ],
[ 2, -2 ], [ 2, -1 ], [ 2, 0 ], [ 2, 1 ], [ 2, 2 ]];
private var surroundings:Array = [[ -1, 0 ], [ 0, -1 ], [ 1, 0 ], [ 0, 1 ]];
public function tick(villager:VillagerVO, mapModel:IMapModel, home:HomeVO):IntPoint
{
if ( villager.status == CVillagerStatus.IDLE )
{
var newPoint:IntPoint;
var objectFounds:Vector.<MapNodeVO> = new Vector.<MapNodeVO>();
// Check sight area
for (var i:int = 0, count:int = sightOffset.length; i < count; i++)
{
var newX:int = villager.position.x + sightOffset[i][0];
var newY:int = villager.position.y + sightOffset[i][1];
if (newX < 0 || newY < 0 || newX >= mapModel.map[0].length || newY >= mapModel.map.length)
{
continue;
}
newPoint = new IntPoint(newX, newY);
var objectType:int = mapModel.map[newY][newX].objectType;
if (objectType != CMapNodeType.OBJECT_NULL && objectType != CMapNodeType.OBJECT_HOME)
{
var nodeVO:MapNodeVO = new MapNodeVO();
nodeVO.pos = newPoint;
nodeVO.node = mapModel.map[newY][newX];
objectFounds[objectFounds.length] = nodeVO;
}
}
// Check surroundings
for (i = 0, count = surroundings.length; i < count; i++)
{
newX = villager.position.x + surroundings[i][0];
newY = villager.position.y + surroundings[i][1];
if (newX < 0 || newY < 0 || newX >= mapModel.map[0].length || newY >= mapModel.map.length)
{
continue;
}
newPoint = new IntPoint(newX, newY);
var objectType:int = mapModel.map[newY][newX].objectType;
if (objectType != CMapNodeType.OBJECT_NULL && objectType != CMapNodeType.OBJECT_HOME)
{
nodeVO = new MapNodeVO();
nodeVO.pos = newPoint;
nodeVO.node = mapModel.map[newY][newX];
objectFounds[objectFounds.length] = nodeVO;
}
}
home.objectFounds = home.objectFounds.concat(objectFounds);
if ( home.objectFounds.length == 0 )
{
// Move randomly
do {
var newPos:int = Math.round(Math.random() * 3);
newX = villager.position.x + surroundings[newPos][0];
newY = villager.position.y + surroundings[newPos][1];
if (newX < 0 || newY < 0 || newX >= mapModel.map[0].length || newY >= mapModel.map.length)
{
continue;
}
newPoint = new IntPoint(newX, newY);
} while (newPoint.x < 0 || newPoint.y < 0 || newPoint.x >= mapModel.map[0].length || newPoint.y >= mapModel.map.length ||
!mapModel.map[newPoint.y][newPoint.x].walkable);
}
else
{
// Go to object
i = 0;
do {
var path:Vector.<IntPoint> = mapModel.getPath(villager.position, home.objectFounds[i].pos);
i++;
} while (path == null && i < home.objectFounds.length)
if (path != null) newPoint = path[0];
}
}
else
{
// Is current task still valid?
}
return newPoint;
}
}
}
|
package ageofai.unit.utils
{
import ageofai.home.vo.HomeVO;
import ageofai.home.vo.MapNodeVO;
import ageofai.map.constant.CMapNodeType;
import ageofai.map.geom.IntPoint;
import ageofai.map.model.IMapModel;
import ageofai.map.model.MapNode;
import ageofai.unit.base.IUnitView;
import ageofai.villager.constant.CVillagerStatus;
import ageofai.villager.model.IVillagerModel;
import ageofai.villager.vo.VillagerVO;
import flash.geom.Point;
/**
* ...
* @author
*/
public class VillagerAI implements IUnitAI
{
private var sightOffset:Array = [[ -2, -2 ], [ -2, -1 ], [ -2, 0 ], [ -2, 1 ], [ -2, 2 ],
[ -1, -2 ], [ -1, -1 ], /*[ -1, 0 ],*/ [ -1, 1 ], [ -1, 2 ],
[ 0, -2 ], /*[ 0, -1 ], [ 0, 1 ],*/ [ 0, 2 ],
[ 1, -2 ], [ 1, -1 ], /*[ 1, 0 ],*/ [ 1, 1 ], [ 1, 2 ],
[ 2, -2 ], [ 2, -1 ], [ 2, 0 ], [ 2, 1 ], [ 2, 2 ]];
private var surroundings:Array = [[ -1, 0 ], [ 0, -1 ], [ 1, 0 ], [ 0, 1 ]];
public function tick(villager:VillagerVO, mapModel:IMapModel, home:HomeVO):IntPoint
{
if ( villager.status == CVillagerStatus.IDLE )
{
var newPoint:IntPoint;
var objectFounds:Vector.<MapNodeVO> = new Vector.<MapNodeVO>();
// Check sight area
for (var i:int = 0, count:int = sightOffset.length; i < count; i++)
{
var newX:int = villager.position.x + sightOffset[i][0];
var newY:int = villager.position.y + sightOffset[i][1];
if (newX < 0 || newY < 0 || newX >= mapModel.map[0].length || newY >= mapModel.map.length)
{
continue;
}
newPoint = new IntPoint(newX, newY);
var objectType:int = mapModel.map[newY][newX].objectType;
if (objectType != CMapNodeType.OBJECT_NULL && objectType != CMapNodeType.OBJECT_HOME)
{
var nodeVO:MapNodeVO = new MapNodeVO();
nodeVO.pos = newPoint;
nodeVO.node = mapModel.map[newY][newX];
objectFounds[objectFounds.length] = nodeVO;
}
}
// Check surroundings
var nextToObject:Boolean;
for (i = 0, count = surroundings.length; i < count; i++)
{
newX = villager.position.x + surroundings[i][0];
newY = villager.position.y + surroundings[i][1];
if (newX < 0 || newY < 0 || newX >= mapModel.map[0].length || newY >= mapModel.map.length)
{
continue;
}
newPoint = new IntPoint(newX, newY);
var objectType:int = mapModel.map[newY][newX].objectType;
if (objectType != CMapNodeType.OBJECT_NULL && objectType != CMapNodeType.OBJECT_HOME)
{
nextToObject = true;
nodeVO = new MapNodeVO();
nodeVO.pos = newPoint;
nodeVO.node = mapModel.map[newY][newX];
objectFounds[objectFounds.length] = nodeVO;
}
}
home.objectFounds = home.objectFounds.concat(objectFounds);
if ( home.objectFounds.length == 0 )
{
// Move randomly
do {
var newPos:int = Math.round(Math.random() * 3);
newX = villager.position.x + surroundings[newPos][0];
newY = villager.position.y + surroundings[newPos][1];
if (newX < 0 || newY < 0 || newX >= mapModel.map[0].length || newY >= mapModel.map.length)
{
continue;
}
newPoint = new IntPoint(newX, newY);
} while (newPoint.x < 0 || newPoint.y < 0 || newPoint.x >= mapModel.map[0].length || newPoint.y >= mapModel.map.length ||
!mapModel.map[newPoint.y][newPoint.x].walkable);
}
else if (nextToObject)
{
villager.status = CVillagerStatus.HARVEST;
newPoint = null;
}
else
{
// Go to object
i = 0;
do {
var path:Vector.<IntPoint> = mapModel.getPath(villager.position, home.objectFounds[i].pos);
i++;
} while (path == null && i < home.objectFounds.length)
if (path != null) newPoint = path[0];
}
}
else
{
// Is current task still valid?
}
return newPoint;
}
}
}
|
Change status
|
Change status
|
ActionScript
|
apache-2.0
|
goc-flashplusplus/ageofai
|
d0f9a89a79bcf41b6f59ef9a647536eb34eee294
|
src/aerys/minko/type/enum/Blending.as
|
src/aerys/minko/type/enum/Blending.as
|
package aerys.minko.type.enum
{
import aerys.minko.ns.minko_render;
import flash.display3D.Context3DBlendFactor;
/**
* The Blending class is an enumeration of the most common values possible
* for the Shader.blending property and the BlendingShaderPart.blend() method.
*
* @author Jean-Marc Le Roux
*
* @see aerys.minko.type.enum.BlendingSource
* @see aerys.minko.type.enum.BlendingDestination
* @see aerys.minko.render.shader.Shader
* @see aerys.minko.render.shader.part.BlendingShaderPart
*
*/
public final class Blending
{
public static const NORMAL : uint = BlendingSource.ONE
| BlendingDestination.ZERO;
public static const ALPHA : uint = BlendingSource.SOURCE_ALPHA
| BlendingDestination.ONE_MINUS_SOURCE_ALPHA;
public static const ADDITIVE : uint = BlendingSource.SOURCE_ALPHA
| BlendingDestination.ONE;
public static const LIGHT : uint = BlendingSource.ZERO
| BlendingDestination.SOURCE_COLOR;
minko_render static const STRINGS : Vector.<String> = new <String>[
Context3DBlendFactor.DESTINATION_ALPHA,
Context3DBlendFactor.DESTINATION_COLOR,
Context3DBlendFactor.ONE,
Context3DBlendFactor.ONE_MINUS_DESTINATION_ALPHA,
Context3DBlendFactor.ONE_MINUS_DESTINATION_COLOR,
Context3DBlendFactor.ONE_MINUS_SOURCE_ALPHA,
Context3DBlendFactor.SOURCE_ALPHA,
Context3DBlendFactor.SOURCE_COLOR,
Context3DBlendFactor.ZERO
];
}
}
|
package aerys.minko.type.enum
{
import aerys.minko.ns.minko_render;
import flash.display3D.Context3DBlendFactor;
/**
* The Blending class is an enumeration of the most common values possible
* for the Shader.blending property and the BlendingShaderPart.blend() method.
*
* @author Jean-Marc Le Roux
*
* @see aerys.minko.type.enum.BlendingSource
* @see aerys.minko.type.enum.BlendingDestination
* @see aerys.minko.render.shader.Shader
* @see aerys.minko.render.shader.part.BlendingShaderPart
*
*/
public final class Blending
{
public static const OPAQUE : uint = BlendingSource.ONE
| BlendingDestination.ZERO;
public static const ALPHA : uint = BlendingSource.SOURCE_ALPHA
| BlendingDestination.ONE_MINUS_SOURCE_ALPHA;
// public static const ADDITIVE : uint = BlendingSource.SOURCE_ALPHA
// | BlendingDestination.ONE;
public static const ADDITIVE : uint = BlendingSource.DESTINATION_ALPHA
| BlendingDestination.ONE;
public static const LIGHT : uint = BlendingSource.ZERO
| BlendingDestination.SOURCE_COLOR;
minko_render static const STRINGS : Vector.<String> = new <String>[
Context3DBlendFactor.DESTINATION_ALPHA,
Context3DBlendFactor.DESTINATION_COLOR,
Context3DBlendFactor.ONE,
Context3DBlendFactor.ONE_MINUS_DESTINATION_ALPHA,
Context3DBlendFactor.ONE_MINUS_DESTINATION_COLOR,
Context3DBlendFactor.ONE_MINUS_SOURCE_ALPHA,
Context3DBlendFactor.SOURCE_ALPHA,
Context3DBlendFactor.SOURCE_COLOR,
Context3DBlendFactor.ZERO
];
}
}
|
rename Blending.NORMAL to Blending.OPAQUE
|
rename Blending.NORMAL to Blending.OPAQUE
|
ActionScript
|
mit
|
aerys/minko-as3
|
399d7321b9dc28b86e4eea1b5433b44f7c3ff6cd
|
src/com/esri/builder/controllers/ApplicationCompleteController.as
|
src/com/esri/builder/controllers/ApplicationCompleteController.as
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////////
package com.esri.builder.controllers
{
import com.esri.ags.components.IdentityManager;
import com.esri.ags.events.IdentityManagerEvent;
import com.esri.builder.components.LogFileTarget;
import com.esri.builder.components.ToolTip;
import com.esri.builder.controllers.supportClasses.MachineDisplayName;
import com.esri.builder.controllers.supportClasses.Settings;
import com.esri.builder.controllers.supportClasses.StartupWidgetTypeLoader;
import com.esri.builder.controllers.supportClasses.WellKnownDirectories;
import com.esri.builder.eventbus.AppEvent;
import com.esri.builder.model.Model;
import com.esri.builder.model.PortalModel;
import com.esri.builder.supportClasses.LogUtil;
import com.esri.builder.views.BuilderAlert;
import com.esri.builder.views.popups.UnknownErrorPopUp;
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import flash.events.UncaughtErrorEvent;
import flash.filesystem.File;
import flash.net.SharedObject;
import flash.net.URLRequestDefaults;
import flash.system.Capabilities;
import mx.core.FlexGlobals;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.managers.ToolTipManager;
import mx.resources.ResourceManager;
import mx.rpc.AsyncResponder;
import mx.rpc.Responder;
import spark.components.WindowedApplication;
public final class ApplicationCompleteController
{
private static const LOG:ILogger = LogUtil.createLogger(ApplicationCompleteController);
private var widgetTypeLoader:StartupWidgetTypeLoader;
private var startupSettings:Settings;
public function ApplicationCompleteController()
{
AppEvent.addListener(AppEvent.APPLICATION_COMPLETE, onApplicationComplete, false, 0, true);
}
private function onApplicationComplete(event:AppEvent):void
{
applicationComplete(event.data as WindowedApplication);
Model.instance.config.isDirty = false;
}
private function applicationComplete(app:WindowedApplication):void
{
if (Log.isInfo())
{
LOG.info('Starting up application.');
}
exportDependenciesToAppStorage();
loadUserPreferences();
loadWebMapSearchHistory();
// Disable HTTP cache for HTML component
URLRequestDefaults.cacheResponse = false;
// Setup some XML global properties
XML.ignoreComments = true;
XML.ignoreWhitespace = true;
XML.prettyIndent = 4;
ToolTipManager.toolTipClass = ToolTip;
// Can only have access to 'loaderInfo' when the app is complete.
app.loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler);
widgetTypeLoader = new StartupWidgetTypeLoader();
widgetTypeLoader.addEventListener(Event.COMPLETE, widgetTypeLoader_completeHandler);
widgetTypeLoader.loadWidgetTypes();
}
private function exportDependenciesToAppStorage():void
{
try
{
if (Log.isInfo())
{
LOG.info('Creating required folders.');
}
WellKnownDirectories.getInstance().customFlexViewer.createDirectory();
WellKnownDirectories.getInstance().customModules.createDirectory();
}
catch (error:Error)
{
BuilderAlert.show(ResourceManager.getInstance().getString('BuilderStrings', 'startup.couldNotCreateCustomDirectories'), ResourceManager.getInstance().getString('BuilderStrings', 'error'));
}
}
private function loadUserPreferences():void
{
if (Log.isInfo())
{
LOG.info('Loading user preferences...');
}
migratePreviousSettingsFolder();
const so:SharedObject = SharedObject.getLocal(Model.USER_PREF);
startupSettings = new Settings();
startupSettings.webServerURL = so.data.baseURL;
startupSettings.webServerFolder = so.data.baseLoc;
startupSettings.locale = so.data.locale ? so.data.locale : getPreferredLocale();
startupSettings.bingKey = so.data.bingKey;
startupSettings.proxyURL = so.data.httpProxy;
if (so.data.hasOwnProperty("userPortalURL"))
{
//updated property for v3.1+
startupSettings.portalURL = so.data.userPortalURL;
startupSettings.geocodeURL = so.data.geocodeURL;
startupSettings.directionsURL = so.data.directionsURL;
startupSettings.printTaskURL = so.data.printTaskURL;
}
else
{
startupSettings.portalURL = (so.data.portalURL) ? so.data.portalURL : PortalModel.DEFAULT_PORTAL_URL;
}
if (so.data.hasOwnProperty("userGeometryServiceURL"))
{
//updated property for v3.1+
startupSettings.geometryServiceURL = so.data.userGeometryServiceURL;
}
else
{
startupSettings.geometryServiceURL = so.data.userGeometryServiceURL = (so.data.geometryServiceURL) ? so.data.geometryServiceURL : "http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer";
}
if (so.data.hasOwnProperty("isTutorialModeEnabled"))
{
startupSettings.isTutorialModeEnabled = so.data.isTutorialModeEnabled;
}
else if (so.data.tutorialModeSettings)
{
startupSettings.isTutorialModeEnabled = so.data.tutorialModeSettings.isTutorialModeEnabled;
}
so.close();
if (!startupSettings.webServerFolder)
{
if (Capabilities.os.toLowerCase().indexOf('win') > -1)
{
startupSettings.webServerFolder = 'C:\\inetpub\\wwwroot\\flexviewers';
}
else if (Capabilities.os.toLowerCase().indexOf('mac') > -1)
{
startupSettings.webServerFolder = File.userDirectory.nativePath + '/Sites/flexviewers';
}
else if (Capabilities.os.toLowerCase().indexOf('linux') > -1)
{
startupSettings.webServerFolder = '/var/httpd/wwwroot/flexviewers'; // TODO - check this !!
}
}
if (startupSettings.webServerURL)
{
applySettings();
}
else
{
tryGetHostName();
}
}
private function migratePreviousSettingsFolder():void
{
var previousBuilderSettingsFolder:File =
File.applicationStorageDirectory.resolvePath("#SharedObjects/AppBuilder.swf/");
if (!previousBuilderSettingsFolder.exists)
{
return;
}
var filesOrFolders:Array = previousBuilderSettingsFolder.getDirectoryListing();
if (filesOrFolders.length == 0)
{
return;
}
if (Log.isInfo())
{
LOG.info('Transferring previous settings folder');
}
var currentBuilderSettingsFolder:File =
File.applicationStorageDirectory.resolvePath("#SharedObjects/Builder.swf/");
try
{
for each (var fileOrFolder:File in filesOrFolders)
{
if (Log.isInfo())
{
LOG.info('Transferring {0}', fileOrFolder.name);
}
fileOrFolder.moveTo(currentBuilderSettingsFolder.resolvePath(fileOrFolder.name),
true);
}
}
catch (error:Error)
{
if (Log.isInfo())
{
LOG.info('Could not transfer previous settings folder: {0} - {1}',
error.errorID, error.toString());
}
}
}
private function applySettings():void
{
Model.instance.importSettings(startupSettings);
startupSettings = null;
}
private function tryGetHostName():void
{
MachineDisplayName.getInstance().resolve(new AsyncResponder(result, fault));
function result(hostname:String, token:Object):void
{
initBaseURL(hostname.toLowerCase());
applySettings();
}
function fault(fault:Object, token:Object):void
{
initBaseURL("localhost");
applySettings();
}
}
private function initBaseURL(hostname:String):void
{
if (Capabilities.os.toLowerCase().indexOf('win') > -1)
{
startupSettings.webServerURL = 'http://' + hostname + '/flexviewers';
}
else if (Capabilities.os.toLowerCase().indexOf('mac') > -1)
{
startupSettings.webServerURL = 'http://' + hostname + '/~' + File.userDirectory.name + '/flexviewers';
}
else if (Capabilities.os.toLowerCase().indexOf('linux') > -1)
{
startupSettings.webServerURL = 'http://' + hostname + '/flexviewers'; // TODO - check this !!
}
}
private function getPreferredLocale():String
{
const preferredLocales:Array = ResourceManager.getInstance().getPreferredLocaleChain();
return (preferredLocales.length > 0) ? preferredLocales[0] : 'en_US';
}
private function loadWebMapSearchHistory():void
{
if (Log.isInfo())
{
LOG.info("Loading web map search history");
}
const so:SharedObject = SharedObject.getLocal(Model.USER_PREF);
var historyString:String = so.data.webMapSearchHistory;
if (historyString != null)
{
Model.instance.webMapSearchHistory = historyString.split("##");
}
so.close();
}
private function uncaughtErrorHandler(event:UncaughtErrorEvent):void
{
event.preventDefault();
if (Log.isFatal())
{
if (event.error is Error) //could be ErrorEvent
{
LOG.fatal('Uncaught error: {0}', event.error.getStackTrace());
}
}
const logFile:File = File.applicationStorageDirectory.resolvePath(LogFileTarget.LOG_FILE_NAME);
const errorContent:String = ResourceManager.getInstance().getString('BuilderStrings', 'unknownErrorMessage',
[ event.error.toString(), logFile.nativePath ]);
const errorPopUp:UnknownErrorPopUp = new UnknownErrorPopUp();
errorPopUp.errorContent = errorContent;
errorPopUp.open(FlexGlobals.topLevelApplication as DisplayObjectContainer, true);
}
private function setStatusAndAlert(text:String):void
{
Model.instance.status = text;
BuilderAlert.show(text, ResourceManager.getInstance().getString('BuilderStrings', 'error'));
}
protected function widgetTypeLoader_completeHandler(event:Event):void
{
(event.currentTarget as StartupWidgetTypeLoader).removeEventListener(Event.COMPLETE, widgetTypeLoader_completeHandler);
initIdentityManager();
}
private function initIdentityManager():void
{
var portalURL:String = PortalModel.getInstance().portalURL;
var idManager:IdentityManager = IdentityManager.instance;
idManager.enabled = true;
if (PortalModel.getInstance().isAGO(portalURL))
{
idManager.addEventListener(IdentityManagerEvent.SHOW_OAUTH_WEB_VIEW, showOAuthWebViewHandler);
PortalModel.getInstance().registerOAuthPortal(portalURL);
idManager.getCredential(portalURL, false, new Responder(getCredentialOutcomeHandler,
getCredentialOutcomeHandler));
function getCredentialOutcomeHandler(outcome:Object):void
{
idManager.removeEventListener(IdentityManagerEvent.SHOW_OAUTH_WEB_VIEW, showOAuthWebViewHandler);
validateSettings();
}
function showOAuthWebViewHandler(event:IdentityManagerEvent):void
{
idManager.removeEventListener(IdentityManagerEvent.SHOW_OAUTH_WEB_VIEW, showOAuthWebViewHandler);
event.preventDefault();
idManager.setCredentialForCurrentSignIn(null);
validateSettings();
}
}
else
{
validateSettings();
}
}
private function validateSettings():void
{
AppEvent.dispatch(AppEvent.SAVE_SETTINGS, Model.instance.exportSettings());
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////////
package com.esri.builder.controllers
{
import com.esri.ags.components.IdentityManager;
import com.esri.ags.events.IdentityManagerEvent;
import com.esri.builder.components.LogFileTarget;
import com.esri.builder.components.ToolTip;
import com.esri.builder.controllers.supportClasses.MachineDisplayName;
import com.esri.builder.controllers.supportClasses.Settings;
import com.esri.builder.controllers.supportClasses.StartupWidgetTypeLoader;
import com.esri.builder.controllers.supportClasses.WellKnownDirectories;
import com.esri.builder.eventbus.AppEvent;
import com.esri.builder.model.Model;
import com.esri.builder.model.PortalModel;
import com.esri.builder.supportClasses.LogUtil;
import com.esri.builder.views.BuilderAlert;
import com.esri.builder.views.popups.UnknownErrorPopUp;
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import flash.events.UncaughtErrorEvent;
import flash.filesystem.File;
import flash.net.SharedObject;
import flash.net.URLRequestDefaults;
import flash.system.Capabilities;
import mx.core.FlexGlobals;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.managers.ToolTipManager;
import mx.resources.ResourceManager;
import mx.rpc.AsyncResponder;
import mx.rpc.Responder;
import spark.components.WindowedApplication;
public final class ApplicationCompleteController
{
private static const LOG:ILogger = LogUtil.createLogger(ApplicationCompleteController);
private var widgetTypeLoader:StartupWidgetTypeLoader;
private var startupSettings:Settings;
public function ApplicationCompleteController()
{
AppEvent.addListener(AppEvent.APPLICATION_COMPLETE, onApplicationComplete, false, 0, true);
}
private function onApplicationComplete(event:AppEvent):void
{
applicationComplete(event.data as WindowedApplication);
Model.instance.config.isDirty = false;
}
private function applicationComplete(app:WindowedApplication):void
{
if (Log.isInfo())
{
LOG.info('Starting up application.');
}
exportDependenciesToAppStorage();
loadUserPreferences();
loadWebMapSearchHistory();
// Disable HTTP cache for HTML component
URLRequestDefaults.cacheResponse = false;
// Setup some XML global properties
XML.ignoreComments = true;
XML.ignoreWhitespace = true;
XML.prettyIndent = 4;
ToolTipManager.toolTipClass = ToolTip;
// Can only have access to 'loaderInfo' when the app is complete.
app.loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler);
widgetTypeLoader = new StartupWidgetTypeLoader();
widgetTypeLoader.addEventListener(Event.COMPLETE, widgetTypeLoader_completeHandler);
widgetTypeLoader.loadWidgetTypes();
}
private function exportDependenciesToAppStorage():void
{
try
{
if (Log.isInfo())
{
LOG.info('Creating required folders.');
}
WellKnownDirectories.getInstance().customFlexViewer.createDirectory();
WellKnownDirectories.getInstance().customModules.createDirectory();
}
catch (error:Error)
{
BuilderAlert.show(ResourceManager.getInstance().getString('BuilderStrings', 'startup.couldNotCreateCustomDirectories'), ResourceManager.getInstance().getString('BuilderStrings', 'error'));
}
}
private function loadUserPreferences():void
{
if (Log.isInfo())
{
LOG.info('Loading user preferences...');
}
migratePreviousSettingsFolder();
const so:SharedObject = SharedObject.getLocal(Model.USER_PREF);
startupSettings = new Settings();
startupSettings.webServerURL = so.data.baseURL;
startupSettings.webServerFolder = so.data.baseLoc;
startupSettings.locale = so.data.locale ? so.data.locale : getPreferredLocale();
startupSettings.bingKey = so.data.bingKey;
startupSettings.proxyURL = so.data.httpProxy;
if (so.data.hasOwnProperty("userPortalURL"))
{
//updated property for v3.1+
startupSettings.portalURL = so.data.userPortalURL;
startupSettings.geocodeURL = so.data.geocodeURL;
startupSettings.directionsURL = so.data.directionsURL;
startupSettings.printTaskURL = so.data.printTaskURL;
}
else
{
startupSettings.portalURL = (so.data.portalURL) ? so.data.portalURL : PortalModel.DEFAULT_PORTAL_URL;
}
if (so.data.hasOwnProperty("userGeometryServiceURL"))
{
//updated property for v3.1+
startupSettings.geometryServiceURL = so.data.userGeometryServiceURL;
}
else
{
startupSettings.geometryServiceURL = so.data.userGeometryServiceURL = (so.data.geometryServiceURL) ? so.data.geometryServiceURL : "http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer";
}
if (so.data.hasOwnProperty("isTutorialModeEnabled"))
{
startupSettings.isTutorialModeEnabled = so.data.isTutorialModeEnabled;
}
else if (so.data.tutorialModeSettings)
{
startupSettings.isTutorialModeEnabled = so.data.tutorialModeSettings.isTutorialModeEnabled;
}
so.close();
if (!startupSettings.webServerFolder)
{
if (Capabilities.os.toLowerCase().indexOf('win') > -1)
{
startupSettings.webServerFolder = 'C:\\inetpub\\wwwroot\\flexviewers';
}
else if (Capabilities.os.toLowerCase().indexOf('mac') > -1)
{
startupSettings.webServerFolder = File.userDirectory.nativePath + '/Sites/flexviewers';
}
else if (Capabilities.os.toLowerCase().indexOf('linux') > -1)
{
startupSettings.webServerFolder = '/var/httpd/wwwroot/flexviewers'; // TODO - check this !!
}
}
if (startupSettings.webServerURL)
{
applySettings();
}
else
{
tryGetHostName();
}
}
private function migratePreviousSettingsFolder():void
{
var previousBuilderSettingsFolder:File =
File.applicationStorageDirectory.resolvePath("#SharedObjects/AppBuilder.swf/");
if (!previousBuilderSettingsFolder.exists)
{
return;
}
var filesOrFolders:Array = previousBuilderSettingsFolder.getDirectoryListing();
if (filesOrFolders.length == 0)
{
return;
}
if (Log.isInfo())
{
LOG.info('Transferring previous settings folder');
}
var currentBuilderSettingsFolder:File =
File.applicationStorageDirectory.resolvePath("#SharedObjects/Builder.swf/");
try
{
for each (var fileOrFolder:File in filesOrFolders)
{
if (Log.isInfo())
{
LOG.info('Transferring {0}', fileOrFolder.name);
}
fileOrFolder.moveTo(currentBuilderSettingsFolder.resolvePath(fileOrFolder.name),
true);
}
}
catch (error:Error)
{
if (Log.isInfo())
{
LOG.info('Could not transfer previous settings folder: {0} - {1}',
error.errorID, error.toString());
}
}
}
private function applySettings():void
{
Model.instance.importSettings(startupSettings);
startupSettings = null;
}
private function tryGetHostName():void
{
MachineDisplayName.getInstance().resolve(new AsyncResponder(result, fault));
function result(hostname:String, token:Object):void
{
initBaseURL(hostname.toLowerCase());
applySettings();
}
function fault(fault:Object, token:Object):void
{
initBaseURL("localhost");
applySettings();
}
}
private function initBaseURL(hostname:String):void
{
if (Capabilities.os.toLowerCase().indexOf('win') > -1)
{
startupSettings.webServerURL = 'http://' + hostname + '/flexviewers';
}
else if (Capabilities.os.toLowerCase().indexOf('mac') > -1)
{
startupSettings.webServerURL = 'http://' + hostname + '/~' + File.userDirectory.name + '/flexviewers';
}
else if (Capabilities.os.toLowerCase().indexOf('linux') > -1)
{
startupSettings.webServerURL = 'http://' + hostname + '/flexviewers'; // TODO - check this !!
}
}
private function getPreferredLocale():String
{
const preferredLocales:Array = ResourceManager.getInstance().getPreferredLocaleChain();
return (preferredLocales.length > 0) ? preferredLocales[0] : 'en_US';
}
private function loadWebMapSearchHistory():void
{
if (Log.isInfo())
{
LOG.info("Loading web map search history");
}
const so:SharedObject = SharedObject.getLocal(Model.USER_PREF);
var historyString:String = so.data.webMapSearchHistory;
if (historyString != null)
{
Model.instance.webMapSearchHistory = historyString.split("##");
}
so.close();
}
private function uncaughtErrorHandler(event:UncaughtErrorEvent):void
{
event.preventDefault();
if (Log.isFatal())
{
if (event.error is Error) //could be ErrorEvent
{
LOG.fatal('Uncaught error: {0}', event.error.getStackTrace());
}
}
const logFile:File = File.applicationStorageDirectory.resolvePath(LogFileTarget.LOG_FILE_NAME);
const errorContent:String = ResourceManager.getInstance().getString('BuilderStrings', 'unknownErrorMessage',
[ event.error.toString(), logFile.nativePath ]);
const errorPopUp:UnknownErrorPopUp = new UnknownErrorPopUp();
errorPopUp.errorContent = errorContent;
errorPopUp.open(FlexGlobals.topLevelApplication as DisplayObjectContainer, true);
}
protected function widgetTypeLoader_completeHandler(event:Event):void
{
(event.currentTarget as StartupWidgetTypeLoader).removeEventListener(Event.COMPLETE, widgetTypeLoader_completeHandler);
initIdentityManager();
}
private function initIdentityManager():void
{
var portalURL:String = PortalModel.getInstance().portalURL;
var idManager:IdentityManager = IdentityManager.instance;
idManager.enabled = true;
if (PortalModel.getInstance().isAGO(portalURL))
{
idManager.addEventListener(IdentityManagerEvent.SHOW_OAUTH_WEB_VIEW, showOAuthWebViewHandler);
PortalModel.getInstance().registerOAuthPortal(portalURL);
idManager.getCredential(portalURL, false, new Responder(getCredentialOutcomeHandler,
getCredentialOutcomeHandler));
function getCredentialOutcomeHandler(outcome:Object):void
{
idManager.removeEventListener(IdentityManagerEvent.SHOW_OAUTH_WEB_VIEW, showOAuthWebViewHandler);
validateSettings();
}
function showOAuthWebViewHandler(event:IdentityManagerEvent):void
{
idManager.removeEventListener(IdentityManagerEvent.SHOW_OAUTH_WEB_VIEW, showOAuthWebViewHandler);
event.preventDefault();
idManager.setCredentialForCurrentSignIn(null);
validateSettings();
}
}
else
{
validateSettings();
}
}
private function validateSettings():void
{
AppEvent.dispatch(AppEvent.SAVE_SETTINGS, Model.instance.exportSettings());
}
}
}
|
Remove unused method.
|
Remove unused method.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
3e2bd58c6477ffaa05ba7068b9c8fc076ced86a9
|
frameworks/as/src/FlexJSUIClasses.as
|
frameworks/as/src/FlexJSUIClasses.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package
{
/**
* @private
* This class is used to link additional classes into rpc.swc
* beyond those that are found by dependecy analysis starting
* from the classes specified in manifest.xml.
*/
internal class FlexJSUIClasses
{
import org.apache.flex.html.staticControls.beads.AlertView; AlertView;
import org.apache.flex.html.staticControls.beads.CheckBoxView; CheckBoxView;
import org.apache.flex.html.staticControls.beads.ComboBoxView; ComboBoxView;
import org.apache.flex.html.staticControls.beads.ContainerView; ContainerView;
import org.apache.flex.html.staticControls.beads.ControlBarMeasurementBead; ControlBarMeasurementBead;
import org.apache.flex.html.staticControls.beads.CSSTextButtonView; CSSTextButtonView;
import org.apache.flex.html.staticControls.beads.DropDownListView; DropDownListView;
import org.apache.flex.html.staticControls.beads.ListView; ListView;
import org.apache.flex.html.staticControls.beads.NumericStepperView; NumericStepperView;
import org.apache.flex.html.staticControls.beads.PanelView; PanelView;
import org.apache.flex.html.staticControls.beads.RadioButtonView; RadioButtonView;
import org.apache.flex.html.staticControls.beads.SimpleAlertView; SimpleAlertView;
import org.apache.flex.html.staticControls.beads.SpinnerView; SpinnerView;
import org.apache.flex.html.staticControls.beads.TextButtonMeasurementBead; TextButtonMeasurementBead;
import org.apache.flex.html.staticControls.beads.TextFieldLabelMeasurementBead; TextFieldLabelMeasurementBead;
import org.apache.flex.html.staticControls.beads.TextAreaView; TextAreaView;
import org.apache.flex.html.staticControls.beads.TextButtonView; TextButtonView;
import org.apache.flex.html.staticControls.beads.TextFieldView; TextFieldView;
import org.apache.flex.html.staticControls.beads.TextInputView; TextInputView;
import org.apache.flex.html.staticControls.beads.TextInputWithBorderView; TextInputWithBorderView;
import org.apache.flex.html.staticControls.beads.TitleBarMeasurementBead; TitleBarMeasurementBead;
import org.apache.flex.html.staticControls.beads.models.AlertModel; AlertModel;
import org.apache.flex.html.staticControls.beads.models.ArraySelectionModel; ArraySelectionModel;
import org.apache.flex.html.staticControls.beads.models.ComboBoxModel; ComboBoxModel;
import org.apache.flex.html.staticControls.beads.models.PanelModel; PanelModel;
import org.apache.flex.html.staticControls.beads.models.SpinnerModel; SpinnerModel;
import org.apache.flex.html.staticControls.beads.models.TextModel; TextModel;
import org.apache.flex.html.staticControls.beads.models.TitleBarModel; TitleBarModel;
import org.apache.flex.html.staticControls.beads.models.ToggleButtonModel; ToggleButtonModel;
import org.apache.flex.html.staticControls.beads.models.ValueToggleButtonModel; ValueToggleButtonModel;
import org.apache.flex.html.staticControls.beads.controllers.DropDownListController; DropDownListController;
import org.apache.flex.html.staticControls.beads.controllers.ListSingleSelectionMouseController; ListSingleSelectionMouseController;
import org.apache.flex.html.staticControls.beads.controllers.ItemRendererMouseController; ItemRendererMouseController;
import org.apache.flex.html.staticControls.beads.layouts.NonVirtualVerticalScrollingLayout; NonVirtualVerticalScrollingLayout;
import org.apache.flex.html.staticControls.beads.TextItemRendererFactoryForArrayData; TextItemRendererFactoryForArrayData;
import org.apache.flex.core.ItemRendererClassFactory; ItemRendererClassFactory;
import org.apache.flex.events.CustomEvent; CustomEvent;
import org.apache.flex.events.Event; Event;
import org.apache.flex.utils.Timer; Timer;
import org.apache.flex.core.SimpleStatesImpl; SimpleStatesImpl;
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package
{
/**
* @private
* This class is used to link additional classes into rpc.swc
* beyond those that are found by dependecy analysis starting
* from the classes specified in manifest.xml.
*/
internal class FlexJSUIClasses
{
import org.apache.flex.html.staticControls.beads.AlertView; AlertView;
import org.apache.flex.html.staticControls.beads.CheckBoxView; CheckBoxView;
import org.apache.flex.html.staticControls.beads.ComboBoxView; ComboBoxView;
import org.apache.flex.html.staticControls.beads.ContainerView; ContainerView;
import org.apache.flex.html.staticControls.beads.ControlBarMeasurementBead; ControlBarMeasurementBead;
import org.apache.flex.html.staticControls.beads.CSSTextButtonView; CSSTextButtonView;
import org.apache.flex.html.staticControls.beads.DropDownListView; DropDownListView;
import org.apache.flex.html.staticControls.beads.ListView; ListView;
import org.apache.flex.html.staticControls.beads.NumericStepperView; NumericStepperView;
import org.apache.flex.html.staticControls.beads.PanelView; PanelView;
import org.apache.flex.html.staticControls.beads.RadioButtonView; RadioButtonView;
import org.apache.flex.html.staticControls.beads.ScrollBarView; ScrollBarView;
import org.apache.flex.html.staticControls.beads.SimpleAlertView; SimpleAlertView;
import org.apache.flex.html.staticControls.beads.SpinnerView; SpinnerView;
import org.apache.flex.html.staticControls.beads.TextButtonMeasurementBead; TextButtonMeasurementBead;
import org.apache.flex.html.staticControls.beads.TextFieldLabelMeasurementBead; TextFieldLabelMeasurementBead;
import org.apache.flex.html.staticControls.beads.TextAreaView; TextAreaView;
import org.apache.flex.html.staticControls.beads.TextButtonView; TextButtonView;
import org.apache.flex.html.staticControls.beads.TextFieldView; TextFieldView;
import org.apache.flex.html.staticControls.beads.TextInputView; TextInputView;
import org.apache.flex.html.staticControls.beads.TextInputWithBorderView; TextInputWithBorderView;
import org.apache.flex.html.staticControls.beads.TitleBarMeasurementBead; TitleBarMeasurementBead;
import org.apache.flex.html.staticControls.beads.models.AlertModel; AlertModel;
import org.apache.flex.html.staticControls.beads.models.ArraySelectionModel; ArraySelectionModel;
import org.apache.flex.html.staticControls.beads.models.ComboBoxModel; ComboBoxModel;
import org.apache.flex.html.staticControls.beads.models.PanelModel; PanelModel;
import org.apache.flex.html.staticControls.beads.models.SpinnerModel; SpinnerModel;
import org.apache.flex.html.staticControls.beads.models.TextModel; TextModel;
import org.apache.flex.html.staticControls.beads.models.TitleBarModel; TitleBarModel;
import org.apache.flex.html.staticControls.beads.models.ToggleButtonModel; ToggleButtonModel;
import org.apache.flex.html.staticControls.beads.models.ValueToggleButtonModel; ValueToggleButtonModel;
import org.apache.flex.html.staticControls.beads.controllers.AlertController; AlertController;
import org.apache.flex.html.staticControls.beads.controllers.DropDownListController; DropDownListController;
import org.apache.flex.html.staticControls.beads.controllers.ItemRendererMouseController; ItemRendererMouseController;
import org.apache.flex.html.staticControls.beads.controllers.ListSingleSelectionMouseController; ListSingleSelectionMouseController;
import org.apache.flex.html.staticControls.beads.controllers.SpinnerMouseController; SpinnerMouseController;
import org.apache.flex.html.staticControls.beads.controllers.VScrollBarMouseController; VScrollBarMouseController;
import org.apache.flex.html.staticControls.beads.layouts.NonVirtualVerticalScrollingLayout; NonVirtualVerticalScrollingLayout;
import org.apache.flex.html.staticControls.beads.layouts.VScrollBarLayout; VScrollBarLayout;
import org.apache.flex.html.staticControls.beads.TextItemRendererFactoryForArrayData; TextItemRendererFactoryForArrayData;
import org.apache.flex.core.ItemRendererClassFactory; ItemRendererClassFactory;
import org.apache.flex.events.CustomEvent; CustomEvent;
import org.apache.flex.events.Event; Event;
import org.apache.flex.utils.Timer; Timer;
import org.apache.flex.core.SimpleStatesImpl; SimpleStatesImpl;
import mx.states.AddItems; AddItems;
import mx.states.SetProperty; SetProperty;
import mx.states.State; State;
}
}
|
Add mx state shims to SWC
|
Add mx state shims to SWC
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
ba581b017faea664715e9093b9abb28932a2d4b5
|
src/aerys/minko/type/math/Vector4.as
|
src/aerys/minko/type/math/Vector4.as
|
package aerys.minko.type.math
{
import aerys.minko.ns.minko_math;
import aerys.minko.type.Factory;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.IWatchable;
import flash.geom.Vector3D;
final public class Vector4 implements IWatchable
{
use namespace minko_math;
public static const X_AXIS : Vector4 = new Vector4(1., 0., 0.);
public static const Y_AXIS : Vector4 = new Vector4(0., 1., 0.);
public static const Z_AXIS : Vector4 = new Vector4(0., 0., 1.);
public static const ZERO : Vector4 = new Vector4(0., 0., 0., 0.);
public static const ONE : Vector4 = new Vector4(1., 1., 1., 1.);
public static const FORWARD : Vector4 = Z_AXIS;
public static const BACKWARD : Vector4 = new Vector4(0., 0., -1.);
public static const LEFT : Vector4 = new Vector4(-1, 0., 0.);
public static const RIGHT : Vector4 = new Vector4(1, 0., 0.);
public static const UP : Vector4 = Y_AXIS;
public static const DOWN : Vector4 = new Vector4(0, -1., 0.);
private static const FACTORY : Factory = Factory.getFactory(Vector4);
private static const UPDATE_NONE : uint = 0;
private static const UPDATE_LENGTH : uint = 1;
private static const UPDATE_LENGTH_SQ : uint = 2;
private static const UPDATE_ALL : uint = 3; // UPDATE_LENGTH | UPDATE_LENGTH_SQ;
private static const DATA_DESCRIPTOR : Object = {
'x' : 'x',
'y' : 'y',
'z' : 'z',
'w' : 'w'
};
minko_math var _vector : Vector3D = new Vector3D();
private var _update : uint = 0;
private var _length : Number = 0.;
private var _lengthSq : Number = 0.;
private var _locked : Boolean = false;
private var _changed : Signal = new Signal('Vector4.changed');
public function get x() : Number
{
return _vector.x;
}
public function set x(value : Number) : void
{
if (value != _vector.x)
{
_vector.x = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
}
public function get y() : Number
{
return _vector.y;
}
public function set y(value : Number) : void
{
if (value != _vector.y)
{
_vector.y = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
}
public function get z() : Number
{
return _vector.z;
}
public function set z(value : Number) : void
{
if (value != _vector.z)
{
_vector.z = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
}
public function get w() : Number
{
return _vector.w;
}
public function set w(value : Number) : void
{
if (value != _vector.w)
{
_vector.w = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
}
public function get lengthSquared() : Number
{
if (_update & UPDATE_LENGTH_SQ)
{
_update ^= UPDATE_LENGTH_SQ;
_lengthSq = _vector.x * _vector.x + _vector.y * _vector.y
+ _vector.z * _vector.z;
}
return _lengthSq;
}
public function get length() : Number
{
if (_update & UPDATE_LENGTH)
{
_update ^= UPDATE_LENGTH;
_length = Math.sqrt(lengthSquared);
}
return _length;
}
public function get locked() : Boolean
{
return _locked;
}
public function get changed() : Signal
{
return _changed;
}
public function Vector4(x : Number = 0.,
y : Number = 0.,
z : Number = 0.,
w : Number = 1.)
{
_vector.x = x;
_vector.y = y;
_vector.z = z;
_vector.w = w;
_update = UPDATE_ALL;
}
public static function add(u : Vector4,
v : Vector4,
out : Vector4 = null) : Vector4
{
out ||= new Vector4();
out.copyFrom(u);
return out.incrementBy(v);
}
public static function subtract(u : Vector4,
v : Vector4,
out : Vector4 = null) : Vector4
{
out ||= new Vector4();
out.copyFrom(u);
return out.decrementBy(v);
}
public static function dotProduct(u : Vector4, v : Vector4) : Number
{
return u._vector.dotProduct(v._vector);
}
public static function crossProduct(u : Vector4, v : Vector4, out : Vector4 = null) : Vector4
{
out ||= FACTORY.create() as Vector4;
out.set(
u._vector.y * v._vector.z - v._vector.y * u._vector.z,
u._vector.z * v._vector.x - v._vector.z * u._vector.x,
u._vector.x * v._vector.y - v._vector.x * u._vector.y
);
return out;
}
public static function distance(u : Vector4, v : Vector4) : Number
{
return Vector3D.distance(u._vector, v._vector);
}
public function copyFrom(source : Vector4) : Vector4
{
var sourceVector : Vector3D = source._vector;
return set(sourceVector.x, sourceVector.y, sourceVector.z, sourceVector..w);
}
public function incrementBy(vector : Vector4) : Vector4
{
_vector.incrementBy(vector._vector);
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function decrementBy(vector : Vector4) : Vector4
{
_vector.decrementBy(vector._vector);
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function scaleBy(scale : Number) : Vector4
{
_vector.scaleBy(scale);
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function lerp(target : Vector4, ratio : Number) : Vector4
{
if (ratio == 1.)
return copyFrom(target);
if (ratio != 0.)
{
var x : Number = _vector.x;
var y : Number = _vector.y;
var z : Number = _vector.z;
var w : Number = _vector.w;
set(
x + (target._vector.x - x) * ratio,
y + (target._vector.y - y) * ratio,
z + (target._vector.z - z) * ratio,
w + (target._vector.w - w) * ratio
);
}
return this;
}
public function equals(v : Vector4, allFour : Boolean = false, tolerance : Number = 0.) : Boolean
{
return tolerance
? _vector.nearEquals(v._vector, tolerance, allFour)
: _vector.equals(v._vector, allFour);
}
public function project() : Vector4
{
_vector.x /= _vector.w;
_vector.y /= _vector.w;
_vector.z /= _vector.w;
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function normalize() : Vector4
{
var l : Number = length;
if (l != 0.)
{
_vector.x /= l;
_vector.y /= l;
_vector.z /= l;
_length = 1.;
_lengthSq = 1.;
_update = UPDATE_NONE;
_changed.execute(this);
}
return this;
}
public function crossProduct(vector : Vector4) : Vector4
{
var x : Number = _vector.x;
var y : Number = _vector.y;
var z : Number = _vector.z;
_vector.x = y * vector._vector.z - vector._vector.y * z;
_vector.y = z * vector._vector.x - vector._vector.z * x;
_vector.z = x * vector._vector.y - vector._vector.x * y;
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function getVector3D() : Vector3D
{
return _vector.clone();
}
public function set(x : Number,
y : Number,
z : Number,
w : Number = 1.) : Vector4
{
if (x != _vector.x || y != _vector.y || z != _vector.z || w != _vector.w)
{
_vector.setTo(x, y, z);
_vector.w = w;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
return this;
}
public function toString() : String
{
return '(' + _vector.x + ', ' + _vector.y + ', ' + _vector.z + ', ' + _vector.w + ')';
}
public static function scale(v : Vector4, s : Number, out : Vector4 = null) : Vector4
{
out ||= FACTORY.create() as Vector4;
out.set(v._vector.x * s, v._vector.y * s, v._vector.z * s, v._vector.w * s);
return out;
}
public function toVector3D(out : Vector3D = null) : Vector3D
{
if (!out)
return _vector.clone();
out.x = _vector.x;
out.y = _vector.y;
out.z = _vector.z;
out.w = _vector.w;
return out;
}
public function lock() : void
{
_locked = true;
}
public function unlock() : void
{
_locked = false;
_changed.execute(this);
}
public function clone() : Vector4
{
return new Vector4(_vector.x, _vector.y, _vector.z, _vector.w);
}
}
}
|
package aerys.minko.type.math
{
import aerys.minko.ns.minko_math;
import aerys.minko.type.Factory;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.IWatchable;
import flash.geom.Vector3D;
final public class Vector4 implements IWatchable
{
use namespace minko_math;
public static const X_AXIS : Vector4 = new Vector4(1., 0., 0.);
public static const Y_AXIS : Vector4 = new Vector4(0., 1., 0.);
public static const Z_AXIS : Vector4 = new Vector4(0., 0., 1.);
public static const ZERO : Vector4 = new Vector4(0., 0., 0., 0.);
public static const ONE : Vector4 = new Vector4(1., 1., 1., 1.);
public static const FORWARD : Vector4 = Z_AXIS;
public static const BACKWARD : Vector4 = new Vector4(0., 0., -1.);
public static const LEFT : Vector4 = new Vector4(-1, 0., 0.);
public static const RIGHT : Vector4 = new Vector4(1, 0., 0.);
public static const UP : Vector4 = Y_AXIS;
public static const DOWN : Vector4 = new Vector4(0, -1., 0.);
private static const FACTORY : Factory = Factory.getFactory(Vector4);
private static const UPDATE_NONE : uint = 0;
private static const UPDATE_LENGTH : uint = 1;
private static const UPDATE_LENGTH_SQ : uint = 2;
private static const UPDATE_ALL : uint = 3; // UPDATE_LENGTH | UPDATE_LENGTH_SQ;
private static const DATA_DESCRIPTOR : Object = {
'x' : 'x',
'y' : 'y',
'z' : 'z',
'w' : 'w'
};
minko_math var _vector : Vector3D = new Vector3D();
private var _update : uint = 0;
private var _length : Number = 0.;
private var _lengthSq : Number = 0.;
private var _locked : Boolean = false;
private var _changed : Signal = new Signal('Vector4.changed');
public function get x() : Number
{
return _vector.x;
}
public function set x(value : Number) : void
{
if (value != _vector.x)
{
_vector.x = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
}
public function get y() : Number
{
return _vector.y;
}
public function set y(value : Number) : void
{
if (value != _vector.y)
{
_vector.y = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
}
public function get z() : Number
{
return _vector.z;
}
public function set z(value : Number) : void
{
if (value != _vector.z)
{
_vector.z = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
}
public function get w() : Number
{
return _vector.w;
}
public function set w(value : Number) : void
{
if (value != _vector.w)
{
_vector.w = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
}
public function get lengthSquared() : Number
{
if (_update & UPDATE_LENGTH_SQ)
{
_update ^= UPDATE_LENGTH_SQ;
_lengthSq = _vector.x * _vector.x + _vector.y * _vector.y
+ _vector.z * _vector.z;
}
return _lengthSq;
}
public function get length() : Number
{
if (_update & UPDATE_LENGTH)
{
_update ^= UPDATE_LENGTH;
_length = Math.sqrt(lengthSquared);
}
return _length;
}
public function get locked() : Boolean
{
return _locked;
}
public function get changed() : Signal
{
return _changed;
}
public function Vector4(x : Number = 0.,
y : Number = 0.,
z : Number = 0.,
w : Number = 1.)
{
_vector.x = x;
_vector.y = y;
_vector.z = z;
_vector.w = w;
_update = UPDATE_ALL;
}
public static function add(u : Vector4,
v : Vector4,
out : Vector4 = null) : Vector4
{
out ||= new Vector4();
out.copyFrom(u);
return out.incrementBy(v);
}
public static function subtract(u : Vector4,
v : Vector4,
out : Vector4 = null) : Vector4
{
out ||= new Vector4();
out.copyFrom(u);
return out.decrementBy(v);
}
public static function dotProduct(u : Vector4, v : Vector4) : Number
{
return u._vector.dotProduct(v._vector);
}
public static function crossProduct(u : Vector4, v : Vector4, out : Vector4 = null) : Vector4
{
out ||= FACTORY.create() as Vector4;
out.set(
u._vector.y * v._vector.z - v._vector.y * u._vector.z,
u._vector.z * v._vector.x - v._vector.z * u._vector.x,
u._vector.x * v._vector.y - v._vector.x * u._vector.y
);
return out;
}
public static function distance(u : Vector4, v : Vector4) : Number
{
return Vector3D.distance(u._vector, v._vector);
}
public function copyFrom(source : Vector4) : Vector4
{
var sourceVector : Vector3D = source._vector;
return set(sourceVector.x, sourceVector.y, sourceVector.z, sourceVector.w);
}
public function incrementBy(vector : Vector4) : Vector4
{
_vector.incrementBy(vector._vector);
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function decrementBy(vector : Vector4) : Vector4
{
_vector.decrementBy(vector._vector);
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function scaleBy(scale : Number) : Vector4
{
_vector.scaleBy(scale);
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function lerp(target : Vector4, ratio : Number) : Vector4
{
if (ratio == 1.)
return copyFrom(target);
if (ratio != 0.)
{
var x : Number = _vector.x;
var y : Number = _vector.y;
var z : Number = _vector.z;
var w : Number = _vector.w;
set(
x + (target._vector.x - x) * ratio,
y + (target._vector.y - y) * ratio,
z + (target._vector.z - z) * ratio,
w + (target._vector.w - w) * ratio
);
}
return this;
}
public function equals(v : Vector4, allFour : Boolean = false, tolerance : Number = 0.) : Boolean
{
return tolerance
? _vector.nearEquals(v._vector, tolerance, allFour)
: _vector.equals(v._vector, allFour);
}
public function project() : Vector4
{
_vector.x /= _vector.w;
_vector.y /= _vector.w;
_vector.z /= _vector.w;
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function normalize() : Vector4
{
var l : Number = length;
if (l != 0.)
{
_vector.x /= l;
_vector.y /= l;
_vector.z /= l;
_length = 1.;
_lengthSq = 1.;
_update = UPDATE_NONE;
_changed.execute(this);
}
return this;
}
public function crossProduct(vector : Vector4) : Vector4
{
var x : Number = _vector.x;
var y : Number = _vector.y;
var z : Number = _vector.z;
_vector.x = y * vector._vector.z - vector._vector.y * z;
_vector.y = z * vector._vector.x - vector._vector.z * x;
_vector.z = x * vector._vector.y - vector._vector.x * y;
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function getVector3D() : Vector3D
{
return _vector.clone();
}
public function set(x : Number,
y : Number,
z : Number,
w : Number = 1.) : Vector4
{
if (x != _vector.x || y != _vector.y || z != _vector.z || w != _vector.w)
{
_vector.setTo(x, y, z);
_vector.w = w;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
return this;
}
public function toString() : String
{
return '(' + _vector.x + ', ' + _vector.y + ', ' + _vector.z + ', ' + _vector.w + ')';
}
public static function scale(v : Vector4, s : Number, out : Vector4 = null) : Vector4
{
out ||= FACTORY.create() as Vector4;
out.set(v._vector.x * s, v._vector.y * s, v._vector.z * s, v._vector.w * s);
return out;
}
public function toVector3D(out : Vector3D = null) : Vector3D
{
if (!out)
return _vector.clone();
out.x = _vector.x;
out.y = _vector.y;
out.z = _vector.z;
out.w = _vector.w;
return out;
}
public function lock() : void
{
_locked = true;
}
public function unlock() : void
{
_locked = false;
_changed.execute(this);
}
public function clone() : Vector4
{
return new Vector4(_vector.x, _vector.y, _vector.z, _vector.w);
}
}
}
|
fix typo
|
fix typo
|
ActionScript
|
mit
|
aerys/minko-as3
|
aa1e4db6510a9c51b1182c5fe397f3890cb40a30
|
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);
initialize();
}
protected function initialize() : void
{
_started = new Dictionary(true);
}
override protected function targetAddedToSceneHandler(target : ISceneNode,
scene : Scene) : void
{
super.targetAddedToSceneHandler(target, scene);
if (_scene && scene != _scene)
throw new Error(
'The same ScriptController instance can not be used in more than one scene ' +
'at a time.'
);
_scene = scene;
}
override protected function targetRemovedFromSceneHandler(target : ISceneNode,
scene : Scene) : void
{
super.targetRemovedFromSceneHandler(target, scene);
if (getNumTargetsInScene(scene))
_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);
initialize();
}
protected function initialize() : void
{
_started = new Dictionary(true);
}
override protected function targetAddedToSceneHandler(target : ISceneNode,
scene : Scene) : void
{
super.targetAddedToSceneHandler(target, scene);
if (_scene && scene != _scene)
throw new Error(
'The same ScriptController instance can not be used in more than one scene ' +
'at a time.'
);
_scene = scene;
}
override protected function targetRemovedFromSceneHandler(target : ISceneNode,
scene : Scene) : void
{
super.targetRemovedFromSceneHandler(target, scene);
if (getNumTargetsInScene(scene))
_scene = null;
}
override protected function sceneEnterFrameHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
_viewport = viewport;
_deltaTime = time - _lastTime;
_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 ScriptController.deltaTime property
|
fix ScriptController.deltaTime property
|
ActionScript
|
mit
|
aerys/minko-as3
|
7054a20a7a901ee1bf3639343d17db9f34e6694b
|
src/fr/manashield/flex/thex/blocks/BlockGenerator.as
|
src/fr/manashield/flex/thex/blocks/BlockGenerator.as
|
package fr.manashield.flex.thex.blocks {
import fr.manashield.flex.thex.Animation;
import fr.manashield.flex.thex.events.BlockLandingEvent;
import fr.manashield.flex.thex.utils.Color;
import flash.geom.Point;
/**
* @author Morgan Peyre ([email protected])
* @author Paul Bonnet
*/
public class BlockGenerator
{
public static var _instance:BlockGenerator;
/*static*/
{
Animation.instance.addEventListener(BlockLandingEvent.LANDING, BlockGenerator.instance.blockLanded);
}
public static function get instance():BlockGenerator
{
return _instance?_instance:_instance=new BlockGenerator();
}
public function spawnBlock(radius:uint = 7, index:int = undefined, addToFallingList:Boolean = true):Block
{
var cell:HexagonalCell = HexagonalGrid.instance.cell(new Point(0,radius));
// Spawn at specified index if any, coerced to [0..6*radius-1]. Else, spawn at random index
// index = "angular" position on a given hexagonal ring
var spawnIndex:int = index != undefined ? (index<0 ? (6*radius)+index%(6*radius) : index%(6*radius)) : Math.random()*6*radius;
for(var i:int=0; i<spawnIndex; ++i)
{
cell = cell.clockwiseNeighbor;
}
var blockColor:Color;
if(addToFallingList)
{
blockColor = Animation.instance.activeColors()[uint(Math.random()*Animation.instance.activeColors().length)];
}
else
{
blockColor = Color.RANDOM;
}
var newBlock:Block = new Block(cell, blockColor);
Animation.instance.addBlock(newBlock, addToFallingList);
if(!addToFallingList)
{
newBlock.symbol.alpha = Animation.STATIC_BLOCK_ALPHA;
}
return newBlock;
}
public function blockLanded(e:BlockLandingEvent):void
{
this.spawnBlock();
}
}
}
|
package fr.manashield.flex.thex.blocks {
import fr.manashield.flex.thex.Animation;
import fr.manashield.flex.thex.events.BlockLandingEvent;
import fr.manashield.flex.thex.utils.Color;
import flash.geom.Point;
/**
* @author Morgan Peyre ([email protected])
* @author Paul Bonnet
*/
public class BlockGenerator
{
public static var _instance:BlockGenerator;
/*static*/
{
Animation.instance.addEventListener(BlockLandingEvent.LANDING, BlockGenerator.instance.blockLanded);
}
public static function get instance():BlockGenerator
{
return _instance?_instance:_instance=new BlockGenerator();
}
public function spawnBlock(radius:uint = 7, index:int = undefined, addToFallingList:Boolean = true):Block
{
var cell:HexagonalCell = HexagonalGrid.instance.cell(new Point(0,radius));
// Spawn at specified index if any, coerced to [0..6*radius-1]. Else, spawn at random index
// index = "angular" position on a given hexagonal ring
var spawnIndex:int = index != undefined ? (index<0 ? (6*radius)+index%(6*radius) : index%(6*radius)) : Math.random()*6*radius;
for(var i:int=0; i<spawnIndex; ++i)
{
cell = cell.clockwiseNeighbor;
}
var blockColor:Color;
if(addToFallingList)
{
blockColor = Animation.instance.activeColors()[uint(Math.random()*Animation.instance.activeColors().length)];
}
else
{
blockColor = Color.RANDOM;
}
var newBlock:Block = new Block(cell, blockColor);
Animation.instance.addBlock(newBlock, addToFallingList);
return newBlock;
}
public function blockLanded(e:BlockLandingEvent):void
{
this.spawnBlock();
}
}
}
|
fix : removed fading effect on static blocks
|
fix : removed fading effect on static blocks
|
ActionScript
|
apache-2.0
|
peyremorgan/thex
|
53569575bd2099c20f7a46f52eb1cd1b765e2ea1
|
src/aerys/minko/scene/controller/mesh/skinning/SkinningController.as
|
src/aerys/minko/scene/controller/mesh/skinning/SkinningController.as
|
package aerys.minko.scene.controller.mesh.skinning
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.Viewport;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.controller.EnterFrameController;
import aerys.minko.scene.controller.IRebindableController;
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.type.animation.SkinningMethod;
import aerys.minko.type.math.Matrix4x4;
import flash.display.BitmapData;
import flash.geom.Matrix3D;
import flash.utils.Dictionary;
public class SkinningController extends EnterFrameController implements IRebindableController
{
private var _skinningHelper : AbstractSkinningHelper;
private var _isDirty : Boolean;
private var _method : uint;
private var _bindShape : Matrix3D;
private var _skeletonRoot : Group;
private var _joints : Vector.<Group>;
private var _invBindMatrices : Vector.<Matrix3D>;
public function get skinningMethod() : uint
{
return _method;
}
public function get bindShape() : Matrix4x4
{
var bindShape : Matrix4x4 = new Matrix4x4();
bindShape.minko_math::_matrix = _bindShape;
return bindShape;
}
public function get skeletonRoot() : Group
{
return _skeletonRoot;
}
public function get joints() : Vector.<Group>
{
return _joints;
}
public function get invBindMatrices() : Vector.<Matrix4x4>
{
var numMatrices : uint = _invBindMatrices.length;
var invBindMatrices : Vector.<Matrix4x4> = new Vector.<Matrix4x4>(numMatrices);
for (var matrixId : uint = 0; matrixId < numMatrices; ++matrixId)
{
invBindMatrices[matrixId] = new Matrix4x4();
invBindMatrices[matrixId].minko_math::_matrix = _invBindMatrices[matrixId];
}
return invBindMatrices;
}
public function SkinningController(method : uint,
skeletonRoot : Group,
joints : Vector.<Group>,
bindShape : Matrix4x4,
invBindMatrices : Vector.<Matrix4x4>)
{
super(Mesh);
var numJoints : uint = joints.length;
_method = method;
_skeletonRoot = skeletonRoot;
_joints = joints.slice();
_bindShape = bindShape.minko_math::_matrix;
_invBindMatrices = new Vector.<Matrix3D>(numJoints, true);
_isDirty = false;
for (var jointId : uint = 0; jointId < numJoints; ++jointId)
_invBindMatrices[jointId] = invBindMatrices[jointId].minko_math::_matrix;
init();
}
private function init() : void
{
if (skinningMethod == SkinningMethod.SOFTWARE_MATRIX)
_skinningHelper = new SoftwareSkinningHelper(_method, _bindShape, _invBindMatrices);
else
_skinningHelper = new ShaderSkinningHelper(_method, _bindShape, _invBindMatrices);
}
override protected function targetAddedHandler(ctrl : EnterFrameController,
target : ISceneNode) : void
{
super.targetAddedHandler(ctrl, target);
if (numTargets == 1)
subscribeToJoints();
_isDirty = true;
_skinningHelper.addMesh(target as Mesh);
}
override protected function targetRemovedHandler(ctrl : EnterFrameController,
target : ISceneNode) : void
{
super.targetRemovedHandler(ctrl, target);
if (numTargets == 0)
unsubscribeFromJoints();
_skinningHelper.removeMesh(target as Mesh);
}
private function jointLocalToWorldChangedHandler(emitter : Matrix4x4) : void
{
_isDirty = true;
}
public function rebindDependencies(nodeMap : Dictionary,
controllerMap : Dictionary) : void
{
var numJoints : uint = _joints.length;
if (numTargets != 0)
unsubscribeFromJoints();
if (_joints.indexOf(_skeletonRoot) == -1 && nodeMap[_skeletonRoot])
_skeletonRoot = nodeMap[_skeletonRoot];
for (var jointId : uint = 0; jointId < numJoints; ++jointId)
if (nodeMap[_joints[jointId]])
_joints[jointId] = nodeMap[_joints[jointId]];
if (numTargets != 0)
subscribeToJoints();
_isDirty = true;
}
private function subscribeToJoints() : void
{
var numJoints : uint = _joints.length;
for (var jointId : uint = 0; jointId < numJoints; ++jointId)
_joints[jointId].localToWorld.changed.add(jointLocalToWorldChangedHandler);
if (_joints.indexOf(_skeletonRoot) == -1)
_skeletonRoot.localToWorld.changed.add(jointLocalToWorldChangedHandler);
}
private function unsubscribeFromJoints() : void
{
var numJoints : uint = _joints.length;
for (var jointId : uint = 0; jointId < numJoints; ++jointId)
_joints[jointId].localToWorld.changed.remove(jointLocalToWorldChangedHandler);
if (_joints.indexOf(_skeletonRoot) == -1)
_skeletonRoot.localToWorld.changed.remove(jointLocalToWorldChangedHandler);
}
override protected function sceneEnterFrameHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
if (_isDirty)
{
_skinningHelper.update(_skeletonRoot, _joints);
_isDirty = false;
}
}
override public function clone() : AbstractController
{
return new SkinningController(_method, _skeletonRoot, _joints, bindShape, invBindMatrices);
}
}
}
|
package aerys.minko.scene.controller.mesh.skinning
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.Viewport;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.controller.EnterFrameController;
import aerys.minko.scene.controller.IRebindableController;
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.type.animation.SkinningMethod;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.math.Matrix4x4;
import flash.display.BitmapData;
import flash.geom.Matrix3D;
import flash.utils.Dictionary;
public final class SkinningController extends EnterFrameController implements IRebindableController
{
private var _skinningHelper : AbstractSkinningHelper;
private var _isDirty : Boolean;
private var _method : uint;
private var _bindShapeMatrix : Matrix3D;
private var _skeletonRoot : Group;
private var _joints : Vector.<Group>;
private var _invBindMatrices : Vector.<Matrix3D>;
private var _numVisibleTargets : uint;
public function get skinningMethod() : uint
{
return _method;
}
public function get bindShape() : Matrix4x4
{
var bindShape : Matrix4x4 = new Matrix4x4();
bindShape.minko_math::_matrix = _bindShapeMatrix;
return bindShape;
}
public function get skeletonRoot() : Group
{
return _skeletonRoot;
}
public function get joints() : Vector.<Group>
{
return _joints;
}
public function get invBindMatrices() : Vector.<Matrix4x4>
{
var numMatrices : uint = _invBindMatrices.length;
var invBindMatrices : Vector.<Matrix4x4> = new Vector.<Matrix4x4>(numMatrices);
for (var matrixId : uint = 0; matrixId < numMatrices; ++matrixId)
{
invBindMatrices[matrixId] = new Matrix4x4();
invBindMatrices[matrixId].minko_math::_matrix = _invBindMatrices[matrixId];
}
return invBindMatrices;
}
public function SkinningController(method : uint,
skeletonRoot : Group,
joints : Vector.<Group>,
bindShape : Matrix4x4,
invBindMatrices : Vector.<Matrix4x4>)
{
super(Mesh);
_method = method;
_skeletonRoot = skeletonRoot;
_bindShapeMatrix = bindShape.minko_math::_matrix;
_isDirty = false;
initialize(joints, invBindMatrices);
}
private function initialize(joints : Vector.<Group>,
invBindMatrices : Vector.<Matrix4x4>) : void
{
var numJoints : uint = joints.length;
_joints = joints.slice();
_invBindMatrices = new Vector.<Matrix3D>(numJoints, true);
for (var jointId : uint = 0; jointId < numJoints; ++jointId)
_invBindMatrices[jointId] = invBindMatrices[jointId].minko_math::_matrix;
if (skinningMethod == SkinningMethod.SOFTWARE_MATRIX)
_skinningHelper = new SoftwareSkinningHelper(_method, _bindShapeMatrix, _invBindMatrices);
else
_skinningHelper = new ShaderSkinningHelper(_method, _bindShapeMatrix, _invBindMatrices);
}
override protected function targetAddedToSceneHandler(target : ISceneNode,
scene : Scene) : void
{
super.targetAddedToSceneHandler(target, scene);
if (numTargetsInScene == 1)
subscribeToJoints();
var mesh : Mesh = target as Mesh;
mesh.bindings.addCallback('inFrustum', meshVisibilityChangedHandler);
_skinningHelper.addMesh(mesh);
_isDirty = true;
}
override protected function targetRemovedFromSceneHandler(target : ISceneNode,
scene : Scene) : void
{
super.targetRemovedFromSceneHandler(target, scene);
if (numTargets == 0)
unsubscribeFromJoints();
var mesh : Mesh = target as Mesh;
mesh.bindings.removeCallback('inFrustum', meshVisibilityChangedHandler);
_skinningHelper.removeMesh(mesh);
}
private function jointLocalToWorldChangedHandler(emitter : Matrix4x4) : void
{
_isDirty = true;
}
public function rebindDependencies(nodeMap : Dictionary,
controllerMap : Dictionary) : void
{
var numJoints : uint = _joints.length;
if (numTargets != 0)
unsubscribeFromJoints();
if (_joints.indexOf(_skeletonRoot) == -1 && nodeMap[_skeletonRoot])
_skeletonRoot = nodeMap[_skeletonRoot];
for (var jointId : uint = 0; jointId < numJoints; ++jointId)
if (nodeMap[_joints[jointId]])
_joints[jointId] = nodeMap[_joints[jointId]];
if (numTargets != 0)
subscribeToJoints();
_isDirty = true;
}
private function subscribeToJoints() : void
{
var numJoints : uint = _joints.length;
for (var jointId : uint = 0; jointId < numJoints; ++jointId)
_joints[jointId].localToWorld.changed.add(jointLocalToWorldChangedHandler);
if (_joints.indexOf(_skeletonRoot) == -1)
_skeletonRoot.localToWorld.changed.add(jointLocalToWorldChangedHandler);
}
private function unsubscribeFromJoints() : void
{
var numJoints : uint = _joints.length;
for (var jointId : uint = 0; jointId < numJoints; ++jointId)
_joints[jointId].localToWorld.changed.remove(jointLocalToWorldChangedHandler);
if (_joints.indexOf(_skeletonRoot) == -1)
_skeletonRoot.localToWorld.changed.remove(jointLocalToWorldChangedHandler);
}
override protected function sceneEnterFrameHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
if (_isDirty && _skinningHelper.numMeshes != 0)
{
_skinningHelper.update(_skeletonRoot, _joints);
_isDirty = false;
}
}
override public function clone() : AbstractController
{
return new SkinningController(_method, _skeletonRoot, _joints, bindShape, invBindMatrices);
}
private function meshVisibilityChangedHandler(bindings : DataBindings,
property : String,
oldValue : Boolean,
newValue : Boolean) : void
{
if (newValue)
_skinningHelper.addMesh(bindings.owner as Mesh);
else
_skinningHelper.removeMesh(bindings.owner as Mesh);
}
}
}
|
update SkinningController to avoid any computation when there is no target in the scene/frustum
|
update SkinningController to avoid any computation when there is no target in the scene/frustum
|
ActionScript
|
mit
|
aerys/minko-as3
|
ab3a320ba2a4fce0ebe968b8712ef81a6b19ee25
|
frameworks/as/src/org/apache/flex/html/staticControls/beads/CSSTextButtonBead.as
|
frameworks/as/src/org/apache/flex/html/staticControls/beads/CSSTextButtonBead.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.staticControls.beads
{
import flash.display.Loader;
import flash.display.Shape;
import flash.display.SimpleButton;
import flash.display.Sprite;
import flash.events.Event;
import flash.net.URLRequest;
import flash.text.TextField;
import flash.text.TextFieldType;
import org.apache.flex.core.CSSTextField;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.ITextModel;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.utils.SolidBorderUtil;
public class CSSTextButtonBead implements ITextButtonBead
{
public function CSSTextButtonBead()
{
upSprite = new Sprite();
downSprite = new Sprite();
overSprite = new Sprite();
upTextField = new CSSTextField();
downTextField = new CSSTextField();
overTextField = new CSSTextField();
upTextField.selectable = false;
upTextField.type = TextFieldType.DYNAMIC;
downTextField.selectable = false;
downTextField.type = TextFieldType.DYNAMIC;
overTextField.selectable = false;
overTextField.type = TextFieldType.DYNAMIC;
upTextField.autoSize = "left";
downTextField.autoSize = "left";
overTextField.autoSize = "left";
upSprite.addChild(upTextField);
downSprite.addChild(downTextField);
overSprite.addChild(overTextField);
}
private var textModel:ITextModel;
private var _strand:IStrand;
private var shape:Shape;
public function set strand(value:IStrand):void
{
_strand = value;
textModel = value.getBeadByType(ITextModel) as ITextModel;
textModel.addEventListener("textChange", textChangeHandler);
textModel.addEventListener("htmlChange", htmlChangeHandler);
shape = new Shape();
shape.graphics.beginFill(0xCCCCCC);
shape.graphics.drawRect(0, 0, 10, 10);
shape.graphics.endFill();
SimpleButton(value).upState = upSprite;
SimpleButton(value).downState = downSprite;
SimpleButton(value).overState = overSprite;
SimpleButton(value).hitTestState = shape;
if (textModel.text !== null)
text = textModel.text;
if (textModel.html !== null)
html = textModel.html;
setupSkin(overSprite, overTextField, "hover");
setupSkin(downSprite, downTextField, "active");
setupSkin(upSprite, upTextField);
}
private function setupSkin(sprite:Sprite, textField:TextField, state:String = null):void
{
var backgroundImage:Object = ValuesManager.valuesImpl.getValue(_strand, "backgroundImage", state);
if (backgroundImage)
{
var loader:Loader = new Loader();
sprite.addChildAt(loader, 0);
loader.load(new URLRequest(backgroundImage as String));
loader.contentLoaderInfo.addEventListener(flash.events.Event.COMPLETE, function (e:flash.events.Event):void {
textField.y = (sprite.height - textField.height) / 2;
textField.x = (sprite.width - textField.width) / 2;
updateHitArea();
});
}
else
{
var borderColor:uint;
var borderThickness:uint;
var borderStyle:String;
var borderStyles:Object = ValuesManager.valuesImpl.getValue(_strand, "border", state);
if (borderStyles is Array)
{
borderColor = borderStyles[2];
borderStyle = borderStyles[1];
borderThickness = borderStyles[0];
}
var padding:Object = ValuesManager.valuesImpl.getValue(_strand, "padding", state);
var backgroundColor:Object = ValuesManager.valuesImpl.getValue(_strand, "backgroundColor", state);
SolidBorderUtil.drawBorder(sprite.graphics,
0, 0, textField.textWidth + Number(padding) * 2, textField.textHeight + Number(padding) * 2,
borderColor, backgroundColor, borderThickness);
textField.y = (sprite.height - textField.height) / 2;
textField.x = (sprite.width - textField.width) / 2;
}
}
private function textChangeHandler(event:org.apache.flex.events.Event):void
{
text = textModel.text;
}
private function htmlChangeHandler(event:org.apache.flex.events.Event):void
{
html = textModel.html;
}
private var upTextField:CSSTextField;
private var downTextField:CSSTextField;
private var overTextField:CSSTextField;
private var upSprite:Sprite;
private var downSprite:Sprite;
private var overSprite:Sprite;
public function get text():String
{
return upTextField.text;
}
public function set text(value:String):void
{
upTextField.text = value;
downTextField.text = value;
overTextField.text = value;
updateHitArea();
}
private function updateHitArea():void
{
shape.graphics.clear();
shape.graphics.beginFill(0xCCCCCC);
shape.graphics.drawRect(0, 0, upSprite.width, upSprite.height);
shape.graphics.endFill();
}
public function get html():String
{
return upTextField.htmlText;
}
public function set html(value:String):void
{
upTextField.htmlText = value;
downTextField.htmlText = value;
overTextField.htmlText = value;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.staticControls.beads
{
import flash.display.Loader;
import flash.display.Shape;
import flash.display.SimpleButton;
import flash.display.Sprite;
import flash.events.Event;
import flash.net.URLRequest;
import flash.text.TextField;
import flash.text.TextFieldType;
import org.apache.flex.core.CSSTextField;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.ITextModel;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.utils.SolidBorderUtil;
public class CSSTextButtonBead implements ITextButtonBead
{
public function CSSTextButtonBead()
{
upSprite = new Sprite();
downSprite = new Sprite();
overSprite = new Sprite();
upTextField = new CSSTextField();
downTextField = new CSSTextField();
overTextField = new CSSTextField();
upTextField.selectable = false;
upTextField.type = TextFieldType.DYNAMIC;
downTextField.selectable = false;
downTextField.type = TextFieldType.DYNAMIC;
overTextField.selectable = false;
overTextField.type = TextFieldType.DYNAMIC;
upTextField.autoSize = "left";
downTextField.autoSize = "left";
overTextField.autoSize = "left";
upSprite.addChild(upTextField);
downSprite.addChild(downTextField);
overSprite.addChild(overTextField);
}
private var textModel:ITextModel;
private var _strand:IStrand;
private var shape:Shape;
public function set strand(value:IStrand):void
{
_strand = value;
textModel = value.getBeadByType(ITextModel) as ITextModel;
textModel.addEventListener("textChange", textChangeHandler);
textModel.addEventListener("htmlChange", htmlChangeHandler);
shape = new Shape();
shape.graphics.beginFill(0xCCCCCC);
shape.graphics.drawRect(0, 0, 10, 10);
shape.graphics.endFill();
SimpleButton(value).upState = upSprite;
SimpleButton(value).downState = downSprite;
SimpleButton(value).overState = overSprite;
SimpleButton(value).hitTestState = shape;
if (textModel.text !== null)
text = textModel.text;
if (textModel.html !== null)
html = textModel.html;
setupSkin(overSprite, overTextField, "hover");
setupSkin(downSprite, downTextField, "active");
setupSkin(upSprite, upTextField);
}
private function setupSkin(sprite:Sprite, textField:TextField, state:String = null):void
{
var borderColor:uint;
var borderThickness:uint;
var borderStyle:String;
var borderStyles:Object = ValuesManager.valuesImpl.getValue(_strand, "border", state);
if (borderStyles is Array)
{
borderColor = borderStyles[2];
borderStyle = borderStyles[1];
borderThickness = borderStyles[0];
}
var value:Object = ValuesManager.valuesImpl.getValue(_strand, "border-style", state);
if (value != null)
borderStyle = value as String;
value = ValuesManager.valuesImpl.getValue(_strand, "border-color", state);
if (value != null)
borderColor = value as uint;
value = ValuesManager.valuesImpl.getValue(_strand, "border-thickness", state);
if (value != null)
borderThickness = value as uint;
var padding:Object = ValuesManager.valuesImpl.getValue(_strand, "padding", state);
var backgroundColor:Object = ValuesManager.valuesImpl.getValue(_strand, "backgroundColor", state);
if (borderStyle == "solid")
{
SolidBorderUtil.drawBorder(sprite.graphics,
0, 0, textField.textWidth + Number(padding) * 2, textField.textHeight + Number(padding) * 2,
borderColor, backgroundColor, borderThickness);
textField.y = (sprite.height - textField.height) / 2;
textField.x = (sprite.width - textField.width) / 2;
}
var backgroundImage:Object = ValuesManager.valuesImpl.getValue(_strand, "backgroundImage", state);
if (backgroundImage)
{
var loader:Loader = new Loader();
sprite.addChildAt(loader, 0);
var url:String = backgroundImage as String;
loader.load(new URLRequest(url));
loader.contentLoaderInfo.addEventListener(flash.events.Event.COMPLETE, function (e:flash.events.Event):void {
textField.y = (sprite.height - textField.height) / 2;
textField.x = (sprite.width - textField.width) / 2;
updateHitArea();
});
}
}
private function textChangeHandler(event:org.apache.flex.events.Event):void
{
text = textModel.text;
}
private function htmlChangeHandler(event:org.apache.flex.events.Event):void
{
html = textModel.html;
}
private var upTextField:CSSTextField;
private var downTextField:CSSTextField;
private var overTextField:CSSTextField;
private var upSprite:Sprite;
private var downSprite:Sprite;
private var overSprite:Sprite;
public function get text():String
{
return upTextField.text;
}
public function set text(value:String):void
{
upTextField.text = value;
downTextField.text = value;
overTextField.text = value;
updateHitArea();
}
private function updateHitArea():void
{
shape.graphics.clear();
shape.graphics.beginFill(0xCCCCCC);
shape.graphics.drawRect(0, 0, upSprite.width, upSprite.height);
shape.graphics.endFill();
}
public function get html():String
{
return upTextField.htmlText;
}
public function set html(value:String):void
{
upTextField.htmlText = value;
downTextField.htmlText = value;
overTextField.htmlText = value;
}
}
}
|
support png/gif/jpg skinning of a buton
|
support png/gif/jpg skinning of a buton
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
22cf44dc25905141a11911e80e62db8937d4e9e2
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/TextFieldViewBase.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/TextFieldViewBase.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.display.DisplayObjectContainer;
import org.apache.flex.core.CSSTextField;
import org.apache.flex.core.IBeadView;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.ITextModel;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.UIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
/**
* The TextFieldViewBase class is the base class for
* the components that display text.
* It displays text using a TextField, so there is no
* right-to-left text support in this view.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class TextFieldViewBase implements IBeadView, ITextFieldView
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function TextFieldViewBase()
{
_textField = new CSSTextField();
}
private var _textField:CSSTextField;
/**
* @copy org.apache.flex.core.ITextModel#textField
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get textField() : CSSTextField
{
return _textField;
}
private var _textModel:ITextModel;
protected var _strand:IStrand;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
_strand = value;
_textModel = value.getBeadByType(ITextModel) as ITextModel;
_textModel.addEventListener("textChange", textChangeHandler);
_textModel.addEventListener("htmlChange", htmlChangeHandler);
IEventDispatcher(_strand).addEventListener("widthChanged", widthChangeHandler);
IEventDispatcher(_strand).addEventListener("heightChanged", heightChangeHandler);
DisplayObjectContainer(value).addChild(_textField);
if (_textModel.text !== null)
text = _textModel.text;
if (_textModel.html !== null)
html = _textModel.html;
}
/**
* @private
*/
public function get host() : IUIBase
{
return _strand as IUIBase;
}
/**
* @copy org.apache.flex.core.ITextModel#text
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get text():String
{
return _textField.text;
}
/**
* @private
*/
public function set text(value:String):void
{
if (value == null)
value = "";
_textField.text = value;
autoSizeIfNeeded();
}
private function autoSizeIfNeeded():void
{
var host:UIBase = UIBase(_strand);
if (autoHeight)
{
if (textField.height != textField.textHeight + 4)
{
textField.height = textField.textHeight + 4;
inHeightChange = true;
host.dispatchEvent(new Event("heightChanged"));
inHeightChange = false;
}
}
if (autoWidth)
{
if (textField.width != textField.textWidth + 4)
{
textField.width = textField.textWidth + 4;
inWidthChange = true;
host.dispatchEvent(new Event("widthChanged"));
inWidthChange = false;
}
}
}
/**
* @copy org.apache.flex.core.ITextModel#html
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get html():String
{
return _textField.htmlText;
}
/**
* @private
*/
public function set html(value:String):void
{
_textField.htmlText = value;
autoSizeIfNeeded();
}
private function textChangeHandler(event:Event):void
{
text = _textModel.text;
}
private function htmlChangeHandler(event:Event):void
{
html = _textModel.html;
}
private var autoHeight:Boolean = true;
private var autoWidth:Boolean = true;
private var inHeightChange:Boolean = false;
private var inWidthChange:Boolean = false;
private function widthChangeHandler(event:Event):void
{
if (!inWidthChange)
{
textField.autoSize = "none";
autoWidth = false;
textField.width = DisplayObject(_strand).width;
if (autoHeight)
autoSizeIfNeeded()
else
textField.height = DisplayObject(_strand).height;
}
}
private function heightChangeHandler(event:Event):void
{
if (!inHeightChange)
{
textField.autoSize = "none";
autoHeight = false;
textField.height = DisplayObject(_strand).height;
if (autoWidth)
autoSizeIfNeeded();
else
textField.width = DisplayObject(_strand).width;
}
}
/**
* @copy org.apache.flex.core.IBeadView#viewHeight
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get viewHeight():Number
{
// textfields with autosize collapse if no text
if (_textField.text == "" && _textField.autoSize != "none")
return ValuesManager.valuesImpl.getValue(_strand, "fontSize") + 4;
return _textField.height;
}
/**
* @copy org.apache.flex.core.IBeadView#viewWidth
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get viewWidth():Number
{
// textfields with autosize collapse if no text
if (_textField.text == "" && _textField.autoSize != "none")
return 0;
return _textField.width;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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.display.DisplayObjectContainer;
import org.apache.flex.core.CSSTextField;
import org.apache.flex.core.IBeadView;
import org.apache.flex.core.ILayoutChild;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.ITextModel;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.UIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
/**
* The TextFieldViewBase class is the base class for
* the components that display text.
* It displays text using a TextField, so there is no
* right-to-left text support in this view.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class TextFieldViewBase implements IBeadView, ITextFieldView
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function TextFieldViewBase()
{
_textField = new CSSTextField();
}
private var _textField:CSSTextField;
/**
* @copy org.apache.flex.core.ITextModel#textField
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get textField() : CSSTextField
{
return _textField;
}
private var _textModel:ITextModel;
protected var _strand:IStrand;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
_strand = value;
_textModel = value.getBeadByType(ITextModel) as ITextModel;
_textModel.addEventListener("textChange", textChangeHandler);
_textModel.addEventListener("htmlChange", htmlChangeHandler);
IEventDispatcher(_strand).addEventListener("widthChanged", widthChangeHandler);
IEventDispatcher(_strand).addEventListener("heightChanged", heightChangeHandler);
IEventDispatcher(_strand).addEventListener("sizeChanged", sizeChangeHandler);
DisplayObjectContainer(value).addChild(_textField);
if (_textModel.text !== null)
text = _textModel.text;
if (_textModel.html !== null)
html = _textModel.html;
var ilc:ILayoutChild = host as ILayoutChild;
autoHeight = ilc.isHeightSizedToContent();
autoWidth = ilc.isWidthSizedToContent();
}
/**
* @private
*/
public function get host() : IUIBase
{
return _strand as IUIBase;
}
/**
* @copy org.apache.flex.core.ITextModel#text
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get text():String
{
return _textField.text;
}
/**
* @private
*/
public function set text(value:String):void
{
if (value == null)
value = "";
_textField.text = value;
autoSizeIfNeeded();
}
private function autoSizeIfNeeded():void
{
var host:UIBase = UIBase(_strand);
if (autoHeight)
{
if (textField.height != textField.textHeight + 4)
{
textField.height = textField.textHeight + 4;
inHeightChange = true;
host.dispatchEvent(new Event("heightChanged"));
inHeightChange = false;
}
}
if (autoWidth)
{
if (textField.width != textField.textWidth + 4)
{
textField.width = textField.textWidth + 4;
inWidthChange = true;
host.dispatchEvent(new Event("widthChanged"));
inWidthChange = false;
}
}
}
/**
* @copy org.apache.flex.core.ITextModel#html
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get html():String
{
return _textField.htmlText;
}
/**
* @private
*/
public function set html(value:String):void
{
_textField.htmlText = value;
autoSizeIfNeeded();
}
private function textChangeHandler(event:Event):void
{
text = _textModel.text;
}
private function htmlChangeHandler(event:Event):void
{
html = _textModel.html;
}
private var autoHeight:Boolean;
private var autoWidth:Boolean;
private var inHeightChange:Boolean = false;
private var inWidthChange:Boolean = false;
private function widthChangeHandler(event:Event):void
{
if (!inWidthChange)
{
textField.autoSize = "none";
autoWidth = false;
textField.width = DisplayObject(_strand).width;
if (autoHeight)
autoSizeIfNeeded()
else
textField.height = DisplayObject(_strand).height;
}
}
private function heightChangeHandler(event:Event):void
{
if (!inHeightChange)
{
textField.autoSize = "none";
autoHeight = false;
textField.height = DisplayObject(_strand).height;
if (autoWidth)
autoSizeIfNeeded();
else
textField.width = DisplayObject(_strand).width;
}
}
private function sizeChangeHandler(event:Event):void
{
var ilc:ILayoutChild = host as ILayoutChild;
autoHeight = ilc.isHeightSizedToContent();
if (!autoHeight)
{
textField.autoSize = "none";
textField.height = DisplayObject(_strand).height;
}
autoWidth = ilc.isWidthSizedToContent();
if (!autoWidth)
{
textField.autoSize = "none";
textField.width = DisplayObject(_strand).width;
}
}
/**
* @copy org.apache.flex.core.IBeadView#viewHeight
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get viewHeight():Number
{
// textfields with autosize collapse if no text
if (_textField.text == "" && _textField.autoSize != "none")
return ValuesManager.valuesImpl.getValue(_strand, "fontSize") + 4;
return _textField.height;
}
/**
* @copy org.apache.flex.core.IBeadView#viewWidth
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get viewWidth():Number
{
// textfields with autosize collapse if no text
if (_textField.text == "" && _textField.autoSize != "none")
return 0;
return _textField.width;
}
}
}
|
fix autosizing
|
fix autosizing
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
45c46b8dab5815f72e7ffddcd093e9bf8477e16f
|
plugins/listPlugin/src/listPluginCode.as
|
plugins/listPlugin/src/listPluginCode.as
|
/**
* KListPlugin
*
* @langversion 3.0
* @playerversion Flash 9.0.28.0
* @author Dan Bacon / www.baconoppenheim.com
*/
package
{
import com.kaltura.kdpfl.plugin.IPlugin;
import com.kaltura.kdpfl.plugin.component.IDataProvider;
import com.kaltura.kdpfl.plugin.component.KList;
import com.kaltura.kdpfl.plugin.component.KListItem;
import fl.core.UIComponent;
import fl.data.DataProvider;
import flash.events.Event;
import flash.events.MouseEvent;
import org.puremvc.as3.interfaces.IFacade;
public class listPluginCode extends UIComponent implements IPlugin
{
private var _facade:IFacade;
private var _klist:KList;
private var _dataProvider:IDataProvider;
private var _itemRendererId:String;
public var rowHeight:Number = 80;
public var listDisabledAlpha:Number = 0.3;
public var excludeFromDisableGUI:Boolean = true;
/**
* by fixing hard-coded styles we broke backward compatibility, so if we are using old templates we will
* ignore the styleName
*/
public var supportNewStyle:Boolean = false;
private var _styleName:String;
/**
* should the scrollbar be on the left side
*/
public var useLeftScrollbar:Boolean = false;
/**
* Constructor
*
*/
public function listPluginCode()
{
_klist = new KList();
_klist.addEventListener( MouseEvent.CLICK , onListItemClick, false, 0, true );
this.addEventListener( MouseEvent.CLICK , onListPluginClick, false, 0, true );
_klist.addEventListener( Event.CHANGE, onListChange, false, 0, true );
_klist.addEventListener( Event.ADDED_TO_STAGE , resizeKdp );
addChild( _klist );
}
public function setSkin( styleName:String, setSkinSize:Boolean=false ):void
{
_styleName = styleName;
_klist.setSkin( styleName, setSkinSize );
}
/**
*
* @param facade
*
*/
public function initializePlugin( facade:IFacade ):void
{
_facade = facade;
if (supportNewStyle && _styleName)
KListItem.stylName = _styleName;
_klist.setStyle('cellRenderer', KListItem );
_klist.rowHeight = rowHeight;
_klist.setDisabledAlpha(listDisabledAlpha);
// TODO error handling
var buildLayout:Function = facade.retrieveProxy("layoutProxy")["buildLayout"];
var kml:XML = facade.retrieveProxy("layoutProxy")["vo"]["layoutXML"];
var itemLayout:XML = kml.descendants().renderer.(@id == this.itemRenderer)[0];
itemLayout = itemLayout.children()[0];
_klist.itemContentFactory = buildLayout;
_klist.itemContentLayout = itemLayout;
_klist.leftScrollBar = useLeftScrollbar;
resizeKdp();
}
public function onListChange( evt:Event ):void
{
_dataProvider.selectedIndex = _klist.selectedIndex;
_klist.scrollToSelected();
}
public function onListItemClick( evt:MouseEvent ):void
{
}
private function onListPluginClick (evt : MouseEvent ) : void
{
}
public function set itemRenderer( value:String ):void
{
_itemRendererId = value;
}
public function get itemRenderer():String
{
return( _itemRendererId )
}
[Bindable]
public function set dataProvider( data:DataProvider ):void
{
if( data )
{
_dataProvider = data as IDataProvider;
_dataProvider.addEventListener( Event.CHANGE, onDataProviderItemChange, false, 0, true );
_klist.dataProvider = data;
}
}
public function onDataProviderItemChange( evt:Event = null ):void
{
if(_dataProvider&&_dataProvider.selectedIndex<_klist.length){
_klist.selectedIndex = _dataProvider.selectedIndex;
_klist.scrollToIndex(_dataProvider.selectedIndex);
}
}
public function get dataProvider():DataProvider
{
return _klist.dataProvider;
}
override public function set width( value:Number ):void
{
_klist.width = super.width = value;
}
override public function set height( value:Number ):void
{
_klist.height = super.height = value;
}
override public function toString():String
{
return( "ListPlugin" );
}
/**
* Hack...fix the bug of sizing...
* @param event
*
*/
private function resizeKdp( event : Event = null ) : void
{
if(_facade)
_facade.retrieveMediator("stageMediator")["onResize"]();
}
override public function set enabled(value:Boolean):void
{
_klist.enabled = value;
}
}
}
|
/**
* KListPlugin
*
* @langversion 3.0
* @playerversion Flash 9.0.28.0
* @author Dan Bacon / www.baconoppenheim.com
*/
package
{
import com.kaltura.kdpfl.plugin.IPlugin;
import com.kaltura.kdpfl.plugin.component.IDataProvider;
import com.kaltura.kdpfl.plugin.component.KList;
import com.kaltura.kdpfl.plugin.component.KListItem;
import fl.core.UIComponent;
import fl.data.DataProvider;
import flash.events.Event;
import flash.events.MouseEvent;
import org.puremvc.as3.interfaces.IFacade;
public class listPluginCode extends UIComponent implements IPlugin
{
private var _facade:IFacade;
private var _klist:KList;
private var _dataProvider:IDataProvider;
private var _itemRendererId:String;
public var rowHeight:Number = 80;
public var listDisabledAlpha:Number = 0.3;
public var excludeFromDisableGUI:Boolean = true;
/**
* by fixing hard-coded styles we broke backward compatibility, so if we are using old templates we will
* ignore the styleName
*/
public var supportNewStyle:Boolean = false;
private var _styleName:String;
/**
* should the scrollbar be on the left side
*/
public var useLeftScrollbar:Boolean = false;
/**
* Constructor
*
*/
public function listPluginCode()
{
_klist = new KList();
_klist.addEventListener( MouseEvent.CLICK , onListItemClick, false, 0, true );
this.addEventListener( MouseEvent.CLICK , onListPluginClick, false, 0, true );
_klist.addEventListener( Event.CHANGE, onListChange, false, 0, true );
_klist.addEventListener( Event.ADDED_TO_STAGE , resizeKdp );
addChild( _klist );
}
public function setSkin( styleName:String, setSkinSize:Boolean=false ):void
{
_styleName = styleName;
_klist.setSkin( styleName, setSkinSize );
}
/**
*
* @param facade
*
*/
public function initializePlugin( facade:IFacade ):void
{
_facade = facade;
if (supportNewStyle && _styleName)
KListItem.stylName = _styleName;
_klist.setStyle('cellRenderer', KListItem );
_klist.rowHeight = rowHeight;
_klist.setDisabledAlpha(listDisabledAlpha);
// TODO error handling
var buildLayout:Function = facade.retrieveProxy("layoutProxy")["buildLayout"];
var kml:XML = facade.retrieveProxy("layoutProxy")["vo"]["layoutXML"];
var itemLayout:XML = kml.descendants().renderer.(@id == this.itemRenderer)[0];
itemLayout = itemLayout.children()[0];
_klist.itemContentFactory = buildLayout;
_klist.itemContentLayout = itemLayout;
_klist.leftScrollBar = useLeftScrollbar;
resizeKdp();
}
public function onListChange( evt:Event ):void
{
_dataProvider.selectedIndex = _klist.selectedIndex;
_klist.scrollToSelected();
}
public function onListItemClick( evt:MouseEvent ):void
{
}
private function onListPluginClick (evt : MouseEvent ) : void
{
}
public function set itemRenderer( value:String ):void
{
_itemRendererId = value;
}
public function get itemRenderer():String
{
return( _itemRendererId )
}
[Bindable]
public function set dataProvider( data:DataProvider ):void
{
if( data )
{
_dataProvider = data as IDataProvider;
_dataProvider.addEventListener( Event.CHANGE, onDataProviderItemChange, false, 0, true );
_klist.dataProvider = data;
}
}
public function onDataProviderItemChange( evt:Event = null ):void
{
if(_dataProvider&&_dataProvider.selectedIndex<_klist.length){
_klist.selectedIndex = _dataProvider.selectedIndex;
_klist.scrollToIndex(_dataProvider.selectedIndex);
}
}
public function get dataProvider():DataProvider
{
return _klist.dataProvider;
}
override public function set width( value:Number ):void
{
_klist.width = super.width = value;
}
override public function set height( value:Number ):void
{
_klist.height = super.height = value;
}
override public function toString():String
{
return( "ListPlugin" );
}
/**
* Hack...fix the bug of sizing...
* @param event
*
*/
private function resizeKdp( event : Event = null ) : void
{
if(_facade)
_facade.retrieveMediator("stageMediator")["onResize"]();
}
override public function set enabled(value:Boolean):void
{
_klist.enabled = value;
}
}
}
|
remove spaces
|
qnd: remove spaces
git-svn-id: 3f608e5a9a704dd448217c0a64c508e7f145cfa1@82444 6b8eccd3-e8c5-4e7d-8186-e12b5326b719
|
ActionScript
|
agpl-3.0
|
shvyrev/kdp,kaltura/kdp,shvyrev/kdp,kaltura/kdp,shvyrev/kdp,kaltura/kdp
|
8d222f08b31410af472a617ba8d43e3a60cfc872
|
dolly-framework/src/test/actionscript/dolly/ClonerTest.as
|
dolly-framework/src/test/actionscript/dolly/ClonerTest.as
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.ClassLevelCloneable;
import dolly.data.ClassLevelCopyableCloneable;
import dolly.data.PropertyLevelCloneable;
import dolly.data.PropertyLevelCopyableCloneable;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertNotNull;
import org.flexunit.asserts.assertNull;
use namespace dolly_internal;
public class ClonerTest {
private var classLevelCloneable:ClassLevelCloneable;
private var classLevelCloneableType:Type;
private var classLevelCopyableCloneable:ClassLevelCopyableCloneable;
private var classLevelCopyableCloneableType:Type;
private var propertyLevelCloneable:PropertyLevelCloneable;
private var propertyLevelCloneableType:Type;
private var propertyLevelCopyableCloneable:PropertyLevelCopyableCloneable;
private var propertyLevelCopyableCloneableType:Type;
[Before]
public function before():void {
classLevelCloneable = new ClassLevelCloneable();
classLevelCloneable.property1 = "value 1";
classLevelCloneable.property2 = "value 2";
classLevelCloneable.property3 = "value 3";
classLevelCloneable.writableField = "value 4";
classLevelCloneableType = Type.forInstance(classLevelCloneable);
classLevelCopyableCloneable = new ClassLevelCopyableCloneable();
classLevelCopyableCloneable.property1 = "value 1";
classLevelCopyableCloneable.property2 = "value 2";
classLevelCopyableCloneable.property3 = "value 3";
classLevelCopyableCloneable.writableField = "value 4";
classLevelCopyableCloneableType = Type.forInstance(classLevelCopyableCloneable);
propertyLevelCloneable = new PropertyLevelCloneable();
propertyLevelCloneable.property1 = "value 1";
propertyLevelCloneable.property2 = "value 2";
propertyLevelCloneable.property3 = "value 3";
propertyLevelCloneable.writableField = "value 4";
propertyLevelCloneableType = Type.forInstance(propertyLevelCloneable);
propertyLevelCopyableCloneable = new PropertyLevelCopyableCloneable();
propertyLevelCopyableCloneable.property1 = "value 1";
propertyLevelCopyableCloneable.property2 = "value 2";
propertyLevelCopyableCloneable.property3 = "value 3";
propertyLevelCopyableCloneable.writableField = "value 4";
propertyLevelCopyableCloneableType = Type.forInstance(propertyLevelCopyableCloneable);
}
[After]
public function after():void {
classLevelCloneable = null;
classLevelCloneableType = null;
classLevelCopyableCloneable = null;
classLevelCopyableCloneableType = null;
propertyLevelCloneable = null;
propertyLevelCloneableType = null;
propertyLevelCopyableCloneable = null;
propertyLevelCopyableCloneableType = null;
}
[Test]
public function testGetCloneableFieldsForTypeClassLevelCloneable():void {
const cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(classLevelCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
}
[Test]
public function testGetCloneableFieldsForTypeClassLevelCopyableCloneable():void {
const cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(classLevelCopyableCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
}
[Test]
public function testGetCloneableFieldsForTypePropertyLevelCloneable():void {
const cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(propertyLevelCloneableType);
assertNotNull(cloneableFields);
assertEquals(3, cloneableFields.length);
}
[Test]
public function testGetCloneableFieldsForTypePropertyLevelCopyableCloneable():void {
const cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(propertyLevelCopyableCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
}
[Test]
public function testCloneClassLevelCloneable():void {
const clone:ClassLevelCloneable = Cloner.clone(classLevelCloneable);
assertNotNull(clone);
assertNotNull(clone.property1);
assertEquals(clone.property1, classLevelCloneable.property1);
assertNotNull(clone.property2);
assertEquals(clone.property2, classLevelCloneable.property2);
assertNotNull(clone.property3);
assertEquals(clone.property3, classLevelCloneable.property3);
assertNotNull(clone.writableField);
assertEquals(clone.writableField, classLevelCloneable.writableField);
}
[Test]
public function testCloneClassLevelCopyableCloneable():void {
const clone:ClassLevelCopyableCloneable = Cloner.clone(classLevelCopyableCloneable);
assertNotNull(clone);
assertNotNull(clone.property1);
assertEquals(clone.property1, classLevelCloneable.property1);
assertNotNull(clone.property2);
assertEquals(clone.property2, classLevelCloneable.property2);
assertNotNull(clone.property3);
assertEquals(clone.property3, classLevelCloneable.property3);
assertNotNull(clone.writableField);
assertEquals(clone.writableField, classLevelCloneable.writableField);
}
[Test]
public function testCloneWithPropertyLevelMetadata():void {
const clone1:PropertyLevelCloneable = Cloner.clone(propertyLevelCloneable);
assertNotNull(clone1);
assertNull(clone1.property1);
assertNotNull(clone1.property2);
assertEquals(clone1.property2, propertyLevelCloneable.property2);
assertNotNull(clone1.property3);
assertEquals(clone1.property3, propertyLevelCloneable.property3);
assertNotNull(clone1.writableField);
assertEquals(clone1.writableField, propertyLevelCloneable.writableField);
const clone2:PropertyLevelCopyableCloneable = Cloner.clone(propertyLevelCopyableCloneable);
assertNotNull(clone2);
assertNotNull(clone2.property1);
assertEquals(clone2.property1, propertyLevelCloneable.property1);
assertNotNull(clone2.property2);
assertEquals(clone2.property2, propertyLevelCloneable.property2);
assertNotNull(clone2.property3);
assertEquals(clone2.property3, propertyLevelCloneable.property3);
assertNotNull(clone2.writableField);
assertEquals(clone2.writableField, propertyLevelCloneable.writableField);
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.ClassLevelCloneable;
import dolly.data.ClassLevelCopyableCloneable;
import dolly.data.PropertyLevelCloneable;
import dolly.data.PropertyLevelCopyableCloneable;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertNotNull;
import org.flexunit.asserts.assertNull;
use namespace dolly_internal;
public class ClonerTest {
private var classLevelCloneable:ClassLevelCloneable;
private var classLevelCloneableType:Type;
private var classLevelCopyableCloneable:ClassLevelCopyableCloneable;
private var classLevelCopyableCloneableType:Type;
private var propertyLevelCloneable:PropertyLevelCloneable;
private var propertyLevelCloneableType:Type;
private var propertyLevelCopyableCloneable:PropertyLevelCopyableCloneable;
private var propertyLevelCopyableCloneableType:Type;
[Before]
public function before():void {
classLevelCloneable = new ClassLevelCloneable();
classLevelCloneable.property1 = "value 1";
classLevelCloneable.property2 = "value 2";
classLevelCloneable.property3 = "value 3";
classLevelCloneable.writableField = "value 4";
classLevelCloneableType = Type.forInstance(classLevelCloneable);
classLevelCopyableCloneable = new ClassLevelCopyableCloneable();
classLevelCopyableCloneable.property1 = "value 1";
classLevelCopyableCloneable.property2 = "value 2";
classLevelCopyableCloneable.property3 = "value 3";
classLevelCopyableCloneable.writableField = "value 4";
classLevelCopyableCloneableType = Type.forInstance(classLevelCopyableCloneable);
propertyLevelCloneable = new PropertyLevelCloneable();
propertyLevelCloneable.property1 = "value 1";
propertyLevelCloneable.property2 = "value 2";
propertyLevelCloneable.property3 = "value 3";
propertyLevelCloneable.writableField = "value 4";
propertyLevelCloneableType = Type.forInstance(propertyLevelCloneable);
propertyLevelCopyableCloneable = new PropertyLevelCopyableCloneable();
propertyLevelCopyableCloneable.property1 = "value 1";
propertyLevelCopyableCloneable.property2 = "value 2";
propertyLevelCopyableCloneable.property3 = "value 3";
propertyLevelCopyableCloneable.writableField = "value 4";
propertyLevelCopyableCloneableType = Type.forInstance(propertyLevelCopyableCloneable);
}
[After]
public function after():void {
classLevelCloneable = null;
classLevelCloneableType = null;
classLevelCopyableCloneable = null;
classLevelCopyableCloneableType = null;
propertyLevelCloneable = null;
propertyLevelCloneableType = null;
propertyLevelCopyableCloneable = null;
propertyLevelCopyableCloneableType = null;
}
[Test]
public function testGetCloneableFieldsForTypeClassLevelCloneable():void {
const cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(classLevelCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
}
[Test]
public function testGetCloneableFieldsForTypeClassLevelCopyableCloneable():void {
const cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(classLevelCopyableCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
}
[Test]
public function testGetCloneableFieldsForTypePropertyLevelCloneable():void {
const cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(propertyLevelCloneableType);
assertNotNull(cloneableFields);
assertEquals(3, cloneableFields.length);
}
[Test]
public function testGetCloneableFieldsForTypePropertyLevelCopyableCloneable():void {
const cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(propertyLevelCopyableCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
}
[Test]
public function testCloneClassLevelCloneable():void {
const clone:ClassLevelCloneable = Cloner.clone(classLevelCloneable);
assertNotNull(clone);
assertNotNull(clone.property1);
assertEquals(clone.property1, classLevelCloneable.property1);
assertNotNull(clone.property2);
assertEquals(clone.property2, classLevelCloneable.property2);
assertNotNull(clone.property3);
assertEquals(clone.property3, classLevelCloneable.property3);
assertNotNull(clone.writableField);
assertEquals(clone.writableField, classLevelCloneable.writableField);
}
[Test]
public function testCloneClassLevelCopyableCloneable():void {
const clone:ClassLevelCopyableCloneable = Cloner.clone(classLevelCopyableCloneable);
assertNotNull(clone);
assertNotNull(clone.property1);
assertEquals(clone.property1, classLevelCloneable.property1);
assertNotNull(clone.property2);
assertEquals(clone.property2, classLevelCloneable.property2);
assertNotNull(clone.property3);
assertEquals(clone.property3, classLevelCloneable.property3);
assertNotNull(clone.writableField);
assertEquals(clone.writableField, classLevelCloneable.writableField);
}
[Test]
public function testClonePropertyLevelCloneable():void {
const clone:PropertyLevelCloneable = Cloner.clone(propertyLevelCloneable);
assertNotNull(clone);
assertNull(clone.property1);
assertNotNull(clone.property2);
assertEquals(clone.property2, propertyLevelCloneable.property2);
assertNotNull(clone.property3);
assertEquals(clone.property3, propertyLevelCloneable.property3);
assertNotNull(clone.writableField);
assertEquals(clone.writableField, propertyLevelCloneable.writableField);
}
[Test]
public function testClonePropertyLevelCopyableCloneable():void {
const clone:PropertyLevelCopyableCloneable = Cloner.clone(propertyLevelCopyableCloneable);
assertNotNull(clone);
assertNotNull(clone.property1);
assertEquals(clone.property1, propertyLevelCloneable.property1);
assertNotNull(clone.property2);
assertEquals(clone.property2, propertyLevelCloneable.property2);
assertNotNull(clone.property3);
assertEquals(clone.property3, propertyLevelCloneable.property3);
assertNotNull(clone.writableField);
assertEquals(clone.writableField, propertyLevelCloneable.writableField);
}
}
}
|
Split method "testCloneWithPropertyLevelMetadata" to a few.
|
Split method "testCloneWithPropertyLevelMetadata" to a few.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
9cac5bc948b5cac2c29c8723b15b831d98c56beb
|
dolly-framework/src/test/actionscript/dolly/CopierTest.as
|
dolly-framework/src/test/actionscript/dolly/CopierTest.as
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.ClassLevelCopyable;
import dolly.data.ClassLevelCopyableCloneable;
import dolly.data.PropertyLevelCopyable;
import dolly.data.PropertyLevelCopyableCloneable;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertNotNull;
import org.flexunit.asserts.assertNull;
use namespace dolly_internal;
public class CopierTest {
private var classLevelCopyable:ClassLevelCopyable;
private var classLevelCopyableType:Type;
private var classLevelCopyableCloneable:ClassLevelCopyableCloneable;
private var classLevelCopyableCloneableType:Type;
private var propertyLevelCopyable:PropertyLevelCopyable;
private var propertyLevelCopyableType:Type;
private var propertyLevelCopyableCloneable:PropertyLevelCopyableCloneable;
private var propertyLevelCopyableCloneableType:Type;
[Before]
public function before():void {
classLevelCopyable = new ClassLevelCopyable();
classLevelCopyable.property1 = "value 1";
classLevelCopyable.property2 = "value 2";
classLevelCopyable.property3 = "value 3";
classLevelCopyable.writableField = "value 4";
classLevelCopyableType = Type.forInstance(classLevelCopyable);
classLevelCopyableCloneable = new ClassLevelCopyableCloneable();
classLevelCopyableCloneable.property1 = "value 1";
classLevelCopyableCloneable.property2 = "value 2";
classLevelCopyableCloneable.property3 = "value 3";
classLevelCopyableCloneable.writableField = "value 4";
classLevelCopyableCloneableType = Type.forInstance(classLevelCopyableCloneable);
propertyLevelCopyable = new PropertyLevelCopyable();
propertyLevelCopyable.property1 = "value 1";
propertyLevelCopyable.property2 = "value 2";
propertyLevelCopyable.property3 = "value 3";
propertyLevelCopyable.writableField = "value 4";
propertyLevelCopyableType = Type.forInstance(propertyLevelCopyable);
propertyLevelCopyableCloneable = new PropertyLevelCopyableCloneable();
propertyLevelCopyableCloneable.property1 = "value 1";
propertyLevelCopyableCloneable.property2 = "value 2";
propertyLevelCopyableCloneable.property3 = "value 3";
propertyLevelCopyableCloneable.writableField = "value 4";
propertyLevelCopyableCloneableType = Type.forInstance(propertyLevelCopyableCloneable);
}
[After]
public function after():void {
classLevelCopyable = null;
classLevelCopyableType = null;
classLevelCopyableCloneable = null;
classLevelCopyableCloneableType = null;
propertyLevelCopyable = null;
propertyLevelCopyableType = null;
propertyLevelCopyableCloneable = null;
propertyLevelCopyableCloneableType = null;
}
[Test]
public function testGetCopyableFieldsForType():void {
var copyableFields:Vector.<Field> = Copier.getCopyableFieldsForType(classLevelCopyableType);
assertNotNull(copyableFields);
assertEquals(4, copyableFields.length);
assertNotNull(copyableFields[0]);
assertNotNull(copyableFields[1]);
assertNotNull(copyableFields[2]);
assertNotNull(copyableFields[3]);
copyableFields = Copier.getCopyableFieldsForType(classLevelCopyableCloneableType);
assertNotNull(copyableFields);
assertEquals(4, copyableFields.length);
assertNotNull(copyableFields[0]);
assertNotNull(copyableFields[1]);
assertNotNull(copyableFields[2]);
assertNotNull(copyableFields[3]);
copyableFields = Copier.getCopyableFieldsForType(propertyLevelCopyableType);
assertNotNull(copyableFields);
assertEquals(3, copyableFields.length);
assertNotNull(copyableFields[0]);
assertNotNull(copyableFields[1]);
assertNotNull(copyableFields[2]);
copyableFields = Copier.getCopyableFieldsForType(propertyLevelCopyableCloneableType);
assertNotNull(copyableFields);
assertEquals(3, copyableFields.length);
assertNotNull(copyableFields[0]);
assertNotNull(copyableFields[1]);
assertNotNull(copyableFields[2]);
}
[Test]
public function testCopyWithClassLevelMetadata():void {
const copy1:ClassLevelCopyable = Copier.copy(classLevelCopyable);
assertNotNull(copy1);
assertNotNull(copy1.property1);
assertEquals(copy1.property1, classLevelCopyable.property1);
assertNotNull(copy1.property2);
assertEquals(copy1.property2, classLevelCopyable.property2);
assertNotNull(copy1.property3);
assertEquals(copy1.property3, classLevelCopyable.property3);
assertNotNull(copy1.writableField);
assertEquals(copy1.writableField, classLevelCopyable.writableField);
const copy2:ClassLevelCopyableCloneable = Copier.copy(classLevelCopyableCloneable);
assertNotNull(copy2);
assertNotNull(copy2.property1);
assertEquals(copy2.property1, classLevelCopyable.property1);
assertNotNull(copy2.property2);
assertEquals(copy2.property2, classLevelCopyable.property2);
assertNotNull(copy2.property3);
assertEquals(copy2.property3, classLevelCopyable.property3);
assertNotNull(copy2.writableField);
assertEquals(copy2.writableField, classLevelCopyable.writableField);
}
[Test]
public function testCopyWithPropertyLevelMetadata():void {
const copy1:PropertyLevelCopyable = Copier.copy(propertyLevelCopyable);
assertNotNull(copy1);
assertNull(copy1.property1);
assertNotNull(copy1.property2);
assertEquals(copy1.property2, classLevelCopyable.property2);
assertNotNull(copy1.property3);
assertEquals(copy1.property3, classLevelCopyable.property3);
assertNotNull(copy1.writableField);
assertEquals(copy1.writableField, classLevelCopyable.writableField);
const copy2:PropertyLevelCopyableCloneable = Copier.copy(propertyLevelCopyableCloneable);
assertNotNull(copy2);
assertNull(copy2.property1);
assertNotNull(copy2.property2);
assertEquals(copy2.property2, classLevelCopyable.property2);
assertNotNull(copy2.property3);
assertEquals(copy2.property3, classLevelCopyable.property3);
assertNotNull(copy2.writableField);
assertEquals(copy2.writableField, classLevelCopyable.writableField);
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.ClassLevelCopyable;
import dolly.data.ClassLevelCopyableCloneable;
import dolly.data.PropertyLevelCopyable;
import dolly.data.PropertyLevelCopyableCloneable;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertNotNull;
import org.flexunit.asserts.assertNull;
use namespace dolly_internal;
public class CopierTest {
private var classLevelCopyable:ClassLevelCopyable;
private var classLevelCopyableType:Type;
private var classLevelCopyableCloneable:ClassLevelCopyableCloneable;
private var classLevelCopyableCloneableType:Type;
private var propertyLevelCopyable:PropertyLevelCopyable;
private var propertyLevelCopyableType:Type;
private var propertyLevelCopyableCloneable:PropertyLevelCopyableCloneable;
private var propertyLevelCopyableCloneableType:Type;
[Before]
public function before():void {
classLevelCopyable = new ClassLevelCopyable();
classLevelCopyable.property1 = "value 1";
classLevelCopyable.property2 = "value 2";
classLevelCopyable.property3 = "value 3";
classLevelCopyable.writableField = "value 4";
classLevelCopyableType = Type.forInstance(classLevelCopyable);
classLevelCopyableCloneable = new ClassLevelCopyableCloneable();
classLevelCopyableCloneable.property1 = "value 1";
classLevelCopyableCloneable.property2 = "value 2";
classLevelCopyableCloneable.property3 = "value 3";
classLevelCopyableCloneable.writableField = "value 4";
classLevelCopyableCloneableType = Type.forInstance(classLevelCopyableCloneable);
propertyLevelCopyable = new PropertyLevelCopyable();
propertyLevelCopyable.property1 = "value 1";
propertyLevelCopyable.property2 = "value 2";
propertyLevelCopyable.property3 = "value 3";
propertyLevelCopyable.writableField = "value 4";
propertyLevelCopyableType = Type.forInstance(propertyLevelCopyable);
propertyLevelCopyableCloneable = new PropertyLevelCopyableCloneable();
propertyLevelCopyableCloneable.property1 = "value 1";
propertyLevelCopyableCloneable.property2 = "value 2";
propertyLevelCopyableCloneable.property3 = "value 3";
propertyLevelCopyableCloneable.writableField = "value 4";
propertyLevelCopyableCloneableType = Type.forInstance(propertyLevelCopyableCloneable);
}
[After]
public function after():void {
classLevelCopyable = null;
classLevelCopyableType = null;
classLevelCopyableCloneable = null;
classLevelCopyableCloneableType = null;
propertyLevelCopyable = null;
propertyLevelCopyableType = null;
propertyLevelCopyableCloneable = null;
propertyLevelCopyableCloneableType = null;
}
[Test]
public function testGetCopyableFieldsForTypeClassLevelCopyable():void {
const copyableFields:Vector.<Field> = Copier.getCopyableFieldsForType(classLevelCopyableType);
assertNotNull(copyableFields);
assertEquals(4, copyableFields.length);
assertNotNull(copyableFields[0]);
assertNotNull(copyableFields[1]);
assertNotNull(copyableFields[2]);
assertNotNull(copyableFields[3]);
}
[Test]
public function testGetCopyableFieldsForTypeClassLevelCopyableCloneable():void {
const copyableFields:Vector.<Field> = Copier.getCopyableFieldsForType(classLevelCopyableCloneableType);
assertNotNull(copyableFields);
assertEquals(4, copyableFields.length);
assertNotNull(copyableFields[0]);
assertNotNull(copyableFields[1]);
assertNotNull(copyableFields[2]);
assertNotNull(copyableFields[3]);
}
[Test]
public function testGetCopyableFieldsForTypePropertyLevelCopyable():void {
const copyableFields:Vector.<Field> = Copier.getCopyableFieldsForType(propertyLevelCopyableType);
assertNotNull(copyableFields);
assertEquals(3, copyableFields.length);
assertNotNull(copyableFields[0]);
assertNotNull(copyableFields[1]);
assertNotNull(copyableFields[2]);
}
[Test]
public function testGetCopyableFieldsForTypePropertyLevelCopyableCloneable():void {
const copyableFields:Vector.<Field> = Copier.getCopyableFieldsForType(propertyLevelCopyableCloneableType);
assertNotNull(copyableFields);
assertEquals(3, copyableFields.length);
assertNotNull(copyableFields[0]);
assertNotNull(copyableFields[1]);
assertNotNull(copyableFields[2]);
}
[Test]
public function testCopyWithClassLevelMetadata():void {
const copy1:ClassLevelCopyable = Copier.copy(classLevelCopyable);
assertNotNull(copy1);
assertNotNull(copy1.property1);
assertEquals(copy1.property1, classLevelCopyable.property1);
assertNotNull(copy1.property2);
assertEquals(copy1.property2, classLevelCopyable.property2);
assertNotNull(copy1.property3);
assertEquals(copy1.property3, classLevelCopyable.property3);
assertNotNull(copy1.writableField);
assertEquals(copy1.writableField, classLevelCopyable.writableField);
const copy2:ClassLevelCopyableCloneable = Copier.copy(classLevelCopyableCloneable);
assertNotNull(copy2);
assertNotNull(copy2.property1);
assertEquals(copy2.property1, classLevelCopyable.property1);
assertNotNull(copy2.property2);
assertEquals(copy2.property2, classLevelCopyable.property2);
assertNotNull(copy2.property3);
assertEquals(copy2.property3, classLevelCopyable.property3);
assertNotNull(copy2.writableField);
assertEquals(copy2.writableField, classLevelCopyable.writableField);
}
[Test]
public function testCopyWithPropertyLevelMetadata():void {
const copy1:PropertyLevelCopyable = Copier.copy(propertyLevelCopyable);
assertNotNull(copy1);
assertNull(copy1.property1);
assertNotNull(copy1.property2);
assertEquals(copy1.property2, classLevelCopyable.property2);
assertNotNull(copy1.property3);
assertEquals(copy1.property3, classLevelCopyable.property3);
assertNotNull(copy1.writableField);
assertEquals(copy1.writableField, classLevelCopyable.writableField);
const copy2:PropertyLevelCopyableCloneable = Copier.copy(propertyLevelCopyableCloneable);
assertNotNull(copy2);
assertNull(copy2.property1);
assertNotNull(copy2.property2);
assertEquals(copy2.property2, classLevelCopyable.property2);
assertNotNull(copy2.property3);
assertEquals(copy2.property3, classLevelCopyable.property3);
assertNotNull(copy2.writableField);
assertEquals(copy2.writableField, classLevelCopyable.writableField);
}
}
}
|
Split method "testGetCopyableFieldsForType" to a few.
|
Split method "testGetCopyableFieldsForType" to a few.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
f14347628288b5d7bf5e03353c85d75e647a8e33
|
actionscript-cafe/src/main/flex/org/servebox/cafe/core/command/IStateCommand.as
|
actionscript-cafe/src/main/flex/org/servebox/cafe/core/command/IStateCommand.as
|
package org.servebox.cafe.core.command
{
import flash.events.IEventDispatcher;
public interface IStateCommand extends ICommand, IEventDispatcher
{
[Bindable("executable_Change")]
function get executable() : Boolean;
function set executable( value :Boolean ) : void;
}
}
|
package org.servebox.cafe.core.command
{
import flash.events.IEventDispatcher;
public interface IStateCommand extends ICommand, IEventDispatcher
{
[Bindable("executable_Change")]
function get executable() : Boolean;
function set executable( value :Boolean ) : void;
function addParameter( key : String , value : Object ) : void;
}
}
|
add addParameter to interface.
|
add addParameter to interface.
|
ActionScript
|
mit
|
servebox/as-cafe
|
d5ea961550037ed7242fa4790fcdaf6d49b31986
|
HLSPlugin/src/org/denivip/osmf/net/httpstreaming/hls/HTTPStreamingMp3Audio2ToPESAudio.as
|
HLSPlugin/src/org/denivip/osmf/net/httpstreaming/hls/HTTPStreamingMp3Audio2ToPESAudio.as
|
/*
* Copyright
* Watchtower stream.jw.org Team
*
*/
package org.denivip.osmf.net.httpstreaming.hls
{
import __AS3__.vec.Vector;
import org.osmf.logging.Logger;
import org.osmf.logging.Log;
import flash.utils.ByteArray;
import org.osmf.net.httpstreaming.flv.FLVTagAudio;
internal class HTTPStreamingMp3Audio2ToPESAudio extends HTTPStreamingMP2PESBase
{
private var _state:int;
private var _haveNewTimestamp:Boolean = false;
private var _audioTime:Number;
private var _audioTimeIncr:Number;
private var _frameLength:int;
private var _remaining:int;
private var _audioData:ByteArray;
private var _version:int;
private var _layer:int;
private var _bitRate:int;
private var _sampleRate:int;
private var _padding:int;
private var _channel:int;
public function HTTPStreamingMp3Audio2ToPESAudio():void
{
_state = 0;
}
private static const MPEG1:int = 0x03;
private static const MPEG2:int = 0x02;
private static const MPEG25:int = 0x01;
private static const LAYER_1:int = 0x03;
private static const LAYER_2:int = 0x02;
private static const LAYER_3:int = 0x01;
private var BITREATE_MAP_FOR_MPEG1_LAYER1:Array = [0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 0];
private var BITREATE_MAP_FOR_MPEG1_LAYER2:Array = [0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 0];
private var BITREATE_MAP_FOR_MPEG1_LAYER3:Array = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0];
private var BITREATE_MAP_FOR_MPEG2_LAYER1:Array = [0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 0];
private var BITREATE_MAP_FOR_MPEG2_LAYER2:Array = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0]; // LAYER3 is same
private var SAMPLERATE_MAP_FOR_MPEG1:Array = [44100, 48000, 32000, 0];
private var SAMPLERATE_MAP_FOR_MPEG2:Array = [22050, 24000, 16000, 0];
private var SAMPLERATE_MAP_FOR_MPEG25:Array = [11025, 12000, 8000, 0];
private function GetBitRate(version:int, layer:int, index:int):int
{
if (version == MPEG1) {
if (layer == LAYER_1) {
return BITREATE_MAP_FOR_MPEG1_LAYER1[index];
}
else if (layer == LAYER_2) {
return BITREATE_MAP_FOR_MPEG1_LAYER2[index];
}
else if (layer == LAYER_3) {
return BITREATE_MAP_FOR_MPEG1_LAYER3[index];
}
}
else if (version == MPEG2) {
if (layer == LAYER_1) {
return BITREATE_MAP_FOR_MPEG2_LAYER1[index];
}
else if (layer == LAYER_2 || layer == LAYER_3) {
return BITREATE_MAP_FOR_MPEG2_LAYER2[index];
}
}
return 0;
}
private function GetSampleRate(version:int, no:int):int
{
if (version == MPEG1) {
return SAMPLERATE_MAP_FOR_MPEG1[no];
} else if (version == MPEG2) {
return SAMPLERATE_MAP_FOR_MPEG2[no];
} else if (version == MPEG25) {
return SAMPLERATE_MAP_FOR_MPEG25[no];
}
return 0;
}
override public function processES(pusi:Boolean, packet:ByteArray, flush:Boolean = false): ByteArray {
if(pusi)
{
// start of a new PES packet
// Start code prefix and packet ID.
value = packet.readUnsignedInt();
packet.position -= 4;
if(packet.readUnsignedInt() != 0x1c0)
{
throw new Error("PES start code not found or not ~");
}
// Ignore packet length and marker bits.
packet.position += 3;
// need PTS only
var flags:uint = (packet.readUnsignedByte() & 0xc0) >> 6;
if(flags != 0x02 && flags != 0x03)
{
throw new Error("No PTS in this audio PES packet");
}
var length:uint = packet.readUnsignedByte();
var pts:Number =
((packet.readUnsignedByte() & 0x0e) << 29) +
((packet.readUnsignedShort() & 0xfffe) << 14) +
((packet.readUnsignedShort() & 0xfffe) >> 1);
var timestamp:Number = Math.round(pts/90);
_haveNewTimestamp = true;
if(!_timestampReseted){
_offset += timestamp - _prevTimestamp;
}
_timestamp = _initialTimestamp + _offset;
_prevTimestamp = timestamp;
_timestampReseted = false;
length -= 5;
// no comp time for audio
// Skip other header data.
packet.position += length;
}
var value:uint;
var tag:FLVTagAudio;
var tagData:ByteArray = new ByteArray();
if(!flush)
{
var dStart:uint = packet.position;
}
if(flush)
{
trace("audio flush at state "+_state.toString());
}
else while(packet.bytesAvailable > 0)
{
if(_state < 7)
{
value = packet.readUnsignedByte();
}
switch(_state)
{
case 0: // first 0x01
if(_haveNewTimestamp)
{
_audioTime = _timestamp;
_haveNewTimestamp = false;
}
if(value == 0xff)
{
_state = 1;
}
break;
case 1:
if (value & 0xe0 == 0xe0) { // 1110 0000
_version = ((value >> 3) & 0x03);
_layer = ((value >> 1) & 0x03);
var crc:int = (value & 0x01);
_state = 2;
} else {
_state = 0;
}
break;
case 2:
var bitrateIndex:int = ((value >> 4) & 0x0f);
var sampleRate:int = ((value >> 2) & 0x03);
_padding = ((value >> 1) & 0x01);
var bit:int = ((value & 0x01));
_state = 3;
_bitRate = GetBitRate(_version, _layer, bitrateIndex);
if (_bitRate == 0) {
_state = 0;
}
_sampleRate = GetSampleRate(_version, sampleRate);
//_audioTimeIncr = 1024000.0 / _sampleRate;
_audioTimeIncr = 144 * 8 * 1000 / _sampleRate;
if (_sampleRate == 0) {
_state = 0;
}
break;
case 3:
_channel = ((value >>6) & 0x03);
var modeExt:int = ((value >> 4) & 0x03);
var copyright:int = ((value >> 3) & 0x01);
var original:int = ((value >> 2) & 0x01);
var emphasis:int = (value & 0x03);
_frameLength = int((144 * _bitRate * 1000 / _sampleRate ) + _padding);
packet.position -= 4
dStart = packet.position;
_audioData = new ByteArray();
_remaining = _frameLength;
_state = 4;
break;
case 4:
var avail:int = packet.length - dStart;
if(avail >= _remaining)
{
_audioData.writeBytes(packet, dStart, _remaining);
packet.position += _remaining - 1;
_remaining = 0;
}
else if(avail > 0)
{
_audioData.writeBytes(packet, dStart, avail);
packet.position += avail;
_remaining -= avail;
}
if(_remaining > 0)
{
//
}
else
{
tag = new FLVTagAudio();
tag.timestamp = _audioTime;
_audioTime += _audioTimeIncr;
tag.soundChannels = (_channel == 0x03 ? FLVTagAudio.SOUND_CHANNELS_MONO : FLVTagAudio.SOUND_CHANNELS_STEREO);
tag.soundFormat = FLVTagAudio.SOUND_FORMAT_MP3;
tag.soundRate = FLVTagAudio.SOUND_RATE_44K; // rather than what is reported
tag.soundSize = FLVTagAudio.SOUND_SIZE_16BITS;
_state = 0;
tag.data = _audioData;
tag.write(tagData); // unrolled out the vector for audio tags
}
break;
} // switch
} // while
/*
var text:String = new String();
for(var i:int = 0; i<tagData.length; i++)
text += uint(tagData[i]).toString(16)+" ";
trace(text);
//*/
tagData.position = 0;
return tagData;
}
CONFIG::LOGGING
{
private var logger:Logger = Log.getLogger('org.denivip.osmf.net.httpstreaming.hls.HTTPStreamingMp3Audio2ToPESAudio') as Logger;
}
}
}
|
/*
* Copyright
* [email protected]
*
*/
package org.denivip.osmf.net.httpstreaming.hls
{
import __AS3__.vec.Vector;
import org.osmf.logging.Logger;
import org.osmf.logging.Log;
import flash.utils.ByteArray;
import org.osmf.net.httpstreaming.flv.FLVTagAudio;
internal class HTTPStreamingMp3Audio2ToPESAudio extends HTTPStreamingMP2PESBase
{
private var _state:int;
private var _haveNewTimestamp:Boolean = false;
private var _audioTime:Number;
private var _audioTimeIncr:Number;
private var _frameLength:int;
private var _remaining:int;
private var _audioData:ByteArray;
private var _version:int;
private var _layer:int;
private var _bitRate:int;
private var _sampleRate:int;
private var _padding:int;
private var _channel:int;
public function HTTPStreamingMp3Audio2ToPESAudio():void
{
_state = 0;
}
private static const MPEG1:int = 0x03;
private static const MPEG2:int = 0x02;
private static const MPEG25:int = 0x01;
private static const LAYER_1:int = 0x03;
private static const LAYER_2:int = 0x02;
private static const LAYER_3:int = 0x01;
private var BITREATE_MAP_FOR_MPEG1_LAYER1:Array = [0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 0];
private var BITREATE_MAP_FOR_MPEG1_LAYER2:Array = [0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 0];
private var BITREATE_MAP_FOR_MPEG1_LAYER3:Array = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0];
private var BITREATE_MAP_FOR_MPEG2_LAYER1:Array = [0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 0];
private var BITREATE_MAP_FOR_MPEG2_LAYER2:Array = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0]; // LAYER3 is same
private var SAMPLERATE_MAP_FOR_MPEG1:Array = [44100, 48000, 32000, 0];
private var SAMPLERATE_MAP_FOR_MPEG2:Array = [22050, 24000, 16000, 0];
private var SAMPLERATE_MAP_FOR_MPEG25:Array = [11025, 12000, 8000, 0];
private function GetBitRate(version:int, layer:int, index:int):int
{
if (version == MPEG1) {
if (layer == LAYER_1) {
return BITREATE_MAP_FOR_MPEG1_LAYER1[index];
}
else if (layer == LAYER_2) {
return BITREATE_MAP_FOR_MPEG1_LAYER2[index];
}
else if (layer == LAYER_3) {
return BITREATE_MAP_FOR_MPEG1_LAYER3[index];
}
}
else if (version == MPEG2) {
if (layer == LAYER_1) {
return BITREATE_MAP_FOR_MPEG2_LAYER1[index];
}
else if (layer == LAYER_2 || layer == LAYER_3) {
return BITREATE_MAP_FOR_MPEG2_LAYER2[index];
}
}
return 0;
}
private function GetSampleRate(version:int, no:int):int
{
if (version == MPEG1) {
return SAMPLERATE_MAP_FOR_MPEG1[no];
} else if (version == MPEG2) {
return SAMPLERATE_MAP_FOR_MPEG2[no];
} else if (version == MPEG25) {
return SAMPLERATE_MAP_FOR_MPEG25[no];
}
return 0;
}
override public function processES(pusi:Boolean, packet:ByteArray, flush:Boolean = false): ByteArray {
if(pusi)
{
// start of a new PES packet
// Start code prefix and packet ID.
value = packet.readUnsignedInt();
packet.position -= 4;
if(packet.readUnsignedInt() != 0x1c0)
{
throw new Error("PES start code not found or not ~");
}
// Ignore packet length and marker bits.
packet.position += 3;
// need PTS only
var flags:uint = (packet.readUnsignedByte() & 0xc0) >> 6;
if(flags != 0x02 && flags != 0x03)
{
throw new Error("No PTS in this audio PES packet");
}
var length:uint = packet.readUnsignedByte();
var pts:Number =
((packet.readUnsignedByte() & 0x0e) << 29) +
((packet.readUnsignedShort() & 0xfffe) << 14) +
((packet.readUnsignedShort() & 0xfffe) >> 1);
var timestamp:Number = Math.round(pts/90);
_haveNewTimestamp = true;
if(!_timestampReseted){
_offset += timestamp - _prevTimestamp;
}
_timestamp = _initialTimestamp + _offset;
_prevTimestamp = timestamp;
_timestampReseted = false;
length -= 5;
// no comp time for audio
// Skip other header data.
packet.position += length;
}
var value:uint;
var tag:FLVTagAudio;
var tagData:ByteArray = new ByteArray();
if(!flush)
{
var dStart:uint = packet.position;
}
if(flush)
{
trace("audio flush at state "+_state.toString());
}
else while(packet.bytesAvailable > 0)
{
if(_state < 7)
{
value = packet.readUnsignedByte();
}
switch(_state)
{
case 0: // first 0x01
if(_haveNewTimestamp)
{
_audioTime = _timestamp;
_haveNewTimestamp = false;
}
if(value == 0xff)
{
_state = 1;
}
break;
case 1:
if (value & 0xe0 == 0xe0) { // 1110 0000
_version = ((value >> 3) & 0x03);
_layer = ((value >> 1) & 0x03);
var crc:int = (value & 0x01);
_state = 2;
} else {
_state = 0;
}
break;
case 2:
var bitrateIndex:int = ((value >> 4) & 0x0f);
var sampleRate:int = ((value >> 2) & 0x03);
_padding = ((value >> 1) & 0x01);
var bit:int = ((value & 0x01));
_state = 3;
_bitRate = GetBitRate(_version, _layer, bitrateIndex);
if (_bitRate == 0) {
_state = 0;
}
_sampleRate = GetSampleRate(_version, sampleRate);
//_audioTimeIncr = 1024000.0 / _sampleRate;
_audioTimeIncr = 144 * 8 * 1000 / _sampleRate;
if (_sampleRate == 0) {
_state = 0;
}
break;
case 3:
_channel = ((value >>6) & 0x03);
var modeExt:int = ((value >> 4) & 0x03);
var copyright:int = ((value >> 3) & 0x01);
var original:int = ((value >> 2) & 0x01);
var emphasis:int = (value & 0x03);
_frameLength = int((144 * _bitRate * 1000 / _sampleRate ) + _padding);
packet.position -= 4
dStart = packet.position;
_audioData = new ByteArray();
_remaining = _frameLength;
_state = 4;
break;
case 4:
var avail:int = packet.length - dStart;
if(avail >= _remaining)
{
_audioData.writeBytes(packet, dStart, _remaining);
packet.position += _remaining - 1;
_remaining = 0;
}
else if(avail > 0)
{
_audioData.writeBytes(packet, dStart, avail);
packet.position += avail;
_remaining -= avail;
}
if(_remaining > 0)
{
//
}
else
{
tag = new FLVTagAudio();
tag.timestamp = _audioTime;
_audioTime += _audioTimeIncr;
tag.soundChannels = (_channel == 0x03 ? FLVTagAudio.SOUND_CHANNELS_MONO : FLVTagAudio.SOUND_CHANNELS_STEREO);
tag.soundFormat = FLVTagAudio.SOUND_FORMAT_MP3;
tag.soundRate = FLVTagAudio.SOUND_RATE_44K; // rather than what is reported
tag.soundSize = FLVTagAudio.SOUND_SIZE_16BITS;
_state = 0;
tag.data = _audioData;
tag.write(tagData); // unrolled out the vector for audio tags
}
break;
} // switch
} // while
tagData.position = 0;
return tagData;
}
CONFIG::LOGGING
{
private var logger:Logger = Log.getLogger('org.denivip.osmf.net.httpstreaming.hls.HTTPStreamingMp3Audio2ToPESAudio') as Logger;
}
}
}
|
Update HTTPStreamingMp3Audio2ToPESAudio.as
|
Update HTTPStreamingMp3Audio2ToPESAudio.as
|
ActionScript
|
isc
|
denivip/osmf-hls-plugin,mruse/osmf-hls-plugin,denivip/osmf-hls-plugin,mruse/osmf-hls-plugin
|
2a5f5a94228c3013313532f69e607457a3d747cb
|
src/flash/htmlelements/VideoElement.as
|
src/flash/htmlelements/VideoElement.as
|
package htmlelements
{
import flash.display.Sprite;
import flash.events.*;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.media.Video;
import flash.media.SoundTransform;
import flash.utils.Timer;
import FlashMediaElement;
import HtmlMediaEvent;
public class VideoElement extends Sprite implements IMediaElement
{
private var _currentUrl:String = "";
private var _autoplay:Boolean = true;
private var _preload:String = "";
private var _isPreloading:Boolean = false;
private var _connection:NetConnection;
private var _stream:NetStream;
private var _video:Video;
private var _element:FlashMediaElement;
private var _soundTransform;
private var _oldVolume:Number = 1;
// event values
private var _duration:Number = 0;
private var _framerate:Number;
private var _isPaused:Boolean = true;
private var _isEnded:Boolean = false;
private var _volume:Number = 1;
private var _isMuted:Boolean = false;
private var _bytesLoaded:Number = 0;
private var _bytesTotal:Number = 0;
private var _bufferedTime:Number = 0;
private var _bufferEmpty:Boolean = false;
private var _videoWidth:Number = -1;
private var _videoHeight:Number = -1;
private var _timer:Timer;
private var _isRTMP:Boolean = false;
private var _isConnected:Boolean = false;
private var _playWhenConnected:Boolean = false;
private var _hasStartedPlaying:Boolean = false;
private var _parentReference:Object;
public function setReference(arg:Object):void {
_parentReference = arg;
}
public function get video():Video {
return _video;
}
public function get videoHeight():Number {
return _videoHeight;
}
public function get videoWidth():Number {
return _videoWidth;
}
public function duration():Number {
return _duration;
}
public function currentProgress():Number {
if(_stream != null) {
return Math.round(_stream.bytesLoaded/_stream.bytesTotal*100);
} else {
return 0;
}
}
public function currentTime():Number {
if (_stream != null) {
return _stream.time;
} else {
return 0;
}
}
// (1) load()
// calls _connection.connect();
// waits for NetConnection.Connect.Success
// _stream gets created
public function VideoElement(element:FlashMediaElement, autoplay:Boolean, preload:String, timerRate:Number, startVolume:Number)
{
_element = element;
_autoplay = autoplay;
_volume = startVolume;
_preload = preload;
_video = new Video();
addChild(_video);
_connection = new NetConnection();
_connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
_connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
//_connection.connect(null);
_timer = new Timer(timerRate);
_timer.addEventListener("timer", timerHandler);
}
private function timerHandler(e:TimerEvent) {
_bytesLoaded = _stream.bytesLoaded;
_bytesTotal = _stream.bytesTotal;
if (!_isPaused)
sendEvent(HtmlMediaEvent.TIMEUPDATE);
//trace("bytes", _bytesLoaded, _bytesTotal);
if (_bytesLoaded < _bytesTotal)
sendEvent(HtmlMediaEvent.PROGRESS);
}
// internal events
private function netStatusHandler(event:NetStatusEvent):void {
trace("netStatus", event.info.code);
switch (event.info.code) {
case "NetStream.Buffer.Empty":
_bufferEmpty = true;
_isEnded ? sendEvent(HtmlMediaEvent.ENDED) : null;
break;
case "NetStream.Buffer.Full":
_bytesLoaded = _stream.bytesLoaded;
_bytesTotal = _stream.bytesTotal;
_bufferEmpty = false;
sendEvent(HtmlMediaEvent.PROGRESS);
break;
case "NetConnection.Connect.Success":
connectStream();
break;
case "NetStream.Play.StreamNotFound":
trace("Unable to locate video");
break;
// STREAM
case "NetStream.Play.Start":
_isPaused = false;
sendEvent(HtmlMediaEvent.LOADEDDATA);
sendEvent(HtmlMediaEvent.CANPLAY);
if (!_isPreloading) {
sendEvent(HtmlMediaEvent.PLAY);
sendEvent(HtmlMediaEvent.PLAYING);
}
_timer.start();
break;
case "NetStream.Seek.Notify":
sendEvent(HtmlMediaEvent.SEEKED);
break;
case "NetStream.Pause.Notify":
_isPaused = true;
sendEvent(HtmlMediaEvent.PAUSE);
break;
case "NetStream.Play.Stop":
_isEnded = true;
_isPaused = false;
_timer.stop();
_bufferEmpty ? sendEvent(HtmlMediaEvent.ENDED) : null;
break;
}
}
private function securityErrorHandler(event:SecurityErrorEvent):void {
trace("securityErrorHandler: " + event);
}
private function asyncErrorHandler(event:AsyncErrorEvent):void {
// ignore AsyncErrorEvent events.
}
private function onMetaDataHandler(info:Object):void {
_duration = info.duration;
_framerate = info.framerate;
_videoWidth = info.width;
_videoHeight = info.height;
// set size?
sendEvent(HtmlMediaEvent.LOADEDMETADATA);
if (_isPreloading) {
_stream.pause();
_isPaused = true;
_isPreloading = false;
sendEvent(HtmlMediaEvent.PROGRESS);
sendEvent(HtmlMediaEvent.TIMEUPDATE);
}
}
// interface members
public function setSrc(url:String):void {
if (_isConnected && _stream) {
// stop and restart
_stream.pause();
}
_currentUrl = url;
_isRTMP = !!_currentUrl.match(/^rtmp(s|t|e|te)?\:\/\//);
_isConnected = false;
_hasStartedPlaying = false;
}
public function load():void {
// disconnect existing stream and connection
if (_isConnected && _stream) {
_stream.pause();
_stream.close();
_connection.close();
}
_isConnected = false;
_isPreloading = false;
// start new connection
if (_isRTMP) {
_connection.connect(_currentUrl.replace(/\/[^\/]+$/,"/"));
} else {
_connection.connect(null);
}
// in a few moments the "NetConnection.Connect.Success" event will fire
// and call createConnection which finishes the "load" sequence
sendEvent(HtmlMediaEvent.LOADSTART);
}
private function connectStream():void {
trace("connectStream");
_stream = new NetStream(_connection);
// explicitly set the sound since it could have come before the connection was made
_soundTransform = new SoundTransform(_volume);
_stream.soundTransform = _soundTransform;
_stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); // same event as connection
_stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
var customClient:Object = new Object();
customClient.onMetaData = onMetaDataHandler;
_stream.client = customClient;
_video.attachNetStream(_stream);
// start downloading without playing )based on preload and play() hasn't been called)
// I wish flash had a load() command to make this less awkward
if (_preload != "none" && !_playWhenConnected) {
_isPaused = true;
//stream.bufferTime = 20;
_stream.play(_currentUrl, 0, 0);
_stream.pause();
_isPreloading = true;
//_stream.pause();
//
//sendEvent(HtmlMediaEvent.PAUSE); // have to send this because the "playing" event gets sent via event handlers
}
_isConnected = true;
if (_playWhenConnected && !_hasStartedPlaying) {
play();
_playWhenConnected = false;
}
}
public function play():void {
if (!_hasStartedPlaying && !_isConnected) {
_playWhenConnected = true;
load();
return;
}
if (_hasStartedPlaying) {
if (_isPaused) {
_stream.resume();
_timer.start();
_isPaused = false;
sendEvent(HtmlMediaEvent.PLAY);
sendEvent(HtmlMediaEvent.PLAYING);
}
} else {
if (_isRTMP) {
_stream.play(_currentUrl.split("/").pop());
} else {
_stream.play(_currentUrl);
}
_timer.start();
_isPaused = false;
_hasStartedPlaying = true;
// don't toss play/playing events here, because we haven't sent a
// canplay / loadeddata event yet. that'll be handled in the net
// event listener
}
}
public function pause():void {
if (_stream == null)
return;
_stream.pause();
_isPaused = true;
if (_bytesLoaded == _bytesTotal) {
_timer.stop();
}
_isPaused = true;
sendEvent(HtmlMediaEvent.PAUSE);
}
public function stop():void {
if (_stream == null)
return;
_stream.close();
_isPaused = false;
_timer.stop();
sendEvent(HtmlMediaEvent.STOP);
}
public function setCurrentTime(pos:Number):void {
if (_stream == null)
return;
sendEvent(HtmlMediaEvent.SEEKING);
_stream.seek(pos);
sendEvent(HtmlMediaEvent.TIMEUPDATE);
}
public function setVolume(volume:Number):void {
if (_stream != null) {
_soundTransform = new SoundTransform(volume);
_stream.soundTransform = _soundTransform;
}
_volume = volume;
_isMuted = (_volume == 0);
sendEvent(HtmlMediaEvent.VOLUMECHANGE);
}
public function getVolume():Number {
if(_isMuted) {
return 0;
} else {
return _volume;
}
}
public function setMuted(muted:Boolean):void {
if (_isMuted == muted)
return;
if (muted) {
_oldVolume = (_stream == null) ? _oldVolume : _stream.soundTransform.volume;
setVolume(0);
} else {
setVolume(_oldVolume);
}
_isMuted = muted;
}
private function sendEvent(eventName:String) {
// calculate this to mimic HTML5
_bufferedTime = _bytesLoaded / _bytesTotal * _duration;
// build JSON
var values:String =
"duration:" + _duration +
",framerate:" + _framerate +
",currentTime:" + (_stream != null ? _stream.time : 0) +
",muted:" + _isMuted +
",paused:" + _isPaused +
",ended:" + _isEnded +
",volume:" + _volume +
",src:\"" + _currentUrl + "\"" +
",bytesTotal:" + _bytesTotal +
",bufferedBytes:" + _bytesLoaded +
",bufferedTime:" + _bufferedTime +
",videoWidth:" + _videoWidth +
",videoHeight:" + _videoHeight +
"";
_element.sendEvent(eventName, values);
}
}
}
|
package htmlelements
{
import flash.display.Sprite;
import flash.events.*;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.media.Video;
import flash.media.SoundTransform;
import flash.utils.Timer;
import FlashMediaElement;
import HtmlMediaEvent;
public class VideoElement extends Sprite implements IMediaElement
{
private var _currentUrl:String = "";
private var _autoplay:Boolean = true;
private var _preload:String = "";
private var _isPreloading:Boolean = false;
private var _connection:NetConnection;
private var _stream:NetStream;
private var _video:Video;
private var _element:FlashMediaElement;
private var _soundTransform;
private var _oldVolume:Number = 1;
// event values
private var _duration:Number = 0;
private var _framerate:Number;
private var _isPaused:Boolean = true;
private var _isEnded:Boolean = false;
private var _volume:Number = 1;
private var _isMuted:Boolean = false;
private var _bytesLoaded:Number = 0;
private var _bytesTotal:Number = 0;
private var _bufferedTime:Number = 0;
private var _bufferEmpty:Boolean = false;
private var _videoWidth:Number = -1;
private var _videoHeight:Number = -1;
private var _timer:Timer;
private var _isRTMP:Boolean = false;
private var _isConnected:Boolean = false;
private var _playWhenConnected:Boolean = false;
private var _hasStartedPlaying:Boolean = false;
private var _parentReference:Object;
public function setReference(arg:Object):void {
_parentReference = arg;
}
public function get video():Video {
return _video;
}
public function get videoHeight():Number {
return _videoHeight;
}
public function get videoWidth():Number {
return _videoWidth;
}
public function duration():Number {
return _duration;
}
public function currentProgress():Number {
if(_stream != null) {
return Math.round(_stream.bytesLoaded/_stream.bytesTotal*100);
} else {
return 0;
}
}
public function currentTime():Number {
if (_stream != null) {
return _stream.time;
} else {
return 0;
}
}
// (1) load()
// calls _connection.connect();
// waits for NetConnection.Connect.Success
// _stream gets created
public function VideoElement(element:FlashMediaElement, autoplay:Boolean, preload:String, timerRate:Number, startVolume:Number)
{
_element = element;
_autoplay = autoplay;
_volume = startVolume;
_preload = preload;
_video = new Video();
addChild(_video);
_connection = new NetConnection();
_connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
_connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
//_connection.connect(null);
_timer = new Timer(timerRate);
_timer.addEventListener("timer", timerHandler);
}
private function timerHandler(e:TimerEvent) {
_bytesLoaded = _stream.bytesLoaded;
_bytesTotal = _stream.bytesTotal;
if (!_isPaused)
sendEvent(HtmlMediaEvent.TIMEUPDATE);
//trace("bytes", _bytesLoaded, _bytesTotal);
if (_bytesLoaded < _bytesTotal)
sendEvent(HtmlMediaEvent.PROGRESS);
}
// internal events
private function netStatusHandler(event:NetStatusEvent):void {
trace("netStatus", event.info.code);
switch (event.info.code) {
case "NetStream.Buffer.Empty":
_bufferEmpty = true;
_isEnded ? sendEvent(HtmlMediaEvent.ENDED) : null;
break;
case "NetStream.Buffer.Full":
_bytesLoaded = _stream.bytesLoaded;
_bytesTotal = _stream.bytesTotal;
_bufferEmpty = false;
sendEvent(HtmlMediaEvent.PROGRESS);
break;
case "NetConnection.Connect.Success":
connectStream();
break;
case "NetStream.Play.StreamNotFound":
trace("Unable to locate video");
break;
// STREAM
case "NetStream.Play.Start":
_isPaused = false;
sendEvent(HtmlMediaEvent.LOADEDDATA);
sendEvent(HtmlMediaEvent.CANPLAY);
if (!_isPreloading) {
sendEvent(HtmlMediaEvent.PLAY);
sendEvent(HtmlMediaEvent.PLAYING);
}
_timer.start();
break;
case "NetStream.Seek.Notify":
sendEvent(HtmlMediaEvent.SEEKED);
break;
case "NetStream.Pause.Notify":
_isPaused = true;
sendEvent(HtmlMediaEvent.PAUSE);
break;
case "NetStream.Play.Stop":
_isEnded = true;
_isPaused = false;
_timer.stop();
_bufferEmpty ? sendEvent(HtmlMediaEvent.ENDED) : null;
break;
}
}
private function securityErrorHandler(event:SecurityErrorEvent):void {
trace("securityErrorHandler: " + event);
}
private function asyncErrorHandler(event:AsyncErrorEvent):void {
// ignore AsyncErrorEvent events.
}
private function onMetaDataHandler(info:Object):void {
_duration = info.duration;
_framerate = info.framerate;
_videoWidth = info.width;
_videoHeight = info.height;
// set size?
sendEvent(HtmlMediaEvent.LOADEDMETADATA);
if (_isPreloading) {
_stream.pause();
_isPaused = true;
_isPreloading = false;
sendEvent(HtmlMediaEvent.PROGRESS);
sendEvent(HtmlMediaEvent.TIMEUPDATE);
}
}
// interface members
public function setSrc(url:String):void {
if (_isConnected && _stream) {
// stop and restart
_stream.pause();
}
_currentUrl = url;
_isRTMP = !!_currentUrl.match(/^rtmp(s|t|e|te)?\:\/\//);
_isConnected = false;
_hasStartedPlaying = false;
}
public function load():void {
// disconnect existing stream and connection
if (_isConnected && _stream) {
_stream.pause();
_stream.close();
_connection.close();
}
_isConnected = false;
_isPreloading = false;
_isEnded = false;
_bufferEmpty = false;
// start new connection
if (_isRTMP) {
_connection.connect(_currentUrl.replace(/\/[^\/]+$/,"/"));
} else {
_connection.connect(null);
}
// in a few moments the "NetConnection.Connect.Success" event will fire
// and call createConnection which finishes the "load" sequence
sendEvent(HtmlMediaEvent.LOADSTART);
}
private function connectStream():void {
trace("connectStream");
_stream = new NetStream(_connection);
// explicitly set the sound since it could have come before the connection was made
_soundTransform = new SoundTransform(_volume);
_stream.soundTransform = _soundTransform;
_stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); // same event as connection
_stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
var customClient:Object = new Object();
customClient.onMetaData = onMetaDataHandler;
_stream.client = customClient;
_video.attachNetStream(_stream);
// start downloading without playing )based on preload and play() hasn't been called)
// I wish flash had a load() command to make this less awkward
if (_preload != "none" && !_playWhenConnected) {
_isPaused = true;
//stream.bufferTime = 20;
_stream.play(_currentUrl, 0, 0);
_stream.pause();
_isPreloading = true;
//_stream.pause();
//
//sendEvent(HtmlMediaEvent.PAUSE); // have to send this because the "playing" event gets sent via event handlers
}
_isConnected = true;
if (_playWhenConnected && !_hasStartedPlaying) {
play();
_playWhenConnected = false;
}
}
public function play():void {
if (!_hasStartedPlaying && !_isConnected) {
_playWhenConnected = true;
load();
return;
}
if (_hasStartedPlaying) {
if (_isPaused) {
_stream.resume();
_timer.start();
_isPaused = false;
sendEvent(HtmlMediaEvent.PLAY);
sendEvent(HtmlMediaEvent.PLAYING);
}
} else {
if (_isRTMP) {
_stream.play(_currentUrl.split("/").pop());
} else {
_stream.play(_currentUrl);
}
_timer.start();
_isPaused = false;
_hasStartedPlaying = true;
// don't toss play/playing events here, because we haven't sent a
// canplay / loadeddata event yet. that'll be handled in the net
// event listener
}
}
public function pause():void {
if (_stream == null)
return;
_stream.pause();
_isPaused = true;
if (_bytesLoaded == _bytesTotal) {
_timer.stop();
}
_isPaused = true;
sendEvent(HtmlMediaEvent.PAUSE);
}
public function stop():void {
if (_stream == null)
return;
_stream.close();
_isPaused = false;
_timer.stop();
sendEvent(HtmlMediaEvent.STOP);
}
public function setCurrentTime(pos:Number):void {
if (_stream == null)
return;
sendEvent(HtmlMediaEvent.SEEKING);
_stream.seek(pos);
sendEvent(HtmlMediaEvent.TIMEUPDATE);
}
public function setVolume(volume:Number):void {
if (_stream != null) {
_soundTransform = new SoundTransform(volume);
_stream.soundTransform = _soundTransform;
}
_volume = volume;
_isMuted = (_volume == 0);
sendEvent(HtmlMediaEvent.VOLUMECHANGE);
}
public function getVolume():Number {
if(_isMuted) {
return 0;
} else {
return _volume;
}
}
public function setMuted(muted:Boolean):void {
if (_isMuted == muted)
return;
if (muted) {
_oldVolume = (_stream == null) ? _oldVolume : _stream.soundTransform.volume;
setVolume(0);
} else {
setVolume(_oldVolume);
}
_isMuted = muted;
}
private function sendEvent(eventName:String) {
// calculate this to mimic HTML5
_bufferedTime = _bytesLoaded / _bytesTotal * _duration;
// build JSON
var values:String =
"duration:" + _duration +
",framerate:" + _framerate +
",currentTime:" + (_stream != null ? _stream.time : 0) +
",muted:" + _isMuted +
",paused:" + _isPaused +
",ended:" + _isEnded +
",volume:" + _volume +
",src:\"" + _currentUrl + "\"" +
",bytesTotal:" + _bytesTotal +
",bufferedBytes:" + _bytesLoaded +
",bufferedTime:" + _bufferedTime +
",videoWidth:" + _videoWidth +
",videoHeight:" + _videoHeight +
"";
_element.sendEvent(eventName, values);
}
}
}
|
reset variables upon load
|
reset variables upon load
|
ActionScript
|
agpl-3.0
|
libeo/Vibeo,libeo/Vibeo,libeo/Vibeo,libeo/Vibeo
|
a64c84aba0ecfb6acf8f01d7b10dc6b67a73f9ac
|
frameworks/projects/Core/src/main/flex/org/apache/flex/utils/Language.as
|
frameworks/projects/Core/src/main/flex/org/apache/flex/utils/Language.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.utils
{
[ExcludeClass]
COMPILE::AS3
public class Language {}
COMPILE::JS
{
import goog.bind;
import goog.global;
}
/**
* @flexjsignoreimport goog.bind
* @flexjsignoreimport goog.global
*/
COMPILE::JS
public class Language
{
//--------------------------------------
// Static Property
//--------------------------------------
/**
* Helper var for sortOn
*/
static private var sortNames:Array;
static private var sortNamesOne:Array = [];
static private var muler:Number;
static private var zeroStr:String = String.fromCharCode(0);
//--------------------------------------
// Static Function
//--------------------------------------
/**
* as()
*
* @param leftOperand The lefthand operand of the
* binary as operator in AS3.
* @param rightOperand The righthand operand of the
* binary operator in AS3.
* @param coercion The cast is a coercion,
* throw exception if it fails.
* @return Returns the lefthand operand if it is of the
* type of the righthand operand, otherwise null.
*/
static public function as(leftOperand:Object, rightOperand:Object, coercion:* = null):Object
{
var error:Error, itIs:Boolean, message:String;
coercion = (coercion !== undefined) ? coercion : false;
itIs = Language.is(leftOperand, rightOperand);
if (!itIs && coercion)
{
message = 'Type Coercion failed';
if (TypeError)
{
error = new TypeError(message);
}
else
{
error = new Error(message);
}
throw error;
}
return (itIs) ? leftOperand : null;
}
/**
* int()
*
* @param value The value to be cast.
* @return {number}
*/
static public function _int(value:Number):Number
{
return value >> 0;
}
/**
* is()
*
* @param leftOperand The lefthand operand of the
* binary as operator in AS3.
* @param rightOperand The righthand operand of the
* binary operator in AS3.
* @return {boolean}
*/
static public function is(leftOperand:Object, rightOperand:Object):Boolean
{
var superClass:Object;
if (leftOperand == null || rightOperand == null)
return false;
if (leftOperand instanceof rightOperand)
return true;
if (rightOperand === Object)
return true; // every value is an Object in ActionScript except null and undefined (caught above)
if (typeof leftOperand === 'string')
return rightOperand === String;
if (typeof leftOperand === 'number')
return rightOperand === Number;
if (typeof leftOperand === 'boolean')
return rightOperand === Boolean;
if (rightOperand === Array)
return Array.isArray(leftOperand);
if (leftOperand.FLEXJS_CLASS_INFO === undefined)
return false; // could be a function but not an instance
if (leftOperand.FLEXJS_CLASS_INFO.interfaces)
{
if (checkInterfaces(leftOperand, rightOperand))
{
return true;
}
}
superClass = leftOperand.constructor;
superClass = superClass.superClass_;
if (superClass)
{
while (superClass && superClass.FLEXJS_CLASS_INFO)
{
if (superClass.FLEXJS_CLASS_INFO.interfaces)
{
if (checkInterfaces(superClass, rightOperand))
{
return true;
}
}
superClass = superClass.constructor;
superClass = superClass.superClass_;
}
}
return false;
}
/**
* Helper function for is()
*/
private static function checkInterfaces(leftOperand:*, rightOperand:*):Boolean
{
var i:int, interfaces:Array;
interfaces = leftOperand.FLEXJS_CLASS_INFO.interfaces;
for (i = interfaces.length - 1; i > -1; i--) {
if (interfaces[i] === rightOperand) {
return true;
}
if (interfaces[i].prototype.FLEXJS_CLASS_INFO.interfaces) {
var isit:Boolean = checkInterfaces(interfaces[i].prototype, rightOperand);
if (isit) return true;
}
}
return false;
}
/**
* Implementation of "classDef is Class"
*/
public function isClass(classDef:*):Boolean
{
return typeof classDef === 'function'
&& classDef.prototype
&& classDef.prototype.constructor === classDef;
}
/**
* Implementation of "classDef as Class"
*/
public function asClass(classDef:*):Class
{
return isClass(classDef) ? classDef : null;
}
/**
* postdecrement handles foo--
*
* @param obj The object with the getter/setter.
* @param prop The name of a property.
* @return {number}
*/
static public function postdecrement(obj:Object, prop:String):int
{
var value:int = obj[prop];
obj[prop] = value - 1;
return value;
}
/**
* postincrement handles foo++
*
* @param obj The object with the getter/setter.
* @param prop The name of a property.
* @return {number}
*/
static public function postincrement(obj:Object, prop:String):int
{
var value:int = obj[prop];
obj[prop] = value + 1;
return value;
}
/**
* predecrement handles --foo
*
* @param obj The object with the getter/setter.
* @param prop The name of a property.
* @return {number}
*/
static public function predecrement(obj:Object, prop:String):int
{
var value:int = obj[prop] - 1;
obj[prop] = value;
return value;
}
/**
* preincrement handles ++foo
*
* @param obj The object with the getter/setter.
* @param prop The name of a property.
* @return {number}
*/
static public function preincrement(obj:Object, prop:String):int
{
var value:int = obj[prop] + 1;
obj[prop] = value;
return value;
}
/**
* superGetter calls the getter on the given class' superclass.
*
* @param clazz The class.
* @param pthis The this pointer.
* @param prop The name of the getter.
* @return {Object}
*/
static public function superGetter(clazz:Object, pthis:Object, prop:String):Object
{
var superClass:Object = clazz.superClass_;
var superdesc:Object = Object.getOwnPropertyDescriptor(superClass, prop);
while (superdesc == null)
{
superClass = superClass.constructor;
superClass = superClass.superClass_;
superdesc = Object.getOwnPropertyDescriptor(superClass, prop);
}
return superdesc.get.call(pthis);
}
/**
* superSetter calls the setter on the given class' superclass.
*
* @param clazz The class.
* @param pthis The this pointer.
* @param prop The name of the getter.
* @param value The value.
*/
static public function superSetter(clazz:Object, pthis:Object, prop:String, value:Object):void
{
var superClass:Object = clazz.superClass_;
var superdesc:Object = Object.getOwnPropertyDescriptor(superClass, prop);
while (superdesc == null)
{
superClass = superClass.constructor;
superClass = superClass.superClass_;
superdesc = Object.getOwnPropertyDescriptor(superClass, prop);
}
superdesc.set.apply(pthis, [value]);
}
static public function trace(...rest):void
{
var theConsole:*;
theConsole = goog.global.console;
if (theConsole === undefined)
{
if(typeof window !== "undefined")
{
theConsole = window.console;
}
else if(typeof console !== "undefined")
{
theConsole = console;
}
}
try
{
if (theConsole && theConsole.log)
{
theConsole.log.apply(theConsole, rest);
}
}
catch (e:Error)
{
// ignore; at least we tried ;-)
}
}
/**
* uint()
*
* @param value The value to be cast.
* @return {number}
*/
static public function uint(value:Number):Number
{
return value >>> 0;
}
/**
* caches closures and returns the one closure
*
* @param fn The method on the instance.
* @param object The instance.
* @param boundMethodName The name to use to cache the closure.
* @return The closure.
*/
static public function closure(fn:Function, object:Object, boundMethodName:String):Function {
if (object.hasOwnProperty(boundMethodName)) {
return object[boundMethodName];
}
var boundMethod:Function = goog.bind(fn, object);
Object.defineProperty(object, boundMethodName, {
value: boundMethod
});
return boundMethod;
};
/**
* @author lizhi
* @param arr
* @param names
* @param opt
*/
public static function sortOn(arr:Array,names:Object,opt:Object=0):void{
if (names is Array){
sortNames = names as Array;
}else{
sortNamesOne[0] = names;
sortNames = sortNamesOne;
}
if (opt is Array){
var opt2:int = 0;
for each(var o:int in opt){
opt2 = opt2 | o;
}
}else{
opt2 = opt as int;
}
muler = (Array.DESCENDING & opt2) > 0?-1: 1;
if(opt2&Array.NUMERIC){
arr.sort(compareNumber);
}else if (opt2&Array.CASEINSENSITIVE){
arr.sort(compareStringCaseinsensitive);
}else{
arr.sort(compareString);
}
}
private static function compareStringCaseinsensitive(a:Object, b:Object):int{
for each(var n:String in sortNames){
var v:int = (a[n]||zeroStr).toString().toLowerCase().localeCompare((b[n]||zeroStr).toString().toLowerCase());
if (v != 0){
return v*muler;
}
}
return 0;
}
private static function compareString(a:Object, b:Object):int{
for each(var n:String in sortNames){
var v:int = (a[n]||zeroStr).toString().localeCompare((b[n]||zeroStr).toString());
if (v != 0){
return v*muler;
}
}
return 0;
}
private static function compareNumber(a:Object, b:Object):int{
for each(var n:String in sortNames){
if (a[n]>b[n]){
return muler;
}else if (a[n]<b[n]){
return -muler;
}
}
return 0;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.utils
{
[ExcludeClass]
COMPILE::AS3
public class Language {}
COMPILE::JS
{
import goog.bind;
import goog.global;
}
/**
* @flexjsignoreimport goog.bind
* @flexjsignoreimport goog.global
*/
COMPILE::JS
public class Language
{
//--------------------------------------
// Static Property
//--------------------------------------
/**
* Helper var for sortOn
*/
static private var sortNames:Array;
static private var sortNamesOne:Array = [];
static private var muler:Number;
static private var zeroStr:String = String.fromCharCode(0);
//--------------------------------------
// Static Function
//--------------------------------------
/**
* as()
*
* @param leftOperand The lefthand operand of the
* binary as operator in AS3.
* @param rightOperand The righthand operand of the
* binary operator in AS3.
* @param coercion The cast is a coercion,
* throw exception if it fails.
* @return Returns the lefthand operand if it is of the
* type of the righthand operand, otherwise null.
*/
static public function as(leftOperand:Object, rightOperand:Object, coercion:* = null):Object
{
var error:Error, itIs:Boolean, message:String;
coercion = (coercion !== undefined) ? coercion : false;
itIs = Language.is(leftOperand, rightOperand);
if (!itIs && coercion)
{
message = 'Type Coercion failed';
if (TypeError)
{
error = new TypeError(message);
}
else
{
error = new Error(message);
}
throw error;
}
return (itIs) ? leftOperand : null;
}
/**
* int()
*
* @param value The value to be cast.
* @return {number}
*/
static public function _int(value:Number):Number
{
return value >> 0;
}
/**
* is()
*
* @param leftOperand The lefthand operand of the
* binary as operator in AS3.
* @param rightOperand The righthand operand of the
* binary operator in AS3.
* @return {boolean}
*/
static public function is(leftOperand:Object, rightOperand:Object):Boolean
{
var superClass:Object;
if (leftOperand == null || rightOperand == null)
return false;
if (leftOperand instanceof rightOperand)
return true;
if (rightOperand === Object)
return true; // every value is an Object in ActionScript except null and undefined (caught above)
if (typeof leftOperand === 'string')
return rightOperand === String;
if (typeof leftOperand === 'number')
return rightOperand === Number;
if (typeof leftOperand === 'boolean')
return rightOperand === Boolean;
if (rightOperand === Array)
return Array.isArray(leftOperand);
if (leftOperand.FLEXJS_CLASS_INFO === undefined)
return false; // could be a function but not an instance
if (leftOperand.FLEXJS_CLASS_INFO.interfaces)
{
if (checkInterfaces(leftOperand, rightOperand))
{
return true;
}
}
superClass = leftOperand.constructor;
superClass = superClass.superClass_;
if (superClass)
{
while (superClass && superClass.FLEXJS_CLASS_INFO)
{
if (superClass.FLEXJS_CLASS_INFO.interfaces)
{
if (checkInterfaces(superClass, rightOperand))
{
return true;
}
}
superClass = superClass.constructor;
superClass = superClass.superClass_;
}
}
return false;
}
/**
* Helper function for is()
*/
private static function checkInterfaces(leftOperand:*, rightOperand:*):Boolean
{
var i:int, interfaces:Array;
interfaces = leftOperand.FLEXJS_CLASS_INFO.interfaces;
for (i = interfaces.length - 1; i > -1; i--) {
if (interfaces[i] === rightOperand) {
return true;
}
if (interfaces[i].prototype.FLEXJS_CLASS_INFO.interfaces) {
var isit:Boolean = checkInterfaces(interfaces[i].prototype, rightOperand);
if (isit) return true;
}
}
return false;
}
/**
* Implementation of "classDef is Class"
*/
public function isClass(classDef:*):Boolean
{
return typeof classDef === 'function'
&& classDef.prototype
&& classDef.prototype.constructor === classDef;
}
/**
* Implementation of "classDef as Class"
*/
public function asClass(classDef:*):Class
{
return isClass(classDef) ? classDef : null;
}
/**
* postdecrement handles foo--
*
* @param obj The object with the getter/setter.
* @param prop The name of a property.
* @return {number}
*/
static public function postdecrement(obj:Object, prop:String):int
{
var value:int = obj[prop];
obj[prop] = value - 1;
return value;
}
/**
* postincrement handles foo++
*
* @param obj The object with the getter/setter.
* @param prop The name of a property.
* @return {number}
*/
static public function postincrement(obj:Object, prop:String):int
{
var value:int = obj[prop];
obj[prop] = value + 1;
return value;
}
/**
* predecrement handles --foo
*
* @param obj The object with the getter/setter.
* @param prop The name of a property.
* @return {number}
*/
static public function predecrement(obj:Object, prop:String):int
{
var value:int = obj[prop] - 1;
obj[prop] = value;
return value;
}
/**
* preincrement handles ++foo
*
* @param obj The object with the getter/setter.
* @param prop The name of a property.
* @return {number}
*/
static public function preincrement(obj:Object, prop:String):int
{
var value:int = obj[prop] + 1;
obj[prop] = value;
return value;
}
/**
* superGetter calls the getter on the given class' superclass.
*
* @param clazz The class.
* @param pthis The this pointer.
* @param prop The name of the getter.
* @return {Object}
*/
static public function superGetter(clazz:Object, pthis:Object, prop:String):Object
{
var superClass:Object = clazz.superClass_;
var superdesc:Object = Object.getOwnPropertyDescriptor(superClass, prop);
while (superdesc == null)
{
superClass = superClass.constructor;
superClass = superClass.superClass_;
superdesc = Object.getOwnPropertyDescriptor(superClass, prop);
}
return superdesc.get.call(pthis);
}
/**
* superSetter calls the setter on the given class' superclass.
*
* @param clazz The class.
* @param pthis The this pointer.
* @param prop The name of the getter.
* @param value The value.
*/
static public function superSetter(clazz:Object, pthis:Object, prop:String, value:Object):void
{
var superClass:Object = clazz.superClass_;
var superdesc:Object = Object.getOwnPropertyDescriptor(superClass, prop);
while (superdesc == null)
{
superClass = superClass.constructor;
superClass = superClass.superClass_;
superdesc = Object.getOwnPropertyDescriptor(superClass, prop);
}
superdesc.set.apply(pthis, [value]);
}
static public function trace(...rest):void
{
var theConsole:*;
theConsole = goog.global.console;
if (theConsole === undefined)
{
if(typeof window !== "undefined")
{
theConsole = window.console;
}
else if(typeof console !== "undefined")
{
theConsole = console;
}
}
try
{
if (theConsole && theConsole.log)
{
theConsole.log.apply(theConsole, rest);
}
}
catch (e:Error)
{
// ignore; at least we tried ;-)
}
}
/**
* uint()
*
* @param value The value to be cast.
* @return {number}
*/
static public function uint(value:Number):Number
{
return value >>> 0;
}
/**
* caches closures and returns the one closure
*
* @param fn The method on the instance.
* @param object The instance.
* @param boundMethodName The name to use to cache the closure.
* @return The closure.
*/
static public function closure(fn:Function, object:Object, boundMethodName:String):Function {
if (object.hasOwnProperty(boundMethodName)) {
return object[boundMethodName];
}
var boundMethod:Function = goog.bind(fn, object);
Object.defineProperty(object, boundMethodName, {
value: boundMethod
});
return boundMethod;
};
/**
* @param arr
* @param names
* @param opt
*/
public static function sortOn(arr:Array,names:Object,opt:Object=0):void{
if (names is Array){
sortNames = names as Array;
}else{
sortNamesOne[0] = names;
sortNames = sortNamesOne;
}
if (opt is Array){
var opt2:int = 0;
for each(var o:int in opt){
opt2 = opt2 | o;
}
}else{
opt2 = opt as int;
}
muler = (Array.DESCENDING & opt2) > 0?-1: 1;
if(opt2&Array.NUMERIC){
arr.sort(compareNumber);
}else if (opt2&Array.CASEINSENSITIVE){
arr.sort(compareStringCaseinsensitive);
}else{
arr.sort(compareString);
}
}
private static function compareStringCaseinsensitive(a:Object, b:Object):int{
for each(var n:String in sortNames){
var v:int = (a[n]||zeroStr).toString().toLowerCase().localeCompare((b[n]||zeroStr).toString().toLowerCase());
if (v != 0){
return v*muler;
}
}
return 0;
}
private static function compareString(a:Object, b:Object):int{
for each(var n:String in sortNames){
var v:int = (a[n]||zeroStr).toString().localeCompare((b[n]||zeroStr).toString());
if (v != 0){
return v*muler;
}
}
return 0;
}
private static function compareNumber(a:Object, b:Object):int{
for each(var n:String in sortNames){
if (a[n]>b[n]){
return muler;
}else if (a[n]<b[n]){
return -muler;
}
}
return 0;
}
}
}
|
remove tag
|
remove tag
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
83a703a35c29e4465e2744c51bf9f5e7d0e0786d
|
src/flash/htmlelements/VideoElement.as
|
src/flash/htmlelements/VideoElement.as
|
package htmlelements
{
import flash.display.Sprite;
import flash.events.*;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.media.Video;
import flash.media.SoundTransform;
import flash.utils.Timer;
import FlashMediaElement;
import HtmlMediaEvent;
public class VideoElement extends Sprite implements IMediaElement
{
private var _currentUrl:String = "";
private var _autoplay:Boolean = true;
private var _preload:String = "";
private var _isPreloading:Boolean = false;
private var _connection:NetConnection;
private var _stream:NetStream;
private var _video:Video;
private var _element:FlashMediaElement;
private var _soundTransform;
private var _oldVolume:Number = 1;
// event values
private var _duration:Number = 0;
private var _framerate:Number;
private var _isPaused:Boolean = true;
private var _isEnded:Boolean = false;
private var _volume:Number = 1;
private var _isMuted:Boolean = false;
private var _bytesLoaded:Number = 0;
private var _bytesTotal:Number = 0;
private var _bufferedTime:Number = 0;
private var _bufferEmpty:Boolean = false;
private var _videoWidth:Number = -1;
private var _videoHeight:Number = -1;
private var _timer:Timer;
private var _isRTMP:Boolean = false;
private var _isConnected:Boolean = false;
private var _playWhenConnected:Boolean = false;
private var _hasStartedPlaying:Boolean = false;
private var _parentReference:Object;
public function setReference(arg:Object):void {
_parentReference = arg;
}
public function setSize(width:Number, height:Number):void {
_video.width = width;
_video.height = height;
}
public function get video():Video {
return _video;
}
public function get videoHeight():Number {
return _videoHeight;
}
public function get videoWidth():Number {
return _videoWidth;
}
public function duration():Number {
return _duration;
}
public function currentProgress():Number {
if(_stream != null) {
return Math.round(_stream.bytesLoaded/_stream.bytesTotal*100);
} else {
return 0;
}
}
public function currentTime():Number {
if (_stream != null) {
return _stream.time;
} else {
return 0;
}
}
// (1) load()
// calls _connection.connect();
// waits for NetConnection.Connect.Success
// _stream gets created
public function VideoElement(element:FlashMediaElement, autoplay:Boolean, preload:String, timerRate:Number, startVolume:Number)
{
_element = element;
_autoplay = autoplay;
_volume = startVolume;
_preload = preload;
_video = new Video();
addChild(_video);
_connection = new NetConnection();
_connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
_connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
//_connection.connect(null);
_timer = new Timer(timerRate);
_timer.addEventListener("timer", timerHandler);
}
private function timerHandler(e:TimerEvent) {
_bytesLoaded = _stream.bytesLoaded;
_bytesTotal = _stream.bytesTotal;
if (!_isPaused)
sendEvent(HtmlMediaEvent.TIMEUPDATE);
//trace("bytes", _bytesLoaded, _bytesTotal);
if (_bytesLoaded < _bytesTotal)
sendEvent(HtmlMediaEvent.PROGRESS);
}
// internal events
private function netStatusHandler(event:NetStatusEvent):void {
trace("netStatus", event.info.code);
switch (event.info.code) {
case "NetStream.Buffer.Empty":
_bufferEmpty = true;
_isEnded ? sendEvent(HtmlMediaEvent.ENDED) : null;
break;
case "NetStream.Buffer.Full":
_bytesLoaded = _stream.bytesLoaded;
_bytesTotal = _stream.bytesTotal;
_bufferEmpty = false;
sendEvent(HtmlMediaEvent.PROGRESS);
break;
case "NetConnection.Connect.Success":
connectStream();
break;
case "NetStream.Play.StreamNotFound":
trace("Unable to locate video");
break;
// STREAM
case "NetStream.Play.Start":
_isPaused = false;
sendEvent(HtmlMediaEvent.LOADEDDATA);
sendEvent(HtmlMediaEvent.CANPLAY);
if (!_isPreloading) {
sendEvent(HtmlMediaEvent.PLAY);
sendEvent(HtmlMediaEvent.PLAYING);
}
_timer.start();
break;
case "NetStream.Seek.Notify":
sendEvent(HtmlMediaEvent.SEEKED);
break;
case "NetStream.Pause.Notify":
_isPaused = true;
sendEvent(HtmlMediaEvent.PAUSE);
break;
case "NetStream.Play.Stop":
_isEnded = true;
_isPaused = false;
_timer.stop();
_bufferEmpty ? sendEvent(HtmlMediaEvent.ENDED) : null;
break;
}
}
private function securityErrorHandler(event:SecurityErrorEvent):void {
trace("securityErrorHandler: " + event);
}
private function asyncErrorHandler(event:AsyncErrorEvent):void {
// ignore AsyncErrorEvent events.
}
private function onMetaDataHandler(info:Object):void {
_duration = info.duration;
_framerate = info.framerate;
_videoWidth = info.width;
_videoHeight = info.height;
// set size?
sendEvent(HtmlMediaEvent.LOADEDMETADATA);
if (_isPreloading) {
_stream.pause();
_isPaused = true;
_isPreloading = false;
sendEvent(HtmlMediaEvent.PROGRESS);
sendEvent(HtmlMediaEvent.TIMEUPDATE);
}
}
// interface members
public function setSrc(url:String):void {
if (_isConnected && _stream) {
// stop and restart
_stream.pause();
}
_currentUrl = url;
_isRTMP = !!_currentUrl.match(/^rtmp(s|t|e|te)?\:\/\//);
_isConnected = false;
_hasStartedPlaying = false;
}
public function load():void {
// disconnect existing stream and connection
if (_isConnected && _stream) {
_stream.pause();
_stream.close();
_connection.close();
}
_isConnected = false;
_isPreloading = false;
_isEnded = false;
_bufferEmpty = false;
// start new connection
if (_isRTMP) {
var rtmpInfo:Object = parseRTMP(_currentUrl);
_connection.connect(rtmpInfo.server);
} else {
_connection.connect(null);
}
// in a few moments the "NetConnection.Connect.Success" event will fire
// and call createConnection which finishes the "load" sequence
sendEvent(HtmlMediaEvent.LOADSTART);
}
private function connectStream():void {
trace("connectStream");
_stream = new NetStream(_connection);
// explicitly set the sound since it could have come before the connection was made
_soundTransform = new SoundTransform(_volume);
_stream.soundTransform = _soundTransform;
_stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); // same event as connection
_stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
var customClient:Object = new Object();
customClient.onMetaData = onMetaDataHandler;
_stream.client = customClient;
_video.attachNetStream(_stream);
// start downloading without playing )based on preload and play() hasn't been called)
// I wish flash had a load() command to make this less awkward
if (_preload != "none" && !_playWhenConnected) {
_isPaused = true;
//stream.bufferTime = 20;
_stream.play(_currentUrl, 0, 0);
_stream.pause();
_isPreloading = true;
//_stream.pause();
//
//sendEvent(HtmlMediaEvent.PAUSE); // have to send this because the "playing" event gets sent via event handlers
}
_isConnected = true;
if (_playWhenConnected && !_hasStartedPlaying) {
play();
_playWhenConnected = false;
}
}
public function play():void {
if (!_hasStartedPlaying && !_isConnected) {
_playWhenConnected = true;
load();
return;
}
if (_hasStartedPlaying) {
if (_isPaused) {
_stream.resume();
_timer.start();
_isPaused = false;
sendEvent(HtmlMediaEvent.PLAY);
sendEvent(HtmlMediaEvent.PLAYING);
}
} else {
if (_isRTMP) {
var rtmpInfo:Object = parseRTMP(_currentUrl);
_stream.play(rtmpInfo.stream);
} else {
_stream.play(_currentUrl);
}
_timer.start();
_isPaused = false;
_hasStartedPlaying = true;
// don't toss play/playing events here, because we haven't sent a
// canplay / loadeddata event yet. that'll be handled in the net
// event listener
}
}
public function pause():void {
if (_stream == null)
return;
_stream.pause();
_isPaused = true;
if (_bytesLoaded == _bytesTotal) {
_timer.stop();
}
_isPaused = true;
sendEvent(HtmlMediaEvent.PAUSE);
}
public function stop():void {
if (_stream == null)
return;
_stream.close();
_isPaused = false;
_timer.stop();
sendEvent(HtmlMediaEvent.STOP);
}
public function setCurrentTime(pos:Number):void {
if (_stream == null)
return;
sendEvent(HtmlMediaEvent.SEEKING);
_stream.seek(pos);
sendEvent(HtmlMediaEvent.TIMEUPDATE);
}
public function setVolume(volume:Number):void {
if (_stream != null) {
_soundTransform = new SoundTransform(volume);
_stream.soundTransform = _soundTransform;
}
_volume = volume;
_isMuted = (_volume == 0);
sendEvent(HtmlMediaEvent.VOLUMECHANGE);
}
public function getVolume():Number {
if(_isMuted) {
return 0;
} else {
return _volume;
}
}
public function setMuted(muted:Boolean):void {
if (_isMuted == muted)
return;
if (muted) {
_oldVolume = (_stream == null) ? _oldVolume : _stream.soundTransform.volume;
setVolume(0);
} else {
setVolume(_oldVolume);
}
_isMuted = muted;
}
private function sendEvent(eventName:String) {
// calculate this to mimic HTML5
_bufferedTime = _bytesLoaded / _bytesTotal * _duration;
// build JSON
var values:String =
"duration:" + _duration +
",framerate:" + _framerate +
",currentTime:" + (_stream != null ? _stream.time : 0) +
",muted:" + _isMuted +
",paused:" + _isPaused +
",ended:" + _isEnded +
",volume:" + _volume +
",src:\"" + _currentUrl + "\"" +
",bytesTotal:" + _bytesTotal +
",bufferedBytes:" + _bytesLoaded +
",bufferedTime:" + _bufferedTime +
",videoWidth:" + _videoWidth +
",videoHeight:" + _videoHeight +
"";
_element.sendEvent(eventName, values);
}
private function parseRTMP(url:String) {
var match:Array = url.match(/(.*)\/((flv|mp4|mp3):.*)/);
var rtmpInfo:Object = {
server: null,
stream: null
};
if (match) {
rtmpInfo.server = match[1];
rtmpInfo.stream = match[2];
}
else {
rtmpInfo.server = url.replace(/\/[^\/]+$/,"/");
rtmpInfo.stream = url.split("/").pop();
}
trace("parseRTMP - server: " + rtmpInfo.server + " stream: " + rtmpInfo.stream);
return rtmpInfo;
}
}
}
|
package htmlelements
{
import flash.display.Sprite;
import flash.events.*;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.media.Video;
import flash.media.SoundTransform;
import flash.utils.Timer;
import FlashMediaElement;
import HtmlMediaEvent;
public class VideoElement extends Sprite implements IMediaElement
{
private var _currentUrl:String = "";
private var _autoplay:Boolean = true;
private var _preload:String = "";
private var _isPreloading:Boolean = false;
private var _connection:NetConnection;
private var _stream:NetStream;
private var _video:Video;
private var _element:FlashMediaElement;
private var _soundTransform;
private var _oldVolume:Number = 1;
// event values
private var _duration:Number = 0;
private var _framerate:Number;
private var _isPaused:Boolean = true;
private var _isEnded:Boolean = false;
private var _volume:Number = 1;
private var _isMuted:Boolean = false;
private var _bytesLoaded:Number = 0;
private var _bytesTotal:Number = 0;
private var _bufferedTime:Number = 0;
private var _bufferEmpty:Boolean = false;
private var _videoWidth:Number = -1;
private var _videoHeight:Number = -1;
private var _timer:Timer;
private var _isRTMP:Boolean = false;
private var _isConnected:Boolean = false;
private var _playWhenConnected:Boolean = false;
private var _hasStartedPlaying:Boolean = false;
private var _parentReference:Object;
public function setReference(arg:Object):void {
_parentReference = arg;
}
public function setSize(width:Number, height:Number):void {
_video.width = width;
_video.height = height;
}
public function get video():Video {
return _video;
}
public function get videoHeight():Number {
return _videoHeight;
}
public function get videoWidth():Number {
return _videoWidth;
}
public function duration():Number {
return _duration;
}
public function currentProgress():Number {
if(_stream != null) {
return Math.round(_stream.bytesLoaded/_stream.bytesTotal*100);
} else {
return 0;
}
}
public function currentTime():Number {
if (_stream != null) {
return _stream.time;
} else {
return 0;
}
}
// (1) load()
// calls _connection.connect();
// waits for NetConnection.Connect.Success
// _stream gets created
public function VideoElement(element:FlashMediaElement, autoplay:Boolean, preload:String, timerRate:Number, startVolume:Number)
{
_element = element;
_autoplay = autoplay;
_volume = startVolume;
_preload = preload;
_video = new Video();
addChild(_video);
_connection = new NetConnection();
_connection.client = { onBWDone: function():void{} };
_connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
_connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
//_connection.connect(null);
_timer = new Timer(timerRate);
_timer.addEventListener("timer", timerHandler);
}
private function timerHandler(e:TimerEvent) {
_bytesLoaded = _stream.bytesLoaded;
_bytesTotal = _stream.bytesTotal;
if (!_isPaused)
sendEvent(HtmlMediaEvent.TIMEUPDATE);
//trace("bytes", _bytesLoaded, _bytesTotal);
if (_bytesLoaded < _bytesTotal)
sendEvent(HtmlMediaEvent.PROGRESS);
}
// internal events
private function netStatusHandler(event:NetStatusEvent):void {
trace("netStatus", event.info.code);
switch (event.info.code) {
case "NetStream.Buffer.Empty":
_bufferEmpty = true;
_isEnded ? sendEvent(HtmlMediaEvent.ENDED) : null;
break;
case "NetStream.Buffer.Full":
_bytesLoaded = _stream.bytesLoaded;
_bytesTotal = _stream.bytesTotal;
_bufferEmpty = false;
sendEvent(HtmlMediaEvent.PROGRESS);
break;
case "NetConnection.Connect.Success":
connectStream();
break;
case "NetStream.Play.StreamNotFound":
trace("Unable to locate video");
break;
// STREAM
case "NetStream.Play.Start":
_isPaused = false;
sendEvent(HtmlMediaEvent.LOADEDDATA);
sendEvent(HtmlMediaEvent.CANPLAY);
if (!_isPreloading) {
sendEvent(HtmlMediaEvent.PLAY);
sendEvent(HtmlMediaEvent.PLAYING);
}
_timer.start();
break;
case "NetStream.Seek.Notify":
sendEvent(HtmlMediaEvent.SEEKED);
break;
case "NetStream.Pause.Notify":
_isPaused = true;
sendEvent(HtmlMediaEvent.PAUSE);
break;
case "NetStream.Play.Stop":
_isEnded = true;
_isPaused = false;
_timer.stop();
_bufferEmpty ? sendEvent(HtmlMediaEvent.ENDED) : null;
break;
}
}
private function securityErrorHandler(event:SecurityErrorEvent):void {
trace("securityErrorHandler: " + event);
}
private function asyncErrorHandler(event:AsyncErrorEvent):void {
// ignore AsyncErrorEvent events.
}
private function onMetaDataHandler(info:Object):void {
_duration = info.duration;
_framerate = info.framerate;
_videoWidth = info.width;
_videoHeight = info.height;
// set size?
sendEvent(HtmlMediaEvent.LOADEDMETADATA);
if (_isPreloading) {
_stream.pause();
_isPaused = true;
_isPreloading = false;
sendEvent(HtmlMediaEvent.PROGRESS);
sendEvent(HtmlMediaEvent.TIMEUPDATE);
}
}
// interface members
public function setSrc(url:String):void {
if (_isConnected && _stream) {
// stop and restart
_stream.pause();
}
_currentUrl = url;
_isRTMP = !!_currentUrl.match(/^rtmp(s|t|e|te)?\:\/\//);
_isConnected = false;
_hasStartedPlaying = false;
}
public function load():void {
// disconnect existing stream and connection
if (_isConnected && _stream) {
_stream.pause();
_stream.close();
_connection.close();
}
_isConnected = false;
_isPreloading = false;
_isEnded = false;
_bufferEmpty = false;
// start new connection
if (_isRTMP) {
var rtmpInfo:Object = parseRTMP(_currentUrl);
_connection.connect(rtmpInfo.server);
} else {
_connection.connect(null);
}
// in a few moments the "NetConnection.Connect.Success" event will fire
// and call createConnection which finishes the "load" sequence
sendEvent(HtmlMediaEvent.LOADSTART);
}
private function connectStream():void {
trace("connectStream");
_stream = new NetStream(_connection);
// explicitly set the sound since it could have come before the connection was made
_soundTransform = new SoundTransform(_volume);
_stream.soundTransform = _soundTransform;
_stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); // same event as connection
_stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
var customClient:Object = new Object();
customClient.onMetaData = onMetaDataHandler;
_stream.client = customClient;
_video.attachNetStream(_stream);
// start downloading without playing )based on preload and play() hasn't been called)
// I wish flash had a load() command to make this less awkward
if (_preload != "none" && !_playWhenConnected) {
_isPaused = true;
//stream.bufferTime = 20;
_stream.play(_currentUrl, 0, 0);
_stream.pause();
_isPreloading = true;
//_stream.pause();
//
//sendEvent(HtmlMediaEvent.PAUSE); // have to send this because the "playing" event gets sent via event handlers
}
_isConnected = true;
if (_playWhenConnected && !_hasStartedPlaying) {
play();
_playWhenConnected = false;
}
}
public function play():void {
if (!_hasStartedPlaying && !_isConnected) {
_playWhenConnected = true;
load();
return;
}
if (_hasStartedPlaying) {
if (_isPaused) {
_stream.resume();
_timer.start();
_isPaused = false;
sendEvent(HtmlMediaEvent.PLAY);
sendEvent(HtmlMediaEvent.PLAYING);
}
} else {
if (_isRTMP) {
var rtmpInfo:Object = parseRTMP(_currentUrl);
_stream.play(rtmpInfo.stream);
} else {
_stream.play(_currentUrl);
}
_timer.start();
_isPaused = false;
_hasStartedPlaying = true;
// don't toss play/playing events here, because we haven't sent a
// canplay / loadeddata event yet. that'll be handled in the net
// event listener
}
}
public function pause():void {
if (_stream == null)
return;
_stream.pause();
_isPaused = true;
if (_bytesLoaded == _bytesTotal) {
_timer.stop();
}
_isPaused = true;
sendEvent(HtmlMediaEvent.PAUSE);
}
public function stop():void {
if (_stream == null)
return;
_stream.close();
_isPaused = false;
_timer.stop();
sendEvent(HtmlMediaEvent.STOP);
}
public function setCurrentTime(pos:Number):void {
if (_stream == null)
return;
sendEvent(HtmlMediaEvent.SEEKING);
_stream.seek(pos);
sendEvent(HtmlMediaEvent.TIMEUPDATE);
}
public function setVolume(volume:Number):void {
if (_stream != null) {
_soundTransform = new SoundTransform(volume);
_stream.soundTransform = _soundTransform;
}
_volume = volume;
_isMuted = (_volume == 0);
sendEvent(HtmlMediaEvent.VOLUMECHANGE);
}
public function getVolume():Number {
if(_isMuted) {
return 0;
} else {
return _volume;
}
}
public function setMuted(muted:Boolean):void {
if (_isMuted == muted)
return;
if (muted) {
_oldVolume = (_stream == null) ? _oldVolume : _stream.soundTransform.volume;
setVolume(0);
} else {
setVolume(_oldVolume);
}
_isMuted = muted;
}
private function sendEvent(eventName:String) {
// calculate this to mimic HTML5
_bufferedTime = _bytesLoaded / _bytesTotal * _duration;
// build JSON
var values:String =
"duration:" + _duration +
",framerate:" + _framerate +
",currentTime:" + (_stream != null ? _stream.time : 0) +
",muted:" + _isMuted +
",paused:" + _isPaused +
",ended:" + _isEnded +
",volume:" + _volume +
",src:\"" + _currentUrl + "\"" +
",bytesTotal:" + _bytesTotal +
",bufferedBytes:" + _bytesLoaded +
",bufferedTime:" + _bufferedTime +
",videoWidth:" + _videoWidth +
",videoHeight:" + _videoHeight +
"";
_element.sendEvent(eventName, values);
}
private function parseRTMP(url:String) {
var match:Array = url.match(/(.*)\/((flv|mp4|mp3):.*)/);
var rtmpInfo:Object = {
server: null,
stream: null
};
if (match) {
rtmpInfo.server = match[1];
rtmpInfo.stream = match[2];
}
else {
rtmpInfo.server = url.replace(/\/[^\/]+$/,"/");
rtmpInfo.stream = url.split("/").pop();
}
trace("parseRTMP - server: " + rtmpInfo.server + " stream: " + rtmpInfo.stream);
return rtmpInfo;
}
}
}
|
Add onBWDone handler to remove errors. See http://stackoverflow.com/questions/2296822/flash-as3-streaming-player-onbwdone
|
Add onBWDone handler to remove errors. See http://stackoverflow.com/questions/2296822/flash-as3-streaming-player-onbwdone
|
ActionScript
|
agpl-3.0
|
libeo/Vibeo,libeo/Vibeo,libeo/Vibeo,libeo/Vibeo
|
8a90a72d5a748b2bbd0cf586a32e7d249521d6ce
|
src/ageofai/home/view/HomeMediator.as
|
src/ageofai/home/view/HomeMediator.as
|
/**
* Created by newkrok on 08/04/16.
*/
package ageofai.home.view
{
<<<<<<< HEAD
import ageofai.home.event.HomeEvent;
import ageofai.home.view.event.HomeViewEvent;
import common.mvc.view.base.ABaseMediator;
public class HomeMediator extends ABaseMediator
{
[Inject]
public var view:HomeView;
override public function initialize():void
{
this.addContextListener( HomeEvent.REQUEST_TO_CREATE_VILLAGER, this.villagerCredatedEventHandler );
this.addContextListener( HomeEvent.VILLAGER_CREATION_IN_PROGRESS, this.villagerCreatingInProgressEventHandler );
this.addContextListener( HomeEvent.FOOD_AMOUNT_UPDATED, this.foodAmountUpdatedHandler );
this.addContextListener( HomeEvent.WOOD_AMOUNT_UPDATED, this.woodAmountUpdatedHandler );
this.addViewListener( HomeViewEvent.VILLAGER_VIEW_CREATED, this.villageViewCreatedHandler );
}
private function villageViewCreatedHandler( e:HomeViewEvent ):void
{
var homeEvent:HomeEvent = new HomeEvent( HomeEvent.VILLAGER_VIEW_CREATED );
homeEvent.villagerView = e.villagerView;
homeEvent.homeVO = e.homeVO;
this.dispatch( homeEvent );
}
private function villagerCredatedEventHandler( e:HomeEvent ):void
{
this.view.createVillagerView( e.homeVO );
}
private function villagerCreatingInProgressEventHandler( e:HomeEvent ):void
{
this.view.showProgressValue( e.progressPercentage / 100 );
}
private function foodAmountUpdatedHandler( event:HomeEvent ):void
{
this.view.updateFoodAmount( event.homeVO.food );
}
private function woodAmountUpdatedHandler( event:HomeEvent ):void
{
this.view.updateWoodAmount( event.homeVO.wood );
}
}
=======
import ageofai.home.event.HomeEvent;
import ageofai.home.view.event.HomeViewEvent;
import ageofai.home.vo.HomeVO;
import common.mvc.view.base.ABaseMediator;
public class HomeMediator extends ABaseMediator
{
[Inject]
public var view:HomeView;
override public function initialize():void
{
this.addContextListener( HomeEvent.REQUEST_TO_CREATE_VILLAGER, this.villagerCredatedEventHandler );
this.addContextListener( HomeEvent.VILLAGER_CREATION_IN_PROGRESS, this.villagerCreatingInProgressEventHandler );
this.addContextListener( HomeEvent.FOOD_AMOUNT_UPDATED, this.foodAmountUpdatedHandler );
this.addContextListener( HomeEvent.WOOD_AMOUNT_UPDATED, this.woodAmountUpdatedHandler );
this.addViewListener( HomeViewEvent.VILLAGER_VIEW_CREATED, this.villagerViewCreatedHandler );
}
private function villagerViewCreatedHandler( e:HomeViewEvent ):void
{
if (e.homeVO.id != this.view.id) return;
var homeEvent:HomeEvent = new HomeEvent( HomeEvent.VILLAGER_VIEW_CREATED );
homeEvent.villagerView = e.villagerView;
homeEvent.homeVO = e.homeVO;
this.dispatch( homeEvent );
}
private function villagerCredatedEventHandler( e:HomeEvent ):void
{
if (e.homeVO.id != this.view.id) return;
this.view.createVillagerView( e.homeVO );
}
private function villagerCreatingInProgressEventHandler( e:HomeEvent ):void
{
if (e.homeVO.id != this.view.id) return;
this.view.showProgressValue( e.progressPercentage / 100 );
}
private function foodAmountUpdatedHandler( home:HomeVO ):void
{
this.view.updateFoodAmount( home.food );
}
private function woodAmountUpdatedHandler( home:HomeVO ):void
{
this.view.updateWoodAmount( home.wood );
}
}
>>>>>>> origin/master
}
|
/**
* Created by newkrok on 08/04/16.
*/
package ageofai.home.view
{
import ageofai.home.event.HomeEvent;
import ageofai.home.view.event.HomeViewEvent;
import ageofai.home.vo.HomeVO;
import common.mvc.view.base.ABaseMediator;
public class HomeMediator extends ABaseMediator
{
[Inject]
public var view:HomeView;
override public function initialize():void
{
this.addContextListener( HomeEvent.REQUEST_TO_CREATE_VILLAGER, this.villagerCredatedEventHandler );
this.addContextListener( HomeEvent.VILLAGER_CREATION_IN_PROGRESS, this.villagerCreatingInProgressEventHandler );
this.addContextListener( HomeEvent.FOOD_AMOUNT_UPDATED, this.foodAmountUpdatedHandler );
this.addContextListener( HomeEvent.WOOD_AMOUNT_UPDATED, this.woodAmountUpdatedHandler );
this.addViewListener( HomeViewEvent.VILLAGER_VIEW_CREATED, this.villagerViewCreatedHandler );
}
private function villagerViewCreatedHandler( e:HomeViewEvent ):void
{
if (e.homeVO.id != this.view.id) return;
var homeEvent:HomeEvent = new HomeEvent( HomeEvent.VILLAGER_VIEW_CREATED );
homeEvent.villagerView = e.villagerView;
homeEvent.homeVO = e.homeVO;
this.dispatch( homeEvent );
}
private function villagerCredatedEventHandler( e:HomeEvent ):void
{
if (e.homeVO.id != this.view.id) return;
this.view.createVillagerView( e.homeVO );
}
private function villagerCreatingInProgressEventHandler( e:HomeEvent ):void
{
if (e.homeVO.id != this.view.id) return;
this.view.showProgressValue( e.progressPercentage / 100 );
}
private function foodAmountUpdatedHandler( event:HomeEvent ):void
{
if (event.homeVO.id != this.view.id) return;
this.view.updateFoodAmount( event.homeVO.food );
}
private function woodAmountUpdatedHandler( event:HomeEvent ):void
{
if (event.homeVO.id != this.view.id) return;
this.view.updateWoodAmount( event.homeVO.wood );
}
}
}
|
Fix merge conflict
|
Fix merge conflict
|
ActionScript
|
apache-2.0
|
goc-flashplusplus/ageofai
|
766b7a3380e59c61c66bd99c63bdec47387115d4
|
snowplow-as3-tracker/src/com/snowplowanalytics/snowplow/tracker/emitter/Emitter.as
|
snowplow-as3-tracker/src/com/snowplowanalytics/snowplow/tracker/emitter/Emitter.as
|
/*
* Copyright (c) 2015 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.snowplowanalytics.snowplow.tracker.emitter
{
import com.adobe.net.URI;
import com.snowplowanalytics.snowplow.tracker.Constants;
import com.snowplowanalytics.snowplow.tracker.Util;
import com.snowplowanalytics.snowplow.tracker.event.EmitterEvent;
import com.snowplowanalytics.snowplow.tracker.payload.IPayload;
import com.snowplowanalytics.snowplow.tracker.payload.SchemaPayload;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
public class Emitter extends EventDispatcher
{
private var _uri:URI;
private var _buffer:Array = [];
protected var bufferSize:int = BufferOption.DEFAULT;
protected var httpMethod:String = URLRequestMethod.GET;
/**
* Create an Emitter instance with a collector URL and HttpMethod to send requests.
* @param URI The collector URL. Don't include "http://" - this is done automatically.
* @param httpMethod The HTTP request method. If GET, <code>BufferOption</code> is set to <code>Instant</code>.
* @param successCallback The callback function to handle success cases when sending events.
* @param errorCallback The callback function to handle error cases when sending events.
*/
public function Emitter(uri:String, httpMethod:String = URLRequestMethod.GET) {
if (httpMethod == URLRequestMethod.GET) {
_uri = new URI("http://" + uri + "/i");
} else { // POST
_uri = new URI("http://" + uri + "/" + Constants.PROTOCOL_VENDOR + "/" + Constants.PROTOCOL_VERSION);
}
this.httpMethod = httpMethod;
}
/**
* Sets whether the buffer should send events instantly or after the buffer has reached
* it's limit. By default, this is set to BufferOption Default.
* @param option Set the BufferOption enum to Instant send events upon creation.
*/
public function setBufferSize(option:int):void {
this.bufferSize = option;
}
/**
* Add event payloads to the emitter's buffer
* @param payload Payload to be added
*/
public function addToBuffer(payload:IPayload):void {
_buffer.push(payload);
if (_buffer.length == bufferSize)
flushBuffer();
}
/**
* Sends all events in the buffer to the collector.
*/
public function checkBufferComplete(successCount:int, totalCount:int, totalPayloads:int, unsentPayloads:Array):void {
if (totalCount == totalPayloads)
{
if (unsentPayloads.length == 0)
{
dispatchEvent(new EmitterEvent(EmitterEvent.SUCCESS, successCount));
}
else
{
dispatchEvent(new EmitterEvent(EmitterEvent.FAILURE, successCount, unsentPayloads, "Not all items in buffer were sent"));
}
}
}
/**
* Sends all events in the buffer to the collector.
*/
public function flushBuffer():void {
if (_buffer.length == 0) {
trace("Buffer is empty, exiting flush operation.");
return;
}
if (httpMethod == URLRequestMethod.GET) {
var successCount:int = 0;
var totalCount:int = 0;
var totalPayloads:int = _buffer.length;
var unsentPayloads:Array = [];
for each (var getPayload:IPayload in _buffer) {
sendGetData(getPayload,
function onGetSuccess (data:*):void {
successCount++;
totalCount++;
checkBufferComplete(successCount, totalCount, totalPayloads, unsentPayloads);
},
function onGetError ():void {
totalCount++;
unsentPayloads.push(payload);
checkBufferComplete(successCount, totalCount, totalPayloads, unsentPayloads);
}
);
}
} else if (httpMethod == URLRequestMethod.POST) {
var unsentPayload:Array = [];
var postPayload:SchemaPayload = new SchemaPayload();
postPayload.setSchema(Constants.SCHEMA_PAYLOAD_DATA);
var eventMaps:Array = [];
for each (var payload:IPayload in _buffer) {
eventMaps.push(payload.getMap());
}
postPayload.setData(eventMaps);
sendPostData(postPayload,
function onPostSuccess (data:*):void
{
dispatchEvent(new EmitterEvent(EmitterEvent.SUCCESS, _buffer.length));
},
function onPostError (event:Event):void
{
unsentPayload.push(postPayload);
dispatchEvent(new EmitterEvent(EmitterEvent.FAILURE, 0, unsentPayloads, event.toString()));
}
);
}
// Empties current buffer
Util.clearArray(_buffer);
}
protected function sendPostData(payload:IPayload, successCallback:Function, errorCallback:Function):void
{
Util.getResponse(_uri.toString(),
successCallback,
errorCallback,
URLRequestMethod.POST,
payload.toString());
}
protected function sendGetData(payload:IPayload, successCallback:Function, errorCallback:Function):void
{
var hashMap:Object = payload.getMap();
_uri.setQueryByMap(hashMap);
Util.getResponse(_uri.toString(),
successCallback,
errorCallback);
}
}
}
|
/*
* Copyright (c) 2015 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.snowplowanalytics.snowplow.tracker.emitter
{
import com.adobe.net.URI;
import com.snowplowanalytics.snowplow.tracker.Constants;
import com.snowplowanalytics.snowplow.tracker.Util;
import com.snowplowanalytics.snowplow.tracker.event.EmitterEvent;
import com.snowplowanalytics.snowplow.tracker.payload.IPayload;
import com.snowplowanalytics.snowplow.tracker.payload.SchemaPayload;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
public class Emitter extends EventDispatcher
{
private var _uri:URI;
private var _buffer:Array = [];
protected var bufferSize:int = BufferOption.DEFAULT;
protected var httpMethod:String = URLRequestMethod.GET;
/**
* Create an Emitter instance with a collector URL and HttpMethod to send requests.
* @param URI The collector URL. Don't include "http://" - this is done automatically.
* @param httpMethod The HTTP request method. If GET, <code>BufferOption</code> is set to <code>Instant</code>.
* @param protocol The protocol for the call. Either http or https. Defaults to https.
*/
public function Emitter(uri:String, httpMethod:String = URLRequestMethod.GET, protocol:String = "https") {
if (httpMethod == URLRequestMethod.GET) {
_uri = new URI(protocol + "://" + uri + "/i");
} else { // POST
_uri = new URI(protocol + "://" + uri + "/" + Constants.PROTOCOL_VENDOR + "/" + Constants.PROTOCOL_VERSION);
}
this.httpMethod = httpMethod;
}
/**
* Sets whether the buffer should send events instantly or after the buffer has reached
* it's limit. By default, this is set to BufferOption Default.
* @param option Set the BufferOption enum to Instant send events upon creation.
*/
public function setBufferSize(option:int):void {
this.bufferSize = option;
}
/**
* Add event payloads to the emitter's buffer
* @param payload Payload to be added
*/
public function addToBuffer(payload:IPayload):void {
_buffer.push(payload);
if (_buffer.length == bufferSize)
flushBuffer();
}
/**
* Sends all events in the buffer to the collector.
*/
public function checkBufferComplete(successCount:int, totalCount:int, totalPayloads:int, unsentPayloads:Array):void {
if (totalCount == totalPayloads)
{
if (unsentPayloads.length == 0)
{
dispatchEvent(new EmitterEvent(EmitterEvent.SUCCESS, successCount));
}
else
{
dispatchEvent(new EmitterEvent(EmitterEvent.FAILURE, successCount, unsentPayloads, "Not all items in buffer were sent"));
}
}
}
/**
* Sends all events in the buffer to the collector.
*/
public function flushBuffer():void {
if (_buffer.length == 0) {
trace("Buffer is empty, exiting flush operation.");
return;
}
if (httpMethod == URLRequestMethod.GET) {
var successCount:int = 0;
var totalCount:int = 0;
var totalPayloads:int = _buffer.length;
var unsentPayloads:Array = [];
for each (var getPayload:IPayload in _buffer) {
sendGetData(getPayload,
function onGetSuccess (data:*):void {
successCount++;
totalCount++;
checkBufferComplete(successCount, totalCount, totalPayloads, unsentPayloads);
},
function onGetError ():void {
totalCount++;
unsentPayloads.push(payload);
checkBufferComplete(successCount, totalCount, totalPayloads, unsentPayloads);
}
);
}
} else if (httpMethod == URLRequestMethod.POST) {
var unsentPayload:Array = [];
var postPayload:SchemaPayload = new SchemaPayload();
postPayload.setSchema(Constants.SCHEMA_PAYLOAD_DATA);
var eventMaps:Array = [];
for each (var payload:IPayload in _buffer) {
eventMaps.push(payload.getMap());
}
postPayload.setData(eventMaps);
sendPostData(postPayload,
function onPostSuccess (data:*):void
{
dispatchEvent(new EmitterEvent(EmitterEvent.SUCCESS, _buffer.length));
},
function onPostError (event:Event):void
{
unsentPayload.push(postPayload);
dispatchEvent(new EmitterEvent(EmitterEvent.FAILURE, 0, unsentPayloads, event.toString()));
}
);
}
// Empties current buffer
Util.clearArray(_buffer);
}
protected function sendPostData(payload:IPayload, successCallback:Function, errorCallback:Function):void
{
Util.getResponse(_uri.toString(),
successCallback,
errorCallback,
URLRequestMethod.POST,
payload.toString());
}
protected function sendGetData(payload:IPayload, successCallback:Function, errorCallback:Function):void
{
var hashMap:Object = payload.getMap();
_uri.setQueryByMap(hashMap);
Util.getResponse(_uri.toString(),
successCallback,
errorCallback);
}
}
}
|
Add ability to choose HTTP protocol for Emitter. Change default to HTTPS.
|
Add ability to choose HTTP protocol for Emitter. Change default to HTTPS.
|
ActionScript
|
apache-2.0
|
snowplow/snowplow-actionscript3-tracker,snowplow/snowplow-actionscript3-tracker,snowplow/snowplow-actionscript3-tracker
|
8928deb3bb6b3b5c46f7bc49de89c1fcb8c6936f
|
portal/web/swf/src/CBioNodeRenderer.as
|
portal/web/swf/src/CBioNodeRenderer.as
|
/*
* This class is used as a special renderer for CBio nodes where details about a node
* can be displayed using 3 different disc segments around the node.
**/
package org.cytoscapeweb.view.render
{
import flare.util.Shapes;
import flare.vis.data.DataSprite;
import flare.vis.data.NodeSprite;
import flash.display.*;
import flash.display.BitmapData;
import flash.display.Graphics;
import flash.display.Sprite;
import flash.geom.Matrix;
import flash.geom.Rectangle;
import flash.ui.Mouse;
import flash.utils.setTimeout;
import mx.utils.StringUtil;
import org.alivepdf.display.Display;
import org.cytoscapeweb.util.GraphUtils;
import org.cytoscapeweb.util.NodeShapes;
public class CBioNodeRenderer extends NodeRenderer
{
private static var _instance:CBioNodeRenderer =
new CBioNodeRenderer();
private var _imgCache:ImageCache = ImageCache.instance;
private var _detailFlag:Boolean = false;
public static function get instance() : CBioNodeRenderer
{
return _instance;
}
public function get detailFlag() : Boolean
{
return this._detailFlag;
}
public function set detailFlag(value:Boolean) : void
{
this._detailFlag = value;
}
public function CBioNodeRenderer(defaultSize:Number=6)
{
super(defaultSize);
}
/** @inheritDoc */
public override function render(d:DataSprite):void {trace("RENDER NODE: " + d.data.id);
var lineAlpha:Number = d.lineAlpha;
var fillAlpha:Number = d.fillAlpha;
var size:Number = d.size * defaultSize;
var g:Graphics = d.graphics;
g.clear();
if (lineAlpha > 0 && d.lineWidth > 0)
{
var pixelHinting:Boolean = d.shape === NodeShapes.ROUND_RECTANGLE;
g.lineStyle(d.lineWidth, d.lineColor, lineAlpha, pixelHinting);
}
if (fillAlpha > 0)
{
// 1. Draw the background color:
// Using a bit mask to avoid transparent mdes when fillcolor=0xffffffff.
// See https://sourceforge.net/forum/message.php?msg_id=7393265
g.beginFill(0xffffff & d.fillColor, fillAlpha);
drawShape(d, d.shape, null);
g.endFill();
// 2. Draw an image on top:
drawImage(d,0,0);
}
}
// Draws the corresponding shape on given sprite
protected override function drawShape(st:Sprite, shape:String, bounds:Rectangle):void
{
var d:DataSprite = st as DataSprite;
var g:Graphics = d.graphics;
var size:Number = d.size*defaultSize;
switch (shape) {
case null:
break;
case NodeShapes.RECTANGLE:
g.drawRect(-size/2, -size/2, size, size);
break;
case NodeShapes.TRIANGLE:
case NodeShapes.DIAMOND:
case NodeShapes.HEXAGON:
case NodeShapes.OCTAGON:
case NodeShapes.PARALLELOGRAM:
case NodeShapes.V:
var r:Rectangle = new Rectangle(-size/2, -size/2, size, size);
var points:Array = NodeShapes.getDrawPoints(r, shape);
Shapes.drawPolygon(g, points);
break;
case NodeShapes.ROUND_RECTANGLE:
g.drawRoundRect(-size/2, -size/2, size, size, size/2, size/2);
break;
case NodeShapes.ELLIPSE:
default:
if (this._detailFlag || Boolean(d.props.detailFlag))
{
// Draws the disc containing details
drawDetails(d, size/2);
}
// Genes are colored according to total alteration percentage
var total:Number = Number(d.data.PERCENT_ALTERED) * 100;
g.beginFill(getNodeColorRW(total), 50);
// Seeded genes (IN_QUERY = true) are drawn with thicker borders
var inQuery:String = d.data.IN_QUERY;
if (inQuery == "false")
{
g.lineStyle(1, 0x000000, 1);
}
else
{
g.lineStyle(5, 0x000000, 1);
}
g.drawCircle(0, 0, size/2);
}
}
protected override function drawImage(d:DataSprite, w:Number, h:Number):void
{
var url:String = d.props.imageUrl;
var size:Number = d.size*defaultSize;
if (size > 0 && url != null && StringUtil.trim(url).length > 0) {
// Load the image into the cache first?
if (!_imgCache.contains(url)) {trace("Will load IMAGE...");
_imgCache.loadImage(url);
}
if (_imgCache.isLoaded(url)) {trace(" .LOADED :-)");
draw();
} else {trace(" .NOT loaded :-(");
drawWhenLoaded();
}
function drawWhenLoaded():void {
setTimeout(function():void {trace(" .TIMEOUT: Checking again...");
if (_imgCache.isLoaded(url)) draw();
else if (!_imgCache.isBroken(url)) drawWhenLoaded();
}, 50);
}
function draw():void {trace("Will draw: " + d.data.id);
// Get the image from cache:
var bd:BitmapData = _imgCache.getImage(url);
if (bd != null) {
var bmpSize:Number = Math.min(bd.height, bd.width);
var scale:Number = size/bmpSize;
var m:Matrix = new Matrix();
m.scale(scale, scale);
m.translate(-(bd.width*scale)/2, -(bd.height*scale)/2);
d.graphics.beginBitmapFill(bd, m, false, true);
drawShape(d, d.shape, null);
d.graphics.endFill();
}
}
}
}
// Draws the details of the node around the node circle
private function drawDetails(d:DataSprite, RADIUS:int):void
{
var g:Graphics = d.graphics;
// Flags represent whether a disc part will be drawn or not
var topFlag:Boolean = false;
var rightFlag:Boolean = false;
var leftFlag:Boolean = false;
var thickness:int = 16; // Thickness of the detail disc
var smoothness:int = 90; // Determines how smooth the ars are drawn
var circleMargin:int = 0; // Margin between the discs and the node
var insideMargin:Number = 1.0; // Inner margins for the percentage slices (should be half the border thickness!)
// These variables are used for the gradient color for unused disc parts
var fillType:String = "linear"
var colors:Array = [0xDCDCDC, 0xFFFFFF];
var alphas:Array = [100, 100];
var ratios:Array = [0x00, 0xFF];
var matrix:Matrix = new Matrix();
matrix.createGradientBox(3, 3, 0, 0, 0);
matrix.rotate(90/360);
var spreadMethod:String = "repeat";
g.lineStyle(0,0x000000,1);
// Following part looks at available data and sets percentages if data is available
// Top disc
if (d.data.PERCENT_CNA_HEMIZYGOUSLY_DELETED != null ||
d.data.PERCENT_CNA_AMPLIFIED != null ||
d.data.PERCENT_CNA_HOMOZYGOUSLY_DELETED != null ||
d.data.PERCENT_CNA_GAINED != null)
{
var hemizygousDeletion:Number = Number(d.data.PERCENT_CNA_HEMIZYGOUSLY_DELETED) * 100;
var amplification:Number = Number(d.data.PERCENT_CNA_AMPLIFIED) * 100;
var homozygousDeletion:Number = Number(d.data.PERCENT_CNA_HOMOZYGOUSLY_DELETED) * 100;
var gain:Number = Number(d.data.PERCENT_CNA_GAINED) * 100;
topFlag = true;
}
// Right disc
if (d.data.PERCENT_MUTATED != null)
{
var mutation:Number = Number(d.data.PERCENT_MUTATED) * 100;
rightFlag = true;
}
// Left disc
if (d.data.PERCENT_MRNA_WAY_UP != null ||
d.data.PERCENT_MRNA_WAY_DOWN != null)
{
var upRegulation:Number = Number(d.data.PERCENT_MRNA_WAY_UP) * 100;
var downRegulation:Number = Number(d.data.PERCENT_MRNA_WAY_DOWN) * 100;
leftFlag = true;
}
/* Following part draws the disc slice if associated flag is on, 3 disc parts are drawn in such a
* way that there are 20 degrees empty space between each part and the parts themselves have a
* 100 degrees space each, adding up to 360 degrees. The gray backgrounds are drawn first and the
* corresponing colored percentages are filled using the data about the node.
*/
// Don't draw anything if none is available
if (!(topFlag || rightFlag || leftFlag))
{
return;
}
var innerRadius:Number;
var outerRadius:Number;
// Draws the top arc if its flag is on
if (topFlag == true)
{
innerRadius = RADIUS + circleMargin;
outerRadius = RADIUS + thickness;
// The gray back part is drawn
g.lineStyle(2, 0xDCDCDC, 1);
g.beginFill(0xFFFFFF, 50);
drawSolidArc(0, 0, innerRadius, outerRadius, 218/360, 104/360, smoothness, g);
innerRadius += insideMargin;
outerRadius -= insideMargin;
g.lineStyle(0, 0xFFFFFF, 0);
var amplificationArc:int = amplification;
g.beginFill(0xFF2500, 50);
drawSolidArc (0, 0, innerRadius, outerRadius, 220/360, (amplificationArc/360), smoothness, g);
var homozygousDeletionArc:int = homozygousDeletion;
g.beginFill(0x0332FF, 50);
drawSolidArc (0, 0, innerRadius, outerRadius, 220/360 + (amplificationArc/360), (homozygousDeletionArc/360), smoothness,g);
var gainArc:int = gain;
g.beginFill(0xFFC5CC, 50);
drawSolidArc (0, 0, innerRadius, outerRadius, 220/360 + ((amplificationArc+homozygousDeletionArc)/360), (gainArc/360), smoothness,g);
var hemizygousDeletionArc:int = hemizygousDeletion;
g.beginFill(0x9EDFE0, 50);
drawSolidArc (0, 0, innerRadius, outerRadius, 220/360 + ((amplificationArc+homozygousDeletionArc+gainArc)/360), (hemizygousDeletionArc/360), smoothness,g);
g.lineStyle(1, 0x000000, 1);
}
else
{
g.lineStyle(1, 0xDCDCDC, 0.5);
g.beginGradientFill(fillType, colors, alphas, ratios, matrix, spreadMethod);
drawSolidArc(0, 0, RADIUS+circleMargin, RADIUS+thickness, 219/360, 102/360, smoothness, g);
g.endFill();
}
if (rightFlag == true)
{
innerRadius = RADIUS + circleMargin;
outerRadius = RADIUS + thickness;
g.lineStyle(2, 0xDCDCDC, 1);
g.beginFill(0xFFFFFF, 50);
drawSolidArc(0, 0, innerRadius, outerRadius, -22/360, 104/360, smoothness, g);
innerRadius += insideMargin;
outerRadius -= insideMargin;
g.lineStyle(0,0xDCDCDC,0);
var mutationArc:int = mutation;
g.beginFill(0x008F00, 50);
drawSolidArc (0, 0, innerRadius, outerRadius, -20/360, (mutationArc/360), smoothness,g);
g.lineStyle(1, 0x000000, 1);
}
else
{
g.lineStyle(1, 0xDCDCDC, 0.5);
g.beginGradientFill(fillType, colors, alphas, ratios, matrix, spreadMethod);
drawSolidArc(0, 0, RADIUS+circleMargin, RADIUS+thickness, -21/360, 102/360, smoothness, g);
g.endFill();
}
if (leftFlag == true)
{
innerRadius = RADIUS + circleMargin;
outerRadius = RADIUS + thickness;
g.lineStyle(2, 0xDCDCDC, 1);
g.beginFill(0xFFFFFF, 50);
drawSolidArc (0, 0, innerRadius, outerRadius, 202/360, -(104/360), smoothness,g);
innerRadius += insideMargin;
outerRadius -= insideMargin;
g.lineStyle(0, 0xDCDCDC, 0);
var upRegulationArc:int = upRegulation;
g.beginFill(0xFFACA9, 50);
drawSolidArc (0, 0, innerRadius, outerRadius, 200/360, -(upRegulationArc/360), smoothness,g);
var downRegulationArc:int = downRegulation;
g.beginFill(0x78AAD6, 50);
drawSolidArc (0, 0, innerRadius, outerRadius, 200/360 - (upRegulationArc/360), -(downRegulationArc/360), smoothness,g);
// When only borders are to be drawn (like in the OncoPrint)
// g.endFill();
// var upRegulationArc:int = upRegulation;
// g.lineStyle(1.5,0xFFACA9,1);
// drawSolidArc (0, 0, RADIUS+circleMargin+1.5, RADIUS+thickness-1.5, 201/360-4/360, -(upRegulationArc/360), smoothness,g);
//
// var downRegulationArc:int = downRegulation;
// g.lineStyle(1.5,0x78AAD6,1);
// drawSolidArc (0, 0, RADIUS+circleMargin+1.5, RADIUS+thickness-1.5, 201/360 - (upRegulationArc/360)-8/360, -(downRegulationArc/360), smoothness,g);
g.lineStyle(1, 0x000000, 1);
}
else
{
g.lineStyle(1, 0xDCDCDC, 0.5);
g.beginGradientFill(fillType, colors, alphas, ratios, matrix, spreadMethod);
drawSolidArc (0, 0, RADIUS+circleMargin, RADIUS+thickness, 201/360, -(102/360), smoothness,g);
g.endFill();
}
g.lineStyle(1, 0x000000, 1);
}
/**
* Draws a solid arc part using the given parameters
*
* @param centerX X-axis of the center of the shape
* @param centerY Y-axis of the center of the shape
* @param innerRadius radius of the inner circle
* @param outerRadius radius of the outer circle
* @param startAngle starting angle of the arc
* @param arcAngle the angle that arc fills
* @param steps determines how smooth the curve of the arc is
* @param g graphics object to draw on it
* Reference: http://www.pixelwit.com/blog/2008/12/drawing-closed-arc-shape/
* */
private function drawSolidArc (centerX:Number, centerY:Number, innerRadius:Number, outerRadius:Number, startAngle:Number, arcAngle:Number, steps:Number, g:Graphics):void{
var twoPI:Number = 2 * Math.PI;
var angleStep:Number = arcAngle/steps;
var angle:Number, i:Number, endAngle:Number;
var xx:Number = centerX + Math.cos(startAngle * twoPI) * innerRadius;
var yy:Number = centerY + Math.sin(startAngle * twoPI) * innerRadius;
var startPoint:Object = {x:xx, y:yy};
g.moveTo(xx, yy);
for(i=1; i<=steps; i++){
angle = (startAngle + i * angleStep) * twoPI;
xx = centerX + Math.cos(angle) * innerRadius;
yy = centerY + Math.sin(angle) * innerRadius;
g.lineTo(xx, yy);
}
endAngle = startAngle + arcAngle;
for(i=0; i<=steps; i++){
angle = (endAngle - i * angleStep) * twoPI;
xx = centerX + Math.cos(angle) * outerRadius;
yy = centerY + Math.sin(angle) * outerRadius;
g.lineTo(xx, yy);
}
g.lineTo(startPoint.x, startPoint.y);
}
// Returns the color between Red and White using the given value as a ratio
private function getNodeColorRW(value:int):Number
{
var high:int = 100;
var low:int = 0;
var highCRed:int = 255;
var highCGreen:int = 0;
var highCBlue:int = 0;
var lowCRed:int = 255;
var lowCGreen:int = 255;
var lowCBlue:int = 255;
// transform percentage value by using the formula:
// y = 0.000166377 x^3 + -0.0380704 x^2 + 3.14277x
// instead of linear scaling, we use polynomial scaling to better
// emphasize lower alteration frequencies
value = (0.000166377 * value * value * value) -
(0.0380704 * value * value) +
(3.14277 * value);
// check boundary values
if (value > 100)
{
value = 100;
}
else if (value < 0)
{
value = 0;
}
if (value >= high)
{
return rgb2hex(highCRed, highCGreen, highCBlue);
}
else if (value > low)
{
return rgb2hex( getValueByRatio(value, low, high, lowCRed, highCRed),
getValueByRatio(value, low, high, lowCGreen, highCGreen),
getValueByRatio(value, low, high, lowCBlue, highCBlue)
);
}
else
{
return rgb2hex(lowCRed, lowCGreen, lowCBlue);
}
}
// used in getNodeColorRW to calculate a color number according to the ratio given
private function getValueByRatio(num:Number,
numLow:Number, numHigh:Number, colorNum1:int, colorNum2:int):int
{
return ((((num - numLow) / (numHigh - numLow)) * (colorNum2 - colorNum1)) + colorNum1)
}
// bitwise conversion of rgb color to a hex value
private function rgb2hex(r:int, g:int, b:int):Number {
return(r<<16 | g<<8 | b);
}
}
}
|
fix for CBioNodeRenderer.as
|
fix for CBioNodeRenderer.as
|
ActionScript
|
agpl-3.0
|
HectorWon/cbioportal,sheridancbio/cbioportal,pughlab/cbioportal,xmao/cbioportal,yichaoS/cbioportal,cBioPortal/cbioportal,leedonghn4/cbioportal,fcriscuo/cbioportal,angelicaochoa/cbioportal,jjgao/cbioportal,onursumer/cbioportal,HectorWon/cbioportal,gsun83/cbioportal,gsun83/cbioportal,bihealth/cbioportal,n1zea144/cbioportal,adamabeshouse/cbioportal,istemi-bahceci/cbioportal,inodb/cbioportal,holtgrewe/cbioportal,j-hudecek/cbioportal,zhx828/cbioportal,j-hudecek/cbioportal,kalletlak/cbioportal,angelicaochoa/cbioportal,d3b-center/pedcbioportal,d3b-center/pedcbioportal,d3b-center/pedcbioportal,IntersectAustralia/cbioportal,IntersectAustralia/cbioportal,j-hudecek/cbioportal,zheins/cbioportal,istemi-bahceci/cbioportal,HectorWon/cbioportal,gsun83/cbioportal,holtgrewe/cbioportal,j-hudecek/cbioportal,fcriscuo/cbioportal,bengusty/cbioportal,onursumer/cbioportal,mandawilson/cbioportal,leedonghn4/cbioportal,n1zea144/cbioportal,IntersectAustralia/cbioportal,istemi-bahceci/cbioportal,sheridancbio/cbioportal,holtgrewe/cbioportal,fcriscuo/cbioportal,cBioPortal/cbioportal,bengusty/cbioportal,shrumit/cbioportal-gsoc-final,leedonghn4/cbio-portal-webgl,n1zea144/cbioportal,gsun83/cbioportal,adamabeshouse/cbioportal,holtgrewe/cbioportal,jjgao/cbioportal,bihealth/cbioportal,gsun83/cbioportal,bengusty/cbioportal,d3b-center/pedcbioportal,d3b-center/pedcbioportal,pughlab/cbioportal,fcriscuo/cbioportal,IntersectAustralia/cbioportal,HectorWon/cbioportal,HectorWon/cbioportal,sheridancbio/cbioportal,inodb/cbioportal,j-hudecek/cbioportal,cBioPortal/cbioportal,leedonghn4/cbio-portal-webgl,zhx828/cbioportal,zhx828/cbioportal,zheins/cbioportal,adamabeshouse/cbioportal,istemi-bahceci/cbioportal,sheridancbio/cbioportal,zhx828/cbioportal,inodb/cbioportal,mandawilson/cbioportal,mandawilson/cbioportal,n1zea144/cbioportal,angelicaochoa/cbioportal,pughlab/cbioportal,inodb/cbioportal,kalletlak/cbioportal,adamabeshouse/cbioportal,HectorWon/cbioportal,leedonghn4/cbio-portal-webgl,n1zea144/cbioportal,fcriscuo/cbioportal,zhx828/cbioportal,bengusty/cbioportal,cBioPortal/cbioportal,n1zea144/cbioportal,xmao/cbioportal,pughlab/cbioportal,cBioPortal/cbioportal,shrumit/cbioportal-gsoc-final,shrumit/cbioportal-gsoc-final,jjgao/cbioportal,j-hudecek/cbioportal,yichaoS/cbioportal,IntersectAustralia/cbioportal,leedonghn4/cbio-portal-webgl,d3b-center/pedcbioportal,zhx828/cbioportal,onursumer/cbioportal,bengusty/cbioportal,shrumit/cbioportal-gsoc-final,leedonghn4/cbioportal,bihealth/cbioportal,jjgao/cbioportal,sheridancbio/cbioportal,zheins/cbioportal,n1zea144/cbioportal,xmao/cbioportal,angelicaochoa/cbioportal,cBioPortal/cbioportal,kalletlak/cbioportal,xmao/cbioportal,holtgrewe/cbioportal,fcriscuo/cbioportal,gsun83/cbioportal,angelicaochoa/cbioportal,IntersectAustralia/cbioportal,kalletlak/cbioportal,onursumer/cbioportal,shrumit/cbioportal-gsoc-final,istemi-bahceci/cbioportal,adamabeshouse/cbioportal,leedonghn4/cbioportal,leedonghn4/cbioportal,adamabeshouse/cbioportal,zheins/cbioportal,yichaoS/cbioportal,pughlab/cbioportal,zheins/cbioportal,kalletlak/cbioportal,inodb/cbioportal,bihealth/cbioportal,bihealth/cbioportal,shrumit/cbioportal-gsoc-final,leedonghn4/cbio-portal-webgl,mandawilson/cbioportal,mandawilson/cbioportal,bengusty/cbioportal,zheins/cbioportal,onursumer/cbioportal,bihealth/cbioportal,pughlab/cbioportal,yichaoS/cbioportal,d3b-center/pedcbioportal,angelicaochoa/cbioportal,yichaoS/cbioportal,yichaoS/cbioportal,inodb/cbioportal,bihealth/cbioportal,leedonghn4/cbio-portal-webgl,jjgao/cbioportal,IntersectAustralia/cbioportal,leedonghn4/cbioportal,shrumit/cbioportal-gsoc-final,gsun83/cbioportal,jjgao/cbioportal,adamabeshouse/cbioportal,pughlab/cbioportal,mandawilson/cbioportal,xmao/cbioportal,kalletlak/cbioportal,holtgrewe/cbioportal,yichaoS/cbioportal,sheridancbio/cbioportal,zhx828/cbioportal,angelicaochoa/cbioportal,xmao/cbioportal,istemi-bahceci/cbioportal,jjgao/cbioportal,onursumer/cbioportal,mandawilson/cbioportal,inodb/cbioportal,kalletlak/cbioportal
|
|
2c21bf31aa36e3db495af347888b9e914638bc89
|
src/flash/htmlelements/VideoElement.as
|
src/flash/htmlelements/VideoElement.as
|
package htmlelements
{
import flash.display.Sprite;
import flash.events.*;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.media.Video;
import flash.media.SoundTransform;
import flash.utils.Timer;
import FlashMediaElement;
import HtmlMediaEvent;
public class VideoElement extends Sprite implements IMediaElement
{
private var _currentUrl:String = "";
private var _autoplay:Boolean = true;
private var _connection:NetConnection;
private var _stream:NetStream;
private var _video:Video;
private var _element:FlashMediaElement;
private var _soundTransform;
private var _oldVolume:Number = 1;
// event values
private var _duration:Number = 0;
private var _framerate:Number;
private var _isPaused:Boolean = true;
private var _isEnded:Boolean = false;
private var _volume:Number = 1;
private var _isMuted:Boolean = false;
private var _bytesLoaded:Number = 0;
private var _bytesTotal:Number = 0;
private var _bufferedTime:Number = 0;
private var _videoWidth:Number = -1;
private var _videoHeight:Number = -1;
private var _timer:Timer;
private var _isRTMP:Boolean = false;
private var _isConnected:Boolean = false;
private var _playWhenConnected:Boolean = false;
private var _hasStartedPlaying:Boolean = false;
public function get video():Video {
return _video;
}
public function get videoHeight():Number {
return _videoHeight;
}
public function get videoWidth():Number {
return _videoWidth;
}
public function duration():Number {
return _duration;
}
public function currentTime():Number {
if (_stream != null) {
return _stream.time;
} else {
return 0;
}
}
// (1) load()
// calls _connection.connect();
// waits for NetConnection.Connect.Success
// _stream gets created
public function VideoElement(element:FlashMediaElement, autoplay:Boolean, timerRate:Number)
{
_element = element;
_autoplay = autoplay;
_video = new Video();
addChild(_video);
_connection = new NetConnection();
_connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
_connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
//_connection.connect(null);
_timer = new Timer(timerRate);
_timer.addEventListener("timer", timerHandler);
}
private function timerHandler(e:TimerEvent) {
_bytesLoaded = _stream.bytesLoaded;
_bytesTotal = _stream.bytesTotal;
sendEvent(HtmlMediaEvent.TIMEUPDATE);
trace("bytes", _bytesLoaded, _bytesTotal);
if (_bytesLoaded < _bytesTotal)
sendEvent(HtmlMediaEvent.PROGRESS);
}
// internal events
private function netStatusHandler(event:NetStatusEvent):void {
trace("netStatus", event.info.code);
switch (event.info.code) {
case "NetStream.Buffer.Empty":
case "NetStream.Buffer.Full":
_bytesLoaded = _stream.bytesLoaded;
_bytesTotal = _stream.bytesTotal;
sendEvent(HtmlMediaEvent.PROGRESS);
break;
case "NetConnection.Connect.Success":
connectStream();
break;
case "NetStream.Play.StreamNotFound":
trace("Unable to locate video");
break;
// STREAM
case "NetStream.Play.Start":
_isPaused = false;
sendEvent(HtmlMediaEvent.CANPLAY);
sendEvent(HtmlMediaEvent.PLAY);
sendEvent(HtmlMediaEvent.PLAYING);
_timer.start();
break;
case "NetStream.Seek.Notify":
sendEvent(HtmlMediaEvent.SEEKED);
break;
case "NetStream.Pause.Notify":
_isPaused = true;
sendEvent(HtmlMediaEvent.PAUSE);
break;
case "NetStream.Play.Stop":
_isPaused = false;
_timer.stop();
sendEvent(HtmlMediaEvent.ENDED);
break;
}
}
private function connectStream():void {
trace("connectStream");
_stream = new NetStream(_connection);
// explicitly set the sound since it could have come before the connection was made
_soundTransform = new SoundTransform(_volume);
_stream.soundTransform = _soundTransform;
_stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); // same event as connection
_stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
var customClient:Object = new Object();
customClient.onMetaData = onMetaDataHandler;
_stream.client = customClient;
_video.attachNetStream(_stream);
_isConnected = true;
if (_playWhenConnected && !_hasStartedPlaying) {
play();
_playWhenConnected = false;
}
}
private function securityErrorHandler(event:SecurityErrorEvent):void {
trace("securityErrorHandler: " + event);
}
private function asyncErrorHandler(event:AsyncErrorEvent):void {
// ignore AsyncErrorEvent events.
}
private function onMetaDataHandler(info:Object):void {
_duration = info.duration;
_framerate = info.framerate;
_videoWidth = info.width;
_videoHeight = info.height;
// set size?
sendEvent(HtmlMediaEvent.LOADEDMETADATA);
}
// interface members
public function setSrc(url:String):void {
if (_isConnected && _stream) {
// stop and restart
_stream.pause();
}
_currentUrl = url;
_isRTMP = !!_currentUrl.match(/^rtmp(s|t|e|te)?\:\/\//);
_isConnected = false;
_hasStartedPlaying = false;
}
public function load():void {
// as far as I know there is no way to start downloading a file without playing it (preload="auto" in HTML5)
// so this "load" just begins a Flash connection
if (_isConnected && _stream) {
_stream.pause();
}
_isConnected = false;
if (_isRTMP) {
_connection.connect(_currentUrl.replace(/\/[^\/]+$/,"/"));
} else {
_connection.connect(null);
}
// in a few moments the "NetConnection.Connect.Success" event will fire
// and call createConnection which finishes the "load" sequence
sendEvent(HtmlMediaEvent.LOADSTART);
}
public function play():void {
if (!_hasStartedPlaying && !_isConnected) {
_playWhenConnected = true;
load();
return;
}
if (_hasStartedPlaying) {
if (_isPaused) {
_stream.resume();
_timer.start();
_isPaused = false;
sendEvent(HtmlMediaEvent.PLAY);
sendEvent(HtmlMediaEvent.PLAYING);
}
} else {
if (_isRTMP) {
_stream.play(_currentUrl.split("/").pop());
} else {
_stream.play(_currentUrl);
}
_timer.start();
_isPaused = false;
sendEvent(HtmlMediaEvent.PLAY);
sendEvent(HtmlMediaEvent.PLAYING);
_hasStartedPlaying = true;
}
}
public function pause():void {
if (_stream == null)
return;
_stream.pause();
_isPaused = true;
_timer.stop();
_isPaused = true;
sendEvent(HtmlMediaEvent.PAUSE);
}
public function stop():void {
if (_stream == null)
return;
_stream.close();
_isPaused = false;
_timer.stop();
sendEvent(HtmlMediaEvent.STOP);
}
public function setCurrentTime(pos:Number):void {
if (_stream == null)
return;
_stream.seek(pos);
sendEvent(HtmlMediaEvent.TIMEUPDATE);
sendEvent(HtmlMediaEvent.SEEKED);
}
public function setVolume(volume:Number):void {
if (_stream != null) {
_soundTransform = new SoundTransform(volume);
_stream.soundTransform = _soundTransform;
}
_volume = volume;
_isMuted = (_volume == 0);
sendEvent(HtmlMediaEvent.VOLUMECHANGE);
}
public function setMuted(muted:Boolean):void {
if (_isMuted == muted)
return;
if (muted) {
_oldVolume = _stream.soundTransform.volume;
setVolume(0);
} else {
setVolume(_oldVolume);
}
_isMuted = muted;
}
private function sendEvent(eventName:String) {
// calculate this to mimic HTML5
_bufferedTime = _bytesLoaded / _bytesTotal + _duration;
// build JSON
var values:String =
"{duration:" + _duration +
",framerate:" + _framerate +
",currentTime:" + (_stream != null ? _stream.time : 0) +
",muted:" + _isMuted +
",paused:" + _isPaused +
",ended:" + _isEnded +
",volume:" + _volume +
",src:\"" + _currentUrl + "\"" +
",bytesTotal:" + _bytesTotal +
",bufferedBytes:" + _bytesLoaded +
",bufferedTime:" + _bufferedTime +
",videoWidth:" + _videoWidth +
",videoHeight:" + _videoHeight +
"}";
_element.sendEvent(eventName, values);
}
}
}
|
package htmlelements
{
import flash.display.Sprite;
import flash.events.*;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.media.Video;
import flash.media.SoundTransform;
import flash.utils.Timer;
import FlashMediaElement;
import HtmlMediaEvent;
public class VideoElement extends Sprite implements IMediaElement
{
private var _currentUrl:String = "";
private var _autoplay:Boolean = true;
private var _connection:NetConnection;
private var _stream:NetStream;
private var _video:Video;
private var _element:FlashMediaElement;
private var _soundTransform;
private var _oldVolume:Number = 1;
// event values
private var _duration:Number = 0;
private var _framerate:Number;
private var _isPaused:Boolean = true;
private var _isEnded:Boolean = false;
private var _volume:Number = 1;
private var _isMuted:Boolean = false;
private var _bytesLoaded:Number = 0;
private var _bytesTotal:Number = 0;
private var _bufferedTime:Number = 0;
private var _videoWidth:Number = -1;
private var _videoHeight:Number = -1;
private var _timer:Timer;
private var _isRTMP:Boolean = false;
private var _isConnected:Boolean = false;
private var _playWhenConnected:Boolean = false;
private var _hasStartedPlaying:Boolean = false;
public function get video():Video {
return _video;
}
public function get videoHeight():Number {
return _videoHeight;
}
public function get videoWidth():Number {
return _videoWidth;
}
public function duration():Number {
return _duration;
}
public function currentTime():Number {
if (_stream != null) {
return _stream.time;
} else {
return 0;
}
}
// (1) load()
// calls _connection.connect();
// waits for NetConnection.Connect.Success
// _stream gets created
public function VideoElement(element:FlashMediaElement, autoplay:Boolean, timerRate:Number)
{
_element = element;
_autoplay = autoplay;
_video = new Video();
addChild(_video);
_connection = new NetConnection();
_connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
_connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
//_connection.connect(null);
_timer = new Timer(timerRate);
_timer.addEventListener("timer", timerHandler);
}
private function timerHandler(e:TimerEvent) {
_bytesLoaded = _stream.bytesLoaded;
_bytesTotal = _stream.bytesTotal;
sendEvent(HtmlMediaEvent.TIMEUPDATE);
trace("bytes", _bytesLoaded, _bytesTotal);
if (_bytesLoaded < _bytesTotal)
sendEvent(HtmlMediaEvent.PROGRESS);
}
// internal events
private function netStatusHandler(event:NetStatusEvent):void {
trace("netStatus", event.info.code);
switch (event.info.code) {
case "NetStream.Buffer.Empty":
_isEnded ? sendEvent(HtmlMediaEvent.ENDED) : null;
break;
case "NetStream.Buffer.Full":
_bytesLoaded = _stream.bytesLoaded;
_bytesTotal = _stream.bytesTotal;
sendEvent(HtmlMediaEvent.PROGRESS);
break;
case "NetConnection.Connect.Success":
connectStream();
break;
case "NetStream.Play.StreamNotFound":
trace("Unable to locate video");
break;
// STREAM
case "NetStream.Play.Start":
_isPaused = false;
sendEvent(HtmlMediaEvent.CANPLAY);
sendEvent(HtmlMediaEvent.PLAY);
sendEvent(HtmlMediaEvent.PLAYING);
_timer.start();
break;
case "NetStream.Seek.Notify":
sendEvent(HtmlMediaEvent.SEEKED);
break;
case "NetStream.Pause.Notify":
_isPaused = true;
sendEvent(HtmlMediaEvent.PAUSE);
break;
case "NetStream.Play.Stop":
_isEnded = true;
_isPaused = false;
_timer.stop();
_bufferEmpty ? sendEvent(HtmlMediaEvent.ENDED) : null;
break;
}
}
private function connectStream():void {
trace("connectStream");
_stream = new NetStream(_connection);
// explicitly set the sound since it could have come before the connection was made
_soundTransform = new SoundTransform(_volume);
_stream.soundTransform = _soundTransform;
_stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); // same event as connection
_stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
var customClient:Object = new Object();
customClient.onMetaData = onMetaDataHandler;
_stream.client = customClient;
_video.attachNetStream(_stream);
_isConnected = true;
if (_playWhenConnected && !_hasStartedPlaying) {
play();
_playWhenConnected = false;
}
}
private function securityErrorHandler(event:SecurityErrorEvent):void {
trace("securityErrorHandler: " + event);
}
private function asyncErrorHandler(event:AsyncErrorEvent):void {
// ignore AsyncErrorEvent events.
}
private function onMetaDataHandler(info:Object):void {
_duration = info.duration;
_framerate = info.framerate;
_videoWidth = info.width;
_videoHeight = info.height;
// set size?
sendEvent(HtmlMediaEvent.LOADEDMETADATA);
}
// interface members
public function setSrc(url:String):void {
if (_isConnected && _stream) {
// stop and restart
_stream.pause();
}
_currentUrl = url;
_isRTMP = !!_currentUrl.match(/^rtmp(s|t|e|te)?\:\/\//);
_isConnected = false;
_hasStartedPlaying = false;
}
public function load():void {
// as far as I know there is no way to start downloading a file without playing it (preload="auto" in HTML5)
// so this "load" just begins a Flash connection
if (_isConnected && _stream) {
_stream.pause();
}
_isConnected = false;
if (_isRTMP) {
_connection.connect(_currentUrl.replace(/\/[^\/]+$/,"/"));
} else {
_connection.connect(null);
}
// in a few moments the "NetConnection.Connect.Success" event will fire
// and call createConnection which finishes the "load" sequence
sendEvent(HtmlMediaEvent.LOADSTART);
}
public function play():void {
if (!_hasStartedPlaying && !_isConnected) {
_playWhenConnected = true;
load();
return;
}
if (_hasStartedPlaying) {
if (_isPaused) {
_stream.resume();
_timer.start();
_isPaused = false;
sendEvent(HtmlMediaEvent.PLAY);
sendEvent(HtmlMediaEvent.PLAYING);
}
} else {
if (_isRTMP) {
_stream.play(_currentUrl.split("/").pop());
} else {
_stream.play(_currentUrl);
}
_timer.start();
_isPaused = false;
sendEvent(HtmlMediaEvent.PLAY);
sendEvent(HtmlMediaEvent.PLAYING);
_hasStartedPlaying = true;
}
}
public function pause():void {
if (_stream == null)
return;
_stream.pause();
_isPaused = true;
_timer.stop();
_isPaused = true;
sendEvent(HtmlMediaEvent.PAUSE);
}
public function stop():void {
if (_stream == null)
return;
_stream.close();
_isPaused = false;
_timer.stop();
sendEvent(HtmlMediaEvent.STOP);
}
public function setCurrentTime(pos:Number):void {
if (_stream == null)
return;
_stream.seek(pos);
sendEvent(HtmlMediaEvent.TIMEUPDATE);
sendEvent(HtmlMediaEvent.SEEKED);
}
public function setVolume(volume:Number):void {
if (_stream != null) {
_soundTransform = new SoundTransform(volume);
_stream.soundTransform = _soundTransform;
}
_volume = volume;
_isMuted = (_volume == 0);
sendEvent(HtmlMediaEvent.VOLUMECHANGE);
}
public function setMuted(muted:Boolean):void {
if (_isMuted == muted)
return;
if (muted) {
_oldVolume = _stream.soundTransform.volume;
setVolume(0);
} else {
setVolume(_oldVolume);
}
_isMuted = muted;
}
private function sendEvent(eventName:String) {
// calculate this to mimic HTML5
_bufferedTime = _bytesLoaded / _bytesTotal + _duration;
// build JSON
var values:String =
"{duration:" + _duration +
",framerate:" + _framerate +
",currentTime:" + (_stream != null ? _stream.time : 0) +
",muted:" + _isMuted +
",paused:" + _isPaused +
",ended:" + _isEnded +
",volume:" + _volume +
",src:\"" + _currentUrl + "\"" +
",bytesTotal:" + _bytesTotal +
",bufferedBytes:" + _bytesLoaded +
",bufferedTime:" + _bufferedTime +
",videoWidth:" + _videoWidth +
",videoHeight:" + _videoHeight +
"}";
_element.sendEvent(eventName, values);
}
}
}
|
fix for issue #49 - "ended" event firing before actual stream end
|
fix for issue #49 - "ended" event firing before actual stream end
|
ActionScript
|
agpl-3.0
|
libeo/Vibeo,libeo/Vibeo,libeo/Vibeo,libeo/Vibeo
|
fe6fc2b7ad6f262bc6b392d46f0c393d2e6084ee
|
src/aerys/minko/type/data/DataBindings.as
|
src/aerys/minko/type/data/DataBindings.as
|
package aerys.minko.type.data
{
import aerys.minko.type.Signal;
import flash.utils.Dictionary;
public class DataBindings
{
private var _bindingNames : Vector.<String> = new Vector.<String>();
private var _bindingNameToValue : Object = {};
private var _bindingNameToChangedSignal : Object = {};
private var _providerToBindingNames : Dictionary = new Dictionary(); // dic[Vector.<String>[]]
private var _attributeToProviders : Dictionary = new Dictionary(); // dic[Vector.<IDataProvider>[]]
private var _attributeToProvidersAttrNames : Dictionary = new Dictionary(); // dic[Vector.<String>[]]
public function get numProperties() : uint
{
return _bindingNames.length;
}
public function DataBindings()
{
}
public function add(provider : IDataProvider) : void
{
if (_providerToBindingNames[provider])
throw new Error('This provider is already binded');
var providerBindingNames : Vector.<String> = new Vector.<String>();
var dataDescriptor : Object = provider.dataDescriptor;
provider.changed.add(onProviderChange);
for (var attrName : String in dataDescriptor)
{
// if this provider attribute is also a dataprovider, let's also bind it
var bindingName : String = dataDescriptor[attrName];
var attribute : Object = provider[attrName]
var dpAttribute : IDataProvider = attribute as IDataProvider;
if (_bindingNames.indexOf(bindingName) != -1)
throw new Error('Another Dataprovider is already declaring "' + bindingName + '". Cannot overwrite.');
if (dpAttribute != null)
{
dpAttribute.changed.add(onProviderAttributeChange);
if (!_attributeToProviders[dpAttribute])
_attributeToProviders[dpAttribute] = new <IDataProvider>[];
if (!_attributeToProvidersAttrNames[dpAttribute])
_attributeToProvidersAttrNames[dpAttribute] = new <String>[];
_attributeToProviders[dpAttribute].push(provider);
_attributeToProvidersAttrNames[dpAttribute].push(attrName);
}
_bindingNameToValue[bindingName] = attribute;
providerBindingNames.push(bindingName);
_bindingNames.push(bindingName);
getPropertyChangedSignal(bindingName).execute(this, bindingName, attribute);
}
_providerToBindingNames[provider] = providerBindingNames;
}
public function remove(provider : IDataProvider) : void
{
var bindingNames : Vector.<String> = _providerToBindingNames[provider];
if (bindingNames == null)
throw new ArgumentError('No such provider was binded');
for each (var bindingName : String in bindingNames)
{
var indexOf : int = _bindingNames.indexOf(bindingName);
_bindingNames.splice(indexOf, 1);
if (_bindingNameToValue[bindingName] is IDataProvider)
IDataProvider(_bindingNameToValue[bindingName]).changed.remove(onProviderAttributeChange);
delete _bindingNameToValue[bindingName];
}
var attributesToDelete : Vector.<Object> = new Vector.<Object>();
for (var attribute : Object in _attributeToProviders)
{
var providers : Vector.<IDataProvider> = _attributeToProviders[attribute];
var attrNames : Vector.<String> = _attributeToProvidersAttrNames[attribute];
var indexOfProvider : int = providers.indexOf(provider);
if (indexOfProvider != -1)
{
providers.splice(indexOfProvider, 1);
attrNames.splice(indexOfProvider, 1);
}
if (providers.length == 0)
attributesToDelete.push(attribute);
}
for (var attributeToDelete : Object in attributesToDelete)
{
delete _attributeToProviders[attributeToDelete];
delete _attributeToProvidersAttrNames[attributeToDelete];
}
provider.changed.remove(onProviderChange);
delete _providerToBindingNames[provider];
for each (bindingName in bindingNames)
{
trace(bindingName);
getPropertyChangedSignal(bindingName).execute(this, bindingName, null);
}
}
public function getPropertyChangedSignal(bindingName : String) : Signal
{
if (!_bindingNameToChangedSignal[bindingName])
_bindingNameToChangedSignal[bindingName] = new Signal('DataBindings.changed[' + bindingName + ']');
return _bindingNameToChangedSignal[bindingName];
}
public function propertyExists(bindingName : String) : Boolean
{
return _bindingNameToValue.hasOwnProperty(bindingName);
}
public function getProperty(bindingName : String) : *
{
return _bindingNameToValue[bindingName];
}
public function getPropertyName(bindingIndex : uint) : String
{
if (bindingIndex > numProperties)
throw new ArgumentError('No such binding');
return _bindingNames[bindingIndex];
}
/**
* A provider attribute has changed, and the provider tells us.
* For example, camera.fov has changed, the camera dispatches a 'changed' signal with 'fov' as attributeName.
*
* It could also be that camera.localToWorld has been replaced by another matrix instance.
*/
private function onProviderChange(source : IDataProvider, attributeName : String) : void
{
if (attributeName == null)
{
throw new Error('DataProviders must change one property at a time.');
}
else if (attributeName == 'dataDescriptor')
{
remove(source);
add(source);
}
else
{
var bindingName : String = source.dataDescriptor[attributeName];
var oldDpValue : IDataProvider = _bindingNameToValue[bindingName] as IDataProvider;
var newValue : Object = source[attributeName];
var newDpValue : IDataProvider = newValue as IDataProvider;
// we are replacing a data provider. We must remove listeners and related mapping keys
if (oldDpValue != null)
{
oldDpValue.changed.remove(onProviderAttributeChange);
var providers : Vector.<IDataProvider> = _attributeToProviders[oldDpValue];
var attrNames : Vector.<String> = _attributeToProvidersAttrNames[oldDpValue];
if (providers.length == 1)
{
delete _attributeToProviders[oldDpValue];
delete _attributeToProvidersAttrNames[oldDpValue];
}
else
{
var index : uint = providers.indexOf(source);
providers.splice(index, 1);
attrNames.splice(index, 1);
}
}
// the new value for this key is a dataprovider, we must listen changes.
if (newDpValue != null)
{
newDpValue.changed.add(onProviderAttributeChange);
if (!_attributeToProviders[newDpValue])
_attributeToProviders[newDpValue] = new <IDataProvider>[];
if (!_attributeToProvidersAttrNames[newDpValue])
_attributeToProvidersAttrNames[newDpValue] = new <String>[];
_attributeToProviders[newDpValue].push(source);
_attributeToProvidersAttrNames[newDpValue].push(attributeName);
}
_bindingNameToValue[bindingName] = newValue;
getPropertyChangedSignal(bindingName).execute(this, bindingName, newValue);
}
}
/**
* A provider attribute has changed, and the attribute tells us.
* For example, camera.localToWorld has been updated.
*/
private function onProviderAttributeChange(source : IDataProvider, key : String) : void
{
var providers : Vector.<IDataProvider> = _attributeToProviders[source];
var attrNames : Vector.<String> = _attributeToProvidersAttrNames[source];
var numProviders : uint = providers.length;
for (var providerId : uint = 0; providerId < numProviders; ++providerId)
{
var provider : IDataProvider = providers[providerId];
var attrName : String = attrNames[providerId];
var bindingName : String = provider.dataDescriptor[attrName];
getPropertyChangedSignal(bindingName).execute(this, bindingName, source);
}
}
}
}
|
package aerys.minko.type.data
{
import aerys.minko.type.Signal;
import flash.utils.Dictionary;
public class DataBindings
{
private var _bindingNames : Vector.<String> = new Vector.<String>();
private var _bindingNameToValue : Object = {};
private var _bindingNameToChangedSignal : Object = {};
private var _providerToBindingNames : Dictionary = new Dictionary(); // dic[Vector.<String>[]]
private var _attributeToProviders : Dictionary = new Dictionary(); // dic[Vector.<IDataProvider>[]]
private var _attributeToProvidersAttrNames : Dictionary = new Dictionary(); // dic[Vector.<String>[]]
public function get numProperties() : uint
{
return _bindingNames.length;
}
public function DataBindings()
{
}
public function add(provider : IDataProvider) : void
{
if (_providerToBindingNames[provider])
throw new Error('This provider is already binded');
var providerBindingNames : Vector.<String> = new Vector.<String>();
var dataDescriptor : Object = provider.dataDescriptor;
provider.changed.add(onProviderChange);
for (var attrName : String in dataDescriptor)
{
// if this provider attribute is also a dataprovider, let's also bind it
var bindingName : String = dataDescriptor[attrName];
var attribute : Object = provider[attrName]
var dpAttribute : IDataProvider = attribute as IDataProvider;
if (_bindingNames.indexOf(bindingName) != -1)
throw new Error('Another Dataprovider is already declaring "' + bindingName + '". Cannot overwrite.');
if (dpAttribute != null)
{
dpAttribute.changed.add(onProviderAttributeChange);
if (!_attributeToProviders[dpAttribute])
_attributeToProviders[dpAttribute] = new <IDataProvider>[];
if (!_attributeToProvidersAttrNames[dpAttribute])
_attributeToProvidersAttrNames[dpAttribute] = new <String>[];
_attributeToProviders[dpAttribute].push(provider);
_attributeToProvidersAttrNames[dpAttribute].push(attrName);
}
_bindingNameToValue[bindingName] = attribute;
providerBindingNames.push(bindingName);
_bindingNames.push(bindingName);
getPropertyChangedSignal(bindingName).execute(this, bindingName, attribute);
}
_providerToBindingNames[provider] = providerBindingNames;
}
public function remove(provider : IDataProvider) : void
{
var bindingNames : Vector.<String> = _providerToBindingNames[provider];
if (bindingNames == null)
throw new ArgumentError('No such provider was binded');
for each (var bindingName : String in bindingNames)
{
var indexOf : int = _bindingNames.indexOf(bindingName);
_bindingNames.splice(indexOf, 1);
if (_bindingNameToValue[bindingName] is IDataProvider)
IDataProvider(_bindingNameToValue[bindingName]).changed.remove(onProviderAttributeChange);
delete _bindingNameToValue[bindingName];
}
var attributesToDelete : Vector.<Object> = new Vector.<Object>();
for (var attribute : Object in _attributeToProviders)
{
var providers : Vector.<IDataProvider> = _attributeToProviders[attribute];
var attrNames : Vector.<String> = _attributeToProvidersAttrNames[attribute];
var indexOfProvider : int = providers.indexOf(provider);
if (indexOfProvider != -1)
{
providers.splice(indexOfProvider, 1);
attrNames.splice(indexOfProvider, 1);
}
if (providers.length == 0)
attributesToDelete.push(attribute);
}
for (var attributeToDelete : Object in attributesToDelete)
{
delete _attributeToProviders[attributeToDelete];
delete _attributeToProvidersAttrNames[attributeToDelete];
}
provider.changed.remove(onProviderChange);
delete _providerToBindingNames[provider];
for each (bindingName in bindingNames)
getPropertyChangedSignal(bindingName).execute(this, bindingName, null);
}
public function getPropertyChangedSignal(bindingName : String) : Signal
{
if (!_bindingNameToChangedSignal[bindingName])
_bindingNameToChangedSignal[bindingName] = new Signal('DataBindings.changed[' + bindingName + ']');
return _bindingNameToChangedSignal[bindingName];
}
public function propertyExists(bindingName : String) : Boolean
{
return _bindingNameToValue.hasOwnProperty(bindingName);
}
public function getProperty(bindingName : String) : *
{
return _bindingNameToValue[bindingName];
}
public function getPropertyName(bindingIndex : uint) : String
{
if (bindingIndex > numProperties)
throw new ArgumentError('No such binding');
return _bindingNames[bindingIndex];
}
/**
* A provider attribute has changed, and the provider tells us.
* For example, camera.fov has changed, the camera dispatches a 'changed' signal with 'fov' as attributeName.
*
* It could also be that camera.localToWorld has been replaced by another matrix instance.
*/
private function onProviderChange(source : IDataProvider, attributeName : String) : void
{
if (attributeName == null)
{
throw new Error('DataProviders must change one property at a time.');
}
else if (attributeName == 'dataDescriptor')
{
remove(source);
add(source);
}
else
{
var bindingName : String = source.dataDescriptor[attributeName];
var oldDpValue : IDataProvider = _bindingNameToValue[bindingName] as IDataProvider;
var newValue : Object = source[attributeName];
var newDpValue : IDataProvider = newValue as IDataProvider;
// we are replacing a data provider. We must remove listeners and related mapping keys
if (oldDpValue != null)
{
oldDpValue.changed.remove(onProviderAttributeChange);
var providers : Vector.<IDataProvider> = _attributeToProviders[oldDpValue];
var attrNames : Vector.<String> = _attributeToProvidersAttrNames[oldDpValue];
if (providers.length == 1)
{
delete _attributeToProviders[oldDpValue];
delete _attributeToProvidersAttrNames[oldDpValue];
}
else
{
var index : uint = providers.indexOf(source);
providers.splice(index, 1);
attrNames.splice(index, 1);
}
}
// the new value for this key is a dataprovider, we must listen changes.
if (newDpValue != null)
{
newDpValue.changed.add(onProviderAttributeChange);
if (!_attributeToProviders[newDpValue])
_attributeToProviders[newDpValue] = new <IDataProvider>[];
if (!_attributeToProvidersAttrNames[newDpValue])
_attributeToProvidersAttrNames[newDpValue] = new <String>[];
_attributeToProviders[newDpValue].push(source);
_attributeToProvidersAttrNames[newDpValue].push(attributeName);
}
_bindingNameToValue[bindingName] = newValue;
getPropertyChangedSignal(bindingName).execute(this, bindingName, newValue);
}
}
/**
* A provider attribute has changed, and the attribute tells us.
* For example, camera.localToWorld has been updated.
*/
private function onProviderAttributeChange(source : IDataProvider, key : String) : void
{
var providers : Vector.<IDataProvider> = _attributeToProviders[source];
var attrNames : Vector.<String> = _attributeToProvidersAttrNames[source];
var numProviders : uint = providers.length;
for (var providerId : uint = 0; providerId < numProviders; ++providerId)
{
var provider : IDataProvider = providers[providerId];
var attrName : String = attrNames[providerId];
var bindingName : String = provider.dataDescriptor[attrName];
getPropertyChangedSignal(bindingName).execute(this, bindingName, source);
}
}
}
}
|
remove debug call to trace() in DataBindings.remove()
|
remove debug call to trace() in DataBindings.remove()
|
ActionScript
|
mit
|
aerys/minko-as3
|
dc39d9e17cbac62d5b1f79e6ffa94501fa295a26
|
bin/Data/Scripts/Editor/EditorGizmo.as
|
bin/Data/Scripts/Editor/EditorGizmo.as
|
// Urho3D editor node transform gizmo handling
Node@ gizmoNode;
StaticModel@ gizmo;
const float axisMaxD = 0.1;
const float axisMaxT = 1.0;
const float rotSensitivity = 50.0;
EditMode lastGizmoMode;
// For undo
bool previousGizmoDrag;
bool needGizmoUndo;
Array<Transform> oldGizmoTransforms;
class GizmoAxis
{
Ray axisRay;
bool selected;
bool lastSelected;
float t;
float d;
float lastT;
float lastD;
GizmoAxis()
{
selected = false;
lastSelected = false;
t = 0.0;
d = 0.0;
lastT = 0.0;
lastD = 0.0;
}
void Update(Ray cameraRay, float scale, bool drag)
{
// Do not select when UI has modal element
if (ui.HasModalElement())
{
selected = false;
return;
}
Vector3 closest = cameraRay.ClosestPoint(axisRay);
Vector3 projected = axisRay.Project(closest);
d = axisRay.Distance(closest);
t = (projected - axisRay.origin).DotProduct(axisRay.direction);
// Determine the sign of d from a plane that goes through the camera position to the axis
Plane axisPlane(cameraNode.position, axisRay.origin, axisRay.origin + axisRay.direction);
if (axisPlane.Distance(closest) < 0.0)
d = -d;
// Update selected status only when not dragging
if (!drag)
{
selected = Abs(d) < axisMaxD * scale && t >= -axisMaxD * scale && t <= axisMaxT * scale;
lastT = t;
lastD = d;
}
}
void Moved()
{
lastT = t;
lastD = d;
}
}
GizmoAxis gizmoAxisX;
GizmoAxis gizmoAxisY;
GizmoAxis gizmoAxisZ;
void CreateGizmo()
{
gizmoNode = Node();
gizmo = gizmoNode.CreateComponent("StaticModel");
gizmo.model = cache.GetResource("Model", "Models/Editor/Axes.mdl");
gizmo.materials[0] = cache.GetResource("Material", "Materials/Editor/RedUnlit.xml");
gizmo.materials[1] = cache.GetResource("Material", "Materials/Editor/GreenUnlit.xml");
gizmo.materials[2] = cache.GetResource("Material", "Materials/Editor/BlueUnlit.xml");
gizmo.enabled = false;
gizmo.viewMask = 0x80000000; // Editor raycasts use viewmask 0x7fffffff
gizmo.occludee = false;
gizmoAxisX.lastSelected = false;
gizmoAxisY.lastSelected = false;
gizmoAxisZ.lastSelected = false;
lastGizmoMode = EDIT_MOVE;
}
void HideGizmo()
{
if (gizmo !is null)
gizmo.enabled = false;
}
void ShowGizmo()
{
if (gizmo !is null)
{
gizmo.enabled = true;
// Because setting enabled = false detaches the gizmo from octree,
// and it is a manually added drawable, must readd to octree when showing
if (editorScene.octree !is null)
editorScene.octree.AddManualDrawable(gizmo);
}
}
void UpdateGizmo()
{
UseGizmo();
PositionGizmo();
ResizeGizmo();
}
void PositionGizmo()
{
if (gizmo is null)
return;
Vector3 center(0, 0, 0);
bool containsScene = false;
for (uint i = 0; i < editNodes.length; ++i)
{
// Scene's transform should not be edited, so hide gizmo if it is included
if (editNodes[i] is editorScene)
{
containsScene = true;
break;
}
center += editNodes[i].worldPosition;
}
if (editNodes.empty || containsScene)
{
HideGizmo();
return;
}
center /= editNodes.length;
gizmoNode.position = center;
if (axisMode == AXIS_WORLD || editNodes.length > 1)
gizmoNode.rotation = Quaternion();
else
gizmoNode.rotation = editNodes[0].worldRotation;
if (editMode != lastGizmoMode)
{
switch (editMode)
{
case EDIT_MOVE:
gizmo.model = cache.GetResource("Model", "Models/Editor/Axes.mdl");
break;
case EDIT_ROTATE:
gizmo.model = cache.GetResource("Model", "Models/Editor/RotateAxes.mdl");
break;
case EDIT_SCALE:
gizmo.model = cache.GetResource("Model", "Models/Editor/ScaleAxes.mdl");
break;
}
lastGizmoMode = editMode;
}
if ((editMode != EDIT_SELECT && !orbiting) && !gizmo.enabled)
ShowGizmo();
else if ((editMode == EDIT_SELECT || orbiting) && gizmo.enabled)
HideGizmo();
}
void ResizeGizmo()
{
if (gizmo is null || !gizmo.enabled)
return;
float scale = 0.1;
if (camera.orthographic)
scale *= camera.orthoSize;
else
scale *= (camera.view.Inverse() * gizmoNode.position).z;
gizmoNode.scale = Vector3(scale, scale, scale);
}
void CalculateGizmoAxes()
{
gizmoAxisX.axisRay = Ray(gizmoNode.position, gizmoNode.rotation * Vector3(1, 0, 0));
gizmoAxisY.axisRay = Ray(gizmoNode.position, gizmoNode.rotation * Vector3(0, 1, 0));
gizmoAxisZ.axisRay = Ray(gizmoNode.position, gizmoNode.rotation * Vector3(0, 0, 1));
}
void GizmoMoved()
{
gizmoAxisX.Moved();
gizmoAxisY.Moved();
gizmoAxisZ.Moved();
}
void UseGizmo()
{
if (gizmo is null || !gizmo.enabled || editMode == EDIT_SELECT)
{
StoreGizmoEditActions();
previousGizmoDrag = false;
return;
}
IntVector2 pos = ui.cursorPosition;
if (ui.GetElementAt(pos) !is null)
return;
Ray cameraRay = GetActiveViewportCameraRay();
float scale = gizmoNode.scale.x;
// Recalculate axes only when not left-dragging
bool drag = input.mouseButtonDown[MOUSEB_LEFT];
if (!drag)
CalculateGizmoAxes();
gizmoAxisX.Update(cameraRay, scale, drag);
gizmoAxisY.Update(cameraRay, scale, drag);
gizmoAxisZ.Update(cameraRay, scale, drag);
if (gizmoAxisX.selected != gizmoAxisX.lastSelected)
{
gizmo.materials[0] = cache.GetResource("Material", gizmoAxisX.selected ? "Materials/Editor/BrightRedUnlit.xml" :
"Materials/Editor/RedUnlit.xml");
gizmoAxisX.lastSelected = gizmoAxisX.selected;
}
if (gizmoAxisY.selected != gizmoAxisY.lastSelected)
{
gizmo.materials[1] = cache.GetResource("Material", gizmoAxisY.selected ? "Materials/Editor/BrightGreenUnlit.xml" :
"Materials/Editor/GreenUnlit.xml");
gizmoAxisY.lastSelected = gizmoAxisY.selected;
}
if (gizmoAxisZ.selected != gizmoAxisZ.lastSelected)
{
gizmo.materials[2] = cache.GetResource("Material", gizmoAxisZ.selected ? "Materials/Editor/BrightBlueUnlit.xml" :
"Materials/Editor/BlueUnlit.xml");
gizmoAxisZ.lastSelected = gizmoAxisZ.selected;
};
if (drag)
{
// Store initial transforms for undo when gizmo drag started
if (!previousGizmoDrag)
{
oldGizmoTransforms.Resize(editNodes.length);
for (uint i = 0; i < editNodes.length; ++i)
oldGizmoTransforms[i].Define(editNodes[i]);
}
bool moved = false;
if (editMode == EDIT_MOVE)
{
Vector3 adjust(0, 0, 0);
if (gizmoAxisX.selected)
adjust += Vector3(1, 0, 0) * (gizmoAxisX.t - gizmoAxisX.lastT);
if (gizmoAxisY.selected)
adjust += Vector3(0, 1, 0) * (gizmoAxisY.t - gizmoAxisY.lastT);
if (gizmoAxisZ.selected)
adjust += Vector3(0, 0, 1) * (gizmoAxisZ.t - gizmoAxisZ.lastT);
moved = MoveNodes(adjust);
}
else if (editMode == EDIT_ROTATE)
{
Vector3 adjust(0, 0, 0);
if (gizmoAxisX.selected)
adjust.x = (gizmoAxisX.d - gizmoAxisX.lastD) * rotSensitivity / scale;
if (gizmoAxisY.selected)
adjust.y = -(gizmoAxisY.d - gizmoAxisY.lastD) * rotSensitivity / scale;
if (gizmoAxisZ.selected)
adjust.z = (gizmoAxisZ.d - gizmoAxisZ.lastD) * rotSensitivity / scale;
moved = RotateNodes(adjust);
}
else if (editMode == EDIT_SCALE)
{
Vector3 adjust(0, 0, 0);
if (gizmoAxisX.selected)
adjust += Vector3(1, 0, 0) * (gizmoAxisX.t - gizmoAxisX.lastT);
if (gizmoAxisY.selected)
adjust += Vector3(0, 1, 0) * (gizmoAxisY.t - gizmoAxisY.lastT);
if (gizmoAxisZ.selected)
adjust += Vector3(0, 0, 1) * (gizmoAxisZ.t - gizmoAxisZ.lastT);
// Special handling for uniform scale: use the unmodified X-axis movement only
if (editMode == EDIT_SCALE && gizmoAxisX.selected && gizmoAxisY.selected && gizmoAxisZ.selected)
{
float x = gizmoAxisX.t - gizmoAxisX.lastT;
adjust = Vector3(x, x, x);
}
moved = ScaleNodes(adjust);
}
if (moved)
{
GizmoMoved();
UpdateNodeAttributes();
needGizmoUndo = true;
}
}
else
{
if (previousGizmoDrag)
StoreGizmoEditActions();
}
previousGizmoDrag = drag;
}
bool IsGizmoSelected()
{
return gizmo !is null && gizmo.enabled && (gizmoAxisX.selected || gizmoAxisY.selected || gizmoAxisZ.selected);
}
bool MoveNodes(Vector3 adjust)
{
bool moved = false;
if (adjust.length > M_EPSILON)
{
for (uint i = 0; i < editNodes.length; ++i)
{
if (moveSnap)
{
float moveStepScaled = moveStep * snapScale;
adjust.x = Floor(adjust.x / moveStepScaled + 0.5) * moveStepScaled;
adjust.y = Floor(adjust.y / moveStepScaled + 0.5) * moveStepScaled;
adjust.z = Floor(adjust.z / moveStepScaled + 0.5) * moveStepScaled;
}
Node@ node = editNodes[i];
Vector3 nodeAdjust = adjust;
if (axisMode == AXIS_LOCAL && editNodes.length == 1)
nodeAdjust = node.worldRotation * nodeAdjust;
Vector3 worldPos = node.worldPosition;
Vector3 oldPos = node.position;
worldPos += nodeAdjust;
if (node.parent is null)
node.position = worldPos;
else
node.position = node.parent.WorldToLocal(worldPos);
if (node.position != oldPos)
moved = true;
}
}
return moved;
}
bool RotateNodes(Vector3 adjust)
{
bool moved = false;
if (rotateSnap)
{
float rotateStepScaled = rotateStep * snapScale;
adjust.x = Floor(adjust.x / rotateStepScaled + 0.5) * rotateStepScaled;
adjust.y = Floor(adjust.y / rotateStepScaled + 0.5) * rotateStepScaled;
adjust.z = Floor(adjust.z / rotateStepScaled + 0.5) * rotateStepScaled;
}
if (adjust.length > M_EPSILON)
{
moved = true;
for (uint i = 0; i < editNodes.length; ++i)
{
Node@ node = editNodes[i];
Quaternion rotQuat(adjust);
if (axisMode == AXIS_LOCAL && editNodes.length == 1)
node.rotation = node.rotation * rotQuat;
else
{
Vector3 offset = node.worldPosition - gizmoAxisX.axisRay.origin;
if (node.parent !is null && node.parent.worldRotation != Quaternion(1, 0, 0, 0))
rotQuat = node.parent.worldRotation.Inverse() * rotQuat * node.parent.worldRotation;
node.rotation = rotQuat * node.rotation;
Vector3 newPosition = gizmoAxisX.axisRay.origin + rotQuat * offset;
if (node.parent !is null)
newPosition = node.parent.WorldToLocal(newPosition);
node.position = newPosition;
}
}
}
return moved;
}
bool ScaleNodes(Vector3 adjust)
{
bool moved = false;
if (adjust.length > M_EPSILON)
{
for (uint i = 0; i < editNodes.length; ++i)
{
Node@ node = editNodes[i];
Vector3 scale = node.scale;
Vector3 oldScale = scale;
if (!scaleSnap)
scale += adjust;
else
{
float scaleStepScaled = scaleStep * snapScale;
if (adjust.x != 0)
{
scale.x += adjust.x * scaleStepScaled;
scale.x = Floor(scale.x / scaleStepScaled + 0.5) * scaleStepScaled;
}
if (adjust.y != 0)
{
scale.y += adjust.y * scaleStepScaled;
scale.y = Floor(scale.y / scaleStepScaled + 0.5) * scaleStepScaled;
}
if (adjust.z != 0)
{
scale.z += adjust.z * scaleStepScaled;
scale.z = Floor(scale.z / scaleStepScaled + 0.5) * scaleStepScaled;
}
}
if (scale != oldScale)
moved = true;
node.scale = scale;
}
}
return moved;
}
void StoreGizmoEditActions()
{
if (needGizmoUndo && editNodes.length > 0 && oldGizmoTransforms.length == editNodes.length)
{
EditActionGroup group;
for (uint i = 0; i < editNodes.length; ++i)
{
EditNodeTransformAction action;
action.Define(editNodes[i], oldGizmoTransforms[i]);
group.actions.Push(action);
}
SaveEditActionGroup(group);
SetSceneModified();
}
needGizmoUndo = false;
}
|
// Urho3D editor node transform gizmo handling
Node@ gizmoNode;
StaticModel@ gizmo;
const float axisMaxD = 0.1;
const float axisMaxT = 1.0;
const float rotSensitivity = 50.0;
EditMode lastGizmoMode;
// For undo
bool previousGizmoDrag;
bool needGizmoUndo;
Array<Transform> oldGizmoTransforms;
class GizmoAxis
{
Ray axisRay;
bool selected;
bool lastSelected;
float t;
float d;
float lastT;
float lastD;
GizmoAxis()
{
selected = false;
lastSelected = false;
t = 0.0;
d = 0.0;
lastT = 0.0;
lastD = 0.0;
}
void Update(Ray cameraRay, float scale, bool drag)
{
// Do not select when UI has modal element
if (ui.HasModalElement())
{
selected = false;
return;
}
Vector3 closest = cameraRay.ClosestPoint(axisRay);
Vector3 projected = axisRay.Project(closest);
d = axisRay.Distance(closest);
t = (projected - axisRay.origin).DotProduct(axisRay.direction);
// Determine the sign of d from a plane that goes through the camera position to the axis
Plane axisPlane(cameraNode.position, axisRay.origin, axisRay.origin + axisRay.direction);
if (axisPlane.Distance(closest) < 0.0)
d = -d;
// Update selected status only when not dragging
if (!drag)
{
selected = Abs(d) < axisMaxD * scale && t >= -axisMaxD * scale && t <= axisMaxT * scale;
lastT = t;
lastD = d;
}
}
void Moved()
{
lastT = t;
lastD = d;
}
}
GizmoAxis gizmoAxisX;
GizmoAxis gizmoAxisY;
GizmoAxis gizmoAxisZ;
void CreateGizmo()
{
gizmoNode = Node();
gizmo = gizmoNode.CreateComponent("StaticModel");
gizmo.model = cache.GetResource("Model", "Models/Editor/Axes.mdl");
gizmo.materials[0] = cache.GetResource("Material", "Materials/Editor/RedUnlit.xml");
gizmo.materials[1] = cache.GetResource("Material", "Materials/Editor/GreenUnlit.xml");
gizmo.materials[2] = cache.GetResource("Material", "Materials/Editor/BlueUnlit.xml");
gizmo.enabled = false;
gizmo.viewMask = 0x80000000; // Editor raycasts use viewmask 0x7fffffff
gizmo.occludee = false;
gizmoAxisX.lastSelected = false;
gizmoAxisY.lastSelected = false;
gizmoAxisZ.lastSelected = false;
lastGizmoMode = EDIT_MOVE;
}
void HideGizmo()
{
if (gizmo !is null)
gizmo.enabled = false;
}
void ShowGizmo()
{
if (gizmo !is null)
{
gizmo.enabled = true;
// Because setting enabled = false detaches the gizmo from octree,
// and it is a manually added drawable, must readd to octree when showing
if (editorScene.octree !is null)
editorScene.octree.AddManualDrawable(gizmo);
}
}
void UpdateGizmo()
{
UseGizmo();
PositionGizmo();
ResizeGizmo();
}
void PositionGizmo()
{
if (gizmo is null)
return;
Vector3 center(0, 0, 0);
bool containsScene = false;
for (uint i = 0; i < editNodes.length; ++i)
{
// Scene's transform should not be edited, so hide gizmo if it is included
if (editNodes[i] is editorScene)
{
containsScene = true;
break;
}
center += editNodes[i].worldPosition;
}
if (editNodes.empty || containsScene)
{
HideGizmo();
return;
}
center /= editNodes.length;
gizmoNode.position = center;
if (axisMode == AXIS_WORLD || editNodes.length > 1)
gizmoNode.rotation = Quaternion();
else
gizmoNode.rotation = editNodes[0].worldRotation;
if (editMode != lastGizmoMode)
{
switch (editMode)
{
case EDIT_MOVE:
gizmo.model = cache.GetResource("Model", "Models/Editor/Axes.mdl");
break;
case EDIT_ROTATE:
gizmo.model = cache.GetResource("Model", "Models/Editor/RotateAxes.mdl");
break;
case EDIT_SCALE:
gizmo.model = cache.GetResource("Model", "Models/Editor/ScaleAxes.mdl");
break;
}
lastGizmoMode = editMode;
}
if ((editMode != EDIT_SELECT && !orbiting) && !gizmo.enabled)
ShowGizmo();
else if ((editMode == EDIT_SELECT || orbiting) && gizmo.enabled)
HideGizmo();
}
void ResizeGizmo()
{
if (gizmo is null || !gizmo.enabled)
return;
float scale = 0.1 / camera.zoom;
if (camera.orthographic)
scale *= camera.orthoSize;
else
scale *= (camera.view * gizmoNode.position).z;
gizmoNode.scale = Vector3(scale, scale, scale);
}
void CalculateGizmoAxes()
{
gizmoAxisX.axisRay = Ray(gizmoNode.position, gizmoNode.rotation * Vector3(1, 0, 0));
gizmoAxisY.axisRay = Ray(gizmoNode.position, gizmoNode.rotation * Vector3(0, 1, 0));
gizmoAxisZ.axisRay = Ray(gizmoNode.position, gizmoNode.rotation * Vector3(0, 0, 1));
}
void GizmoMoved()
{
gizmoAxisX.Moved();
gizmoAxisY.Moved();
gizmoAxisZ.Moved();
}
void UseGizmo()
{
if (gizmo is null || !gizmo.enabled || editMode == EDIT_SELECT)
{
StoreGizmoEditActions();
previousGizmoDrag = false;
return;
}
IntVector2 pos = ui.cursorPosition;
if (ui.GetElementAt(pos) !is null)
return;
Ray cameraRay = GetActiveViewportCameraRay();
float scale = gizmoNode.scale.x;
// Recalculate axes only when not left-dragging
bool drag = input.mouseButtonDown[MOUSEB_LEFT];
if (!drag)
CalculateGizmoAxes();
gizmoAxisX.Update(cameraRay, scale, drag);
gizmoAxisY.Update(cameraRay, scale, drag);
gizmoAxisZ.Update(cameraRay, scale, drag);
if (gizmoAxisX.selected != gizmoAxisX.lastSelected)
{
gizmo.materials[0] = cache.GetResource("Material", gizmoAxisX.selected ? "Materials/Editor/BrightRedUnlit.xml" :
"Materials/Editor/RedUnlit.xml");
gizmoAxisX.lastSelected = gizmoAxisX.selected;
}
if (gizmoAxisY.selected != gizmoAxisY.lastSelected)
{
gizmo.materials[1] = cache.GetResource("Material", gizmoAxisY.selected ? "Materials/Editor/BrightGreenUnlit.xml" :
"Materials/Editor/GreenUnlit.xml");
gizmoAxisY.lastSelected = gizmoAxisY.selected;
}
if (gizmoAxisZ.selected != gizmoAxisZ.lastSelected)
{
gizmo.materials[2] = cache.GetResource("Material", gizmoAxisZ.selected ? "Materials/Editor/BrightBlueUnlit.xml" :
"Materials/Editor/BlueUnlit.xml");
gizmoAxisZ.lastSelected = gizmoAxisZ.selected;
};
if (drag)
{
// Store initial transforms for undo when gizmo drag started
if (!previousGizmoDrag)
{
oldGizmoTransforms.Resize(editNodes.length);
for (uint i = 0; i < editNodes.length; ++i)
oldGizmoTransforms[i].Define(editNodes[i]);
}
bool moved = false;
if (editMode == EDIT_MOVE)
{
Vector3 adjust(0, 0, 0);
if (gizmoAxisX.selected)
adjust += Vector3(1, 0, 0) * (gizmoAxisX.t - gizmoAxisX.lastT);
if (gizmoAxisY.selected)
adjust += Vector3(0, 1, 0) * (gizmoAxisY.t - gizmoAxisY.lastT);
if (gizmoAxisZ.selected)
adjust += Vector3(0, 0, 1) * (gizmoAxisZ.t - gizmoAxisZ.lastT);
moved = MoveNodes(adjust);
}
else if (editMode == EDIT_ROTATE)
{
Vector3 adjust(0, 0, 0);
if (gizmoAxisX.selected)
adjust.x = (gizmoAxisX.d - gizmoAxisX.lastD) * rotSensitivity / scale;
if (gizmoAxisY.selected)
adjust.y = -(gizmoAxisY.d - gizmoAxisY.lastD) * rotSensitivity / scale;
if (gizmoAxisZ.selected)
adjust.z = (gizmoAxisZ.d - gizmoAxisZ.lastD) * rotSensitivity / scale;
moved = RotateNodes(adjust);
}
else if (editMode == EDIT_SCALE)
{
Vector3 adjust(0, 0, 0);
if (gizmoAxisX.selected)
adjust += Vector3(1, 0, 0) * (gizmoAxisX.t - gizmoAxisX.lastT);
if (gizmoAxisY.selected)
adjust += Vector3(0, 1, 0) * (gizmoAxisY.t - gizmoAxisY.lastT);
if (gizmoAxisZ.selected)
adjust += Vector3(0, 0, 1) * (gizmoAxisZ.t - gizmoAxisZ.lastT);
// Special handling for uniform scale: use the unmodified X-axis movement only
if (editMode == EDIT_SCALE && gizmoAxisX.selected && gizmoAxisY.selected && gizmoAxisZ.selected)
{
float x = gizmoAxisX.t - gizmoAxisX.lastT;
adjust = Vector3(x, x, x);
}
moved = ScaleNodes(adjust);
}
if (moved)
{
GizmoMoved();
UpdateNodeAttributes();
needGizmoUndo = true;
}
}
else
{
if (previousGizmoDrag)
StoreGizmoEditActions();
}
previousGizmoDrag = drag;
}
bool IsGizmoSelected()
{
return gizmo !is null && gizmo.enabled && (gizmoAxisX.selected || gizmoAxisY.selected || gizmoAxisZ.selected);
}
bool MoveNodes(Vector3 adjust)
{
bool moved = false;
if (adjust.length > M_EPSILON)
{
for (uint i = 0; i < editNodes.length; ++i)
{
if (moveSnap)
{
float moveStepScaled = moveStep * snapScale;
adjust.x = Floor(adjust.x / moveStepScaled + 0.5) * moveStepScaled;
adjust.y = Floor(adjust.y / moveStepScaled + 0.5) * moveStepScaled;
adjust.z = Floor(adjust.z / moveStepScaled + 0.5) * moveStepScaled;
}
Node@ node = editNodes[i];
Vector3 nodeAdjust = adjust;
if (axisMode == AXIS_LOCAL && editNodes.length == 1)
nodeAdjust = node.worldRotation * nodeAdjust;
Vector3 worldPos = node.worldPosition;
Vector3 oldPos = node.position;
worldPos += nodeAdjust;
if (node.parent is null)
node.position = worldPos;
else
node.position = node.parent.WorldToLocal(worldPos);
if (node.position != oldPos)
moved = true;
}
}
return moved;
}
bool RotateNodes(Vector3 adjust)
{
bool moved = false;
if (rotateSnap)
{
float rotateStepScaled = rotateStep * snapScale;
adjust.x = Floor(adjust.x / rotateStepScaled + 0.5) * rotateStepScaled;
adjust.y = Floor(adjust.y / rotateStepScaled + 0.5) * rotateStepScaled;
adjust.z = Floor(adjust.z / rotateStepScaled + 0.5) * rotateStepScaled;
}
if (adjust.length > M_EPSILON)
{
moved = true;
for (uint i = 0; i < editNodes.length; ++i)
{
Node@ node = editNodes[i];
Quaternion rotQuat(adjust);
if (axisMode == AXIS_LOCAL && editNodes.length == 1)
node.rotation = node.rotation * rotQuat;
else
{
Vector3 offset = node.worldPosition - gizmoAxisX.axisRay.origin;
if (node.parent !is null && node.parent.worldRotation != Quaternion(1, 0, 0, 0))
rotQuat = node.parent.worldRotation.Inverse() * rotQuat * node.parent.worldRotation;
node.rotation = rotQuat * node.rotation;
Vector3 newPosition = gizmoAxisX.axisRay.origin + rotQuat * offset;
if (node.parent !is null)
newPosition = node.parent.WorldToLocal(newPosition);
node.position = newPosition;
}
}
}
return moved;
}
bool ScaleNodes(Vector3 adjust)
{
bool moved = false;
if (adjust.length > M_EPSILON)
{
for (uint i = 0; i < editNodes.length; ++i)
{
Node@ node = editNodes[i];
Vector3 scale = node.scale;
Vector3 oldScale = scale;
if (!scaleSnap)
scale += adjust;
else
{
float scaleStepScaled = scaleStep * snapScale;
if (adjust.x != 0)
{
scale.x += adjust.x * scaleStepScaled;
scale.x = Floor(scale.x / scaleStepScaled + 0.5) * scaleStepScaled;
}
if (adjust.y != 0)
{
scale.y += adjust.y * scaleStepScaled;
scale.y = Floor(scale.y / scaleStepScaled + 0.5) * scaleStepScaled;
}
if (adjust.z != 0)
{
scale.z += adjust.z * scaleStepScaled;
scale.z = Floor(scale.z / scaleStepScaled + 0.5) * scaleStepScaled;
}
}
if (scale != oldScale)
moved = true;
node.scale = scale;
}
}
return moved;
}
void StoreGizmoEditActions()
{
if (needGizmoUndo && editNodes.length > 0 && oldGizmoTransforms.length == editNodes.length)
{
EditActionGroup group;
for (uint i = 0; i < editNodes.length; ++i)
{
EditNodeTransformAction action;
action.Define(editNodes[i], oldGizmoTransforms[i]);
group.actions.Push(action);
}
SaveEditActionGroup(group);
SetSceneModified();
}
needGizmoUndo = false;
}
|
Fix wrong matrix math in gizmo scaling. Take zoom into account.
|
Fix wrong matrix math in gizmo scaling. Take zoom into account.
|
ActionScript
|
mit
|
weitjong/Urho3D,luveti/Urho3D,PredatorMF/Urho3D,codemon66/Urho3D,cosmy1/Urho3D,bacsmar/Urho3D,SuperWangKai/Urho3D,luveti/Urho3D,cosmy1/Urho3D,helingping/Urho3D,eugeneko/Urho3D,xiliu98/Urho3D,weitjong/Urho3D,codedash64/Urho3D,xiliu98/Urho3D,codedash64/Urho3D,xiliu98/Urho3D,xiliu98/Urho3D,henu/Urho3D,SuperWangKai/Urho3D,codedash64/Urho3D,iainmerrick/Urho3D,urho3d/Urho3D,henu/Urho3D,codemon66/Urho3D,299299/Urho3D,abdllhbyrktr/Urho3D,299299/Urho3D,victorholt/Urho3D,299299/Urho3D,orefkov/Urho3D,henu/Urho3D,bacsmar/Urho3D,iainmerrick/Urho3D,victorholt/Urho3D,SirNate0/Urho3D,carnalis/Urho3D,tommy3/Urho3D,victorholt/Urho3D,cosmy1/Urho3D,henu/Urho3D,MeshGeometry/Urho3D,helingping/Urho3D,fire/Urho3D-1,cosmy1/Urho3D,bacsmar/Urho3D,helingping/Urho3D,kostik1337/Urho3D,eugeneko/Urho3D,codemon66/Urho3D,rokups/Urho3D,kostik1337/Urho3D,codedash64/Urho3D,rokups/Urho3D,iainmerrick/Urho3D,tommy3/Urho3D,abdllhbyrktr/Urho3D,tommy3/Urho3D,MonkeyFirst/Urho3D,c4augustus/Urho3D,victorholt/Urho3D,kostik1337/Urho3D,iainmerrick/Urho3D,helingping/Urho3D,abdllhbyrktr/Urho3D,henu/Urho3D,PredatorMF/Urho3D,PredatorMF/Urho3D,helingping/Urho3D,eugeneko/Urho3D,iainmerrick/Urho3D,SirNate0/Urho3D,MeshGeometry/Urho3D,weitjong/Urho3D,MonkeyFirst/Urho3D,MeshGeometry/Urho3D,bacsmar/Urho3D,MonkeyFirst/Urho3D,PredatorMF/Urho3D,c4augustus/Urho3D,codedash64/Urho3D,luveti/Urho3D,c4augustus/Urho3D,victorholt/Urho3D,abdllhbyrktr/Urho3D,carnalis/Urho3D,rokups/Urho3D,SirNate0/Urho3D,SuperWangKai/Urho3D,SirNate0/Urho3D,urho3d/Urho3D,c4augustus/Urho3D,fire/Urho3D-1,299299/Urho3D,MeshGeometry/Urho3D,fire/Urho3D-1,luveti/Urho3D,carnalis/Urho3D,orefkov/Urho3D,carnalis/Urho3D,orefkov/Urho3D,rokups/Urho3D,tommy3/Urho3D,urho3d/Urho3D,codemon66/Urho3D,c4augustus/Urho3D,fire/Urho3D-1,weitjong/Urho3D,rokups/Urho3D,fire/Urho3D-1,299299/Urho3D,kostik1337/Urho3D,codemon66/Urho3D,abdllhbyrktr/Urho3D,weitjong/Urho3D,eugeneko/Urho3D,299299/Urho3D,SirNate0/Urho3D,SuperWangKai/Urho3D,SuperWangKai/Urho3D,tommy3/Urho3D,luveti/Urho3D,carnalis/Urho3D,rokups/Urho3D,MonkeyFirst/Urho3D,orefkov/Urho3D,kostik1337/Urho3D,cosmy1/Urho3D,MeshGeometry/Urho3D,urho3d/Urho3D,xiliu98/Urho3D,MonkeyFirst/Urho3D
|
0ef06393761a5e9586d9b01f017d93f706aca7bc
|
actionscript/src/com/freshplanet/ane/AirPushNotification/PushNotification.as
|
actionscript/src/com/freshplanet/ane/AirPushNotification/PushNotification.as
|
/**
* Copyright 2017 FreshPlanet
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.freshplanet.ane.AirPushNotification {
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.system.Capabilities;
/**
*
*/
public class PushNotification extends EventDispatcher {
// --------------------------------------------------------------------------------------//
// //
// PUBLIC API //
// //
// --------------------------------------------------------------------------------------//
public static const RECURRENCE_NONE:int = 0;
public static const RECURRENCE_DAILY:int = 1;
public static const RECURRENCE_WEEK:int = 2;
public static const RECURRENCE_MONTH:int = 3;
public static const RECURRENCE_YEAR:int = 4;
public static const DEFAULT_LOCAL_NOTIFICATION_ID:int = 0;
/**
* If <code>true</code>, logs will be displayed at the ActionScript level.
*/
public static var logEnabled:Boolean = false;
/**
*
*/
public static function get isSupported():Boolean {
return _isIOS() || _isAndroid();
}
/**
*
*/
public static function get instance():PushNotification {
return _instance ? _instance : new PushNotification();
}
/**
* return true if notifs are enabled for this app in device settings
* If iOS < 8 or android < 4.1 this isn't available, so will always return true.
*/
public function getNotificationsEnabled():void {
if (!isSupported)
return;
_context.call("getNotificationsEnabled");
}
/**
* Check if notificationChannel is enabled in Android notification settings
* @param channelId
* @return
*/
public function isNotificationChannelEnabled(channelId:String):Boolean {
if (!isSupported)
return false;
if(_isIOS())
return true;
return _context.call("checkNotificationChannelEnabled", channelId);
}
/**
* return true if OS permits sending user to settings (iOS 8, Android
*/
public function get canSendUserToSettings():Boolean {
if (!isSupported)
return false;
return _context.call("getCanSendUserToSettings");
}
/**
*
*/
public function openDeviceNotificationSettings(channelId:String = null):void {
if(!channelId)
channelId = "";
if (isSupported)
_context.call("openDeviceNotificationSettings", channelId);
}
/**
* Needs Project id for Android Notifications.
* The project id is the one the developer used to register to gcm.
* @param projectId: project id to use
* @param iOSNotificationCategories: notification categories used on iOS (PushNotificationCategoryiOS)
*/
public function registerForPushNotification(projectId:String = null, iOSNotificationCategories:Array = null):void {
if(!isSupported)
return;
if (_isAndroid())
_context.call("registerPush", projectId);
else if(_isIOS())
_context.call("registerPush", iOSNotificationCategories != null ? JSON.stringify(iOSNotificationCategories) : null);
}
/**
*
* @param value
*/
public function setBadgeNumberValue(value:int):void {
if (isSupported)
_context.call("setBadgeNb", value);
}
/**
* Sends a local notification to the device.
* @param message the local notification text displayed
* @param timestamp when the local notification should appear (in sec)
* @param title (Android Only) Title of the local notification
* @param recurrenceType
* @param notificationId
* @param deepLinkPath
* @param iconPath
* @param groupId used to group notifications together
* @param categoryId used to display custom summaries on iOS
* @param makeSquare used to display square icons on Android, will default to round
*/
public function sendLocalNotification(message:String,
timestamp:int,
title:String,
recurrenceType:int = RECURRENCE_NONE,
notificationId:int = DEFAULT_LOCAL_NOTIFICATION_ID,
deepLinkPath:String = null,
iconPath:String = null,
groupId:String = null,
categoryId:String = null,
makeSquare:Boolean = false
):void {
if (!isSupported)
return;
if(!iconPath)
iconPath = "";
if(!deepLinkPath)
deepLinkPath = "";
if(!groupId)
groupId = "";
if(!categoryId)
categoryId = "";
_context.call("sendLocalNotification", message, timestamp, title, recurrenceType, notificationId, deepLinkPath, iconPath, groupId, categoryId, makeSquare);
}
/**
* Not implemented on Android for now.
* @param notificationId
*/
public function cancelLocalNotification(notificationId:int = DEFAULT_LOCAL_NOTIFICATION_ID):void {
if (isSupported) {
if (notificationId == DEFAULT_LOCAL_NOTIFICATION_ID)
_context.call("cancelLocalNotification");
else
_context.call("cancelLocalNotification", notificationId);
}
}
/**
*
*/
public function cancelAllLocalNotifications():void {
if (isSupported)
_context.call("cancelAllLocalNotifications");
}
/**
*
* @param value
*/
public function setIsAppInForeground(value:Boolean, appGroupId:String):void {
if (isSupported)
_context.call("setIsAppInForeground", value, appGroupId);
}
/**
*
* @param listener
*/
public function addListenerForStarterNotifications(listener:Function):void {
if (isSupported) {
this.addEventListener(PushNotificationEvent.APP_STARTING_FROM_NOTIFICATION_EVENT, listener);
_context.call("fetchStarterNotification");
}
}
public function checkAppNotificationSettingsRequest():void {
if (_isIOS()) {
_context.call("checkAppNotificationSettingsRequest");
}
}
public function storeTrackingNotifUrl(url:String, appGroupId:String):void {
if (isSupported)
_context.call("storeNotifTrackingInfo", url, appGroupId);
}
/**
* Create Android notification channel
* @param channelId
* @param channelName
* @param importance
* @param enableLights
* @param enableVibration
*/
public function createAndroidNotificationChannel(channelId:String, channelName:String, importance:int, enableLights:Boolean, enableVibration:Boolean):void {
if (_isAndroid())
_context.call("createNotificationChannel", channelId, channelName, importance, enableLights, enableVibration);
}
// --------------------------------------------------------------------------------------//
// //
// PRIVATE API //
// //
// --------------------------------------------------------------------------------------//
private static const EXTENSION_ID:String = "com.freshplanet.ane.AirPushNotification";
private static var _instance:PushNotification = null;
private var _context:ExtensionContext = null;
/**
* "private" singleton constructor
*/
public function PushNotification() {
super();
if (_instance)
throw Error("This is a singleton, use getInstance(), do not call the constructor directly.");
_instance = this;
_context = ExtensionContext.createExtensionContext(EXTENSION_ID, null);
if (!_context)
_log("ERROR", "Extension context is null. Please check if extension.xml is setup correctly.");
else
_context.addEventListener(StatusEvent.STATUS, _onStatus);
}
/**
*
* @param strings
*/
private function _log(...strings):void {
if (logEnabled) {
strings.unshift(EXTENSION_ID);
trace.apply(null, strings);
}
}
/**
*
* @return true if iOS
*/
private static function _isIOS():Boolean {
return Capabilities.manufacturer.indexOf("iOS") > -1 && Capabilities.os.indexOf("x86_64") < 0 && Capabilities.os.indexOf("i386") < 0;
}
/**
*
* @return true if Android
*/
private static function _isAndroid():Boolean {
return Capabilities.manufacturer.indexOf("Android") > -1;
}
/**
*
* @param e
*/
private function _onStatus(e:StatusEvent):void {
var event:PushNotificationEvent = null;
var data:String = e.level;
switch (e.code) {
case "TOKEN_SUCCESS":
event = new PushNotificationEvent(PushNotificationEvent.PERMISSION_GIVEN_WITH_TOKEN_EVENT);
event.token = e.level;
break;
case "TOKEN_FAIL":
event = new PushNotificationEvent(PushNotificationEvent.PERMISSION_REFUSED_EVENT);
event.errorCode = "NativeCodeError";
event.errorMessage = e.level;
break;
case "COMING_FROM_NOTIFICATION":
event = new PushNotificationEvent(PushNotificationEvent.COMING_FROM_NOTIFICATION_EVENT);
if (data != null) {
try {
event.parameters = JSON.parse(data);
}
catch (error:Error) {
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "APP_STARTING_FROM_NOTIFICATION":
event = new PushNotificationEvent(PushNotificationEvent.APP_STARTING_FROM_NOTIFICATION_EVENT);
if (data != null) {
try {
event.parameters = JSON.parse(data);
}
catch (error:Error) {
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "APP_BROUGHT_TO_FOREGROUND_FROM_NOTIFICATION":
event = new PushNotificationEvent(PushNotificationEvent.APP_BROUGHT_TO_FOREGROUND_FROM_NOTIFICATION_EVENT);
if (data != null) {
try {
event.parameters = JSON.parse(data);
}
catch (error:Error) {
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "APP_STARTED_IN_BACKGROUND_FROM_NOTIFICATION":
event = new PushNotificationEvent(PushNotificationEvent.APP_STARTED_IN_BACKGROUND_FROM_NOTIFICATION_EVENT);
if (data != null) {
try {
event.parameters = JSON.parse(data);
}
catch (error:Error) {
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "NOTIFICATION_RECEIVED_WHEN_IN_FOREGROUND":
event = new PushNotificationEvent(PushNotificationEvent.NOTIFICATION_RECEIVED_WHEN_IN_FOREGROUND_EVENT);
if (data != null) {
try {
event.parameters = JSON.parse(data);
}
catch (error:Error) {
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "NOTIFICATION_SETTINGS_ENABLED":
event = new PushNotificationEvent(PushNotificationEvent.NOTIFICATION_SETTINGS_ENABLED);
break;
case "NOTIFICATION_SETTINGS_DISABLED":
event = new PushNotificationEvent(PushNotificationEvent.NOTIFICATION_SETTINGS_DISABLED);
break;
case "GET_NOTIFICATIONS_ENABLED_RESULT":
event = new PushNotificationEvent(PushNotificationEvent.GET_NOTIFICATIONS_ENABLED_RESULT, e.level == "true");
break;
case "OPEN_APP_NOTIFICATION_SETTINGS":
event = new PushNotificationEvent(PushNotificationEvent.OPEN_APP_NOTIFICATION_SETTINGS);
break;
case "LOGGING":
trace(e, e.level);
break;
}
if (event != null)
this.dispatchEvent(event);
}
}
}
|
/**
* Copyright 2017 FreshPlanet
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.freshplanet.ane.AirPushNotification {
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.system.Capabilities;
/**
*
*/
public class PushNotification extends EventDispatcher {
// --------------------------------------------------------------------------------------//
// //
// PUBLIC API //
// //
// --------------------------------------------------------------------------------------//
public static const RECURRENCE_NONE:int = 0;
public static const RECURRENCE_DAILY:int = 1;
public static const RECURRENCE_WEEK:int = 2;
public static const RECURRENCE_MONTH:int = 3;
public static const RECURRENCE_YEAR:int = 4;
public static const DEFAULT_LOCAL_NOTIFICATION_ID:int = 0;
/**
* If <code>true</code>, logs will be displayed at the ActionScript level.
*/
public static var logEnabled:Boolean = false;
/**
*
*/
public static function get isSupported():Boolean {
return _isIOS() || _isAndroid();
}
/**
*
*/
public static function get instance():PushNotification {
return _instance ? _instance : new PushNotification();
}
private function callContext(...args):*
{
var context: ExtensionContext = getContext();
if(!context) {
_log("ERROR", "Extension context is null. Please check if extension.xml is setup correctly.")
return null;
}
try {
return context.call.apply(context, args);
} catch (e: Error) {
_log("ERROR", "Error calling extension context: " + e.message + " : " + e.getStackTrace());
}
return null;
}
/**
* return true if notifs are enabled for this app in device settings
* If iOS < 8 or android < 4.1 this isn't available, so will always return true.
*/
public function getNotificationsEnabled():void {
if (!isSupported)
return;
callContext("getNotificationsEnabled");
}
/**
* Check if notificationChannel is enabled in Android notification settings
* @param channelId
* @return
*/
public function isNotificationChannelEnabled(channelId:String):Boolean {
if (!isSupported)
return false;
if(_isIOS())
return true;
return callContext("checkNotificationChannelEnabled", channelId);
}
/**
* return true if OS permits sending user to settings (iOS 8, Android
*/
public function get canSendUserToSettings():Boolean {
if (!isSupported)
return false;
return callContext("getCanSendUserToSettings");
}
/**
*
*/
public function openDeviceNotificationSettings(channelId:String = null):void {
if(!channelId)
channelId = "";
if (isSupported)
callContext("openDeviceNotificationSettings", channelId);
}
/**
* Needs Project id for Android Notifications.
* The project id is the one the developer used to register to gcm.
* @param projectId: project id to use
* @param iOSNotificationCategories: notification categories used on iOS (PushNotificationCategoryiOS)
*/
public function registerForPushNotification(projectId:String = null, iOSNotificationCategories:Array = null):void {
if(!isSupported)
return;
if (_isAndroid())
callContext("registerPush", projectId);
else if(_isIOS())
callContext("registerPush", iOSNotificationCategories != null ? JSON.stringify(iOSNotificationCategories) : null);
}
/**
*
* @param value
*/
public function setBadgeNumberValue(value:int):void {
if (isSupported)
callContext("setBadgeNb", value);
}
/**
* Sends a local notification to the device.
* @param message the local notification text displayed
* @param timestamp when the local notification should appear (in sec)
* @param title (Android Only) Title of the local notification
* @param recurrenceType
* @param notificationId
* @param deepLinkPath
* @param iconPath
* @param groupId used to group notifications together
* @param categoryId used to display custom summaries on iOS
* @param makeSquare used to display square icons on Android, will default to round
*/
public function sendLocalNotification(message:String,
timestamp:int,
title:String,
recurrenceType:int = RECURRENCE_NONE,
notificationId:int = DEFAULT_LOCAL_NOTIFICATION_ID,
deepLinkPath:String = null,
iconPath:String = null,
groupId:String = null,
categoryId:String = null,
makeSquare:Boolean = false
):void {
if (!isSupported)
return;
if(!iconPath)
iconPath = "";
if(!deepLinkPath)
deepLinkPath = "";
if(!groupId)
groupId = "";
if(!categoryId)
categoryId = "";
callContext("sendLocalNotification", message, timestamp, title, recurrenceType, notificationId, deepLinkPath, iconPath, groupId, categoryId, makeSquare);
}
/**
* Not implemented on Android for now.
* @param notificationId
*/
public function cancelLocalNotification(notificationId:int = DEFAULT_LOCAL_NOTIFICATION_ID):void {
if (isSupported) {
if (notificationId == DEFAULT_LOCAL_NOTIFICATION_ID)
callContext("cancelLocalNotification");
else
callContext("cancelLocalNotification", notificationId);
}
}
/**
*
*/
public function cancelAllLocalNotifications():void {
if (isSupported)
callContext("cancelAllLocalNotifications");
}
/**
*
* @param value
*/
public function setIsAppInForeground(value:Boolean, appGroupId:String):void {
if (isSupported)
callContext("setIsAppInForeground", value, appGroupId);
}
/**
*
* @param listener
*/
public function addListenerForStarterNotifications(listener:Function):void {
if (isSupported) {
this.addEventListener(PushNotificationEvent.APP_STARTING_FROM_NOTIFICATION_EVENT, listener);
callContext("fetchStarterNotification");
}
}
public function checkAppNotificationSettingsRequest():void {
if (_isIOS()) {
callContext("checkAppNotificationSettingsRequest");
}
}
public function storeTrackingNotifUrl(url:String, appGroupId:String):void {
if (isSupported)
callContext("storeNotifTrackingInfo", url, appGroupId);
}
/**
* Create Android notification channel
* @param channelId
* @param channelName
* @param importance
* @param enableLights
* @param enableVibration
*/
public function createAndroidNotificationChannel(channelId:String, channelName:String, importance:int, enableLights:Boolean, enableVibration:Boolean):void {
if (_isAndroid())
callContext("createNotificationChannel", channelId, channelName, importance, enableLights, enableVibration);
}
// --------------------------------------------------------------------------------------//
// //
// PRIVATE API //
// //
// --------------------------------------------------------------------------------------//
private static const EXTENSION_ID:String = "com.freshplanet.ane.AirPushNotification";
private static var _instance:PushNotification = null;
/**
* "private" singleton constructor
*/
public function PushNotification() {
super();
if (_instance)
throw Error("This is a singleton, use getInstance(), do not call the constructor directly.");
_instance = this;
}
private var __context:ExtensionContext;
private function getContext():ExtensionContext
{
if (!__context) {
__context = ExtensionContext.createExtensionContext(EXTENSION_ID, null);
if (!__context) {
_log("ERROR", "Extension context is null. Please check if extension.xml is setup correctly.");
} else {
__context.addEventListener(StatusEvent.STATUS, _onStatus);
}
}
return __context;
}
/**
*
* @param strings
*/
private function _log(...strings):void {
if (logEnabled) {
strings.unshift(EXTENSION_ID);
trace.apply(null, strings);
}
}
/**
*
* @return true if iOS
*/
private static function _isIOS():Boolean {
return Capabilities.manufacturer.indexOf("iOS") > -1 && Capabilities.os.indexOf("x86_64") < 0 && Capabilities.os.indexOf("i386") < 0;
}
/**
*
* @return true if Android
*/
private static function _isAndroid():Boolean {
return Capabilities.manufacturer.indexOf("Android") > -1;
}
/**
*
* @param e
*/
private function _onStatus(e:StatusEvent):void {
var event:PushNotificationEvent = null;
var data:String = e.level;
switch (e.code) {
case "TOKEN_SUCCESS":
event = new PushNotificationEvent(PushNotificationEvent.PERMISSION_GIVEN_WITH_TOKEN_EVENT);
event.token = e.level;
break;
case "TOKEN_FAIL":
event = new PushNotificationEvent(PushNotificationEvent.PERMISSION_REFUSED_EVENT);
event.errorCode = "NativeCodeError";
event.errorMessage = e.level;
break;
case "COMING_FROM_NOTIFICATION":
event = new PushNotificationEvent(PushNotificationEvent.COMING_FROM_NOTIFICATION_EVENT);
if (data != null) {
try {
event.parameters = JSON.parse(data);
}
catch (error:Error) {
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "APP_STARTING_FROM_NOTIFICATION":
event = new PushNotificationEvent(PushNotificationEvent.APP_STARTING_FROM_NOTIFICATION_EVENT);
if (data != null) {
try {
event.parameters = JSON.parse(data);
}
catch (error:Error) {
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "APP_BROUGHT_TO_FOREGROUND_FROM_NOTIFICATION":
event = new PushNotificationEvent(PushNotificationEvent.APP_BROUGHT_TO_FOREGROUND_FROM_NOTIFICATION_EVENT);
if (data != null) {
try {
event.parameters = JSON.parse(data);
}
catch (error:Error) {
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "APP_STARTED_IN_BACKGROUND_FROM_NOTIFICATION":
event = new PushNotificationEvent(PushNotificationEvent.APP_STARTED_IN_BACKGROUND_FROM_NOTIFICATION_EVENT);
if (data != null) {
try {
event.parameters = JSON.parse(data);
}
catch (error:Error) {
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "NOTIFICATION_RECEIVED_WHEN_IN_FOREGROUND":
event = new PushNotificationEvent(PushNotificationEvent.NOTIFICATION_RECEIVED_WHEN_IN_FOREGROUND_EVENT);
if (data != null) {
try {
event.parameters = JSON.parse(data);
}
catch (error:Error) {
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "NOTIFICATION_SETTINGS_ENABLED":
event = new PushNotificationEvent(PushNotificationEvent.NOTIFICATION_SETTINGS_ENABLED);
break;
case "NOTIFICATION_SETTINGS_DISABLED":
event = new PushNotificationEvent(PushNotificationEvent.NOTIFICATION_SETTINGS_DISABLED);
break;
case "GET_NOTIFICATIONS_ENABLED_RESULT":
event = new PushNotificationEvent(PushNotificationEvent.GET_NOTIFICATIONS_ENABLED_RESULT, e.level == "true");
break;
case "OPEN_APP_NOTIFICATION_SETTINGS":
event = new PushNotificationEvent(PushNotificationEvent.OPEN_APP_NOTIFICATION_SETTINGS);
break;
case "LOGGING":
trace(e, e.level);
break;
}
if (event != null)
this.dispatchEvent(event);
}
}
}
|
create context lazily to avoid intermittent #3500 errors
|
create context lazily to avoid intermittent #3500 errors
|
ActionScript
|
apache-2.0
|
freshplanet/ANE-Push-Notification,freshplanet/ANE-Push-Notification,freshplanet/ANE-Push-Notification
|
5bb63caaf2da8f60bfdd8899eee0f1550739f3d4
|
src/aerys/minko/render/shader/Shader.as
|
src/aerys/minko/render/shader/Shader.as
|
package aerys.minko.render.shader
{
import aerys.minko.ns.minko_render;
import aerys.minko.ns.minko_shader;
import aerys.minko.render.RenderTarget;
import aerys.minko.render.resource.Context3DResource;
import aerys.minko.render.resource.Program3DResource;
import aerys.minko.render.shader.compiler.graph.ShaderGraph;
import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode;
import aerys.minko.render.shader.part.ShaderPart;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import flash.utils.getQualifiedClassName;
use namespace minko_shader;
/**
* The base class to extend in order to create ActionScript shaders
* and program the GPU using AS3.
*
* @author Jean-Marc Le Roux
* @author Romain Gilliotte
*
* @see aerys.minko.render.shader.ShaderPart
* @see aerys.minko.render.shader.ShaderInstance
* @see aerys.minko.render.shader.ShaderSignature
* @see aerys.minko.render.shader.ShaderDataBindings
*/
public class Shader extends ShaderPart
{
use namespace minko_shader;
use namespace minko_render;
minko_shader var _meshBindings : ShaderDataBindings = null;
minko_shader var _sceneBindings : ShaderDataBindings = null;
minko_shader var _kills : Vector.<AbstractNode> = new <AbstractNode>[];
private var _name : String = null;
private var _enabled : Boolean = true;
private var _defaultSettings : ShaderSettings = new ShaderSettings(null);
private var _instances : Vector.<ShaderInstance> = new <ShaderInstance>[]
private var _numActiveInstances : uint = 0;
private var _numRenderedInstances : uint = 0;
private var _settings : Vector.<ShaderSettings> = new <ShaderSettings>[];
private var _programs : Vector.<Program3DResource> = new <Program3DResource>[];
private var _begin : Signal = new Signal('Shader.begin');
private var _end : Signal = new Signal('Shader.end');
/**
* The name of the shader. Default value is the qualified name of the
* ActionScript shader class (example: "aerys.minko.render.effect.basic::BasicShader").
*
* @return
*
*/
public function get name() : String
{
return _name;
}
public function set name(value : String) : void
{
_name = value;
}
/**
* The signal executed when the shader (one of its forks) is used
* for rendering for the very first time during the current frame.
* Callbacks for this signal must accept the following arguments:
* <ul>
* <li>shader : Shader, the shader executing the signal</li>
* <li>context : Context3D, the context used for rendering</li>
* <li>backBuffer : RenderTarget, the render target used as the back-buffer</li>
* </ul>
*
* @return
*
*/
public function get begin() : Signal
{
return _begin;
}
/**
* The signal executed when the shader (one of its forks) is used
* for rendering for the very last time during the current frame.
* Callbacks for this signal must accept the following arguments:
* <ul>
* <li>shader : Shader, the shader executing the signal</li>
* <li>context : Context3D, the context used for rendering</li>
* <li>backBuffer : RenderTarget, the render target used as the back-buffer</li>
* </ul>
*
* @return
*
*/
public function get end() : Signal
{
return _end;
}
/**
* Whether the shader (and all its forks) are enabled for rendering
* or not.
*
* @return
*
*/
public function get enabled() : Boolean
{
return _enabled;
}
public function set enabled(value : Boolean) : void
{
_enabled = value;
}
/**
*
* @param priority Default value is 0.
* @param renderTarget Default value is null.
*
*/
public function Shader(renderTarget : RenderTarget = null,
priority : Number = 0.0)
{
super(this);
_defaultSettings.renderTarget = renderTarget;
_defaultSettings.priority = priority;
_name = getQualifiedClassName(this);
}
public function fork(meshBindings : DataBindings,
sceneBindings : DataBindings) : ShaderInstance
{
var pass : ShaderInstance = findPass(meshBindings, sceneBindings);
if (pass == null)
{
var signature : Signature = new Signature(_name);
var config : ShaderSettings = findOrCreateSettings(meshBindings, sceneBindings);
signature.mergeWith(config.signature);
var program : Program3DResource = null;
if (config.enabled)
{
program = findOrCreateProgram(meshBindings, sceneBindings);
signature.mergeWith(program.signature);
}
pass = new ShaderInstance(this, config, program, signature);
pass.retained.add(shaderInstanceRetainedHandler);
pass.released.add(shaderInstanceReleasedHandler);
_instances.push(pass);
}
return pass;
}
public function disposeUnusedResources() : void
{
var numInstances : uint = _instances.length;
var currentId : uint = 0;
for (var instanceId : uint = 0; instanceId < numInstances; ++instanceId)
{
var passInstance : ShaderInstance = _instances[instanceId];
if (!passInstance.isDisposable)
_instances[currentId++] = passInstance;
}
_instances.length = currentId;
}
/**
* Override this method to initialize the settings
* - such as the blending operands or the triangle culling - of the shader.
* This values can be read from both the mesh and the scene bindings.
*
* @param settings
*
* @see aerys.minko.render.shader.ShaderSettings
*
*/
protected function initializeSettings(settings : ShaderSettings) : void
{
// nothing
}
/**
* The getVertexPosition() method is called to evaluate the vertex shader
* program that shall be executed on the GPU.
*
* @return The position of the vertex in clip space (normalized screen space).
*
*/
protected function getVertexPosition() : SFloat
{
throw new Error("The method 'getVertexPosition' must be implemented.");
}
/**
* The getPixelColor() method is called to evaluate the fragment shader
* program that shall be executed on the GPU.
*
* @return The color of the pixel on the screen.
*
*/
protected function getPixelColor() : SFloat
{
throw new Error("The method 'getPixelColor' must be implemented.");
}
private function findPass(meshBindings : DataBindings,
sceneBindings : DataBindings) : ShaderInstance
{
var numPasses : int = _instances.length;
for (var passId : uint = 0; passId < numPasses; ++passId)
if (_instances[passId].signature.isValid(meshBindings, sceneBindings))
return _instances[passId];
return null;
}
private function findOrCreateProgram(meshBindings : DataBindings,
sceneBindings : DataBindings) : Program3DResource
{
var numPrograms : int = _programs.length;
var program : Program3DResource;
for (var programId : uint = 0; programId < numPrograms; ++programId)
if (_programs[programId].signature.isValid(meshBindings, sceneBindings))
return _programs[programId];
var signature : Signature = new Signature(_name);
_meshBindings = new ShaderDataBindings(meshBindings, signature, Signature.SOURCE_MESH);
_sceneBindings = new ShaderDataBindings(sceneBindings, signature, Signature.SOURCE_SCENE);
var vertexPosition : AbstractNode = getVertexPosition()._node;
var pixelColor : AbstractNode = getPixelColor()._node;
var shaderGraph : ShaderGraph = new ShaderGraph(vertexPosition, pixelColor, _kills);
program = shaderGraph.generateProgram(_name, signature);
_meshBindings = null;
_sceneBindings = null;
_kills.length = 0;
_programs.push(program);
return program;
}
private function findOrCreateSettings(meshBindings : DataBindings,
sceneBindings : DataBindings) : ShaderSettings
{
var numConfigs : int = _settings.length;
var config : ShaderSettings = null;
for (var configId : int = 0; configId < numConfigs; ++configId)
if (_settings[configId].signature.isValid(meshBindings, sceneBindings))
return _settings[configId];
var signature : Signature = new Signature(_name);
config = _defaultSettings.clone(signature);
_meshBindings = new ShaderDataBindings(meshBindings, signature, Signature.SOURCE_MESH);
_sceneBindings = new ShaderDataBindings(sceneBindings, signature, Signature.SOURCE_SCENE);
initializeSettings(config);
_meshBindings = null;
_sceneBindings = null;
_settings.push(config);
return config;
}
private function shaderInstanceRetainedHandler(instance : ShaderInstance,
numUses : uint) : void
{
if (numUses == 1)
{
++_numActiveInstances;
instance.begin.add(shaderInstanceBeginHandler);
instance.end.add(shaderInstanceEndHandler);
}
}
private function shaderInstanceReleasedHandler(instance : ShaderInstance,
numUses : uint) : void
{
if (numUses == 0)
{
--_numActiveInstances;
instance.begin.remove(shaderInstanceBeginHandler);
instance.end.remove(shaderInstanceEndHandler);
}
}
private function shaderInstanceBeginHandler(instance : ShaderInstance,
context : Context3DResource,
backBuffer : RenderTarget) : void
{
if (_numRenderedInstances == 0)
_begin.execute(this, context, backBuffer);
}
private function shaderInstanceEndHandler(instance : ShaderInstance,
context : Context3DResource,
backBuffer : RenderTarget) : void
{
_numRenderedInstances++;
if (_numRenderedInstances == _numActiveInstances)
{
_numRenderedInstances = 0;
_end.execute(this, context, backBuffer);
}
}
}
}
|
package aerys.minko.render.shader
{
import aerys.minko.ns.minko_render;
import aerys.minko.ns.minko_shader;
import aerys.minko.render.RenderTarget;
import aerys.minko.render.resource.Context3DResource;
import aerys.minko.render.resource.Program3DResource;
import aerys.minko.render.shader.compiler.graph.ShaderGraph;
import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode;
import aerys.minko.render.shader.part.ShaderPart;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import flash.utils.getQualifiedClassName;
use namespace minko_shader;
/**
* The base class to extend in order to create ActionScript shaders
* and program the GPU using AS3.
*
* @author Jean-Marc Le Roux
* @author Romain Gilliotte
*
* @see aerys.minko.render.shader.ShaderPart
* @see aerys.minko.render.shader.ShaderInstance
* @see aerys.minko.render.shader.ShaderSignature
* @see aerys.minko.render.shader.ShaderDataBindings
*/
public class Shader extends ShaderPart
{
use namespace minko_shader;
use namespace minko_render;
minko_shader var _meshBindings : ShaderDataBindings = null;
minko_shader var _sceneBindings : ShaderDataBindings = null;
minko_shader var _kills : Vector.<AbstractNode> = new <AbstractNode>[];
private var _name : String = null;
private var _enabled : Boolean = true;
private var _defaultSettings : ShaderSettings = new ShaderSettings(null);
private var _instances : Vector.<ShaderInstance> = new <ShaderInstance>[];
private var _numActiveInstances : uint = 0;
private var _numRenderedInstances : uint = 0;
private var _settings : Vector.<ShaderSettings> = new <ShaderSettings>[];
private var _programs : Vector.<Program3DResource> = new <Program3DResource>[];
private var _begin : Signal = new Signal('Shader.begin');
private var _end : Signal = new Signal('Shader.end');
/**
* The name of the shader. Default value is the qualified name of the
* ActionScript shader class (example: "aerys.minko.render.effect.basic::BasicShader").
*
* @return
*
*/
public function get name() : String
{
return _name;
}
public function set name(value : String) : void
{
_name = value;
}
/**
* The signal executed when the shader (one of its forks) is used
* for rendering for the very first time during the current frame.
* Callbacks for this signal must accept the following arguments:
* <ul>
* <li>shader : Shader, the shader executing the signal</li>
* <li>context : Context3D, the context used for rendering</li>
* <li>backBuffer : RenderTarget, the render target used as the back-buffer</li>
* </ul>
*
* @return
*
*/
public function get begin() : Signal
{
return _begin;
}
/**
* The signal executed when the shader (one of its forks) is used
* for rendering for the very last time during the current frame.
* Callbacks for this signal must accept the following arguments:
* <ul>
* <li>shader : Shader, the shader executing the signal</li>
* <li>context : Context3D, the context used for rendering</li>
* <li>backBuffer : RenderTarget, the render target used as the back-buffer</li>
* </ul>
*
* @return
*
*/
public function get end() : Signal
{
return _end;
}
/**
* Whether the shader (and all its forks) are enabled for rendering
* or not.
*
* @return
*
*/
public function get enabled() : Boolean
{
return _enabled;
}
public function set enabled(value : Boolean) : void
{
_enabled = value;
}
/**
*
* @param priority Default value is 0.
* @param renderTarget Default value is null.
*
*/
public function Shader(renderTarget : RenderTarget = null,
priority : Number = 0.0)
{
super(this);
_defaultSettings.renderTarget = renderTarget;
_defaultSettings.priority = priority;
_name = getQualifiedClassName(this);
}
public function fork(meshBindings : DataBindings,
sceneBindings : DataBindings) : ShaderInstance
{
var pass : ShaderInstance = findPass(meshBindings, sceneBindings);
if (pass == null)
{
var signature : Signature = new Signature(_name);
var config : ShaderSettings = findOrCreateSettings(meshBindings, sceneBindings);
signature.mergeWith(config.signature);
var program : Program3DResource = null;
if (config.enabled)
{
program = findOrCreateProgram(meshBindings, sceneBindings);
signature.mergeWith(program.signature);
}
pass = new ShaderInstance(this, config, program, signature);
pass.retained.add(shaderInstanceRetainedHandler);
pass.released.add(shaderInstanceReleasedHandler);
_instances.push(pass);
}
return pass;
}
public function disposeUnusedResources() : void
{
var numInstances : uint = _instances.length;
var currentId : uint = 0;
for (var instanceId : uint = 0; instanceId < numInstances; ++instanceId)
{
var passInstance : ShaderInstance = _instances[instanceId];
if (!passInstance.isDisposable)
_instances[currentId++] = passInstance;
}
_instances.length = currentId;
}
/**
* Override this method to initialize the settings
* - such as the blending operands or the triangle culling - of the shader.
* This values can be read from both the mesh and the scene bindings.
*
* @param settings
*
* @see aerys.minko.render.shader.ShaderSettings
*
*/
protected function initializeSettings(settings : ShaderSettings) : void
{
// nothing
}
/**
* The getVertexPosition() method is called to evaluate the vertex shader
* program that shall be executed on the GPU.
*
* @return The position of the vertex in clip space (normalized screen space).
*
*/
protected function getVertexPosition() : SFloat
{
throw new Error("The method 'getVertexPosition' must be implemented.");
}
/**
* The getPixelColor() method is called to evaluate the fragment shader
* program that shall be executed on the GPU.
*
* @return The color of the pixel on the screen.
*
*/
protected function getPixelColor() : SFloat
{
throw new Error("The method 'getPixelColor' must be implemented.");
}
private function findPass(meshBindings : DataBindings,
sceneBindings : DataBindings) : ShaderInstance
{
var numPasses : int = _instances.length;
for (var passId : uint = 0; passId < numPasses; ++passId)
if (_instances[passId].signature.isValid(meshBindings, sceneBindings))
return _instances[passId];
return null;
}
private function findOrCreateProgram(meshBindings : DataBindings,
sceneBindings : DataBindings) : Program3DResource
{
var numPrograms : int = _programs.length;
var program : Program3DResource;
for (var programId : uint = 0; programId < numPrograms; ++programId)
if (_programs[programId].signature.isValid(meshBindings, sceneBindings))
return _programs[programId];
var signature : Signature = new Signature(_name);
_meshBindings = new ShaderDataBindings(meshBindings, signature, Signature.SOURCE_MESH);
_sceneBindings = new ShaderDataBindings(sceneBindings, signature, Signature.SOURCE_SCENE);
var vertexPosition : AbstractNode = getVertexPosition()._node;
var pixelColor : AbstractNode = getPixelColor()._node;
var shaderGraph : ShaderGraph = new ShaderGraph(vertexPosition, pixelColor, _kills);
program = shaderGraph.generateProgram(_name, signature);
_meshBindings = null;
_sceneBindings = null;
_kills.length = 0;
_programs.push(program);
return program;
}
private function findOrCreateSettings(meshBindings : DataBindings,
sceneBindings : DataBindings) : ShaderSettings
{
var numConfigs : int = _settings.length;
var config : ShaderSettings = null;
for (var configId : int = 0; configId < numConfigs; ++configId)
if (_settings[configId].signature.isValid(meshBindings, sceneBindings))
return _settings[configId];
var signature : Signature = new Signature(_name);
config = _defaultSettings.clone(signature);
_meshBindings = new ShaderDataBindings(meshBindings, signature, Signature.SOURCE_MESH);
_sceneBindings = new ShaderDataBindings(sceneBindings, signature, Signature.SOURCE_SCENE);
initializeSettings(config);
_meshBindings = null;
_sceneBindings = null;
_settings.push(config);
return config;
}
private function shaderInstanceRetainedHandler(instance : ShaderInstance,
numUses : uint) : void
{
if (numUses == 1)
{
++_numActiveInstances;
instance.begin.add(shaderInstanceBeginHandler);
instance.end.add(shaderInstanceEndHandler);
}
}
private function shaderInstanceReleasedHandler(instance : ShaderInstance,
numUses : uint) : void
{
if (numUses == 0)
{
--_numActiveInstances;
instance.begin.remove(shaderInstanceBeginHandler);
instance.end.remove(shaderInstanceEndHandler);
}
}
private function shaderInstanceBeginHandler(instance : ShaderInstance,
context : Context3DResource,
backBuffer : RenderTarget) : void
{
if (_numRenderedInstances == 0)
_begin.execute(this, context, backBuffer);
}
private function shaderInstanceEndHandler(instance : ShaderInstance,
context : Context3DResource,
backBuffer : RenderTarget) : void
{
_numRenderedInstances++;
if (_numRenderedInstances == _numActiveInstances)
{
_numRenderedInstances = 0;
_end.execute(this, context, backBuffer);
}
}
}
}
|
fix missing ; at eol
|
fix missing ; at eol
|
ActionScript
|
mit
|
aerys/minko-as3
|
5e709c8dd91870617f2bc1cfda44237aa75298e3
|
src/org/mangui/hls/demux/AACDemuxer.as
|
src/org/mangui/hls/demux/AACDemuxer.as
|
package org.mangui.hls.demux {
import org.mangui.hls.model.AudioTrack;
import org.mangui.hls.flv.FLVTag;
import flash.utils.ByteArray;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
/** Constants and utilities for the AAC audio format. **/
public class AACDemuxer implements Demuxer {
/** ADTS Syncword (111111111111), ID (MPEG4), layer (00) and protection_absent (1).**/
private static const SYNCWORD : uint = 0xFFF1;
/** ADTS Syncword with MPEG2 stream ID (used by e.g. Squeeze 7). **/
private static const SYNCWORD_2 : uint = 0xFFF9;
/** ADTS Syncword with MPEG2 stream ID (used by e.g. Envivio 4Caster). **/
private static const SYNCWORD_3 : uint = 0xFFF8;
/** ADTS/ADIF sample rates index. **/
private static const RATES : Array = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
/** ADIF profile index (ADTS doesn't have Null). **/
private static const PROFILES : Array = ['Null', 'Main', 'LC', 'SSR', 'LTP', 'SBR'];
/** Byte data to be read **/
private var _data : ByteArray;
/* callback functions for audio selection, and parsing progress/complete */
private var _callback_audioselect : Function;
private var _callback_progress : Function;
private var _callback_complete : Function;
/** append new data */
public function append(data : ByteArray) : void {
if (_data == null) {
_data = new ByteArray();
}
_data.writeBytes(data);
}
/** cancel demux operation */
public function cancel() : void {
_data = null;
}
public function notifycomplete() : void {
CONFIG::LOGGING {
Log.debug("AAC: extracting AAC tags");
}
var audioTags : Vector.<FLVTag> = new Vector.<FLVTag>();
/* parse AAC, convert Elementary Streams to TAG */
_data.position = 0;
var id3 : ID3 = new ID3(_data);
// AAC should contain ID3 tag filled with a timestamp
var frames : Vector.<AudioFrame> = AACDemuxer.getFrames(_data, _data.position);
var adif : ByteArray = getADIF(_data, id3.len);
var adifTag : FLVTag = new FLVTag(FLVTag.AAC_HEADER, id3.timestamp, id3.timestamp, true);
adifTag.push(adif, 0, adif.length);
audioTags.push(adifTag);
var audioTag : FLVTag;
var stamp : uint;
var i : int = 0;
while (i < frames.length) {
stamp = Math.round(id3.timestamp + i * 1024 * 1000 / frames[i].rate);
audioTag = new FLVTag(FLVTag.AAC_RAW, stamp, stamp, false);
if (i != frames.length - 1) {
audioTag.push(_data, frames[i].start, frames[i].length);
} else {
audioTag.push(_data, frames[i].start, _data.length - frames[i].start);
}
audioTags.push(audioTag);
i++;
}
var audiotracks : Vector.<AudioTrack> = new Vector.<AudioTrack>();
audiotracks.push(new AudioTrack('AAC ES', AudioTrack.FROM_DEMUX, 0, true));
// report unique audio track. dont check return value as obviously the track will be selected
_callback_audioselect(audiotracks);
CONFIG::LOGGING {
Log.debug("AAC: all tags extracted, callback demux");
}
_data = null;
_callback_progress(audioTags);
_callback_complete();
}
public function AACDemuxer(callback_audioselect : Function, callback_progress : Function, callback_complete : Function) : void {
_callback_audioselect = callback_audioselect;
_callback_progress = callback_progress;
_callback_complete = callback_complete;
};
public static function probe(data : ByteArray) : Boolean {
var pos : uint = data.position;
var id3 : ID3 = new ID3(data);
// AAC should contain ID3 tag filled with a timestamp
if (id3.hasTimestamp) {
while (data.bytesAvailable > 1) {
// Check for ADTS header
var short : uint = data.readUnsignedShort();
if (short == SYNCWORD || short == SYNCWORD_2 || short == SYNCWORD_3) {
// rewind to sync word
data.position -= 2;
return true;
} else {
data.position--;
}
}
data.position = pos;
}
return false;
}
/** Get ADIF header from ADTS stream. **/
public static function getADIF(adts : ByteArray, position : uint) : ByteArray {
adts.position = position;
var short : uint;
// we need at least 6 bytes, 2 for sync word, 4 for frame length
while ((adts.bytesAvailable > 5) && (short != SYNCWORD) && (short != SYNCWORD_2) && (short != SYNCWORD_3)) {
short = adts.readUnsignedShort();
}
if (short == SYNCWORD || short == SYNCWORD_2 || short == SYNCWORD_3) {
var profile : uint = (adts.readByte() & 0xF0) >> 6;
// Correcting zero-index of ADIF and Flash playing only LC/HE.
if (profile > 3) {
profile = 5;
} else {
profile = 2;
}
adts.position--;
var srate : uint = (adts.readByte() & 0x3C) >> 2;
adts.position--;
var channels : uint = (adts.readShort() & 0x01C0) >> 6;
} else {
throw new Error("Stream did not start with ADTS header.");
}
// 5 bits profile + 4 bits samplerate + 4 bits channels.
var adif : ByteArray = new ByteArray();
adif.writeByte((profile << 3) + (srate >> 1));
adif.writeByte((srate << 7) + (channels << 3));
CONFIG::LOGGING {
Log.debug('AAC: ' + PROFILES[profile] + ', ' + RATES[srate] + ' Hz ' + channels + ' channel(s)');
}
// Reset position and return adif.
adts.position -= 4;
adif.position = 0;
return adif;
};
/** Get a list with AAC frames from ADTS stream. **/
public static function getFrames(adts : ByteArray, position : uint) : Vector.<AudioFrame> {
var frames : Vector.<AudioFrame> = new Vector.<AudioFrame>();
var frame_start : uint;
var frame_length : uint;
var id3 : ID3 = new ID3(adts);
position += id3.len;
// Get raw AAC frames from audio stream.
adts.position = position;
var samplerate : uint;
// we need at least 6 bytes, 2 for sync word, 4 for frame length
while (adts.bytesAvailable > 5) {
// Check for ADTS header
var short : uint = adts.readUnsignedShort();
if (short == SYNCWORD || short == SYNCWORD_2 || short == SYNCWORD_3) {
// Store samplerate for offsetting timestamps.
if (!samplerate) {
samplerate = RATES[(adts.readByte() & 0x3C) >> 2];
adts.position--;
}
// Store raw AAC preceding this header.
if (frame_start) {
frames.push(new AudioFrame(frame_start, frame_length, frame_length, samplerate));
}
if (short == SYNCWORD_3) {
// ADTS header is 9 bytes.
frame_length = ((adts.readUnsignedInt() & 0x0003FFE0) >> 5) - 9;
frame_start = adts.position + 3;
adts.position += frame_length + 3;
} else {
// ADTS header is 7 bytes.
frame_length = ((adts.readUnsignedInt() & 0x0003FFE0) >> 5) - 7;
frame_start = adts.position + 1;
adts.position += frame_length + 1;
}
} else {
CONFIG::LOGGING {
Log.debug("no ADTS header found, probing...");
}
adts.position--;
}
}
if (frame_start) {
// check if we have a complete frame available at the end, i.e. last found frame is fitting in this PES packet
var overflow : int = frame_start + frame_length - adts.length;
if (overflow <= 0 ) {
// no overflow, Write raw AAC after last header.
frames.push(new AudioFrame(frame_start, frame_length, frame_length, samplerate));
} else {
CONFIG::LOGGING {
Log.debug2("ADTS overflow at the end of PES packet, missing " + overflow + " bytes to complete the ADTS frame");
}
}
} else if (frames.length == 0) {
null;
CONFIG::LOGGING {
Log.warn("No ADTS headers found in this stream.");
}
}
adts.position = position;
return frames;
};
}
}
|
package org.mangui.hls.demux {
import org.mangui.hls.model.AudioTrack;
import org.mangui.hls.flv.FLVTag;
import flash.utils.ByteArray;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
/** Constants and utilities for the AAC audio format, refer to
* http://wiki.multimedia.cx/index.php?title=ADTS
**/
public class AACDemuxer implements Demuxer {
/** ADTS Syncword (0xFFF), ID:0 (MPEG4), layer (00) and protection_absent (1:no CRC).**/
private static const SYNCWORD : uint = 0xFFF1;
/** ADTS Syncword (0xFFF), ID:1 (MPEG2), layer (00) and protection_absent (1: no CRC).**/
private static const SYNCWORD_2 : uint = 0xFFF9;
/** ADTS Syncword (0xFFF), ID:1 (MPEG2), layer (00) and protection_absent (0: CRC).**/
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 {
if (_data == null) {
_data = new ByteArray();
}
_data.writeBytes(data);
}
/** cancel demux operation */
public function cancel() : void {
_data = null;
}
public function notifycomplete() : void {
CONFIG::LOGGING {
Log.debug("AAC: extracting AAC tags");
}
var audioTags : Vector.<FLVTag> = new Vector.<FLVTag>();
/* parse AAC, convert Elementary Streams to TAG */
_data.position = 0;
var id3 : ID3 = new ID3(_data);
// AAC should contain ID3 tag filled with a timestamp
var frames : Vector.<AudioFrame> = AACDemuxer.getFrames(_data, _data.position);
var adif : ByteArray = getADIF(_data, id3.len);
var adifTag : FLVTag = new FLVTag(FLVTag.AAC_HEADER, id3.timestamp, id3.timestamp, true);
adifTag.push(adif, 0, adif.length);
audioTags.push(adifTag);
var audioTag : FLVTag;
var stamp : uint;
var i : int = 0;
while (i < frames.length) {
stamp = Math.round(id3.timestamp + i * 1024 * 1000 / frames[i].rate);
audioTag = new FLVTag(FLVTag.AAC_RAW, stamp, stamp, false);
if (i != frames.length - 1) {
audioTag.push(_data, frames[i].start, frames[i].length);
} else {
audioTag.push(_data, frames[i].start, _data.length - frames[i].start);
}
audioTags.push(audioTag);
i++;
}
var audiotracks : Vector.<AudioTrack> = new Vector.<AudioTrack>();
audiotracks.push(new AudioTrack('AAC ES', AudioTrack.FROM_DEMUX, 0, true));
// report unique audio track. dont check return value as obviously the track will be selected
_callback_audioselect(audiotracks);
CONFIG::LOGGING {
Log.debug("AAC: all tags extracted, callback demux");
}
_data = null;
_callback_progress(audioTags);
_callback_complete();
}
public function AACDemuxer(callback_audioselect : Function, callback_progress : Function, callback_complete : Function) : void {
_callback_audioselect = callback_audioselect;
_callback_progress = callback_progress;
_callback_complete = callback_complete;
};
public static function probe(data : ByteArray) : Boolean {
var pos : uint = data.position;
var id3 : ID3 = new ID3(data);
// AAC should contain ID3 tag filled with a timestamp
if (id3.hasTimestamp) {
while (data.bytesAvailable > 1) {
// Check for ADTS header
var short : uint = data.readUnsignedShort();
if (short == SYNCWORD || short == SYNCWORD_2 || short == SYNCWORD_3) {
// rewind to sync word
data.position -= 2;
return true;
} else {
data.position--;
}
}
data.position = pos;
}
return false;
}
/** Get ADIF header from ADTS stream. **/
public static function getADIF(adts : ByteArray, position : uint) : ByteArray {
adts.position = position;
var short : uint;
// we need at least 6 bytes, 2 for sync word, 4 for frame length
while ((adts.bytesAvailable > 5) && (short != SYNCWORD) && (short != SYNCWORD_2) && (short != SYNCWORD_3)) {
short = adts.readUnsignedShort();
adts.position--;
}
adts.position++;
if (short == SYNCWORD || short == SYNCWORD_2 || short == SYNCWORD_3) {
var profile : uint = (adts.readByte() & 0xF0) >> 6;
// Correcting zero-index of ADIF and Flash playing only LC/HE.
if (profile > 3) {
profile = 5;
} else {
profile = 2;
}
adts.position--;
var srate : uint = (adts.readByte() & 0x3C) >> 2;
adts.position--;
var channels : uint = (adts.readShort() & 0x01C0) >> 6;
} else {
throw new Error("Stream did not start with ADTS header.");
}
// 5 bits profile + 4 bits samplerate + 4 bits channels.
var adif : ByteArray = new ByteArray();
adif.writeByte((profile << 3) + (srate >> 1));
adif.writeByte((srate << 7) + (channels << 3));
CONFIG::LOGGING {
Log.debug('AAC: ' + PROFILES[profile] + ', ' + RATES[srate] + ' Hz ' + channels + ' channel(s)');
}
// Reset position and return adif.
adts.position -= 4;
adif.position = 0;
return adif;
};
/** Get a list with AAC frames from ADTS stream. **/
public static function getFrames(adts : ByteArray, position : uint) : Vector.<AudioFrame> {
var frames : Vector.<AudioFrame> = new Vector.<AudioFrame>();
var frame_start : uint;
var frame_length : uint;
var id3 : ID3 = new ID3(adts);
position += id3.len;
// Get raw AAC frames from audio stream.
adts.position = position;
var samplerate : uint;
// we need at least 6 bytes, 2 for sync word, 4 for frame length
while (adts.bytesAvailable > 5) {
// Check for ADTS header
var short : uint = adts.readUnsignedShort();
if (short == SYNCWORD || short == SYNCWORD_2 || short == SYNCWORD_3) {
// Store samplerate for offsetting timestamps.
if (!samplerate) {
samplerate = RATES[(adts.readByte() & 0x3C) >> 2];
adts.position--;
}
// Store raw AAC preceding this header.
if (frame_start) {
frames.push(new AudioFrame(frame_start, frame_length, frame_length, samplerate));
}
// protection_absent=1, crc_len = 0,protection_absent=0,crc_len=2
var crc_len : int = (1 - (short & 0x1)) << 1;
// ADTS header is 7+crc_len bytes.
frame_length = ((adts.readUnsignedInt() & 0x0003FFE0) >> 5) - 7 - crc_len;
frame_start = adts.position + 1 + crc_len;
adts.position += frame_length + 1 + crc_len;
} else {
CONFIG::LOGGING {
Log.debug2("no ADTS header found, probing...");
}
adts.position--;
}
}
if (frame_start) {
// check if we have a complete frame available at the end, i.e. last found frame is fitting in this PES packet
var overflow : int = frame_start + frame_length - adts.length;
if (overflow <= 0 ) {
// no overflow, Write raw AAC after last header.
frames.push(new AudioFrame(frame_start, frame_length, frame_length, samplerate));
} else {
CONFIG::LOGGING {
Log.debug2("ADTS overflow at the end of PES packet, missing " + overflow + " bytes to complete the ADTS frame");
}
}
} else if (frames.length == 0) {
null;
CONFIG::LOGGING {
Log.warn("No ADTS headers found in this stream.");
}
}
adts.position = position;
return frames;
};
}
}
|
simplify ADTS header parsing code related to #135
|
simplify ADTS header parsing code
related to #135
|
ActionScript
|
mpl-2.0
|
Peer5/flashls,viktorot/flashls,NicolasSiver/flashls,clappr/flashls,fixedmachine/flashls,thdtjsdn/flashls,vidible/vdb-flashls,stevemayhew/flashls,aevange/flashls,neilrackett/flashls,suuhas/flashls,aevange/flashls,hola/flashls,neilrackett/flashls,loungelogic/flashls,suuhas/flashls,Boxie5/flashls,ryanhefner/flashls,aevange/flashls,ryanhefner/flashls,ryanhefner/flashls,Peer5/flashls,NicolasSiver/flashls,fixedmachine/flashls,School-Improvement-Network/flashls,thdtjsdn/flashls,ryanhefner/flashls,clappr/flashls,Boxie5/flashls,jlacivita/flashls,School-Improvement-Network/flashls,JulianPena/flashls,mangui/flashls,jlacivita/flashls,mangui/flashls,suuhas/flashls,hola/flashls,stevemayhew/flashls,dighan/flashls,Peer5/flashls,codex-corp/flashls,Corey600/flashls,stevemayhew/flashls,JulianPena/flashls,School-Improvement-Network/flashls,tedconf/flashls,viktorot/flashls,stevemayhew/flashls,viktorot/flashls,aevange/flashls,Peer5/flashls,loungelogic/flashls,Corey600/flashls,codex-corp/flashls,tedconf/flashls,vidible/vdb-flashls,suuhas/flashls,dighan/flashls
|
c7e263eb34a6d6a8684e92b06c9c053869b50a1a
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/layouts/NonVirtualVerticalLayout.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/layouts/NonVirtualVerticalLayout.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.beads.layouts
{
import org.apache.flex.core.IBeadLayout;
import org.apache.flex.core.ILayoutChild;
import org.apache.flex.core.ILayoutParent;
import org.apache.flex.core.IParentIUIBase;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
/**
* The NonVirtualVerticalLayout class is a simple layout
* bead. It takes the set of children and lays them out
* vertically in one column, separating them according to
* CSS layout rules for margin and horizontal-align styles.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class NonVirtualVerticalLayout implements IBeadLayout
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function NonVirtualVerticalLayout()
{
}
private var _strand:IStrand;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
_strand = value;
IEventDispatcher(value).addEventListener("heightChanged", changeHandler);
IEventDispatcher(value).addEventListener("childrenAdded", changeHandler);
IEventDispatcher(value).addEventListener("itemsCreated", changeHandler);
IEventDispatcher(value).addEventListener("beadsAdded", changeHandler);
}
private function changeHandler(event:Event):void
{
var layoutParent:ILayoutParent = _strand.getBeadByType(ILayoutParent) as ILayoutParent;
var contentView:IParentIUIBase = layoutParent ? layoutParent.contentView : IParentIUIBase(_strand);
var n:int = contentView.numElements;
var hasHorizontalFlex:Boolean;
var flexibleHorizontalMargins:Array = [];
var ilc:ILayoutChild;
var marginLeft:Object;
var marginRight:Object;
var marginTop:Object;
var marginBottom:Object;
var margin:Object;
var maxWidth:Number = 0;
for (var i:int = 0; i < n; i++)
{
var child:IUIBase = contentView.getElementAt(i) as IUIBase;
margin = ValuesManager.valuesImpl.getValue(child, "margin");
if (margin is Array)
{
if (margin.length == 1)
marginLeft = marginTop = marginRight = marginBottom = margin[0];
else if (margin.length <= 3)
{
marginLeft = marginRight = margin[1];
marginTop = marginBottom = margin[0];
}
else if (margin.length == 4)
{
marginLeft = margin[3];
marginBottom = margin[2];
marginRight = margin[1];
marginTop = margin[0];
}
}
else if (margin == null)
{
marginLeft = ValuesManager.valuesImpl.getValue(child, "margin-left");
marginTop = ValuesManager.valuesImpl.getValue(child, "margin-top");
marginRight = ValuesManager.valuesImpl.getValue(child, "margin-right");
marginBottom = ValuesManager.valuesImpl.getValue(child, "margin-bottom");
}
else
{
marginLeft = marginTop = marginBottom = marginRight = margin;
}
var ml:Number;
var mr:Number;
var mt:Number;
var mb:Number;
var lastmb:Number;
mt = Number(marginTop);
if (isNaN(mt))
mt = 0;
mb = Number(marginBottom);
if (isNaN(mb))
mb = 0;
var yy:Number;
if (i == 0)
child.y = mt;
else
child.y = yy + Math.max(mt, lastmb);
if (child is ILayoutChild)
{
ilc = child as ILayoutChild;
if (!isNaN(ilc.percentHeight))
ilc.setHeight(contentView.height * ilc.percentHeight / 100);
}
yy = child.y + child.height;
lastmb = mb;
flexibleHorizontalMargins[i] = {};
if (marginLeft == "auto")
{
ml = 0;
flexibleHorizontalMargins[i].marginLeft = marginLeft;
hasHorizontalFlex = true;
}
else
{
ml = Number(marginLeft);
if (isNaN(ml))
{
ml = 0;
flexibleHorizontalMargins[i].marginLeft = marginLeft;
}
else
flexibleHorizontalMargins[i].marginLeft = ml;
}
if (marginRight == "auto")
{
mr = 0;
flexibleHorizontalMargins[i].marginRight = marginRight;
hasHorizontalFlex = true;
}
else
{
mr = Number(marginRight);
if (isNaN(mr))
{
mr = 0;
flexibleHorizontalMargins[i].marginRight = marginRight;
}
else
flexibleHorizontalMargins[i].marginRight = mr;
}
child.x = ml;
maxWidth = Math.max(maxWidth, ml + child.width + mr);
}
if (hasHorizontalFlex)
{
for (i = 0; i < n; i++)
{
child = contentView.getElementAt(i) as IUIBase;
if (child is ILayoutChild)
{
ilc = child as ILayoutChild;
if (!isNaN(ilc.percentWidth))
ilc.setWidth(contentView.width * ilc.percentWidth / 100);
}
var obj:Object = flexibleHorizontalMargins[i];
if (obj.marginLeft == "auto" && obj.marginRight == "auto")
child.x = maxWidth - child.width / 2;
else if (obj.marginLeft == "auto")
child.x = maxWidth - child.width - obj.marginRight;
}
}
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.beads.layouts
{
import org.apache.flex.core.IBeadLayout;
import org.apache.flex.core.ILayoutChild;
import org.apache.flex.core.ILayoutParent;
import org.apache.flex.core.IParentIUIBase;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
/**
* The NonVirtualVerticalLayout class is a simple layout
* bead. It takes the set of children and lays them out
* vertically in one column, separating them according to
* CSS layout rules for margin and horizontal-align styles.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class NonVirtualVerticalLayout implements IBeadLayout
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function NonVirtualVerticalLayout()
{
}
private var _strand:IStrand;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
_strand = value;
IEventDispatcher(value).addEventListener("heightChanged", changeHandler);
IEventDispatcher(value).addEventListener("childrenAdded", changeHandler);
IEventDispatcher(value).addEventListener("itemsCreated", changeHandler);
IEventDispatcher(value).addEventListener("layoutNeeded", changeHandler);
IEventDispatcher(value).addEventListener("beadsAdded", changeHandler);
}
private function changeHandler(event:Event):void
{
var layoutParent:ILayoutParent = _strand.getBeadByType(ILayoutParent) as ILayoutParent;
var contentView:IParentIUIBase = layoutParent ? layoutParent.contentView : IParentIUIBase(_strand);
var n:int = contentView.numElements;
var hasHorizontalFlex:Boolean;
var flexibleHorizontalMargins:Array = [];
var ilc:ILayoutChild;
var marginLeft:Object;
var marginRight:Object;
var marginTop:Object;
var marginBottom:Object;
var margin:Object;
var maxWidth:Number = 0;
for (var i:int = 0; i < n; i++)
{
var child:IUIBase = contentView.getElementAt(i) as IUIBase;
margin = ValuesManager.valuesImpl.getValue(child, "margin");
if (margin is Array)
{
if (margin.length == 1)
marginLeft = marginTop = marginRight = marginBottom = margin[0];
else if (margin.length <= 3)
{
marginLeft = marginRight = margin[1];
marginTop = marginBottom = margin[0];
}
else if (margin.length == 4)
{
marginLeft = margin[3];
marginBottom = margin[2];
marginRight = margin[1];
marginTop = margin[0];
}
}
else if (margin == null)
{
marginLeft = ValuesManager.valuesImpl.getValue(child, "margin-left");
marginTop = ValuesManager.valuesImpl.getValue(child, "margin-top");
marginRight = ValuesManager.valuesImpl.getValue(child, "margin-right");
marginBottom = ValuesManager.valuesImpl.getValue(child, "margin-bottom");
}
else
{
marginLeft = marginTop = marginBottom = marginRight = margin;
}
var ml:Number;
var mr:Number;
var mt:Number;
var mb:Number;
var lastmb:Number;
mt = Number(marginTop);
if (isNaN(mt))
mt = 0;
mb = Number(marginBottom);
if (isNaN(mb))
mb = 0;
var yy:Number;
if (i == 0)
child.y = mt;
else
child.y = yy + Math.max(mt, lastmb);
if (child is ILayoutChild)
{
ilc = child as ILayoutChild;
if (!isNaN(ilc.percentHeight))
ilc.setHeight(contentView.height * ilc.percentHeight / 100);
}
yy = child.y + child.height;
lastmb = mb;
flexibleHorizontalMargins[i] = {};
if (marginLeft == "auto")
{
ml = 0;
flexibleHorizontalMargins[i].marginLeft = marginLeft;
hasHorizontalFlex = true;
}
else
{
ml = Number(marginLeft);
if (isNaN(ml))
{
ml = 0;
flexibleHorizontalMargins[i].marginLeft = marginLeft;
}
else
flexibleHorizontalMargins[i].marginLeft = ml;
}
if (marginRight == "auto")
{
mr = 0;
flexibleHorizontalMargins[i].marginRight = marginRight;
hasHorizontalFlex = true;
}
else
{
mr = Number(marginRight);
if (isNaN(mr))
{
mr = 0;
flexibleHorizontalMargins[i].marginRight = marginRight;
}
else
flexibleHorizontalMargins[i].marginRight = mr;
}
child.x = ml;
if (child is ILayoutChild)
{
ilc = child as ILayoutChild;
if (!isNaN(ilc.percentWidth))
ilc.setWidth(contentView.width * ilc.percentWidth / 100);
}
maxWidth = Math.max(maxWidth, ml + child.width + mr);
}
if (hasHorizontalFlex)
{
for (i = 0; i < n; i++)
{
child = contentView.getElementAt(i) as IUIBase;
var obj:Object = flexibleHorizontalMargins[i];
if (obj.marginLeft == "auto" && obj.marginRight == "auto")
child.x = maxWidth - child.width / 2;
else if (obj.marginLeft == "auto")
child.x = maxWidth - child.width - obj.marginRight;
}
}
}
}
}
|
fix when we set the width of children
|
fix when we set the width of children
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
e65f85a7a99ef96da0f20a75d9caeb094245a767
|
src/utils/TextureUtil.as
|
src/utils/TextureUtil.as
|
package utils
{
import flash.geom.Rectangle;
/**
* For place texture
*/
public final class TextureUtil
{
private static const HIGHEST:uint = 0xFFFFFFFF;
/**
* Place textures by textureAtlasXML data
*/
public static function packTextures(widthDefault:uint, padding:uint, rectMap:Object, verticalSide:Boolean = false):Rectangle
{
for each(var rect:Rectangle in rectMap)
{
break;
}
if(!rect)
{
return null;
}
var dimensions:uint = 0;
var rectList:Vector.<Rectangle> = new Vector.<Rectangle>;
for each(rect in rectMap)
{
dimensions += rect.width * rect.height;
rectList.push(rect);
}
//sort texture by size
rectList.sort(sortRectList);
if(widthDefault == 0)
{
//calculate width for Auto size
widthDefault = Math.sqrt(dimensions);
}
widthDefault = getNearest2N(Math.max(int(rectList[0].width) + padding, widthDefault));
var heightMax:uint = HIGHEST;
var remainAreaList:Vector.<Rectangle> = new Vector.<Rectangle>;
remainAreaList.push(new Rectangle(0, 0, widthDefault, heightMax));
var isFit:Boolean;
var width:int;
var height:int;
var area:Rectangle;
var areaPrev:Rectangle;
var areaNext:Rectangle;
var areaID:int;
var rectID:int;
do
{
//Find highest blank area
area = getHighestArea(remainAreaList);
areaID = remainAreaList.indexOf(area);
isFit = false;
rectID = 0;
for each(rect in rectList)
{
//check if the area is fit
width = int(rect.width) + padding;
height = int(rect.height) + padding;
if (area.width >= width && area.height >= height)
{
//place portrait texture
if(
verticalSide?
(
height > width * 4?
(
areaID > 0?
(area.height - height >= remainAreaList[areaID - 1].height):
true
):
true
):
true
)
{
isFit = true;
break;
}
}
rectID ++;
}
if(isFit)
{
//place texture if size is fit
rect.x = area.x;
rect.y = area.y;
rectList.splice(rectID, 1);
remainAreaList.splice(
areaID + 1,
0,
new Rectangle(area.x + width, area.y, area.width - width, area.height)
);
area.y += height;
area.width = width;
area.height -= height;
}
else
{
//not fit, don't place it, merge blank area to others toghther
if(areaID == 0)
{
areaNext = remainAreaList[areaID + 1];
}
else if(areaID == remainAreaList.length - 1)
{
areaNext = remainAreaList[areaID - 1];
}
else
{
areaPrev = remainAreaList[areaID - 1];
areaNext = remainAreaList[areaID + 1];
areaNext = areaPrev.height <= areaNext.height?areaNext:areaPrev;
}
if(area.x < areaNext.x)
{
areaNext.x = area.x;
}
areaNext.width = area.width + areaNext.width;
remainAreaList.splice(areaID, 1);
}
}
while (rectList.length > 0);
heightMax = getNearest2N(heightMax - getLowestArea(remainAreaList).height);
return new Rectangle(0, 0, widthDefault, heightMax);
}
private static function sortRectList(rect1:Rectangle, rect2:Rectangle):int
{
var v1:uint = rect1.width + rect1.height;
var v2:uint = rect2.width + rect2.height;
if (v1 == v2)
{
return rect1.width > rect2.width?-1:1;
}
return v1 > v2?-1:1;
}
private static function getNearest2N(_n:uint):uint
{
return _n & _n - 1?1 << _n.toString(2).length:_n;
}
private static function getHighestArea(areaList:Vector.<Rectangle>):Rectangle
{
var height:uint = 0;
var areaHighest:Rectangle;
for each(var area:Rectangle in areaList)
{
if (area.height > height)
{
height = area.height;
areaHighest = area;
}
}
return areaHighest;
}
private static function getLowestArea(areaList:Vector.<Rectangle>):Rectangle
{
var height:uint = HIGHEST;
var areaLowest:Rectangle;
for each(var area:Rectangle in areaList)
{
if (area.height < height)
{
height = area.height;
areaLowest = area;
}
}
return areaLowest;
}
}
}
|
package utils
{
import flash.geom.Rectangle;
/**
* For place texture
*/
public final class TextureUtil
{
private static const HIGHEST:uint = 0xFFFFFFFF;
/**
* Place textures by textureAtlasXML data
*/
public static function packTextures(widthDefault:uint, padding:uint, rectMap:Object, verticalSide:Boolean = false):Rectangle
{
for each(var rect:Rectangle in rectMap)
{
break;
}
if(!rect)
{
return null;
}
var dimensions:uint = 0;
var maxWidth:Number = 0;
var rectList:Vector.<Rectangle> = new Vector.<Rectangle>;
for each(rect in rectMap)
{
dimensions += rect.width * rect.height;
rectList.push(rect);
maxWidth = Math.max(rect.width, maxWidth);
}
//sort texture by size
rectList.sort(sortRectList);
if(widthDefault == 0)
{
//calculate width for Auto size
widthDefault = Math.sqrt(dimensions);
}
widthDefault = getNearest2N(Math.max(maxWidth + padding, widthDefault));
var heightMax:uint = HIGHEST;
var remainAreaList:Vector.<Rectangle> = new Vector.<Rectangle>;
remainAreaList.push(new Rectangle(0, 0, widthDefault, heightMax));
var isFit:Boolean;
var width:int;
var height:int;
var area:Rectangle;
var areaPrev:Rectangle;
var areaNext:Rectangle;
var areaID:int;
var rectID:int;
do
{
//Find highest blank area
area = getHighestArea(remainAreaList);
areaID = remainAreaList.indexOf(area);
isFit = false;
rectID = 0;
for each(rect in rectList)
{
//check if the area is fit
width = int(rect.width) + padding;
height = int(rect.height) + padding;
if (area.width >= width && area.height >= height)
{
//place portrait texture
if(
verticalSide?
(
height > width * 4?
(
areaID > 0?
(area.height - height >= remainAreaList[areaID - 1].height):
true
):
true
):
true
)
{
isFit = true;
break;
}
}
rectID ++;
}
if(isFit)
{
//place texture if size is fit
rect.x = area.x;
rect.y = area.y;
rectList.splice(rectID, 1);
remainAreaList.splice(
areaID + 1,
0,
new Rectangle(area.x + width, area.y, area.width - width, area.height)
);
area.y += height;
area.width = width;
area.height -= height;
}
else
{
//not fit, don't place it, merge blank area to others toghther
if(areaID == 0)
{
areaNext = remainAreaList[areaID + 1];
}
else if(areaID == remainAreaList.length - 1)
{
areaNext = remainAreaList[areaID - 1];
}
else
{
areaPrev = remainAreaList[areaID - 1];
areaNext = remainAreaList[areaID + 1];
areaNext = areaPrev.height <= areaNext.height?areaNext:areaPrev;
}
if(area.x < areaNext.x)
{
areaNext.x = area.x;
}
areaNext.width = area.width + areaNext.width;
remainAreaList.splice(areaID, 1);
}
}
while (rectList.length > 0);
heightMax = getNearest2N(heightMax - getLowestArea(remainAreaList).height);
return new Rectangle(0, 0, widthDefault, heightMax);
}
private static function sortRectList(rect1:Rectangle, rect2:Rectangle):int
{
var v1:uint = rect1.width + rect1.height;
var v2:uint = rect2.width + rect2.height;
if (v1 == v2)
{
return rect1.width > rect2.width?-1:1;
}
return v1 > v2?-1:1;
}
private static function getNearest2N(_n:uint):uint
{
return _n & _n - 1?1 << _n.toString(2).length:_n;
}
private static function getHighestArea(areaList:Vector.<Rectangle>):Rectangle
{
var height:uint = 0;
var areaHighest:Rectangle;
for each(var area:Rectangle in areaList)
{
if (area.height > height)
{
height = area.height;
areaHighest = area;
}
}
return areaHighest;
}
private static function getLowestArea(areaList:Vector.<Rectangle>):Rectangle
{
var height:uint = HIGHEST;
var areaLowest:Rectangle;
for each(var area:Rectangle in areaList)
{
if (area.height < height)
{
height = area.height;
areaLowest = area;
}
}
return areaLowest;
}
}
}
|
fix get TextureAtlas width bug
|
fix get TextureAtlas width bug
|
ActionScript
|
mit
|
DragonBones/DesignPanel
|
0ee55d9476903fecd7fa09e467548d4b316d3b9f
|
runtime/src/main/as/flump/display/Movie.as
|
runtime/src/main/as/flump/display/Movie.as
|
//
// Flump - Copyright 2013 Flump Authors
package flump.display {
import flump.mold.MovieMold;
import react.Signal;
import starling.animation.IAnimatable;
import starling.display.DisplayObject;
import starling.display.Sprite;
import starling.events.Event;
/**
* A movie created from flump-exported data. It has children corresponding to the layers in the
* movie in Flash, in the same order and with the same names. It fills in those children
* initially with the image or movie of the symbol on that exported layer. After the initial
* population, it only applies the keyframe-based transformations to the child at the index
* corresponding to the layer. This means it's safe to swap in other DisplayObjects at those
* positions to have them animated in place of the initial child.
*
* <p>A Movie will not animate unless it's added to a Juggler (or its advanceTime() function
* is otherwise called). When the movie is added to a juggler, it advances its playhead with the
* frame ticks if isPlaying is true. It will automatically remove itself from its juggler when
* removed from the stage.</p>
*
* @see Library and LibraryLoader to create instances of Movie.
*/
public class Movie extends Sprite
implements IAnimatable
{
/** A label fired by all movies when entering their first frame. */
public static const FIRST_FRAME :String = "flump.movie.FIRST_FRAME";
/** A label fired by all movies when entering their last frame. */
public static const LAST_FRAME :String = "flump.movie.LAST_FRAME";
/** Fires the label string whenever it's passed in playing. */
public const labelPassed :Signal = new Signal(String);
/** @private */
public function Movie (src :MovieMold, frameRate :Number, library :Library) {
this.name = src.id;
_labels = src.labels;
_frameRate = frameRate;
if (src.flipbook) {
_layers = new Vector.<Layer>(1, true);
_layers[0] = new Layer(this, src.layers[0], library, /*flipbook=*/true);
_numFrames = src.layers[0].frames;
} else {
_layers = new Vector.<Layer>(src.layers.length, true);
for (var ii :int = 0; ii < _layers.length; ii++) {
_layers[ii] = new Layer(this, src.layers[ii], library, /*flipbook=*/false);
_numFrames = Math.max(src.layers[ii].frames, _numFrames);
}
}
_duration = _numFrames / _frameRate;
updateFrame(0, 0);
// When we're removed from the stage, remove ourselves from any juggler animating us.
addEventListener(Event.REMOVED_FROM_STAGE, function (..._) :void {
dispatchEventWith(Event.REMOVE_FROM_JUGGLER);
});
}
/** @return the frame being displayed. */
public function get frame () :int { return _frame; }
/** @return the number of frames in the movie. */
public function get numFrames () :int { return _numFrames; }
/** @return true if the movie is currently playing. */
public function get isPlaying () :Boolean { return _playing; }
/** @return true if the movie contains the given label. */
public function hasLabel (label :String) :Boolean {
return getFrameForLabel(label) >= 0;
}
/** Plays the movie from its current frame. The movie will loop forever. */
public function loop () :Movie {
_playing = true;
_stopFrame = NO_FRAME;
return this;
}
/** Plays the movie from its current frame, stopping when it reaches its last frame. */
public function playOnce () :Movie { return playTo(LAST_FRAME); }
/**
* Moves to the given String label or int frame. Doesn't alter playing status or stop frame.
* If there are labels at the given position, they're fired as part of the goto, even if the
* current frame is equal to the destination. Labels between the current frame and the
* destination frame are not fired.
*
* @param position the int frame or String label to goto.
*
* @return this movie for chaining
*
* @throws Error if position isn't an int or String, or if it is a String and that String isn't
* a label on this movie
*/
public function goTo (position :Object) :Movie {
const frame :int = extractFrame(position);
updateFrame(frame, 0);
return this;
}
/**
* Plays the movie from its current frame. The movie will stop when it reaches the given label
* or frame.
*
* @param position to int frame or String label to stop at
*
* @return this movie for chaining
*
* @throws Error if position isn't an int or String, or if it is a String and that String isn't
* a label on this movie.
*/
public function playTo (position :Object) :Movie {
_stopFrame = extractFrame(position);
// don't play if we're already at the stop frame
_playing = (_frame != _stopFrame);
return this;
}
/** Stops playback if it's currently active. Doesn't alter the current frame or stop frame. */
public function stop () :Movie {
_playing = false;
return this;
}
/** Advances the playhead by the give number of seconds. From IAnimatable. */
public function advanceTime (dt :Number) :void {
if (dt < 0) throw new Error("Invalid time [dt=" + dt + "]");
if (_skipAdvanceTime) { _skipAdvanceTime = false; return; }
if (!_playing) return;
if (_numFrames > 1) {
_playTime += dt;
var actualPlaytime :Number = _playTime;
if (_playTime >= _duration) _playTime %= _duration;
// If _playTime is very close to _duration, rounding error can cause us to
// land on lastFrame + 1. Protect against that.
var newFrame :int = clamp(int(_playTime * _frameRate), 0, _numFrames - 1);
// If the update crosses or goes to the stopFrame:
// go to the stopFrame, stop the movie, clear the stopFrame
if (_stopFrame != NO_FRAME) {
// how many frames remain to the stopframe?
var framesRemaining :int =
(_frame <= _stopFrame ? _stopFrame - _frame : _numFrames - _frame + _stopFrame);
var framesElapsed :int = int(actualPlaytime * _frameRate) - _frame;
if (framesElapsed >= framesRemaining) {
_playing = false;
newFrame = _stopFrame;
_stopFrame = NO_FRAME;
}
}
updateFrame(newFrame, dt);
}
for (var ii :int = this.numChildren - 1; ii >= 0; --ii) {
var child :DisplayObject = getChildAt(ii);
if (child is Movie) {
Movie(child).advanceTime(dt);
}
}
}
/** notify this Movie that it has been added to the Layer after initialization */
public function addedToLayer() :void
{
goTo(0);
_skipAdvanceTime = true;
}
/** @private */
protected function extractFrame (position :Object) :int {
if (position is int) return int(position);
if (!(position is String)) throw new Error("Movie position must be an int frame or String label");
const label :String = String(position);
var frame :int = getFrameForLabel(label);
if (frame < 0) {
throw new Error("No such label '" + label + "'");
}
return frame;
}
/**
* @private
*
* Returns the frame index for the given label, or -1 if the label doesn't exist.
*/
protected function getFrameForLabel (label :String) :int {
for (var ii :int = 0; ii < _labels.length; ii++) {
if (_labels[ii] != null && _labels[ii].indexOf(label) != -1) return ii;
}
return -1;
}
/**
* @private
*
* @param dt the timeline's elapsed time since the last update. This should be 0
* for updates that are the result of a "goTo" call.
*/
protected function updateFrame (newFrame :int, dt :Number) :void {
if (newFrame < 0 || newFrame >= _numFrames) {
throw new Error("Invalid frame [frame=" + newFrame,
" validRange=0-" + (_numFrames - 1) + "]");
}
if (_isUpdatingFrame) {
_pendingFrame = newFrame;
return;
} else {
_pendingFrame = NO_FRAME;
_isUpdatingFrame = true;
}
const isGoTo :Boolean = (dt <= 0);
const wrapped :Boolean = (dt >= _duration) || (newFrame < _frame);
if (newFrame != _frame) {
if (wrapped) {
for each (var layer :Layer in _layers) {
layer.movieLooped();
}
}
for each (layer in _layers) layer.drawFrame(newFrame);
}
if (isGoTo) _playTime = newFrame / _frameRate;
// Update the frame before firing frame label signals, so if firing changes the frame,
// it sticks.
const oldFrame :int = _frame;
_frame = newFrame;
// determine which labels to fire signals for
var startFrame :int;
var frameCount :int;
if (isGoTo) {
startFrame = newFrame;
frameCount = 1;
} else {
startFrame = (oldFrame + 1 < _numFrames ? oldFrame + 1 : 0);
frameCount = (_frame - oldFrame);
if (wrapped) frameCount += _numFrames;
}
// Fire signals. Stop if pendingFrame is updated, which indicates that the client
// has called goTo()
var frameIdx :int = startFrame;
for (var ii :int = 0; ii < frameCount; ++ii) {
if (_pendingFrame != NO_FRAME) break;
if (_labels[frameIdx] != null) {
for each (var label :String in _labels[frameIdx]) {
labelPassed.emit(label);
if (_pendingFrame != NO_FRAME) break;
}
}
// avoid modulo division by updating frameIdx each time through the loop
if (++frameIdx == _numFrames) {
frameIdx = 0;
}
}
_isUpdatingFrame = false;
// If we were interrupted by a goTo(), update to that frame now.
if (_pendingFrame != NO_FRAME) {
newFrame = _pendingFrame;
updateFrame(newFrame, 0);
}
}
protected static function clamp (n :Number, min :Number, max :Number) :Number {
return Math.min(Math.max(n, min), max);
}
/** @private */
protected var _isUpdatingFrame :Boolean;
/** @private */
protected var _pendingFrame :int = NO_FRAME;
/** @private */
protected var _frame :int = NO_FRAME, _stopFrame :int = NO_FRAME;
/** @private */
protected var _playing :Boolean = true;
/** @private */
protected var _playTime :Number, _duration :Number;
/** @private */
protected var _layers :Vector.<Layer>;
/** @private */
protected var _numFrames :int;
/** @private */
protected var _frameRate :Number;
/** @private */
protected var _labels :Vector.<Vector.<String>>;
/** @private */
private var _skipAdvanceTime :Boolean = false;
/** @private */
internal var _playerData :MoviePlayerNode;
private static const NO_FRAME :int = -1;
}
}
|
//
// Flump - Copyright 2013 Flump Authors
package flump.display {
import flump.mold.MovieMold;
import react.Signal;
import starling.animation.IAnimatable;
import starling.display.DisplayObject;
import starling.display.Sprite;
import starling.events.Event;
/**
* A movie created from flump-exported data. It has children corresponding to the layers in the
* movie in Flash, in the same order and with the same names. It fills in those children
* initially with the image or movie of the symbol on that exported layer. After the initial
* population, it only applies the keyframe-based transformations to the child at the index
* corresponding to the layer. This means it's safe to swap in other DisplayObjects at those
* positions to have them animated in place of the initial child.
*
* <p>A Movie will not animate unless it's added to a Juggler (or its advanceTime() function
* is otherwise called). When the movie is added to a juggler, it advances its playhead with the
* frame ticks if isPlaying is true. It will automatically remove itself from its juggler when
* removed from the stage.</p>
*
* @see Library and LibraryLoader to create instances of Movie.
*/
public class Movie extends Sprite
implements IAnimatable
{
/** A label fired by all movies when entering their first frame. */
public static const FIRST_FRAME :String = "flump.movie.FIRST_FRAME";
/** A label fired by all movies when entering their last frame. */
public static const LAST_FRAME :String = "flump.movie.LAST_FRAME";
/** Fires the label string whenever it's passed in playing. */
public const labelPassed :Signal = new Signal(String);
/** @private */
public function Movie (src :MovieMold, frameRate :Number, library :Library) {
this.name = src.id;
_labels = src.labels;
_frameRate = frameRate;
if (src.flipbook) {
_layers = new Vector.<Layer>(1, true);
_layers[0] = new Layer(this, src.layers[0], library, /*flipbook=*/true);
_numFrames = src.layers[0].frames;
} else {
_layers = new Vector.<Layer>(src.layers.length, true);
for (var ii :int = 0; ii < _layers.length; ii++) {
_layers[ii] = new Layer(this, src.layers[ii], library, /*flipbook=*/false);
_numFrames = Math.max(src.layers[ii].frames, _numFrames);
}
}
_duration = _numFrames / _frameRate;
updateFrame(0, 0);
// When we're removed from the stage, remove ourselves from any juggler animating us.
addEventListener(Event.REMOVED_FROM_STAGE, function (..._) :void {
dispatchEventWith(Event.REMOVE_FROM_JUGGLER);
});
}
/** @return the frame being displayed. */
public function get frame () :int { return _frame; }
/** @return the number of frames in the movie. */
public function get numFrames () :int { return _numFrames; }
/** @return true if the movie is currently playing. */
public function get isPlaying () :Boolean { return _playing; }
/** @return true if the movie contains the given label. */
public function hasLabel (label :String) :Boolean {
return getFrameForLabel(label) >= 0;
}
/** Plays the movie from its current frame. The movie will loop forever. */
public function loop () :Movie {
_playing = true;
_stopFrame = NO_FRAME;
return this;
}
/** Plays the movie from its current frame, stopping when it reaches its last frame. */
public function playOnce () :Movie { return playTo(LAST_FRAME); }
/**
* Moves to the given String label or int frame. Doesn't alter playing status or stop frame.
* If there are labels at the given position, they're fired as part of the goto, even if the
* current frame is equal to the destination. Labels between the current frame and the
* destination frame are not fired.
*
* @param position the int frame or String label to goto.
*
* @return this movie for chaining
*
* @throws Error if position isn't an int or String, or if it is a String and that String isn't
* a label on this movie
*/
public function goTo (position :Object) :Movie {
const frame :int = extractFrame(position);
updateFrame(frame, 0);
return this;
}
/**
* Plays the movie from its current frame. The movie will stop when it reaches the given label
* or frame.
*
* @param position to int frame or String label to stop at
*
* @return this movie for chaining
*
* @throws Error if position isn't an int or String, or if it is a String and that String isn't
* a label on this movie.
*/
public function playTo (position :Object) :Movie {
_stopFrame = extractFrame(position);
// don't play if we're already at the stop frame
_playing = (_frame != _stopFrame);
return this;
}
/** Stops playback if it's currently active. Doesn't alter the current frame or stop frame. */
public function stop () :Movie {
_playing = false;
return this;
}
/** Advances the playhead by the give number of seconds. From IAnimatable. */
public function advanceTime (dt :Number) :void {
if (dt < 0) throw new Error("Invalid time [dt=" + dt + "]");
if (_skipAdvanceTime) { _skipAdvanceTime = false; return; }
if (!_playing) return;
if (_numFrames > 1) {
_playTime += dt;
var actualPlaytime :Number = _playTime;
if (_playTime >= _duration) _playTime %= _duration;
// If _playTime is very close to _duration, rounding error can cause us to
// land on lastFrame + 1. Protect against that.
var newFrame :int = clamp(int(_playTime * _frameRate), 0, _numFrames - 1);
// If the update crosses or goes to the stopFrame:
// go to the stopFrame, stop the movie, clear the stopFrame
if (_stopFrame != NO_FRAME) {
// how many frames remain to the stopframe?
var framesRemaining :int =
(_frame <= _stopFrame ? _stopFrame - _frame : _numFrames - _frame + _stopFrame);
var framesElapsed :int = int(actualPlaytime * _frameRate) - _frame;
if (framesElapsed >= framesRemaining) {
_playing = false;
newFrame = _stopFrame;
_stopFrame = NO_FRAME;
}
}
updateFrame(newFrame, dt);
}
for (var ii :int = this.numChildren - 1; ii >= 0; --ii) {
var child :DisplayObject = getChildAt(ii);
if (child is Movie) {
Movie(child).advanceTime(dt);
}
}
}
/** notify this Movie that it has been added to the Layer after initialization */
public function addedToLayer() :void
{
goTo(0);
_skipAdvanceTime = true;
}
/** @private */
protected function extractFrame (position :Object) :int {
if (position is int) return int(position);
if (!(position is String)) throw new Error("Movie position must be an int frame or String label");
const label :String = String(position);
var frame :int = getFrameForLabel(label);
if (frame < 0) {
throw new Error("No such label '" + label + "'");
}
return frame;
}
/**
* @private
*
* Returns the frame index for the given label, or -1 if the label doesn't exist.
*/
protected function getFrameForLabel (label :String) :int {
for (var ii :int = 0; ii < _labels.length; ii++) {
if (_labels[ii] != null && _labels[ii].indexOf(label) != -1) return ii;
}
return -1;
}
/**
* @private
*
* @param dt the timeline's elapsed time since the last update. This should be 0
* for updates that are the result of a "goTo" call.
*/
protected function updateFrame (newFrame :int, dt :Number) :void {
if (newFrame < 0 || newFrame >= _numFrames) {
throw new Error("Invalid frame [frame=" + newFrame,
" validRange=0-" + (_numFrames - 1) + "]");
}
if (_isUpdatingFrame) {
_pendingFrame = newFrame;
return;
} else {
_pendingFrame = NO_FRAME;
_isUpdatingFrame = true;
}
const isGoTo :Boolean = (dt <= 0);
const wrapped :Boolean = (dt >= _duration) || (newFrame < _frame);
if (newFrame != _frame) {
if (wrapped) {
for each (var layer :Layer in _layers) {
layer.movieLooped();
}
}
for each (layer in _layers) layer.drawFrame(newFrame);
}
if (isGoTo) _playTime = newFrame / _frameRate;
// Update the frame before firing frame label signals, so if firing changes the frame,
// it sticks.
const oldFrame :int = _frame;
_frame = newFrame;
// determine which labels to fire signals for
var startFrame :int;
var frameCount :int;
if (isGoTo) {
startFrame = newFrame;
frameCount = 1;
} else {
startFrame = (oldFrame + 1 < _numFrames ? oldFrame + 1 : 0);
frameCount = (_frame - oldFrame);
if (wrapped) frameCount += _numFrames;
}
// Fire signals. Stop if pendingFrame is updated, which indicates that the client
// has called goTo()
var frameIdx :int = startFrame;
for (var ii :int = 0; ii < frameCount; ++ii) {
if (_pendingFrame != NO_FRAME) break;
if (_labels[frameIdx] != null) {
for each (var label :String in _labels[frameIdx]) {
labelPassed.emit(label);
if (_pendingFrame != NO_FRAME) break;
}
}
// avoid modulo division by updating frameIdx each time through the loop
if (++frameIdx == _numFrames) {
frameIdx = 0;
}
}
_isUpdatingFrame = false;
// If we were interrupted by a goTo(), update to that frame now.
if (_pendingFrame != NO_FRAME) {
newFrame = _pendingFrame;
updateFrame(newFrame, 0);
}
}
protected static function clamp (n :Number, min :Number, max :Number) :Number {
return Math.min(Math.max(n, min), max);
}
/** @private */
protected var _isUpdatingFrame :Boolean;
/** @private */
protected var _pendingFrame :int = NO_FRAME;
/** @private */
protected var _frame :int = NO_FRAME, _stopFrame :int = NO_FRAME;
/** @private */
protected var _playing :Boolean = true;
/** @private */
protected var _playTime :Number, _duration :Number;
/** @private */
protected var _layers :Vector.<Layer>;
/** @private */
protected var _numFrames :int;
/** @private */
protected var _frameRate :Number;
/** @private */
protected var _labels :Vector.<Vector.<String>>;
/** @private */
private var _skipAdvanceTime :Boolean = false;
/** @private */
internal var _playerData :MoviePlayerNode;
private static const NO_FRAME :int = -1;
}
}
|
remove errant newline
|
remove errant newline
|
ActionScript
|
mit
|
mathieuanthoine/flump,funkypandagame/flump,mathieuanthoine/flump,tconkling/flump,tconkling/flump,mathieuanthoine/flump,funkypandagame/flump
|
5ffc5d2c5a25fbd9b1feac9d815cfe2ed9004f7a
|
krew-framework/krewfw/core/KrewActor.as
|
krew-framework/krewfw/core/KrewActor.as
|
package krewfw.core {
import flash.geom.Rectangle;
import starling.animation.Transitions;
import starling.animation.Tween;
import starling.display.DisplayObject;
import starling.display.Image;
import starling.text.TextField;
import starling.textures.Texture;
import krewfw.KrewConfig;
import krewfw.builtin_actor.display.ColorRect;
import krewfw.core_internal.KrewSharedObjects;
import krewfw.core_internal.ProfileData;
import krewfw.core_internal.StageLayer;
import krewfw.core_internal.StuntAction;
import krewfw.core_internal.StuntActionInstructor;
import krewfw.utils.as3.KrewTimeKeeper;
//------------------------------------------------------------
public class KrewActor extends KrewGameObject {
private var _hasInitialized:Boolean = false;
private var _hasDisposed:Boolean = false;
private var _markedForDeath:Boolean = false; // 死亡フラグ
protected var _checkDisplayArea:Boolean = false;
protected var _cachedWidth :Number;
protected var _cachedHeight:Number;
private var _initFuncList :Vector.<Function> = new Vector.<Function>();
private var _imageList :Vector.<Image> = new Vector.<Image>();
private var _displayObjList:Vector.<DisplayObject> = new Vector.<DisplayObject>();
private var _textList :Vector.<TextField> = new Vector.<TextField>();
private var _childActors :Vector.<KrewActor> = new Vector.<KrewActor>();
private var _color:uint = 0xffffff;
public var applyForNewActor:Function;
public var layer:StageLayer; // reference of layer this actor belonged to
public var layerName:String;
private var _actionInstructors:Vector.<StuntActionInstructor> = new Vector.<StuntActionInstructor>();
private var _timeKeeper:KrewTimeKeeper = new KrewTimeKeeper();
/** high is front */
public var displayOrder:int = 0;
/**
* addActor 前に false にすると addActor 時に addChild を行わない
* (Starling の DisplayList にのせない.)
* 見た目を持たずに仕事をする Actor はこれを false にすればよい
*/
public var displayable:Boolean = true;
/** false にすると CollisionShape が衝突判定を行わない */
public var collidable:Boolean = true;
//------------------------------------------------------------
// accessors
//------------------------------------------------------------
/**
* [CAUTION] starling.display.DisplayObjectContainer の
* width / height の getter は重い行列計算が走るので滅多なことでもない限り使うな
*/
public function get cachedWidth():Number {
return _cachedWidth;
}
/** @see cachedWidth */
public function get cachedHeight():Number {
return _cachedHeight;
}
public function get color():uint {
return _color;
}
/** Actor が持つ Image や TextField 全てに色をセットする */
public function set color(color:uint):void {
_color = color;
for each (var image:Image in _imageList) {
image.color = color;
}
for each (var text:TextField in _textList) {
text.color = color;
}
}
public function get childActors():Vector.<KrewActor> {
return _childActors;
}
public function get numActor():int {
return _childActors.length;
}
public function get isDead():Boolean {
return _markedForDeath;
}
public function get hasInitialized():Boolean {
return _hasInitialized;
}
//------------------------------------------------------------
// constructors
//------------------------------------------------------------
public function KrewActor() {}
/**
* init が呼ばれる時(KrewScene.setUpActor に渡された時、または
* Actor から addActor されたとき)に、init 後に呼ばれる関数を登録。
* コンストラクタでの使用を想定.
*
* コンストラクタで引数を渡して init に用いたい場合、クラスメンバに値を
* 保持しておくなどの手間がかかるため、それを楽にするためのもの。
* 登録した関数は init 実行後に、登録した順番で呼ばれる。
*/
public function addInitializer(initFunc:Function):void {
_initFuncList.push(initFunc);
}
/** @private */
public function setUp(sharedObj:KrewSharedObjects, applyForNewActor:Function,
layer:StageLayer, layerName:String):void
{
if (_hasInitialized) {
krew.fwlog('[Warning] KrewActor has initialized twice.');
return;
}
_hasInitialized = true;
this.sharedObj = sharedObj;
this.applyForNewActor = applyForNewActor;
this.layer = layer;
this.layerName = layerName;
_doInit();
ProfileData.countActor(1, this.layerName);
}
private function _doInit():void {
init();
for each (var initFunc:Function in _initFuncList) {
initFunc();
}
}
//------------------------------------------------------------
// destructors
//------------------------------------------------------------
/** @private */
public override function dispose():void {
if (_hasDisposed) { return; }
_hasDisposed = true;
if (_hasInitialized) {
_hasInitialized = false;
ProfileData.countActor(-1, this.layerName);
}
for each (var child:KrewActor in _childActors) {
child.dispose();
}
removeChildren(0, -1, true);
removeCollision();
removeTweens();
_disposeImageTextures();
_disposeTexts();
_disposeDisplayObjs();
_timeKeeper.dispose();
_initFuncList = null;
_imageList = null;
_textList = null;
_childActors = null;
_actionInstructors = null;
_timeKeeper = null;
onDispose();
super.dispose();
}
/** @private */
protected function _disposeImageTextures():void {
for (var i:uint=0; i < _imageList.length; ++i) {
_imageList[i].texture.dispose();
_imageList[i].dispose();
}
}
/** @private */
protected function _disposeTexts():void {
for each (var text:TextField in _textList) {
text.dispose();
}
}
/** @private */
protected function _disposeDisplayObjs():void {
for each (var obj:DisplayObject in _displayObjList) {
obj.dispose();
}
}
/** @private */
protected function removeCollision():void {
if (!sharedObj) { return; }
sharedObj.collisionSystem.removeShapeWithActor(this);
}
//------------------------------------------------------------
// public interface
//------------------------------------------------------------
/**
* addChild の代わりに addImage を呼ぶことで破棄時に Image.texture の dispose が
* 呼ばれるようになる。また、KrewActor.color の指定で全 Image に色がかかるようになる
*/
public function addImage(image:Image,
width:Number=NaN, height:Number=NaN,
x:Number=0, y:Number=0,
anchorX:Number=0.5, anchorY:Number=0.5):void
{
image.x = x;
image.y = y;
if (!isNaN(width )) { image.width = width; }
if (!isNaN(height)) { image.height = height; }
// pivotX, Y は回転の軸だけでなく座標指定にも影響する
// そして何故かソースの画像の解像度に対する座標で指定してやらないといけないようだ
var textureRect:Rectangle = image.texture.frame;
image.pivotX = (textureRect.width * anchorX);
image.pivotY = (textureRect.height * anchorY);
_cachedWidth = width;
_cachedHeight = height;
super.addChild(image);
_imageList.push(image);
}
public function changeImage(image:Image, imageName:String):void {
var newTexture:Texture = sharedObj.resourceManager.getTexture(imageName);
image.texture.dispose();
image.texture = newTexture;
}
/**
* Actor 全体の color に影響させたい場合は addChild ではなく addText で足す
*/
public function addText(text:TextField, x:Number=NaN, y:Number=NaN):void {
if (!isNaN(x)) { text.x = x; }
if (!isNaN(y)) { text.y = y; }
super.addChild(text);
_textList.push(text);
}
/**
* addChild したものは Actor 破棄時に勝手に dispose が呼ばれる
*/
public override function addChild(child:DisplayObject):DisplayObject {
super.addChild(child);
_displayObjList.push(child);
return child;
}
/**
* krewFramework のシステムに Actor を登録し、同時に Starling の DisplayList に追加する.
* 見た目を持たずに仕事をするような Actor は putOnDisplayList に false を渡すか、
* Actor のコンストラクタで displayable に false を設定しておくと Starling の DisplayList
* には追加しない
*/
public function addActor(actor:KrewActor, putOnDisplayList:Boolean=true):void {
_childActors.push(actor);
if (putOnDisplayList && actor.displayable) {
addChild(actor);
}
if (actor.hasInitialized) { return; }
actor.setUp(sharedObj, applyForNewActor, layer, layerName);
}
public function createActor(newActor:KrewActor, layerName:String=null):void {
if (!newActor) {
throw new Error("[Error] [KrewActor :: createActor] newActor is required.");
}
// layerName 省略時は自分と同じ layer に出す
if (layerName == null) {
layerName = this.layerName;
}
applyForNewActor(newActor, layerName);
}
public function passAway():void {
_markedForDeath = true;
}
public function setVertexColor(color1:int=0, color2:int=0,
color3:int=0, color4:int=0):void {
for each (var image:Image in _imageList) {
image.setVertexColor(0, color1);
image.setVertexColor(1, color2);
image.setVertexColor(2, color3);
image.setVertexColor(3, color4);
}
}
//------------------------------------------------------------
// Helpers for Tween
//------------------------------------------------------------
public function addTween(tween:Tween):void {
if (!layer) {
krew.fwlog('[Error] This actor does not belong to any layer.');
return;
}
layer.juggler.add(tween);
}
public function removeTweens():void {
if (!layer) {
krew.fwlog('[Error] This actor does not belong to any layer.');
return;
}
layer.juggler.removeTweens(this);
}
public function enchant(duration:Number, transition:String=Transitions.LINEAR):Tween {
var tween:Tween = new Tween(this, duration, transition);
addTween(tween);
return tween;
}
//------------------------------------------------------------
// Multi Tasker
//------------------------------------------------------------
public function act(action:StuntAction=null):StuntAction {
var actionInstructor:StuntActionInstructor = new StuntActionInstructor(this, action);
_actionInstructors.push(actionInstructor);
return actionInstructor.action;
}
// purge actions
public function react():void {
_actionInstructors.length = 0;
removeTweens();
}
private function _updateAction(passedTime:Number):void {
for (var i:int=0; i <_actionInstructors.length; ++i) {
var actionInstructor:StuntActionInstructor = _actionInstructors[i];
actionInstructor.update(passedTime);
if (actionInstructor.isAllActionFinished) {
_actionInstructors.splice(i, 1); // remove instructor from Array
--i;
}
}
}
/** Equivalent to setTimeout() */
public function addScheduledTask(timeout:Number, task:Function):void {
if (timeout <= 0) {
task();
return;
}
_timeKeeper.addPeriodicTask(timeout, task, 1);
}
/** Alias for addScheduledTask */
public function delayed(timeout:Number, task:Function):void {
addScheduledTask(timeout, task);
}
/** Equivalent to setInterval() */
public function addPeriodicTask(interval:Number, task:Function, times:int=-1):void {
_timeKeeper.addPeriodicTask(interval, task, times);
}
/** Alias for addPeriodicTask */
public function cyclic(interval:Number, task:Function, times:int=-1):void {
addPeriodicTask(interval, task, times);
}
// for touch action
public function addTouchMarginNode(touchWidth:Number=0, touchHeight:Number=0):void {
var margin:ColorRect = new ColorRect(touchWidth, touchHeight);
margin.touchable = true;
margin.alpha = 0;
margin.x = -touchWidth / 2;
margin.y = -touchHeight / 2;
addActor(margin);
}
/**
* displayOrder の値でツリーをソート。 children が皆 KrewActor である前提。
* tkActor.displayOrder = 1; のように設定した上で
* getLayer('hoge').sortDisplayOrder(); のように使う
*/
public function sortDisplayOrder():void {
sortChildren(function(a:KrewActor, b:KrewActor):int {
if (a.displayOrder < b.displayOrder) { return -1; }
if (a.displayOrder > b.displayOrder) { return 1; }
return 0;
});
}
//------------------------------------------------------------
// Called by framework
//------------------------------------------------------------
/** @private */
public function update(passedTime:Number):void {
if (_hasDisposed) { return; }
// update children actors
for (var i:int=0; i < _childActors.length; ++i) {
var child:KrewActor = _childActors[i];
if (child.isDead) {
_childActors.splice(i, 1); // remove dead actor from Array
removeChild(child);
child.dispose();
--i;
continue;
}
child.update(passedTime);
}
onUpdate(passedTime);
_updateAction(passedTime);
_timeKeeper.update(passedTime);
_disappearInOutside();
}
/**
* _checkDisplayArea = true の Actor は、画面外にいるときは表示を off にする。
* これをやってあげないと少なくとも Flash では
* 画面外でも普通に描画コストがかかってしまうようだ.
*
* いずれにせよ visible false でなければ Starling は描画のための
* 計算とかをしだすので、それを避けるにはこれをやった方がいい
*
* つまるところ、数が多く画像のアンカーが中央にあるような Actor を
* _checkDisplayArea = true にすればよい
*/
private function _disappearInOutside():void {
if (!_checkDisplayArea) { return; }
// starling.display.DisplayObjectContainer の width / height は
// getBounds という重い処理が走るのでうかつにさわってはいけない
// オーバヘッドを抑えるため、ラフに計算。回転を考慮して大きめにとる。
// 横長の画像などについては考えてないのでどうしようもないときは
// _checkDisplayArea を false のままにしておくか、
// _cachedWidth とかを書き換えるか、もしくは override してくれ
var halfWidth :Number = (_cachedWidth / 1.5) * scaleX;
var halfHeight:Number = (_cachedHeight / 1.5) * scaleY;
if (x + halfWidth > 0 && x - halfWidth < KrewConfig.SCREEN_WIDTH &&
y + halfHeight > 0 && y - halfHeight < KrewConfig.SCREEN_HEIGHT) {
visible = true;
} else {
visible = false;
}
}
}
}
|
package krewfw.core {
import flash.geom.Rectangle;
import starling.animation.Transitions;
import starling.animation.Tween;
import starling.display.DisplayObject;
import starling.display.Image;
import starling.text.TextField;
import starling.textures.Texture;
import krewfw.KrewConfig;
import krewfw.builtin_actor.display.ColorRect;
import krewfw.core_internal.KrewSharedObjects;
import krewfw.core_internal.ProfileData;
import krewfw.core_internal.StageLayer;
import krewfw.core_internal.StuntAction;
import krewfw.core_internal.StuntActionInstructor;
import krewfw.utils.as3.KrewTimeKeeper;
//------------------------------------------------------------
public class KrewActor extends KrewGameObject {
private var _hasInitialized:Boolean = false;
private var _hasDisposed:Boolean = false;
private var _markedForDeath:Boolean = false; // 死亡フラグ
protected var _checkDisplayArea:Boolean = false;
protected var _cachedWidth :Number;
protected var _cachedHeight:Number;
private var _initFuncList :Vector.<Function> = new Vector.<Function>();
private var _imageList :Vector.<Image> = new Vector.<Image>();
private var _displayObjList:Vector.<DisplayObject> = new Vector.<DisplayObject>();
private var _textList :Vector.<TextField> = new Vector.<TextField>();
private var _childActors :Vector.<KrewActor> = new Vector.<KrewActor>();
private var _color:uint = 0xffffff;
public var applyForNewActor:Function;
public var layer:StageLayer; // reference of layer this actor belonged to
public var layerName:String;
private var _actionInstructors:Vector.<StuntActionInstructor> = new Vector.<StuntActionInstructor>();
private var _timeKeeper:KrewTimeKeeper = new KrewTimeKeeper();
/** high is front */
public var displayOrder:int = 0;
/**
* addActor 前に false にすると addActor 時に addChild を行わない
* (Starling の DisplayList にのせない.)
* 見た目を持たずに仕事をする Actor はこれを false にすればよい
*/
public var displayable:Boolean = true;
/** false にすると CollisionShape が衝突判定を行わない */
public var collidable:Boolean = true;
//------------------------------------------------------------
// accessors
//------------------------------------------------------------
/**
* [CAUTION] starling.display.DisplayObjectContainer の
* width / height の getter は重い行列計算が走るので滅多なことでもない限り使うな
*/
public function get cachedWidth():Number {
return _cachedWidth;
}
/** @see cachedWidth */
public function get cachedHeight():Number {
return _cachedHeight;
}
public function get color():uint {
return _color;
}
/** Actor が持つ Image や TextField 全てに色をセットする */
public function set color(color:uint):void {
_color = color;
for each (var image:Image in _imageList) {
image.color = color;
}
for each (var text:TextField in _textList) {
text.color = color;
}
}
public function get childActors():Vector.<KrewActor> {
return _childActors;
}
public function get numActor():int {
return _childActors.length;
}
public function get isDead():Boolean {
return _markedForDeath;
}
public function get hasInitialized():Boolean {
return _hasInitialized;
}
//------------------------------------------------------------
// constructors
//------------------------------------------------------------
public function KrewActor() {}
/**
* init が呼ばれる時(KrewScene.setUpActor に渡された時、または
* Actor から addActor されたとき)に、init 後に呼ばれる関数を登録。
* コンストラクタでの使用を想定.
*
* コンストラクタで引数を渡して init に用いたい場合、クラスメンバに値を
* 保持しておくなどの手間がかかるため、それを楽にするためのもの。
* 登録した関数は init 実行後に、登録した順番で呼ばれる。
*/
public function addInitializer(initFunc:Function):void {
_initFuncList.push(initFunc);
}
/** @private */
public function setUp(sharedObj:KrewSharedObjects, applyForNewActor:Function,
layer:StageLayer, layerName:String):void
{
if (_hasInitialized) {
krew.fwlog('[Warning] KrewActor has initialized twice.');
return;
}
_hasInitialized = true;
this.sharedObj = sharedObj;
this.applyForNewActor = applyForNewActor;
this.layer = layer;
this.layerName = layerName;
_doInit();
ProfileData.countActor(1, this.layerName);
}
private function _doInit():void {
init();
for each (var initFunc:Function in _initFuncList) {
initFunc();
}
}
//------------------------------------------------------------
// destructors
//------------------------------------------------------------
/** @private */
public override function dispose():void {
if (_hasDisposed) { return; }
_hasDisposed = true;
if (_hasInitialized) {
_hasInitialized = false;
ProfileData.countActor(-1, this.layerName);
}
for each (var child:KrewActor in _childActors) {
child.dispose();
}
removeChildren(0, -1, true);
removeCollision();
removeTweens();
_disposeImageTextures();
_disposeTexts();
_disposeDisplayObjs();
_timeKeeper.dispose();
_initFuncList = null;
_imageList = null;
_textList = null;
_displayObjList = null;
_childActors = null;
_actionInstructors = null;
_timeKeeper = null;
onDispose();
super.dispose();
}
/** @private */
protected function _disposeImageTextures():void {
for (var i:uint=0; i < _imageList.length; ++i) {
_imageList[i].texture.dispose();
_imageList[i].dispose();
}
}
/** @private */
protected function _disposeTexts():void {
for each (var text:TextField in _textList) {
text.dispose();
}
}
/** @private */
protected function _disposeDisplayObjs():void {
for each (var obj:DisplayObject in _displayObjList) {
obj.dispose();
}
}
/** @private */
protected function removeCollision():void {
if (!sharedObj) { return; }
sharedObj.collisionSystem.removeShapeWithActor(this);
}
//------------------------------------------------------------
// public interface
//------------------------------------------------------------
/**
* addChild の代わりに addImage を呼ぶことで破棄時に Image.texture の dispose が
* 呼ばれるようになる。また、KrewActor.color の指定で全 Image に色がかかるようになる
*/
public function addImage(image:Image,
width:Number=NaN, height:Number=NaN,
x:Number=0, y:Number=0,
anchorX:Number=0.5, anchorY:Number=0.5):void
{
image.x = x;
image.y = y;
if (!isNaN(width )) { image.width = width; }
if (!isNaN(height)) { image.height = height; }
// pivotX, Y は回転の軸だけでなく座標指定にも影響する
// そして何故かソースの画像の解像度に対する座標で指定してやらないといけないようだ
var textureRect:Rectangle = image.texture.frame;
image.pivotX = (textureRect.width * anchorX);
image.pivotY = (textureRect.height * anchorY);
_cachedWidth = width;
_cachedHeight = height;
super.addChild(image);
_imageList.push(image);
}
public function changeImage(image:Image, imageName:String):void {
var newTexture:Texture = sharedObj.resourceManager.getTexture(imageName);
image.texture.dispose();
image.texture = newTexture;
}
/**
* Actor 全体の color に影響させたい場合は addChild ではなく addText で足す
*/
public function addText(text:TextField, x:Number=NaN, y:Number=NaN):void {
if (!isNaN(x)) { text.x = x; }
if (!isNaN(y)) { text.y = y; }
super.addChild(text);
_textList.push(text);
}
/**
* addChild したものは Actor 破棄時に勝手に dispose が呼ばれる
*/
public override function addChild(child:DisplayObject):DisplayObject {
super.addChild(child);
_displayObjList.push(child);
return child;
}
/**
* krewFramework のシステムに Actor を登録し、同時に Starling の DisplayList に追加する.
* 見た目を持たずに仕事をするような Actor は putOnDisplayList に false を渡すか、
* Actor のコンストラクタで displayable に false を設定しておくと Starling の DisplayList
* には追加しない
*/
public function addActor(actor:KrewActor, putOnDisplayList:Boolean=true):void {
_childActors.push(actor);
if (putOnDisplayList && actor.displayable) {
addChild(actor);
}
if (actor.hasInitialized) { return; }
actor.setUp(sharedObj, applyForNewActor, layer, layerName);
}
public function createActor(newActor:KrewActor, layerName:String=null):void {
if (!newActor) {
throw new Error("[Error] [KrewActor :: createActor] newActor is required.");
}
// layerName 省略時は自分と同じ layer に出す
if (layerName == null) {
layerName = this.layerName;
}
applyForNewActor(newActor, layerName);
}
public function passAway():void {
_markedForDeath = true;
}
public function setVertexColor(color1:int=0, color2:int=0,
color3:int=0, color4:int=0):void {
for each (var image:Image in _imageList) {
image.setVertexColor(0, color1);
image.setVertexColor(1, color2);
image.setVertexColor(2, color3);
image.setVertexColor(3, color4);
}
}
//------------------------------------------------------------
// Helpers for Tween
//------------------------------------------------------------
public function addTween(tween:Tween):void {
if (!layer) {
krew.fwlog('[Error] This actor does not belong to any layer.');
return;
}
layer.juggler.add(tween);
}
public function removeTweens():void {
if (!layer) {
krew.fwlog('[Error] This actor does not belong to any layer.');
return;
}
layer.juggler.removeTweens(this);
}
public function enchant(duration:Number, transition:String=Transitions.LINEAR):Tween {
var tween:Tween = new Tween(this, duration, transition);
addTween(tween);
return tween;
}
//------------------------------------------------------------
// Multi Tasker
//------------------------------------------------------------
public function act(action:StuntAction=null):StuntAction {
var actionInstructor:StuntActionInstructor = new StuntActionInstructor(this, action);
_actionInstructors.push(actionInstructor);
return actionInstructor.action;
}
// purge actions
public function react():void {
_actionInstructors.length = 0;
removeTweens();
}
private function _updateAction(passedTime:Number):void {
for (var i:int=0; i <_actionInstructors.length; ++i) {
var actionInstructor:StuntActionInstructor = _actionInstructors[i];
actionInstructor.update(passedTime);
if (actionInstructor.isAllActionFinished) {
_actionInstructors.splice(i, 1); // remove instructor from Array
--i;
}
}
}
/** Equivalent to setTimeout() */
public function addScheduledTask(timeout:Number, task:Function):void {
if (timeout <= 0) {
task();
return;
}
_timeKeeper.addPeriodicTask(timeout, task, 1);
}
/** Alias for addScheduledTask */
public function delayed(timeout:Number, task:Function):void {
addScheduledTask(timeout, task);
}
/** Equivalent to setInterval() */
public function addPeriodicTask(interval:Number, task:Function, times:int=-1):void {
_timeKeeper.addPeriodicTask(interval, task, times);
}
/** Alias for addPeriodicTask */
public function cyclic(interval:Number, task:Function, times:int=-1):void {
addPeriodicTask(interval, task, times);
}
// for touch action
public function addTouchMarginNode(touchWidth:Number=0, touchHeight:Number=0):void {
var margin:ColorRect = new ColorRect(touchWidth, touchHeight);
margin.touchable = true;
margin.alpha = 0;
margin.x = -touchWidth / 2;
margin.y = -touchHeight / 2;
addActor(margin);
}
/**
* displayOrder の値でツリーをソート。 children が皆 KrewActor である前提。
* tkActor.displayOrder = 1; のように設定した上で
* getLayer('hoge').sortDisplayOrder(); のように使う
*/
public function sortDisplayOrder():void {
sortChildren(function(a:KrewActor, b:KrewActor):int {
if (a.displayOrder < b.displayOrder) { return -1; }
if (a.displayOrder > b.displayOrder) { return 1; }
return 0;
});
}
//------------------------------------------------------------
// Called by framework
//------------------------------------------------------------
/** @private */
public function update(passedTime:Number):void {
if (_hasDisposed) { return; }
// update children actors
for (var i:int=0; i < _childActors.length; ++i) {
var child:KrewActor = _childActors[i];
if (child.isDead) {
_childActors.splice(i, 1); // remove dead actor from Array
removeChild(child);
child.dispose();
--i;
continue;
}
child.update(passedTime);
}
onUpdate(passedTime);
_updateAction(passedTime);
_timeKeeper.update(passedTime);
_disappearInOutside();
}
/**
* _checkDisplayArea = true の Actor は、画面外にいるときは表示を off にする。
* これをやってあげないと少なくとも Flash では
* 画面外でも普通に描画コストがかかってしまうようだ.
*
* いずれにせよ visible false でなければ Starling は描画のための
* 計算とかをしだすので、それを避けるにはこれをやった方がいい
*
* つまるところ、数が多く画像のアンカーが中央にあるような Actor を
* _checkDisplayArea = true にすればよい
*/
private function _disappearInOutside():void {
if (!_checkDisplayArea) { return; }
// starling.display.DisplayObjectContainer の width / height は
// getBounds という重い処理が走るのでうかつにさわってはいけない
// オーバヘッドを抑えるため、ラフに計算。回転を考慮して大きめにとる。
// 横長の画像などについては考えてないのでどうしようもないときは
// _checkDisplayArea を false のままにしておくか、
// _cachedWidth とかを書き換えるか、もしくは override してくれ
var halfWidth :Number = (_cachedWidth / 1.5) * scaleX;
var halfHeight:Number = (_cachedHeight / 1.5) * scaleY;
if (x + halfWidth > 0 && x - halfWidth < KrewConfig.SCREEN_WIDTH &&
y + halfHeight > 0 && y - halfHeight < KrewConfig.SCREEN_HEIGHT) {
visible = true;
} else {
visible = false;
}
}
}
}
|
Modify KrewActor.dispose
|
Modify KrewActor.dispose
|
ActionScript
|
mit
|
tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework
|
4e370143968f05cf1c30876a42e8e8b5e657399e
|
src/aerys/minko/render/shader/SFloat.as
|
src/aerys/minko/render/shader/SFloat.as
|
package aerys.minko.render.shader
{
import aerys.minko.ns.minko_shader;
import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode;
import aerys.minko.render.shader.compiler.graph.nodes.leaf.Constant;
import aerys.minko.render.shader.compiler.graph.nodes.vertex.Extract;
import aerys.minko.render.shader.compiler.graph.nodes.vertex.Instruction;
import aerys.minko.render.shader.compiler.graph.nodes.vertex.Overwriter;
import aerys.minko.render.shader.compiler.register.Components;
import aerys.minko.type.math.Matrix4x4;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
/**
* SFloat (Shader Float) objects are GPU-side computed value proxies
* declared, defined and used in ActionScript shaders.
*
* <p>
* ActionScript shaders define what operations will be
* performed on the GPU. Those operations take arguments and return
* values that will be computed and accessible on the graphics hardware
* only. Those values are represented by SFloat objects.
* </p>
*
* <p>
* Because SFloat objects are just hardware memory proxies, it is not
* possible (and does not make sense to try) to read their actual value
* using CPU-side code. For the very same reason, most of the errors will
* be detected at runtime only. The only available property is the size
* (number of components) of the corresponding value (ie. 3D vector
* operations will return SFloat objects of size 3, dot-product will
* return a scalar SFloat object of size 1, ...).
* </p>
*
* <p>
* SFloat objects also provide OOP shader programming by encapsulating
* common operations (add, multiply, ...). They also allow the use of
* dynamic properties in order to read or write sub-components of
* non-scalar values. Example:
* </p>
*
* <pre>
* public function getOutputColor() : void
* {
* var diffuse : SFloat = sampleTexture(BasicStyle.DIFFUSE_MAP);
*
* // use the RGB components of the diffuse map but use a
* // fixed alpha = 0.5
* return combine(diffuse.rgb, 0.5);
* }
* </pre>
*
* <p>
* Each SFloat object wraps a shader graph node that will be evaluated
* by the compiler in order to create the corresponding AGAL bytecode.
* </p>
*
* @author Jean-Marc Le Roux
*
*/
public dynamic final class SFloat extends Proxy
{
use namespace minko_shader;
minko_shader var _node : AbstractNode = null;
public final function get size() : uint
{
return _node.size;
}
public function SFloat(value : Object)
{
_node = getNode(value);
}
public final function scaleBy(arg : Object) : SFloat
{
_node = new Instruction(Instruction.MUL, _node, getNode(arg));
return this;
}
public final function incrementBy(value : Object) : SFloat
{
_node = new Instruction(Instruction.ADD, _node, getNode(value));
return this;
}
public final function decrementBy(value : Object) : SFloat
{
_node = new Instruction(Instruction.SUB, _node, getNode(value));
return this;
}
public final function normalize() : SFloat
{
_node = new Instruction(Instruction.NRM, _node);
return this;
}
public final function negate() : SFloat
{
_node = new Instruction(Instruction.NEG, _node);
return this;
}
override flash_proxy function getProperty(name : *) : *
{
return new SFloat(new Extract(_node, Components.stringToComponent(name)));
}
override flash_proxy function setProperty(name : *, value : *) : void
{
var nodeComponent : uint = Components.createContinuous(0, 0, _node.size, _node.size);
var propertyComponent : uint = Components.stringToComponent(name);
var propertyNode : AbstractNode = getNode(value);
_node = new Overwriter(
new <AbstractNode>[_node, propertyNode],
new <uint>[nodeComponent, propertyComponent]
);
}
private function getNode(value : Object) : AbstractNode
{
if (value is AbstractNode)
return value as AbstractNode;
if (value is SFloat)
return (value as SFloat)._node;
if (value is uint || value is int || value is Number)
return new Constant(new <Number>[Number(value)]);
if (value is Matrix4x4)
return new Constant(Matrix4x4(value).getRawData(null, 0, false));
throw new Error('This type cannot be casted to a shader value.');
}
}
}
|
package aerys.minko.render.shader
{
import aerys.minko.ns.minko_shader;
import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode;
import aerys.minko.render.shader.compiler.graph.nodes.leaf.Constant;
import aerys.minko.render.shader.compiler.graph.nodes.vertex.Extract;
import aerys.minko.render.shader.compiler.graph.nodes.vertex.Instruction;
import aerys.minko.render.shader.compiler.graph.nodes.vertex.Overwriter;
import aerys.minko.render.shader.compiler.register.Components;
import aerys.minko.type.math.Matrix4x4;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
/**
* SFloat (Shader Float) objects are GPU-side computed value proxies
* declared, defined and used in ActionScript shaders.
*
* <p>
* ActionScript shaders define what operations will be
* performed on the GPU. Those operations take arguments and return
* values that will be computed and accessible on the graphics hardware
* only. Those values are represented by SFloat objects.
* </p>
*
* <p>
* Because SFloat objects are just hardware memory proxies, it is not
* possible (and does not make sense to try) to read their actual value
* using CPU-side code. For the very same reason, most of the errors will
* be detected at runtime only. The only available property is the size
* (number of components) of the corresponding value (ie. 3D vector
* operations will return SFloat objects of size 3, dot-product will
* return a scalar SFloat object of size 1, ...).
* </p>
*
* <p>
* SFloat objects also provide OOP shader programming by encapsulating
* common operations (add, multiply, ...). They also allow the use of
* dynamic properties in order to read or write sub-components of
* non-scalar values. Example:
* </p>
*
* <pre>
* public function getOutputColor() : void
* {
* var diffuse : SFloat = sampleTexture(BasicStyle.DIFFUSE_MAP);
*
* // use the RGB components of the diffuse map but use a
* // fixed alpha = 0.5
* return combine(diffuse.rgb, 0.5);
* }
* </pre>
*
* <p>
* Each SFloat object wraps a shader graph node that will be evaluated
* by the compiler in order to create the corresponding AGAL bytecode.
* </p>
*
* @author Jean-Marc Le Roux
*
*/
public dynamic final class SFloat extends Proxy
{
use namespace minko_shader;
minko_shader var _node : AbstractNode = null;
public final function get size() : uint
{
return _node.size;
}
public function SFloat(value : Object)
{
_node = getNode(value);
}
public final function scaleBy(arg : Object) : SFloat
{
_node = new Instruction(Instruction.MUL, _node, getNode(arg));
return this;
}
public final function incrementBy(value : Object) : SFloat
{
_node = new Instruction(Instruction.ADD, _node, getNode(value));
return this;
}
public final function decrementBy(value : Object) : SFloat
{
_node = new Instruction(Instruction.SUB, _node, getNode(value));
return this;
}
public final function normalize() : SFloat
{
_node = new Instruction(Instruction.NRM, _node);
return this;
}
public final function negate() : SFloat
{
_node = new Instruction(Instruction.NEG, _node);
return this;
}
override flash_proxy function getProperty(name : *) : *
{
return new SFloat(new Extract(_node, Components.stringToComponent(name)));
}
override flash_proxy function setProperty(name : *, value : *) : void
{
var propertyName : String = String(name);
var propertyComponent : uint = getPropertyWriteComponentMask(propertyName);
var propertyNode : AbstractNode = getNode(value);
var nodeComponent : uint = Components.createContinuous(0, 0, _node.size, _node.size);
propertyNode = new Overwriter(
new <AbstractNode>[propertyNode],
new <uint>[Components.createContinuous(0, 0, 4, propertyNode.size)]
);
_node = new Overwriter(
new <AbstractNode>[_node, propertyNode],
new <uint>[nodeComponent, propertyComponent]
);
}
public static function getPropertyWriteComponentMask(string : String) : uint
{
var result : uint = 0x04040404;
for (var i : uint = 0; i < 4; ++i)
if (i < string.length)
switch (string.charAt(i))
{
case 'x': case 'X': case 'r': case 'R':
result = (0xffffff00 & result) | i;
result |= i << (8 * 0);
break;
case 'y': case 'Y': case 'g': case 'G':
result = (0xffff00ff & result) | i << 8;
break;
case 'z': case 'Z': case 'b': case 'B':
result = (0xff00ffff & result) | i << 16;
break;
case 'w': case 'W': case 'a': case 'A':
result = (0x00ffffff & result) | i << 24;
break;
default:
throw new Error('Invalid string.');
}
return result;
}
private function getNode(value : Object) : AbstractNode
{
if (value is AbstractNode)
return value as AbstractNode;
if (value is SFloat)
return (value as SFloat)._node;
if (value is uint || value is int || value is Number)
return new Constant(new <Number>[Number(value)]);
if (value is Matrix4x4)
return new Constant(Matrix4x4(value).getRawData(null, 0, false));
throw new Error('This type cannot be casted to a shader value.');
}
}
}
|
fix SFloat.setProperty()
|
fix SFloat.setProperty()
|
ActionScript
|
mit
|
aerys/minko-as3
|
57b533f7b98db5c2323f31b457b436b9698085b0
|
src/flash/src/com/XMLHttpRequest.as
|
src/flash/src/com/XMLHttpRequest.as
|
package com
{
import com.errors.RuntimeError;
import com.utils.URLStreamProgress;
import flash.events.DataEvent;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.FileReference;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.net.URLRequestMethod;
import flash.net.URLStream;
import flash.net.URLVariables;
import flash.utils.ByteArray;
import flash.utils.clearTimeout;
import flash.utils.setTimeout;
import mxi.Utils;
import mxi.events.OErrorEvent;
import mxi.events.OProgressEvent;
public class XMLHttpRequest extends EventDispatcher
{
// events dispatched by this class
public static var dispatches:Object = {
"LoadStart": Event.OPEN,
"Progress": OProgressEvent.PROGRESS,
"UploadProgress": ProgressEvent.PROGRESS,
"Load": Event.COMPLETE,
"Error": OErrorEvent.ERROR
};
public static const UNSENT:uint = 0;
public static const OPENED:uint = 1;
public static const HEADERS_RECEIVED:uint = 2;
public static const LOADING:uint = 3;
public static const DONE:uint = 4;
public static const ABORTED:uint = 5;
private var _methods:Object = {
'GET': URLRequestMethod.GET,
'POST': URLRequestMethod.POST
};
private var _options:Object;
private var _multipart:Boolean = false;
private var _blob:*;
private var _blobName:String;
private var _blobFieldName:String = 'Filedata';
private var _postData:URLVariables = new URLVariables;
private var _conn:*;
private var _response:ByteArray;
private var _status:int;
private var _readyState:uint = XMLHttpRequest.UNSENT;
private var _onCompleteTimeout:uint = 0;
private var _notCachedSize:uint = 0;
public function append(name:String, value:*) : void
{
_multipart = true;
if (name == 'Filename') { // Flash will add this by itself, so we need to omit potential duplicate
return;
}
if (/\[\]$/.test(name)) { // handle arrays
if (!_postData.hasOwnProperty(name)) {
_postData[name] = [];
}
_postData[name].push(value);
} else {
_postData[name] = value;
}
}
public function appendBlob(name:String, blob:*, fileName:String = null) : void
{
_multipart = true;
_blobName = fileName || 'blob' + new Date().getTime();
if (typeof blob === 'string') {
blob = Moxie.compFactory.get(blob);
if (!fileName && blob is File && blob.hasOwnProperty('name')) {
_blobName = blob.name;
}
}
_blob = blob;
_blobFieldName = name;
}
public function send(meta:Object, blob:* = null) : void
{
if (_blob) {
blob = _blob;
}
meta.method = meta.method.toUpperCase();
_options = meta;
if (typeof blob === 'string') {
blob = Moxie.compFactory.get(blob);
if (blob is File && blob.hasOwnProperty('name')) {
_blobName = blob.name;
}
}
if (blob && _options.method == 'POST') {
if (_options.transport == 'client' && _multipart && blob.isFileRef() && Utils.isEmptyObj(_options.headers)) {
_uploadFileRef(blob);
} else {
_preloadBlob(blob, _doURLStreamRequest);
}
} else {
_doURLStreamRequest();
}
}
public function getResponseAsBlob() : Object
{
var blob:Blob;
if (!_response) {
return null;
}
blob = new File([_response], { name: _options.url.replace(/^.+?\/([\w\-\.]+)$/, '$1').toLowerCase() });
Moxie.compFactory.add(blob.uid, blob);
return blob.toObject();
}
public function getStatus() : int
{
return _status;
}
public function abort() : void
{
if (!_conn) {
// mark as aborted in order to be handled as soon as possible
_readyState = XMLHttpRequest.ABORTED;
return;
}
if (_conn is FileReference) {
_conn.cancel();
} else if (_conn is URLStream && _conn.connected) {
_conn.close();
}
removeEventListeners(_conn);
_conn = null;
}
private function onOpen() : void {
dispatchEvent(new Event(Event.OPEN));
}
private function onProgress(e:ProgressEvent) : void {
dispatchEvent(new OProgressEvent(OProgressEvent.PROGRESS, e.bytesLoaded, e.bytesTotal));
}
private function onUploadProgress(e:ProgressEvent):void {
dispatchEvent(e);
}
private function onUploadComplete(e:*) : void {
if (_onCompleteTimeout) {
clearTimeout(_onCompleteTimeout);
}
// if status still equal to zero, than we are ok
if (_status == 0) {
_status = 200;
}
// save response
_response = new ByteArray;
if (_conn is FileReference && e.hasOwnProperty('data')) {
_response.writeUTFBytes(e.data);
} else if (_conn is URLStream) {
_conn.readBytes(_response);
}
removeEventListeners(e.target);
_readyState = XMLHttpRequest.DONE;
dispatchEvent(new Event(Event.COMPLETE));
}
private function onComplete(e:*) : void {
// give upload complete event a chance to fire
_onCompleteTimeout = setTimeout(onUploadComplete, 500, e);
}
// The httpStatus event is dispatched only for upload failures.
private function onStatus(e:HTTPStatusEvent) : void {
_status = e.status;
}
private function onIOError(e:IOErrorEvent) : void {
if (_status == 0) { // httpStatus might have already set status to some failure code (according to livedocs)
_status = 404; // assume that request succeeded, but url was wrong
}
onUploadComplete(e);
}
private function onError(e:*) : void {
removeEventListeners(e.target);
_readyState = XMLHttpRequest.DONE;
dispatchEvent(new OErrorEvent(OErrorEvent.ERROR));
}
private function removeEventListeners(target:*) : void {
// some of these event handlers may not even be attached, but we try to remove them all for simplicity
target.removeEventListener(Event.OPEN, onOpen);
target.removeEventListener(ProgressEvent.PROGRESS, onProgress);
target.removeEventListener(ProgressEvent.PROGRESS, onUploadProgress);
target.removeEventListener(Event.COMPLETE, onComplete);
target.removeEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onUploadComplete);
target.removeEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
target.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
target.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
}
private function _uploadFileRef(blob:Blob) : void
{
var request:URLRequest;
request = new URLRequest();
request.method = URLRequestMethod.POST;
request.url = _options.url;
request.data = _postData;
_conn = blob.getFileRef();
_readyState = XMLHttpRequest.OPENED;
_conn.addEventListener(Event.COMPLETE, onComplete);
_conn.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onUploadComplete);
_conn.addEventListener(ProgressEvent.PROGRESS, onUploadProgress);
_conn.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
_conn.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
_conn.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
// _conn.addEventListener(Event.OPEN, onOpen); doesn't fire, ideas?
onOpen(); // trigger it manually
_readyState = XMLHttpRequest.LOADING;
_conn.upload(request, _blobFieldName, false);
}
private function _preloadBlob(blob:*, callback:Function) : void
{
var fr:FileReader = new FileReader;
fr.addEventListener(ProgressEvent.PROGRESS, function(e:ProgressEvent) : void {
if (_readyState == XMLHttpRequest.ABORTED) {
fr.abort();
}
});
fr.addEventListener(Event.COMPLETE, function() : void {
fr.removeAllEventsListeners();
if (_readyState == XMLHttpRequest.ABORTED) {
fr.abort();
return;
}
callback(fr.result);
});
//_notCachedSize = blob.realSize - blob.cachedSize;
fr.readAsByteArray(blob);
}
private function _doURLStreamRequest(ba:ByteArray = null) : void
{
var request:URLRequest,
progress:URLStreamProgress,
start:Date, end:Date; // we are going to measure upload time for each piece of data and make correction to the progress watch
request = new URLRequest(_options.url);
// set custom headers if required
if (!Utils.isEmptyObj(_options.headers)) {
for (var name:String in _options.headers) {
request.requestHeaders.push(new URLRequestHeader(name, _options.headers[name]));
}
}
// only GET/POST is supported at the moment
if (['POST', 'GET'].indexOf(_options.method) === -1) {
dispatchEvent(new OErrorEvent(OErrorEvent.ERROR, RuntimeError.SYNTAX_ERR));
return;
}
request.method = _methods[_options.method];
if (_multipart) {
request.data = _formatAsMultipart(ba, request);
} else if (ba) {
request.data = ba;
}
_conn = new URLStream;
_readyState = XMLHttpRequest.OPENED;
// _conn.addEventListener(Event.OPEN, onOpen); // doesn't trigger (I remember it did), maybe adobe abandoned it?..
_conn.addEventListener(ProgressEvent.PROGRESS, onProgress);
_conn.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
_conn.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
_conn.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
if (ba) {
progress = new URLStreamProgress({ url: _options.url });
progress.addEventListener(ProgressEvent.PROGRESS, onUploadProgress);
progress.addEventListener(Event.OPEN, function() : void {
start = new Date;
onOpen(); // trigger it manually
_conn.load(request);
});
_conn.addEventListener(Event.COMPLETE, function(e:Event) : void {
progress.stop();
progress.removeAllEventsListeners();
// correlate upload speed
end = new Date;
URLStreamProgress.calculateSpeed(request.data.length, end.time - start.time);
onComplete(e);
});
progress.start(request.data.length);
}
else {
_conn.addEventListener(Event.COMPLETE, onComplete);
onOpen(); // trigger it manually
_conn.load(request);
}
_readyState = XMLHttpRequest.LOADING;
}
private function _formatAsMultipart(ba:ByteArray, request:URLRequest) : ByteArray
{
var boundary:String = '----moxieboundary' + new Date().getTime(),
dashdash:String = '--', crlf:String = '\r\n',
tmpBa:ByteArray;
tmpBa = new ByteArray;
request.requestHeaders.push(new URLRequestHeader("Content-Type", 'multipart/form-data; boundary=' + boundary));
// recursively append mutltipart parameters
(function eachPostData(key:String, postData:*) : void {
for (var name:String in postData) {
if (postData[name] is Array) {
eachPostData(name, postData[name]); // name will be common for all elements of the array
} else {
tmpBa.writeUTFBytes(
dashdash + boundary + crlf +
'Content-Disposition: form-data; name="' + (key || name) + '"' + crlf + crlf +
postData[name] + crlf
);
}
}
}(null, _postData)); // self-invoke with global _postData object
// append file if available
if (ba) {
tmpBa.writeUTFBytes(
dashdash + boundary + crlf +
'Content-Disposition: form-data; name="' + _blobFieldName + '"; filename="' + _blobName + '"' + crlf +
'Content-Type: ' + _options.mimeType + crlf + crlf
);
tmpBa.writeBytes(ba, 0, ba.length);
ba.clear();
tmpBa.writeUTFBytes(crlf);
}
// wrap it up
tmpBa.writeUTFBytes(dashdash + boundary + dashdash + crlf);
return tmpBa;
}
}
}
|
package com
{
import com.errors.RuntimeError;
import com.utils.URLStreamProgress;
import flash.events.DataEvent;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.FileReference;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.net.URLRequestMethod;
import flash.net.URLStream;
import flash.utils.ByteArray;
import flash.utils.clearTimeout;
import flash.utils.setTimeout;
import mxi.Utils;
import mxi.events.OErrorEvent;
import mxi.events.OProgressEvent;
public class XMLHttpRequest extends EventDispatcher
{
// events dispatched by this class
public static var dispatches:Object = {
"LoadStart": Event.OPEN,
"Progress": OProgressEvent.PROGRESS,
"UploadProgress": ProgressEvent.PROGRESS,
"Load": Event.COMPLETE,
"Error": OErrorEvent.ERROR
};
public static const UNSENT:uint = 0;
public static const OPENED:uint = 1;
public static const HEADERS_RECEIVED:uint = 2;
public static const LOADING:uint = 3;
public static const DONE:uint = 4;
public static const ABORTED:uint = 5;
private var _methods:Object = {
'GET': URLRequestMethod.GET,
'POST': URLRequestMethod.POST
};
private var _options:Object;
private var _multipart:Boolean = false;
private var _blob:*;
private var _blobName:String;
private var _blobFieldName:String = 'Filedata';
private var _postData:Array = [];
private var _conn:*;
private var _response:ByteArray;
private var _status:int;
private var _readyState:uint = XMLHttpRequest.UNSENT;
private var _onCompleteTimeout:uint = 0;
private var _notCachedSize:uint = 0;
public function append(name:String, value:*) : void
{
_multipart = true;
if (name == 'Filename') { // Flash will add this by itself, so we need to omit potential duplicate
return;
}
_postData.push([name, value]);
}
public function appendBlob(name:String, blob:*, fileName:String = null) : void
{
_multipart = true;
_blobName = fileName || 'blob' + new Date().getTime();
if (typeof blob === 'string') {
blob = Moxie.compFactory.get(blob);
if (!fileName && blob is File && blob.hasOwnProperty('name')) {
_blobName = blob.name;
}
}
_blob = blob;
_blobFieldName = name;
}
public function send(meta:Object, blob:* = null) : void
{
if (_blob) {
blob = _blob;
}
meta.method = meta.method.toUpperCase();
_options = meta;
if (typeof blob === 'string') {
blob = Moxie.compFactory.get(blob);
if (blob is File && blob.hasOwnProperty('name')) {
_blobName = blob.name;
}
}
if (blob && _options.method == 'POST') {
if (_options.transport == 'client' && _multipart && blob.isFileRef() && Utils.isEmptyObj(_options.headers)) {
_uploadFileRef(blob);
} else {
_preloadBlob(blob, _doURLStreamRequest);
}
} else {
_doURLStreamRequest();
}
}
public function getResponseAsBlob() : Object
{
var blob:Blob;
if (!_response) {
return null;
}
blob = new File([_response], { name: _options.url.replace(/^.+?\/([\w\-\.]+)$/, '$1').toLowerCase() });
Moxie.compFactory.add(blob.uid, blob);
return blob.toObject();
}
public function getStatus() : int
{
return _status;
}
public function abort() : void
{
if (!_conn) {
// mark as aborted in order to be handled as soon as possible
_readyState = XMLHttpRequest.ABORTED;
return;
}
if (_conn is FileReference) {
_conn.cancel();
} else if (_conn is URLStream && _conn.connected) {
_conn.close();
}
removeEventListeners(_conn);
_conn = null;
}
private function onOpen() : void {
dispatchEvent(new Event(Event.OPEN));
}
private function onProgress(e:ProgressEvent) : void {
dispatchEvent(new OProgressEvent(OProgressEvent.PROGRESS, e.bytesLoaded, e.bytesTotal));
}
private function onUploadProgress(e:ProgressEvent):void {
dispatchEvent(e);
}
private function onUploadComplete(e:*) : void {
if (_onCompleteTimeout) {
clearTimeout(_onCompleteTimeout);
}
// if status still equal to zero, than we are ok
if (_status == 0) {
_status = 200;
}
// save response
_response = new ByteArray;
if (_conn is FileReference && e.hasOwnProperty('data')) {
_response.writeUTFBytes(e.data);
} else if (_conn is URLStream) {
_conn.readBytes(_response);
}
removeEventListeners(e.target);
_readyState = XMLHttpRequest.DONE;
dispatchEvent(new Event(Event.COMPLETE));
}
private function onComplete(e:*) : void {
// give upload complete event a chance to fire
_onCompleteTimeout = setTimeout(onUploadComplete, 500, e);
}
// The httpStatus event is dispatched only for upload failures.
private function onStatus(e:HTTPStatusEvent) : void {
_status = e.status;
}
private function onIOError(e:IOErrorEvent) : void {
if (_status == 0) { // httpStatus might have already set status to some failure code (according to livedocs)
_status = 404; // assume that request succeeded, but url was wrong
}
onUploadComplete(e);
}
private function onError(e:*) : void {
removeEventListeners(e.target);
_readyState = XMLHttpRequest.DONE;
dispatchEvent(new OErrorEvent(OErrorEvent.ERROR));
}
private function removeEventListeners(target:*) : void {
// some of these event handlers may not even be attached, but we try to remove them all for simplicity
target.removeEventListener(Event.OPEN, onOpen);
target.removeEventListener(ProgressEvent.PROGRESS, onProgress);
target.removeEventListener(ProgressEvent.PROGRESS, onUploadProgress);
target.removeEventListener(Event.COMPLETE, onComplete);
target.removeEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onUploadComplete);
target.removeEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
target.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
target.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
}
private function _uploadFileRef(blob:Blob) : void
{
var request:URLRequest;
request = new URLRequest();
request.method = URLRequestMethod.POST;
request.url = _options.url;
var qs:Array = [];
for (var i:int=0; i < _postData.length; i++) {
qs.push(escape(_postData[i][0]) + '=' + escape(_postData[i][1]));
}
request.data = qs.join('&')
_conn = blob.getFileRef();
_readyState = XMLHttpRequest.OPENED;
_conn.addEventListener(Event.COMPLETE, onComplete);
_conn.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onUploadComplete);
_conn.addEventListener(ProgressEvent.PROGRESS, onUploadProgress);
_conn.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
_conn.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
_conn.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
// _conn.addEventListener(Event.OPEN, onOpen); doesn't fire, ideas?
onOpen(); // trigger it manually
_readyState = XMLHttpRequest.LOADING;
_conn.upload(request, _blobFieldName, false);
}
private function _preloadBlob(blob:*, callback:Function) : void
{
var fr:FileReader = new FileReader;
fr.addEventListener(ProgressEvent.PROGRESS, function(e:ProgressEvent) : void {
if (_readyState == XMLHttpRequest.ABORTED) {
fr.abort();
}
});
fr.addEventListener(Event.COMPLETE, function() : void {
fr.removeAllEventsListeners();
if (_readyState == XMLHttpRequest.ABORTED) {
fr.abort();
return;
}
callback(fr.result);
});
//_notCachedSize = blob.realSize - blob.cachedSize;
fr.readAsByteArray(blob);
}
private function _doURLStreamRequest(ba:ByteArray = null) : void
{
var request:URLRequest,
progress:URLStreamProgress,
start:Date, end:Date; // we are going to measure upload time for each piece of data and make correction to the progress watch
request = new URLRequest(_options.url);
// set custom headers if required
if (!Utils.isEmptyObj(_options.headers)) {
for (var name:String in _options.headers) {
request.requestHeaders.push(new URLRequestHeader(name, _options.headers[name]));
}
}
// only GET/POST is supported at the moment
if (['POST', 'GET'].indexOf(_options.method) === -1) {
dispatchEvent(new OErrorEvent(OErrorEvent.ERROR, RuntimeError.SYNTAX_ERR));
return;
}
request.method = _methods[_options.method];
if (_multipart) {
request.data = _formatAsMultipart(ba, request);
} else if (ba) {
request.data = ba;
}
_conn = new URLStream;
_readyState = XMLHttpRequest.OPENED;
// _conn.addEventListener(Event.OPEN, onOpen); // doesn't trigger (I remember it did), maybe adobe abandoned it?..
_conn.addEventListener(ProgressEvent.PROGRESS, onProgress);
_conn.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
_conn.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
_conn.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
if (ba) {
progress = new URLStreamProgress({ url: _options.url });
progress.addEventListener(ProgressEvent.PROGRESS, onUploadProgress);
progress.addEventListener(Event.OPEN, function() : void {
start = new Date;
onOpen(); // trigger it manually
_conn.load(request);
});
_conn.addEventListener(Event.COMPLETE, function(e:Event) : void {
progress.stop();
progress.removeAllEventsListeners();
// correlate upload speed
end = new Date;
URLStreamProgress.calculateSpeed(request.data.length, end.time - start.time);
onComplete(e);
});
progress.start(request.data.length);
}
else {
_conn.addEventListener(Event.COMPLETE, onComplete);
onOpen(); // trigger it manually
_conn.load(request);
}
_readyState = XMLHttpRequest.LOADING;
}
private function _formatAsMultipart(ba:ByteArray, request:URLRequest) : ByteArray
{
var boundary:String = '----moxieboundary' + new Date().getTime(),
dashdash:String = '--', crlf:String = '\r\n',
tmpBa:ByteArray;
tmpBa = new ByteArray;
request.requestHeaders.push(new URLRequestHeader("Content-Type", 'multipart/form-data; boundary=' + boundary));
for (var i:int=0; i < _postData.length; i++) {
var name:String = _postData[i][0];
var value:String = _postData[i][1];
tmpBa.writeUTFBytes(
dashdash + boundary + crlf +
'Content-Disposition: form-data; name="' + name + '"' + crlf + crlf +
value + crlf
);
}
// append file if available
if (ba) {
tmpBa.writeUTFBytes(
dashdash + boundary + crlf +
'Content-Disposition: form-data; name="' + _blobFieldName + '"; filename="' + _blobName + '"' + crlf +
'Content-Type: ' + _options.mimeType + crlf + crlf
);
tmpBa.writeBytes(ba, 0, ba.length);
ba.clear();
tmpBa.writeUTFBytes(crlf);
}
// wrap it up
tmpBa.writeUTFBytes(dashdash + boundary + dashdash + crlf);
return tmpBa;
}
}
}
|
Stop using UrlVariables since it is un-ordered.
|
Stop using UrlVariables since it is un-ordered.
UrlVariables will output the params in random order. 99% of the time this
doesn't matter but occasionally it does. This removes the use of UrlVariables.
It is now just a simple list of params and when doing a UrlRequest I encode it
myself.
This has the side benefit of getting rid of the recursive array logic. Params
are not just flat and if someone want to encode an array they can do so without
us caring since we don't have to worry about keys overwritting each other.
|
ActionScript
|
agpl-3.0
|
moxiecode/moxie,moxiecode/moxie,moxiecode/moxie,moxiecode/moxie
|
f601bbafdd5be2d0a0aa84d3f7de48ee7140e776
|
com/segonquart/Preloader.as
|
com/segonquart/Preloader.as
|
class com Preloader extends MovieClip{
private var target_mc:MovieClip;
private var progress_mc:MovieClip;
private var pct_str:String;
private var dispatchEvent:Function;
public var addEventListener:Function;
public var removeEventListener:Function;
function Preloader()
{
mx.events.EventDispatcher.initialize(this);
}
public function startPreload(t:MovieClip)
{
target_mc = t;
this.gotoAndPlay("IN");
}
private function onAnimateIn()
{
this.stop();
this.onEnterFrame = this.checkLoadProgress;
}
private function checkLoadProgress()
{
var bl = target_mc.getBytesLoaded();
var bt = target_mc.getBytesTotal();
var pct = bl / bt;
var cf = progress_mc._currentframe;
var tf = progress_mc._totalframes;
var f = Math.ceil(tf * pct);
if (f > cf)
{
progress_mc.play();
}
else
{
progress_mc.stop();
}
this.pct_str = (Math.round(cf / tf * 100)).toString();
if (bt > 20 && bl == bt && cf == tf && progress_mc)
{
onPreloadComplete();
}
}
private function onPreloadComplete()
{
this.onEnterFrame = null;
this.gotoAndPlay("OUT");
}
private function onAnimateOut()
{
this.stop();
dispatchEvent({target:this, type:'onPreloaderOut'});
}
}
|
class Preloader extends MovieClip{
private var target_mc:MovieClip;
private var progress_mc:MovieClip;
private var pct_str:String;
private var dispatchEvent:Function;
public var addEventListener:Function;
public var removeEventListener:Function;
function Preloader()
{
mx.events.EventDispatcher.initialize(this);
}
public function startPreload(t:MovieClip)
{
target_mc = t;
this.gotoAndPlay("IN");
}
private function onAnimateIn()
{
this.stop();
this.onEnterFrame = this.checkLoadProgress;
}
private function checkLoadProgress()
{
var bl = target_mc.getBytesLoaded();
var bt = target_mc.getBytesTotal();
var pct = bl / bt;
var cf = progress_mc._currentframe;
var tf = progress_mc._totalframes;
var f = Math.ceil(tf * pct);
if (f > cf)
{
progress_mc.play();
}
else
{
progress_mc.stop();
}
this.pct_str = (Math.round(cf / tf * 100)).toString();
if (bt > 20 && bl == bt && cf == tf && progress_mc)
{
onPreloadComplete();
}
}
private function onPreloadComplete()
{
this.onEnterFrame = null;
this.gotoAndPlay("OUT");
}
private function onAnimateOut()
{
this.stop();
dispatchEvent({target:this, type:'onPreloaderOut'});
}
}
|
Update Preloader.as
|
Update Preloader.as
|
ActionScript
|
bsd-3-clause
|
delfiramirez/web-talking-wear,delfiramirez/web-talking-wear,delfiramirez/web-talking-wear
|
2c5d0664ea79c6de25ea7b43c8c395aa4a1903d0
|
src/Demo.as
|
src/Demo.as
|
package
{
import com.jonas.net.Multipart;
import flash.display.Bitmap;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.net.URLLoader;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.utils.ByteArray;
[SWF(width="600", height="400", frameRate="30", backgroundColor="#CCCCCC")]
public class Demo extends Sprite
{
[Embed(source="../assets/icon480.png")]
public var iconClass:Class;
public var iconBitmap:Bitmap;
public var textField:TextField;
private var url:String = "http://labs.positronic.fr/flash/multipart/upload.php";
public function Demo()
{
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
var container:Sprite = new Sprite();
container.addEventListener(MouseEvent.CLICK, onClick);
container.buttonMode = true;
container.y = 20;
addChild(container);
iconBitmap = new iconClass() as Bitmap;
iconBitmap.scaleX = iconBitmap.scaleY = 0.5;
container.addChild(iconBitmap);
textField = new TextField();
textField.width = 400;
textField.multiline = textField.wordWrap = true;
textField.autoSize = TextFieldAutoSize.LEFT;
textField.x = container.width+20;
textField.y = container.y;
addChild(textField);
textField.text = "Click to upload";
if(loaderInfo.parameters["url"] != null){
url = loaderInfo.parameters["url"];
}
}
protected function onClick(event:Event):void
{
textField.text = "loading...";
// Create an image ByteArray with Thibault Imbert's JPEGEncoder
// http://www.bytearray.org/wp-content/projects/fastjpeg/JPEGEncoder.as
var jpg:JPEGEncoder = new JPEGEncoder(80);
var image:ByteArray = jpg.encode(iconBitmap.bitmapData);
// Create an ascii text ByteArray
var text:ByteArray = new ByteArray();
text.writeMultiByte("Hello", "ascii");
// Instanciate Multipart with url
var form:Multipart = new Multipart(url);
// Add fields
form.addField("field1", "hello");
form.addField("field2", "world");
// Add files
form.addFile("file1", text, "text/plain", "test.txt");
form.addFile("file2", image, "image/jpeg", "test.jpg");
// Load request
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onComplete);
try {
loader.load(form.request);
} catch (error: Error) {
textField.text = "Unable to load request : "+error.message;
}
}
protected function onComplete(event:Event):void
{
textField.text = event.target["data"];
}
}
}
|
package
{
import com.jonas.net.Multipart;
import flash.display.Bitmap;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.net.URLLoader;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.utils.ByteArray;
[SWF(width="600", height="400", frameRate="30", backgroundColor="#CCCCCC")]
public class Demo extends Sprite
{
[Embed(source="../assets/icon480.png")]
public var iconClass:Class;
public var iconBitmap:Bitmap;
public var textField:TextField;
private var url:String = "http://labs.positronic.fr/flash/multipart/upload.php";
public function Demo()
{
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
var container:Sprite = new Sprite();
container.addEventListener(MouseEvent.CLICK, onClick);
container.buttonMode = true;
container.y = 20;
addChild(container);
iconBitmap = new iconClass() as Bitmap;
iconBitmap.scaleX = iconBitmap.scaleY = 0.5;
container.addChild(iconBitmap);
textField = new TextField();
textField.width = 400;
textField.multiline = textField.wordWrap = true;
textField.autoSize = TextFieldAutoSize.LEFT;
textField.x = container.width+20;
textField.y = container.y;
addChild(textField);
textField.text = "Click to upload";
if(loaderInfo.parameters["url"] != null){
url = loaderInfo.parameters["url"];
}
}
protected function onClick(event:Event):void
{
textField.text = "loading...";
// Create an image ByteArray with Thibault Imbert's JPEGEncoder
// http://www.bytearray.org/wp-content/projects/fastjpeg/JPEGEncoder.as
var jpg:JPEGEncoder = new JPEGEncoder(80);
var image:ByteArray = jpg.encode(iconBitmap.bitmapData);
// Create an ascii text ByteArray
var text:ByteArray = new ByteArray();
text.writeMultiByte("Hello", "ascii");
// Instanciate Multipart with url
var form:Multipart = new Multipart(url);
// Add fields
form.addField("field1", "hello");
form.addField("field2", "world");
form.addField("field3", "Voici des caractères accentués pour tester l'encodage.");
// Add files
form.addFile("file1", text, "text/plain", "test.txt");
form.addFile("file2", image, "image/jpeg", "test.jpg");
// Load request
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onComplete);
try {
loader.load(form.request);
} catch (error: Error) {
textField.text = "Unable to load request : "+error.message;
}
}
protected function onComplete(event:Event):void
{
textField.text = event.target["data"];
}
}
}
|
Add accented characters to test encoding
|
Add accented characters to test encoding
|
ActionScript
|
apache-2.0
|
jimojon/Multipart.as
|
1183889fee6a3619a4137b08c6c20ba6774c868d
|
WeaveJS/src/weavejs/data/column/ReferencedColumn.as
|
WeaveJS/src/weavejs/data/column/ReferencedColumn.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.column
{
import weave.api.data.IWeaveTreeNode;
import weavejs.WeaveAPI;
import weavejs.api.core.ILinkableHashMap;
import weavejs.api.data.IAttributeColumn;
import weavejs.api.data.IColumnWrapper;
import weavejs.api.data.IDataSource;
import weavejs.api.data.IQualifiedKey;
import weavejs.api.data.IWeaveTreeNode;
import weavejs.core.CallbackCollection;
import weavejs.core.LinkableString;
import weavejs.core.LinkableVariable;
import weavejs.core.LinkableWatcher;
import weavejs.data.hierarchy.GlobalColumnDataSource;
/**
* This provides a wrapper for a referenced column.
*
* @author adufilie
*/
public class ReferencedColumn extends CallbackCollection implements IColumnWrapper
{
public function ReferencedColumn()
{
super();
}
private var _initialized:Boolean = false;
private var _dataSource:IDataSource;
private function updateDataSource():void
{
var root:ILinkableHashMap = Weave.getRoot(this);
if (!root)
return;
if (!_initialized)
{
root.childListCallbacks.addImmediateCallback(this, updateDataSource);
_initialized = true;
}
var ds:IDataSource = root.getObject(dataSourceName.value) as IDataSource;
if (!ds)
ds = GlobalColumnDataSource.getInstance(root);
if (_dataSource != ds)
{
_dataSource = ds;
triggerCallbacks();
}
}
/**
* This is the name of an IDataSource in the top level session state.
*/
public const dataSourceName:LinkableString = Weave.linkableChild(this, LinkableString, updateDataSource);
/**
* This holds the metadata used to identify a column.
*/
public const metadata:LinkableVariable = Weave.linkableChild(this, LinkableVariable);
public function getDataSource():IDataSource
{
return _dataSource;
}
public function getHierarchyNode():IWeaveTreeNode
{
if (!_dataSource)
return null;
var meta:Object = metadata.getSessionState();
return _dataSource.findHierarchyNode(meta);
}
/**
* Updates the session state to refer to a new column.
*/
public function setColumnReference(dataSource:IDataSource, metadata:Object):void
{
delayCallbacks();
dataSourceName.value = Weave.getRoot(this).getName(dataSource);
this.metadata.setSessionState(metadata);
resumeCallbacks();
}
/**
* The trigger counter value at the last time the internal column was retrieved.
*/
private var _prevTriggerCounter:uint = 0;
/**
* the internal referenced column
*/
private var _internalColumn:IAttributeColumn = null;
private var _columnWatcher:LinkableWatcher = Weave.linkableChild(this, LinkableWatcher);
public function getInternalColumn():IAttributeColumn
{
if (_prevTriggerCounter != triggerCounter)
{
if (Weave.wasDisposed(_dataSource))
_dataSource = null;
_columnWatcher.target = _internalColumn = WeaveAPI.AttributeColumnCache.getColumn(_dataSource, metadata.state);
_prevTriggerCounter = triggerCounter;
}
return _internalColumn;
}
/************************************
* Begin IAttributeColumn interface
************************************/
public function getMetadata(attributeName:String):String
{
if (_prevTriggerCounter != triggerCounter)
getInternalColumn();
return _internalColumn ? _internalColumn.getMetadata(attributeName) : null;
}
public function getMetadataPropertyNames():Array
{
if (_prevTriggerCounter != triggerCounter)
getInternalColumn();
return _internalColumn ? _internalColumn.getMetadataPropertyNames() : [];
}
/**
* @return the keys associated with this column.
*/
public function get keys():Array
{
if (_prevTriggerCounter != triggerCounter)
getInternalColumn();
return _internalColumn ? _internalColumn.keys : [];
}
/**
* @param key A key to test.
* @return true if the key exists in this IKeySet.
*/
public function containsKey(key:IQualifiedKey):Boolean
{
if (_prevTriggerCounter != triggerCounter)
getInternalColumn();
return _internalColumn && _internalColumn.containsKey(key);
}
/**
* getValueFromKey
* @param key A key of the type specified by keyType.
* @return The value associated with the given key.
*/
public function getValueFromKey(key:IQualifiedKey, dataType:Class = null):*
{
if (_prevTriggerCounter != triggerCounter)
getInternalColumn();
return _internalColumn ? _internalColumn.getValueFromKey(key, dataType) : undefined;
}
}
}
|
/* ***** 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.column
{
import weavejs.WeaveAPI;
import weavejs.api.core.ILinkableHashMap;
import weavejs.api.data.IAttributeColumn;
import weavejs.api.data.IColumnWrapper;
import weavejs.api.data.IDataSource;
import weavejs.api.data.IQualifiedKey;
import weavejs.api.data.IWeaveTreeNode;
import weavejs.core.CallbackCollection;
import weavejs.core.LinkableString;
import weavejs.core.LinkableVariable;
import weavejs.core.LinkableWatcher;
import weavejs.data.hierarchy.GlobalColumnDataSource;
/**
* This provides a wrapper for a referenced column.
*
* @author adufilie
*/
public class ReferencedColumn extends CallbackCollection implements IColumnWrapper
{
public function ReferencedColumn()
{
super();
}
private var _initialized:Boolean = false;
private var _dataSource:IDataSource;
private function updateDataSource():void
{
var root:ILinkableHashMap = Weave.getRoot(this);
if (!root)
return;
if (!_initialized)
{
root.childListCallbacks.addImmediateCallback(this, updateDataSource);
_initialized = true;
}
var ds:IDataSource = root.getObject(dataSourceName.value) as IDataSource;
if (!ds)
ds = GlobalColumnDataSource.getInstance(root);
if (_dataSource != ds)
{
_dataSource = ds;
triggerCallbacks();
}
}
/**
* This is the name of an IDataSource in the top level session state.
*/
public const dataSourceName:LinkableString = Weave.linkableChild(this, LinkableString, updateDataSource);
/**
* This holds the metadata used to identify a column.
*/
public const metadata:LinkableVariable = Weave.linkableChild(this, LinkableVariable);
public function getDataSource():IDataSource
{
return _dataSource;
}
public function getHierarchyNode():IWeaveTreeNode
{
if (!_dataSource)
return null;
var meta:Object = metadata.getSessionState();
return _dataSource.findHierarchyNode(meta);
}
/**
* Updates the session state to refer to a new column.
*/
public function setColumnReference(dataSource:IDataSource, metadata:Object):void
{
delayCallbacks();
dataSourceName.value = Weave.getRoot(this).getName(dataSource);
this.metadata.setSessionState(metadata);
resumeCallbacks();
}
/**
* The trigger counter value at the last time the internal column was retrieved.
*/
private var _prevTriggerCounter:uint = 0;
/**
* the internal referenced column
*/
private var _internalColumn:IAttributeColumn = null;
private var _columnWatcher:LinkableWatcher = Weave.linkableChild(this, LinkableWatcher);
public function getInternalColumn():IAttributeColumn
{
if (_prevTriggerCounter != triggerCounter)
{
if (Weave.wasDisposed(_dataSource))
_dataSource = null;
_columnWatcher.target = _internalColumn = WeaveAPI.AttributeColumnCache.getColumn(_dataSource, metadata.state);
_prevTriggerCounter = triggerCounter;
}
return _internalColumn;
}
/************************************
* Begin IAttributeColumn interface
************************************/
public function getMetadata(attributeName:String):String
{
if (_prevTriggerCounter != triggerCounter)
getInternalColumn();
return _internalColumn ? _internalColumn.getMetadata(attributeName) : null;
}
public function getMetadataPropertyNames():Array
{
if (_prevTriggerCounter != triggerCounter)
getInternalColumn();
return _internalColumn ? _internalColumn.getMetadataPropertyNames() : [];
}
/**
* @return the keys associated with this column.
*/
public function get keys():Array
{
if (_prevTriggerCounter != triggerCounter)
getInternalColumn();
return _internalColumn ? _internalColumn.keys : [];
}
/**
* @param key A key to test.
* @return true if the key exists in this IKeySet.
*/
public function containsKey(key:IQualifiedKey):Boolean
{
if (_prevTriggerCounter != triggerCounter)
getInternalColumn();
return _internalColumn && _internalColumn.containsKey(key);
}
/**
* getValueFromKey
* @param key A key of the type specified by keyType.
* @return The value associated with the given key.
*/
public function getValueFromKey(key:IQualifiedKey, dataType:Class = null):*
{
if (_prevTriggerCounter != triggerCounter)
getInternalColumn();
return _internalColumn ? _internalColumn.getValueFromKey(key, dataType) : undefined;
}
}
}
|
remove incorrect import
|
remove incorrect import
|
ActionScript
|
mpl-2.0
|
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
|
8860abe5c790bec5c01f3b0b9cf0400c926d439d
|
skin-src/goplayer/BufferingIndicator.as
|
skin-src/goplayer/BufferingIndicator.as
|
package goplayer
{
import flash.display.Sprite
import flash.events.Event
import flash.utils.getTimer
public class BufferingIndicator extends Component
{
private static const dotCount : uint = 10
private static const period : Duration = Duration.seconds(1)
private const canvas : Sprite = new Sprite
private var elapsedTime : Duration = Duration.milliseconds(0)
private var lastState : uint = 0
public function BufferingIndicator()
{
mouseEnabled = false
mouseChildren = false
addChild(new Background(0x000000, 0.5))
addChild(canvas)
addEventListener(Event.ENTER_FRAME, handleEnterFrame)
}
private function handleEnterFrame(event : Event) : void
{
elapsedTime = Duration.milliseconds(getTimer())
if (currentState != lastState)
update(), lastState = currentState
}
private function get currentState() : uint
{ return Math.floor(elapsedTime.dividedBy(stateLength)) % dotCount }
private function get stateLength() : Duration
{ return Duration.seconds(period.seconds / dotCount) }
override public function update() : void
{
super.update()
canvas.graphics.clear()
for (var i : uint = 0; i < dotCount; ++i)
drawDot(i)
}
private function drawDot(index : uint) : void
{
const position : Position = getDotPosition(index)
canvas.graphics.beginFill(getDotColor(index), getDotAlpha(index))
canvas.graphics.drawCircle(position.x, position.y, getDotRadius(index))
canvas.graphics.endFill()
}
private function getDotPosition(index : uint) : Position
{
return Angle.ratio(-(index / dotCount)).position
.scaledBy(radius).plus(dimensions.halved)
}
private function get radius() : Number
{ return dimensions.innerSquare.width / 16 }
private function getDotColor(index : uint) : uint
{ return 0xffffff }
private function getDotAlpha(index : uint) : Number
{ return (dotCount - modulated(index)) / dotCount }
private function getDotRadius(index : uint) : Number
{ return radius / 4 }
private function modulated(index : uint) : uint
{ return (index + currentState) % dotCount }
}
}
|
package goplayer
{
import flash.display.Sprite
import flash.events.Event
import flash.utils.getTimer
public class BufferingIndicator extends Component
{
private static const dotCount : uint = 10
private static const period : Duration = Duration.seconds(1)
private const canvas : Sprite = new Sprite
private var elapsedTime : Duration = Duration.milliseconds(0)
private var lastState : uint = 0
public function BufferingIndicator()
{
mouseEnabled = false
mouseChildren = false
addChild(canvas)
addEventListener(Event.ENTER_FRAME, handleEnterFrame)
}
private function handleEnterFrame(event : Event) : void
{
elapsedTime = Duration.milliseconds(getTimer())
if (currentState != lastState)
update(), lastState = currentState
}
private function get currentState() : uint
{ return Math.floor(elapsedTime.dividedBy(stateLength)) % dotCount }
private function get stateLength() : Duration
{ return Duration.seconds(period.seconds / dotCount) }
override public function update() : void
{
super.update()
canvas.graphics.clear()
for (var i : uint = 0; i < dotCount; ++i)
drawDot(i)
}
private function drawDot(index : uint) : void
{
const position : Position = getDotPosition(index)
canvas.graphics.beginFill(getDotColor(index), getDotAlpha(index))
canvas.graphics.drawCircle(position.x, position.y, getDotRadius(index))
canvas.graphics.endFill()
}
private function getDotPosition(index : uint) : Position
{
return Angle.ratio(-(index / dotCount)).position
.scaledBy(radius).plus(dimensions.halved)
}
private function get radius() : Number
{ return dimensions.innerSquare.width / 16 }
private function getDotColor(index : uint) : uint
{ return 0xffffff }
private function getDotAlpha(index : uint) : Number
{ return (dotCount - modulated(index)) / dotCount }
private function getDotRadius(index : uint) : Number
{ return radius / 4 }
private function modulated(index : uint) : uint
{ return (index + currentState) % dotCount }
}
}
|
Remove background of buffering indicator.
|
Remove background of buffering indicator.
|
ActionScript
|
mit
|
dbrock/goplayer,dbrock/goplayer
|
ed9cadfdfabb3e25bd5a3c17dc08bff604b93130
|
src/com/esri/builder/eventbus/EventBus.as
|
src/com/esri/builder/eventbus/EventBus.as
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////////
package com.esri.builder.eventbus
{
import flash.events.EventDispatcher;
/**
* The EventBus allows centralized application communication.
* It uses the singleton design pattern to make sure one event bus
* is available globally.
*/
public class EventBus extends EventDispatcher
{
/** Application event bus instance */
public static const instance:EventBus = new EventBus();
/**
* Normally the EventBus is not instantiated via the <b>new</b> method directly.
* The constructor helps enforce only one EventBus available for the application
* (singleton) so that it assures the communication only via a single event bus.
*/
public function EventBus()
{
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////////
package com.esri.builder.eventbus
{
import flash.events.EventDispatcher;
/**
* The EventBus allows centralized application communication.
*/
public class EventBus extends EventDispatcher
{
/** Application event bus instance */
public static const instance:EventBus = new EventBus();
/**
* Normally the EventBus is not instantiated via the <b>new</b> method directly.
*/
public function EventBus()
{
}
}
}
|
Clean up EventBus comments.
|
Clean up EventBus comments.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
8a10e16d12132048abeb9df8d3dd79d7e2dd41bb
|
HLSPlugin/src/com/kaltura/hls/HLSVideoElement.as
|
HLSPlugin/src/com/kaltura/hls/HLSVideoElement.as
|
/*****************************************************
*
* Copyright 2009 Adobe Systems Incorporated. All Rights Reserved.
*
*****************************************************
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
*
* The Initial Developer of the Original Code is Adobe Systems Incorporated.
* Portions created by Adobe Systems Incorporated are Copyright (C) 2009 Adobe Systems
* Incorporated. All Rights Reserved.
*
*****************************************************/
package com.kaltura.hls
{
import __AS3__.vec.Vector;
import org.osmf.media.MediaResourceBase;
import org.osmf.net.NetLoader;
import org.osmf.net.rtmpstreaming.RTMPDynamicStreamingNetLoader;
import org.osmf.traits.LoaderBase;
import org.osmf.elements.VideoElement;
import flash.geom.Point;
import flash.display.Stage;
import flash.utils.Timer;
import flash.events.TimerEvent;
CONFIG::FLASH_10_1
{
import flash.events.DRMAuthenticateEvent;
import flash.events.DRMErrorEvent;
import flash.events.DRMStatusEvent;
import flash.net.drm.DRMContentData;
import flash.system.SystemUpdaterType;
import flash.system.SystemUpdater;
import org.osmf.net.drm.NetStreamDRMTrait;
import org.osmf.net.httpstreaming.HTTPStreamingNetLoader;
}
public class HLSVideoElement extends VideoElement
{
public var cropHackTimer:Timer;
public function HLSVideoElement(resource:MediaResourceBase=null, loader:NetLoader=null)
{
super(resource, loader);
cropHackTimer = new Timer(250, 0);
cropHackTimer.addEventListener(TimerEvent.TIMER, onCropHackTimer);
cropHackTimer.start();
}
protected function onCropHackTimer(te:TimerEvent):void
{
// Sweet hax to adjust the zoom of the stage video.
if(stage.stageVideos.length > 0)
{
stage.stageVideos[0].zoom = new Point(HLSManifestParser.FORCE_CROP_WORKAROUND_ZOOM_X, HLSManifestParser.FORCE_CROP_WORKAROUND_ZOOM_Y);
stage.stageVideos[0].pan = new Point(HLSManifestParser.FORCE_CROP_WORKAROUND_PAN_X, FORCE_CROP_WORKAROUND_PAN_Y);
}
}
/**
* @private
*/
override protected function processReadyState():void
{
super.processReadyState();
}
}
}
|
/*****************************************************
*
* Copyright 2009 Adobe Systems Incorporated. All Rights Reserved.
*
*****************************************************
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
*
* The Initial Developer of the Original Code is Adobe Systems Incorporated.
* Portions created by Adobe Systems Incorporated are Copyright (C) 2009 Adobe Systems
* Incorporated. All Rights Reserved.
*
*****************************************************/
package com.kaltura.hls
{
import __AS3__.vec.Vector;
import org.osmf.media.MediaResourceBase;
import org.osmf.net.NetLoader;
import org.osmf.net.rtmpstreaming.RTMPDynamicStreamingNetLoader;
import org.osmf.traits.LoaderBase;
import org.osmf.elements.VideoElement;
import flash.geom.Point;
import flash.display.Stage;
import flash.display.DisplayObject;
import flash.utils.Timer;
import flash.events.TimerEvent;
import com.kaltura.hls.manifest.HLSManifestParser;
CONFIG::FLASH_10_1
{
import flash.events.DRMAuthenticateEvent;
import flash.events.DRMErrorEvent;
import flash.events.DRMStatusEvent;
import flash.net.drm.DRMContentData;
import flash.system.SystemUpdaterType;
import flash.system.SystemUpdater;
import org.osmf.net.drm.NetStreamDRMTrait;
import org.osmf.net.httpstreaming.HTTPStreamingNetLoader;
}
public class HLSVideoElement extends VideoElement
{
public var cropHackTimer:Timer;
public function HLSVideoElement(resource:MediaResourceBase=null, loader:NetLoader=null)
{
super(resource, loader);
cropHackTimer = new Timer(250, 0);
cropHackTimer.addEventListener(TimerEvent.TIMER, onCropHackTimer);
cropHackTimer.start();
}
protected function onCropHackTimer(te:TimerEvent):void
{
// Sweet hax to adjust the zoom of the stage video.
var containerDO:DisplayObject = container as DisplayObject;
if(!containerDO)
return;
var stage:Stage = containerDO.stage;
if(stage.stageVideos.length > 0)
{
stage.stageVideos[0].zoom = new Point(HLSManifestParser.FORCE_CROP_WORKAROUND_ZOOM_X, HLSManifestParser.FORCE_CROP_WORKAROUND_ZOOM_Y);
stage.stageVideos[0].pan = new Point(HLSManifestParser.FORCE_CROP_WORKAROUND_PAN_X, HLSManifestParser.FORCE_CROP_WORKAROUND_PAN_Y);
}
}
/**
* @private
*/
override protected function processReadyState():void
{
super.processReadyState();
}
}
}
|
Fix some dumb mistakes!
|
Fix some dumb mistakes!
|
ActionScript
|
agpl-3.0
|
kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF
|
559baa873f1ed7cf556fd107f7d9d9ca72a77806
|
src/RTMP.as
|
src/RTMP.as
|
package {
import flash.display.Sprite;
import flash.external.ExternalInterface;
import flash.system.Security;
import flash.net.NetStream;
import flash.events.*;
import org.osmf.containers.MediaContainer;
import org.osmf.elements.VideoElement;
import org.osmf.net.NetStreamLoadTrait;
import org.osmf.media.DefaultMediaFactory;
import org.osmf.media.MediaElement;
import org.osmf.media.MediaPlayer;
import org.osmf.media.URLResource;
import org.osmf.events.TimeEvent;
import org.osmf.events.BufferEvent;
import org.osmf.events.MediaElementEvent;
import org.osmf.events.LoadEvent;
import org.osmf.traits.MediaTraitType;
[SWF(width="640", height="360")]
public class RTMP extends Sprite {
private var playbackId:String;
private var mediaFactory:DefaultMediaFactory;
private var mediaContainer:MediaContainer;
private var mediaPlayer:MediaPlayer;
private var netStream:NetStream;
private var mediaElement:MediaElement;
private var netStreamLoadTrait:NetStreamLoadTrait;
private var playbackState:String = "IDLE";
public function RTMP() {
Security.allowDomain('*');
Security.allowInsecureDomain('*');
playbackId = this.root.loaderInfo.parameters.playbackId;
mediaFactory = new DefaultMediaFactory();
mediaContainer = new MediaContainer();
setupCallbacks();
setupGetters();
ExternalInterface.call('console.log', 'clappr rtmp 0.4-alpha');
_triggerEvent('flashready');
}
private function setupCallbacks():void {
ExternalInterface.addCallback("playerLoad", playerLoad);
ExternalInterface.addCallback("playerPlay", playerPlay);
ExternalInterface.addCallback("playerPause", playerPause);
ExternalInterface.addCallback("playerStop", playerStop);
ExternalInterface.addCallback("playerSeek", playerSeek);
}
private function setupGetters():void {
ExternalInterface.addCallback("getState", getState);
ExternalInterface.addCallback("getPosition", getPosition);
ExternalInterface.addCallback("getDuration", getDuration);
}
private function playerLoad(url:String):void {
mediaElement = mediaFactory.createMediaElement(new URLResource(url));
mediaElement.addEventListener(MediaElementEvent.TRAIT_ADD, onTraitAdd);
mediaPlayer = new MediaPlayer(mediaElement);
mediaPlayer.autoPlay = false;
mediaPlayer.addEventListener(TimeEvent.CURRENT_TIME_CHANGE, onTimeUpdated);
mediaPlayer.addEventListener(TimeEvent.DURATION_CHANGE, onTimeUpdated);
mediaContainer.addMediaElement(mediaElement);
addChild(mediaContainer);
}
private function onTraitAdd(event:MediaElementEvent):void {
if (mediaElement.hasTrait(MediaTraitType.LOAD)) {
netStreamLoadTrait = mediaElement.getTrait(MediaTraitType.LOAD) as NetStreamLoadTrait;
netStreamLoadTrait.addEventListener(LoadEvent.LOAD_STATE_CHANGE, onLoaded);
}
}
private function onLoaded(event:LoadEvent):void {
netStream = netStreamLoadTrait.netStream;
netStream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
}
private function netStatusHandler(event:NetStatusEvent):void {
ExternalInterface.call('console.log', 'new event:' + event.info.code);
if (event.info.code === "NetStream.Buffer.Full") {
playbackState = "PLAYING";
} else if (isBuffering(event.info.code)) {
playbackState = "PLAYING_BUFFERING";
} else if (event.info.code == "NetStream.Play.Stop") {
playbackState = "ENDED";
} else if (event.info.code == "NetStream.Buffer.Empty") {
playbackState = "BUFFERING";
}
_triggerEvent('statechanged');
}
private function isBuffering(code:String):Boolean {
return Boolean(code == "NetStream.Buffer.Empty" && playbackState != "ENDED" ||
code == "NetStream.SeekStart.Notify" ||
code == "NetStream.Play.Start");
}
private function playerPlay():void {
mediaPlayer.play();
}
private function playerPause():void {
mediaPlayer.pause();
}
private function playerSeek(seconds:Number):void {
mediaPlayer.seek(seconds);
}
private function playerStop():void {
mediaPlayer.stop();
}
private function onTimeUpdated(event:TimeEvent):void {
_triggerEvent('progress');
_triggerEvent('timeupdate');
}
private function getPosition():Number {
return mediaPlayer.currentTime;
}
private function getDuration():Number {
return mediaPlayer.duration;
}
private function _triggerEvent(name: String):void {
ExternalInterface.call('Clappr.Mediator.trigger("' + playbackId + ':' + name +'")');
}
private function getState():String {
return playbackState;
}
}
}
|
package {
import flash.display.Sprite;
import flash.external.ExternalInterface;
import flash.system.Security;
import flash.net.NetStream;
import flash.events.*;
import org.osmf.containers.MediaContainer;
import org.osmf.elements.VideoElement;
import org.osmf.net.NetStreamLoadTrait;
import org.osmf.media.DefaultMediaFactory;
import org.osmf.media.MediaElement;
import org.osmf.media.MediaPlayer;
import org.osmf.media.URLResource;
import org.osmf.events.TimeEvent;
import org.osmf.events.BufferEvent;
import org.osmf.events.MediaElementEvent;
import org.osmf.events.LoadEvent;
import org.osmf.traits.MediaTraitType;
[SWF(width="640", height="360")]
public class RTMP extends Sprite {
private var playbackId:String;
private var mediaFactory:DefaultMediaFactory;
private var mediaContainer:MediaContainer;
private var mediaPlayer:MediaPlayer;
private var netStream:NetStream;
private var mediaElement:MediaElement;
private var netStreamLoadTrait:NetStreamLoadTrait;
private var playbackState:String = "IDLE";
public function RTMP() {
Security.allowDomain('*');
Security.allowInsecureDomain('*');
playbackId = this.root.loaderInfo.parameters.playbackId;
mediaFactory = new DefaultMediaFactory();
mediaContainer = new MediaContainer();
setupCallbacks();
setupGetters();
ExternalInterface.call('console.log', 'clappr rtmp 0.6-alpha');
_triggerEvent('flashready');
}
private function setupCallbacks():void {
ExternalInterface.addCallback("playerLoad", playerLoad);
ExternalInterface.addCallback("playerPlay", playerPlay);
ExternalInterface.addCallback("playerPause", playerPause);
ExternalInterface.addCallback("playerStop", playerStop);
ExternalInterface.addCallback("playerSeek", playerSeek);
ExternalInterface.addCallback("playerVolume", playerVolume);
}
private function setupGetters():void {
ExternalInterface.addCallback("getState", getState);
ExternalInterface.addCallback("getPosition", getPosition);
ExternalInterface.addCallback("getDuration", getDuration);
}
private function playerLoad(url:String):void {
mediaElement = mediaFactory.createMediaElement(new URLResource(url));
mediaElement.addEventListener(MediaElementEvent.TRAIT_ADD, onTraitAdd);
mediaPlayer = new MediaPlayer(mediaElement);
mediaPlayer.autoPlay = false;
mediaPlayer.addEventListener(TimeEvent.CURRENT_TIME_CHANGE, onTimeUpdated);
mediaPlayer.addEventListener(TimeEvent.DURATION_CHANGE, onTimeUpdated);
mediaContainer.addMediaElement(mediaElement);
addChild(mediaContainer);
}
private function onTraitAdd(event:MediaElementEvent):void {
if (mediaElement.hasTrait(MediaTraitType.LOAD)) {
netStreamLoadTrait = mediaElement.getTrait(MediaTraitType.LOAD) as NetStreamLoadTrait;
netStreamLoadTrait.addEventListener(LoadEvent.LOAD_STATE_CHANGE, onLoaded);
}
}
private function onLoaded(event:LoadEvent):void {
netStream = netStreamLoadTrait.netStream;
netStream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
}
private function netStatusHandler(event:NetStatusEvent):void {
ExternalInterface.call('console.log', 'new event:' + event.info.code);
if (event.info.code === "NetStream.Buffer.Full") {
playbackState = "PLAYING";
} else if (isBuffering(event.info.code)) {
playbackState = "PLAYING_BUFFERING";
} else if (event.info.code == "NetStream.Play.Stop") {
playbackState = "ENDED";
} else if (event.info.code == "NetStream.Buffer.Empty") {
playbackState = "BUFFERING";
}
_triggerEvent('statechanged');
}
private function isBuffering(code:String):Boolean {
return Boolean(code == "NetStream.Buffer.Empty" && playbackState != "ENDED" ||
code == "NetStream.SeekStart.Notify" ||
code == "NetStream.Play.Start");
}
private function playerPlay():void {
mediaPlayer.play();
}
private function playerPause():void {
mediaPlayer.pause();
}
private function playerSeek(seconds:Number):void {
mediaPlayer.seek(seconds);
}
private function playerStop():void {
mediaPlayer.stop();
}
private function playerVolume(level:Number):void {
mediaPlayer.volume = level;
}
private function getState():String {
return playbackState;
}
private function getPosition():Number {
return mediaPlayer.currentTime;
}
private function getDuration():Number {
return mediaPlayer.duration;
}
private function onTimeUpdated(event:TimeEvent):void {
_triggerEvent('progress');
_triggerEvent('timeupdate');
}
private function _triggerEvent(name: String):void {
ExternalInterface.call('Clappr.Mediator.trigger("' + playbackId + ':' + name +'")');
}
}
}
|
support setVolume() calls (refs #4)
|
RTMP.as: support setVolume() calls (refs #4)
|
ActionScript
|
apache-2.0
|
video-dev/clappr-rtmp-plugin,eventials/clappr-rtmp-plugin,clappr/clappr-rtmp-plugin,video-dev/clappr-rtmp-plugin,hxl-dy/clappr-rtmp-plugin,clappr/clappr-rtmp-plugin,flavioribeiro/clappr-rtmp-plugin,hxl-dy/clappr-rtmp-plugin,flavioribeiro/clappr-rtmp-plugin,eventials/clappr-rtmp-plugin,flavioribeiro/clappr-rtmp-plugin,hxl-dy/clappr-rtmp-plugin,eventials/clappr-rtmp-plugin,clappr/clappr-rtmp-plugin,video-dev/clappr-rtmp-plugin
|
2a93fe032ad0800d7e5efae7ec0a0bff90818e27
|
src/com/axis/mjpgplayer/IPCam.as
|
src/com/axis/mjpgplayer/IPCam.as
|
package com.axis.mjpgplayer {
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
import flash.system.Security;
import flash.external.ExternalInterface;
import flash.display.LoaderInfo;
import mx.utils.URLUtil;
[Event(name="image",type="flash.events.Event")]
[Event(name="connect",type="flash.events.Event")]
[Event(name="error",type="flash.events.Event")]
/**
* Error codes:
* 0: Socket or security errors
* 1: Client side validation errors
* 2: Server HTTP response errors
* 3: Valid HTTP response (200), but invalid content
*/
public class IPCam extends EventDispatcher {
private var jsEventCallbackName:String = "console.log";
private var socket:Socket = null;
private var buffer:ByteArray = null;
private var dataBuffer:ByteArray = null;
private var url:String = "";
private var params:Object;
private var parseHeaders:Boolean = true;
private var headers:Vector.<String> = new Vector.<String>();
private var clen:int;
private var parseSubheaders:Boolean = true;
public var image:ByteArray = null;
public function IPCam() {
// Set up JS API
ExternalInterface.marshallExceptions = true;
ExternalInterface.addCallback("play", connect);
ExternalInterface.addCallback("pause", disconnect);
ExternalInterface.addCallback("stop", stop);
ExternalInterface.addCallback("setEventCallbackName", setJsEventCallbackName);
Security.allowDomain("*");
Security.allowInsecureDomain("*");
buffer = new ByteArray();
dataBuffer = new ByteArray();
socket = new Socket();
socket.timeout = 5000;
socket.addEventListener(Event.CONNECT, onSockConn);
socket.addEventListener(Event.CLOSE, onClose);
socket.addEventListener(ProgressEvent.SOCKET_DATA, onSockData);
socket.addEventListener(IOErrorEvent.IO_ERROR, onError);
socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
}
public function sendLoadedEvent():void {
// Tell the external JS environent that we are ready to accept API calls
ExternalInterface.call(jsEventCallbackName, 'loaded');
}
public function setJsEventCallbackName(jsEventCallbackName:String):void {
this.jsEventCallbackName = jsEventCallbackName;
}
public function getJsEventCallbackName():String {
return jsEventCallbackName;
}
private function onError(e:ErrorEvent):void {
sendError(0, e.text);
}
private function sendError(errNo:Number = 0, msg:String = ""):void {
disconnect();
dispatchEvent(new Event("error"));
ExternalInterface.call(jsEventCallbackName, "error", errNo, msg);
}
public function disconnect():void {
if (socket.connected) {
socket.close();
}
image = null;
buffer = null;
dispatchEvent(new Event("disconnect"));
}
public function stop():void {
disconnect();
dispatchEvent(new Event("clear"));
}
public function connect(url:String = null):void {
disconnect();
if (url != null) {
this.url = url;
}
if (!URLUtil.isHttpURL(this.url)) {
sendError(1, "Invalid Url");
return;
}
socket.connect(URLUtil.getServerName(this.url), 80);
}
private function onSockConn(event:Event):void {
buffer = new ByteArray();
dataBuffer = new ByteArray();
parseHeaders = true;
socket.writeUTFBytes("GET " + url + " HTTP/1.0\r\n");
socket.writeUTFBytes("Host: " + URLUtil.getServerName(url) + "\r\n");
socket.writeUTFBytes("\r\n");
}
private function onClose(e:Event):void {
// Security error is thrown if this line is excluded
socket.close();
}
private function readline():Boolean {
while (dataBuffer.bytesAvailable > 0) {
var t:String = dataBuffer.readMultiByte(1, "us-ascii");
if (t == "\r") {
continue;
}
if (t == "\n") {
return true;
}
buffer.writeMultiByte(t, "us-ascii");
}
return false;
}
private function getContentType():String {
var content:String = "content-type: ";
for each (var str:String in headers) {
if (str.toLowerCase().indexOf(content) >= 0) {
return str.substr(str.indexOf(content) + content.length).toLowerCase();
}
}
return "";
}
private function onParseHeaders():Boolean {
headers.length = 0;
while (1) {
var wholeLine:Boolean = readline();
if (!wholeLine) {
return false;
}
if (buffer.length == 0) {
parseHeaders = false;
break;
}
headers.push(buffer.toString());
buffer.clear();
}
try {
var arr:Array = headers[0].split(" ");
if (arr[1] == "200") {
var content:String = getContentType();
if (content.indexOf("multipart/x-mixed-replace") >= 0) {
dispatchEvent(new Event("connect"));
return true;
}
throw(new Error("error"));
} else {
sendError(2, "Server retured error code " + arr[1] + ".");
}
}
catch (e:Error) {
sendError(3, "Invalid response received.");
}
return false;
}
private function onSockData(event:ProgressEvent):void {
socket.readBytes(dataBuffer, dataBuffer.length);
if (parseHeaders) {
if (!onParseHeaders()) {
return;
}
}
if (parseSubheaders) {
if (!parseSubHeader()) {
return;
}
}
findImage();
}
private function parseSubHeader():Boolean {
while (parseSubheaders) {
var wholeLine:Boolean = readline();
if (!wholeLine) {
return false;
}
if (buffer.length == 0) {
break;
}
var subHeaders:Array = buffer.toString().split(": ");
if ((subHeaders[0] as String).toLowerCase() == "content-length") {
clen = subHeaders[1];
}
buffer.clear();
}
parseSubheaders = false;
return true;
}
private function findImage():void {
if (dataBuffer.bytesAvailable < clen + 2) {
return;
}
image = new ByteArray()
dataBuffer.readBytes(image, 0, clen + 2);
//dataBuffer.readMultiByte(2, "us-ascii"); // Why is this not needed? Probably the cause of stability issues
var copy:ByteArray = new ByteArray();
dataBuffer.readBytes(copy, 0);
dataBuffer = copy;
dispatchEvent(new Event("image"));
clen = 0;
parseSubheaders = true;
}
}
}
|
package com.axis.mjpgplayer {
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
import flash.system.Security;
import flash.external.ExternalInterface;
import flash.display.LoaderInfo;
import mx.utils.URLUtil;
[Event(name="image",type="flash.events.Event")]
[Event(name="connect",type="flash.events.Event")]
[Event(name="error",type="flash.events.Event")]
/**
* Error codes:
* 0: Socket or security errors
* 1: Client side validation errors
* 2: Server HTTP response errors
* 3: Valid HTTP response (200), but invalid content
*/
public class IPCam extends EventDispatcher {
private var jsEventCallbackName:String = "console.log";
private var socket:Socket = null;
private var buffer:ByteArray = null;
private var dataBuffer:ByteArray = null;
private var url:String = "";
private var params:Object;
private var parseHeaders:Boolean = true;
private var headers:Vector.<String> = new Vector.<String>();
private var clen:int;
private var parseSubheaders:Boolean = true;
public var image:ByteArray = null;
public function IPCam() {
// Set up JS API
ExternalInterface.marshallExceptions = true;
ExternalInterface.addCallback("play", connect);
ExternalInterface.addCallback("pause", disconnect);
ExternalInterface.addCallback("stop", stop);
ExternalInterface.addCallback("setEventCallbackName", setJsEventCallbackName);
Security.allowDomain("*");
Security.allowInsecureDomain("*");
buffer = new ByteArray();
dataBuffer = new ByteArray();
socket = new Socket();
socket.timeout = 5000;
socket.addEventListener(Event.CONNECT, onSockConn);
socket.addEventListener(Event.CLOSE, onClose);
socket.addEventListener(ProgressEvent.SOCKET_DATA, onSockData);
socket.addEventListener(IOErrorEvent.IO_ERROR, onError);
socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
}
public function sendLoadedEvent():void {
// Tell the external JS environent that we are ready to accept API calls
ExternalInterface.call(jsEventCallbackName, 'loaded');
}
public function setJsEventCallbackName(jsEventCallbackName:String):void {
this.jsEventCallbackName = jsEventCallbackName;
}
public function getJsEventCallbackName():String {
return jsEventCallbackName;
}
private function onError(e:ErrorEvent):void {
sendError(0, e.text);
}
private function sendError(errNo:Number = 0, msg:String = ""):void {
disconnect();
dispatchEvent(new Event("error"));
ExternalInterface.call(jsEventCallbackName, "error", errNo, msg);
}
public function disconnect():void {
if (socket.connected) {
socket.close();
}
image = null;
buffer = null;
dispatchEvent(new Event("disconnect"));
}
public function stop():void {
disconnect();
dispatchEvent(new Event("clear"));
}
public function connect(url:String = null):void {
disconnect();
if (url != null) {
this.url = url;
}
if (!URLUtil.isHttpURL(this.url)) {
sendError(1, "Invalid Url");
return;
}
socket.connect(URLUtil.getServerName(this.url), 80);
}
private function onSockConn(event:Event):void {
buffer = new ByteArray();
dataBuffer = new ByteArray();
parseHeaders = true;
socket.writeUTFBytes("GET " + url + " HTTP/1.0\r\n");
socket.writeUTFBytes("Host: " + URLUtil.getServerName(url) + "\r\n");
socket.writeUTFBytes("\r\n");
}
private function onClose(e:Event):void {
// Security error is thrown if this line is excluded
socket.close();
ExternalInterface.call(jsEventCallbackName, "stopped");
}
private function readline():Boolean {
while (dataBuffer.bytesAvailable > 0) {
var t:String = dataBuffer.readMultiByte(1, "us-ascii");
if (t == "\r") {
continue;
}
if (t == "\n") {
return true;
}
buffer.writeMultiByte(t, "us-ascii");
}
return false;
}
private function getContentType():String {
var content:String = "content-type: ";
for each (var str:String in headers) {
if (str.toLowerCase().indexOf(content) >= 0) {
return str.substr(str.indexOf(content) + content.length).toLowerCase();
}
}
return "";
}
private function onParseHeaders():Boolean {
headers.length = 0;
while (1) {
var wholeLine:Boolean = readline();
if (!wholeLine) {
return false;
}
if (buffer.length == 0) {
parseHeaders = false;
break;
}
headers.push(buffer.toString());
buffer.clear();
}
try {
var arr:Array = headers[0].split(" ");
if (arr[1] == "200") {
var content:String = getContentType();
if (content.indexOf("multipart/x-mixed-replace") >= 0) {
dispatchEvent(new Event("connect"));
return true;
}
throw(new Error("error"));
} else {
sendError(2, "Server retured error code " + arr[1] + ".");
}
}
catch (e:Error) {
sendError(3, "Invalid response received.");
}
return false;
}
private function onSockData(event:ProgressEvent):void {
socket.readBytes(dataBuffer, dataBuffer.length);
if (parseHeaders) {
if (!onParseHeaders()) {
return;
}
}
if (parseSubheaders) {
if (!parseSubHeader()) {
return;
}
}
findImage();
}
private function parseSubHeader():Boolean {
while (parseSubheaders) {
var wholeLine:Boolean = readline();
if (!wholeLine) {
return false;
}
if (buffer.length == 0) {
break;
}
var subHeaders:Array = buffer.toString().split(": ");
if ((subHeaders[0] as String).toLowerCase() == "content-length") {
clen = subHeaders[1];
}
buffer.clear();
}
parseSubheaders = false;
return true;
}
private function findImage():void {
if (dataBuffer.bytesAvailable < clen + 2) {
return;
}
image = new ByteArray()
dataBuffer.readBytes(image, 0, clen + 2);
//dataBuffer.readMultiByte(2, "us-ascii"); // Why is this not needed? Probably the cause of stability issues
var copy:ByteArray = new ByteArray();
dataBuffer.readBytes(copy, 0);
dataBuffer = copy;
dispatchEvent(new Event("image"));
clen = 0;
parseSubheaders = true;
}
}
}
|
Throw event when stream closes
|
Throw event when stream closes
Solves: Trouble 52041
Solves: Trouble 52371
Change-Id: I66c55ad90e348539957db66c23c72bf97ad78141
Reference: 4a371182d378ce08461de7e0c09e03d07097467b
Reviewed-on: https://gittools.se.axis.com/gerrit/1281
Reviewed-by: Torbjörn Weiland <[email protected]>
Tested-by: Oskar Gustafsson <[email protected]>
Reviewed-by: Oskar Gustafsson <[email protected]>
Daily-Built: Oskar Gustafsson <[email protected]>
|
ActionScript
|
bsd-3-clause
|
gaetancollaud/locomote-video-player,AxisCommunications/locomote-video-player
|
7c412eac2ef2b94b8419b0002ec5f253f47ba038
|
vivified/core/vivi_initialize.as
|
vivified/core/vivi_initialize.as
|
/* Vivified
* Copyright (C) 2007 Benjamin Otte <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
/*** general objects ***/
Wrap = function () {};
Wrap.prototype = {};
Wrap.prototype.toString = Native.wrap_toString;
Frame = function () extends Wrap {};
Frame.prototype = new Wrap ();
Frame.prototype.addProperty ("code", Native.frame_code_get, null);
Frame.prototype.addProperty ("name", Native.frame_name_get, null);
Frame.prototype.addProperty ("next", Native.frame_next_get, null);
/*** breakpoints ***/
Breakpoint = function () extends Native.Breakpoint {
super ();
Breakpoint.list.push (this);
};
Breakpoint.list = new Array ();
Breakpoint.prototype.addProperty ("active", Native.breakpoint_active_get, Native.breakpoint_active_set);
/*** information about the player ***/
Player = {};
Player.addProperty ("filename", Native.player_filename_get, Native.player_filename_set);
Player.addProperty ("frame", Native.player_frame_get, null);
Player.addProperty ("global", Native.player_global_get, null);
Player.addProperty ("variables", Native.player_variables_get, Native.player_variables_set);
/*** commands available for debugging ***/
Commands = new Object ();
Commands.print = Native.print;
Commands.error = Native.error;
Commands.r = Native.run;
Commands.run = Native.run;
Commands.halt = Native.stop;
Commands.stop = Native.stop;
Commands.s = Native.step;
Commands.step = Native.step;
Commands.reset = Native.reset;
Commands.restart = function () {
Commands.reset ();
Commands.run ();
};
Commands.quit = Native.quit;
/* can't use "break" as a function name, it's a keyword in JS */
Commands.add = function (name) {
if (name == undefined) {
Commands.error ("add command requires a function name");
return undefined;
}
var ret = new Breakpoint ();
ret.onStartFrame = function (frame) {
if (frame.name != name)
return false;
Commands.print ("Breakpoint: function " + name + " called");
Commands.print (" " + frame);
return true;
};
ret.toString = function () {
return "function call " + name;
};
return ret;
};
Commands.list = function () {
var a = Breakpoint.list;
var i;
for (i = 0; i < a.length; i++) {
Commands.print (i + ": " + a[i]);
}
};
Commands.del = function (id) {
var a = Breakpoint.list;
if (id == undefined) {
while (a[0])
Commands.del (0);
}
var b = a[id];
a.splice (id, 1);
b.active = false;
};
Commands.delete = Commands.del;
Commands.where = function () {
var frame = Player.frame;
if (frame == undefined) {
Commands.print ("---");
return;
}
var i = 0;
while (frame) {
Commands.print (i++ + ": " + frame);
frame = frame.next;
}
};
Commands.backtrace = Commands.where;
Commands.bt = Commands.where;
Commands.watch = function () {
var object;
var name;
if (arguments.length == 1) {
name = arguments[0];
} else if (arguments.length == 2) {
object = arguments[0];
name = arguments[1];
} else {
Commands.error ("usage: watch [object] name");
return;
}
var ret = new Breakpoint ();
ret.onSetVariable = function (o, variable, value) {
if (object && o != object)
return false;
if (variable != name)
return;
if (object) {
Commands.print ("Breakpoint: variable " + name + " on " + object);
} else {
Commands.print ("Breakpoint: variable " + name);
}
Commands.print (" " + Player.frame);
return true;
};
ret.toString = function () {
var s = "watch " + name;
if (object)
s += " on " + object;
return s;
};
return ret;
};
|
/* Vivified
* Copyright (C) 2007 Benjamin Otte <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
/*** general objects ***/
Wrap = function () {};
Wrap.prototype = {};
Wrap.prototype.toString = Native.wrap_toString;
Frame = function () extends Wrap {};
Frame.prototype = new Wrap ();
Frame.prototype.addProperty ("code", Native.frame_code_get, null);
Frame.prototype.addProperty ("name", Native.frame_name_get, null);
Frame.prototype.addProperty ("next", Native.frame_next_get, null);
/*** breakpoints ***/
Breakpoint = function () extends Native.Breakpoint {
super ();
Breakpoint.list.push (this);
};
Breakpoint.list = new Array ();
Breakpoint.prototype.addProperty ("active", Native.breakpoint_active_get, Native.breakpoint_active_set);
Breakpoint.prototype.toString = function () {
return "user-defined breakpoint";
};
/*** information about the player ***/
Player = {};
Player.addProperty ("filename", Native.player_filename_get, Native.player_filename_set);
Player.addProperty ("frame", Native.player_frame_get, null);
Player.addProperty ("global", Native.player_global_get, null);
Player.addProperty ("variables", Native.player_variables_get, Native.player_variables_set);
/*** commands available for debugging ***/
Commands = new Object ();
Commands.print = Native.print;
Commands.error = Native.error;
Commands.r = Native.run;
Commands.run = Native.run;
Commands.halt = Native.stop;
Commands.stop = Native.stop;
Commands.s = Native.step;
Commands.step = Native.step;
Commands.reset = Native.reset;
Commands.restart = function () {
Commands.reset ();
Commands.run ();
};
Commands.quit = Native.quit;
/* can't use "break" as a function name, it's a keyword in JS */
Commands.add = function (name) {
if (name == undefined) {
Commands.error ("add command requires a function name");
return undefined;
}
var ret = new Breakpoint ();
ret.onStartFrame = function (frame) {
if (frame.name != name)
return false;
Commands.print ("Breakpoint: function " + name + " called");
Commands.print (" " + frame);
return true;
};
ret.toString = function () {
return "function call " + name;
};
return ret;
};
Commands.list = function () {
var a = Breakpoint.list;
var i;
for (i = 0; i < a.length; i++) {
Commands.print (i + ": " + a[i]);
}
};
Commands.del = function (id) {
var a = Breakpoint.list;
if (id == undefined) {
while (a[0])
Commands.del (0);
}
var b = a[id];
a.splice (id, 1);
b.active = false;
};
Commands.delete = Commands.del;
Commands.where = function () {
var frame = Player.frame;
if (frame == undefined) {
Commands.print ("---");
return;
}
var i = 0;
while (frame) {
Commands.print (i++ + ": " + frame);
frame = frame.next;
}
};
Commands.backtrace = Commands.where;
Commands.bt = Commands.where;
Commands.watch = function () {
var object;
var name;
if (arguments.length == 1) {
name = arguments[0];
} else if (arguments.length == 2) {
object = arguments[0];
name = arguments[1];
} else {
Commands.error ("usage: watch [object] name");
return;
}
var ret = new Breakpoint ();
ret.onSetVariable = function (o, variable, value) {
if (object && o != object)
return false;
if (variable != name)
return;
if (object) {
Commands.print ("Breakpoint: variable " + name + " on " + object);
} else {
Commands.print ("Breakpoint: variable " + name);
}
Commands.print (" " + Player.frame);
return true;
};
ret.toString = function () {
var s = "watch " + name;
if (object)
s += " on " + object;
return s;
};
return ret;
};
|
add toString () for breakpoints
|
add toString () for breakpoints
|
ActionScript
|
lgpl-2.1
|
freedesktop-unofficial-mirror/swfdec__swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,mltframework/swfdec,mltframework/swfdec
|
da4c5bbb5410a0404a1352640c7856ed9e7ffbd0
|
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);
}
}
public function hasProvider(provider : DataProvider) : Boolean
{
for each (var accessibleProvider : DataProvider in _providers)
{
if (accessibleProvider == provider)
return true;
}
return false;
}
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 flash.utils.Dictionary;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.type.Signal;
import aerys.minko.type.enum.DataProviderUsage;
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 : IDataProvider) : Boolean
{
for each (var accessibleProvider : IDataProvider in _providers)
{
if (accessibleProvider == provider)
return true;
}
return false;
}
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;
}
}
}
|
Fix hasProvider function
|
Fix hasProvider function
|
ActionScript
|
mit
|
aerys/minko-as3
|
92d51513dd0be5981f5ab95373a33ab2c76d44f6
|
src/jp/promotal/ssplayer/data/SSAttribute.as
|
src/jp/promotal/ssplayer/data/SSAttribute.as
|
package jp.promotal.ssplayer.data {
import jp.promotal.ssplayer.utils.SSInterpolation;
public class SSAttribute {
private var _xml:XML;
private var _tag:String;
public function get tag():String {
return this._tag;
}
public function set tag(value:String):void {
this._tag = value;
if (defaultValue(value) === undefined) {
trace("SSAttribute.tag(): Attribute not supported:", value);
}
}
public static function defaultValue(tag:String):* {
switch (tag) {
case "CELL":
return null;
case "HIDE":
return 0;
case "POSX":
return 0;
case "POSY":
return 0;
case "ROTZ":
return 0;
case "SCLX":
return 1;
case "SCLY":
return 1;
case "ALPH":
return 1;
default:
return undefined;
}
}
private var _keyFrames:Array;
public function get keyFrames():Array {
return this._keyFrames;
}
private var _frames:Array;
public function get frames():Array {
if (this._frames) {
return this._frames;
}
this._frames = [];
for each (var keyFrame:SSKeyFrame in this.keyFrames) {
this._frames[keyFrame.time] = keyFrame;
}
for (var i:int = 0; i < this._frames.length; i++) {
var startFrame:SSFrame = this._frames[i];
if (startFrame) {
var endFrame:SSFrame = null;
for (var j:int = i + 1; j < this._frames.length; j++) {
if (this._frames[j]) {
endFrame = this._frames[j];
break;
}
}
if (endFrame) {
for (var k:int = i + 1; k < j; k++) {
var frame:SSFrame = new SSFrame();
frame.value = SSInterpolation.interpolate(startFrame.ipType, i, j, k, startFrame.value, endFrame.value);
this._frames[k] = frame;
}
i = j - 1;
}
}
}
return this._frames;
}
public function valueAt(time:Number):* {
var prevKeyFrame:SSKeyFrame = null;
var nextKeyFrame:SSKeyFrame = null;
for each (var keyFrame:SSKeyFrame in this.keyFrames) {
if (keyFrame.time <= time) {
if (!prevKeyFrame || keyFrame.time > prevKeyFrame.time) {
prevKeyFrame = keyFrame;
}
} else {
if (!nextKeyFrame || keyFrame.time < nextKeyFrame.time) {
nextKeyFrame = keyFrame;
}
}
}
if (!prevKeyFrame) {
return nextKeyFrame ? nextKeyFrame.value : defaultValue(this.tag);
}
if (!nextKeyFrame) {
return prevKeyFrame.value;
}
return SSInterpolation.interpolate(prevKeyFrame.ipType, prevKeyFrame.time, nextKeyFrame.time, time, prevKeyFrame.value, nextKeyFrame.value);
}
public function SSAttribute() {
super();
this._keyFrames = [];
}
public static function empty(tag:String):SSAttribute {
var result:SSAttribute = new SSAttribute();
result.tag = tag;
return result;
}
public static function fromXML(xml:XML):SSAttribute {
var result:SSAttribute = new SSAttribute();
if (SSProject.DEBUG) {
result._xml = xml;
}
result.tag = xml.@tag;
for each (var key:XML in xml.key) {
var keyFrame:SSKeyFrame = SSKeyFrame.fromXML(key);
result._keyFrames.push(keyFrame);
}
return result;
}
}
}
|
package jp.promotal.ssplayer.data {
import jp.promotal.ssplayer.utils.SSInterpolation;
public class SSAttribute {
private var _xml:XML;
private var _tag:String;
public function get tag():String {
return this._tag;
}
public function set tag(value:String):void {
this._tag = value;
if (defaultValue(value) === undefined) {
trace("[SSProject] SSAttribute.tag(): Attribute not supported:", value);
}
}
public static function defaultValue(tag:String):* {
switch (tag) {
case "CELL":
return null;
case "HIDE":
return 0;
case "POSX":
return 0;
case "POSY":
return 0;
case "ROTZ":
return 0;
case "SCLX":
return 1;
case "SCLY":
return 1;
case "ALPH":
return 1;
default:
return undefined;
}
}
private var _keyFrames:Array;
public function get keyFrames():Array {
return this._keyFrames;
}
private var _frames:Array;
public function get frames():Array {
if (this._frames) {
return this._frames;
}
this._frames = [];
for each (var keyFrame:SSKeyFrame in this.keyFrames) {
this._frames[keyFrame.time] = keyFrame;
}
for (var i:int = 0; i < this._frames.length; i++) {
var startFrame:SSFrame = this._frames[i];
if (startFrame) {
var endFrame:SSFrame = null;
for (var j:int = i + 1; j < this._frames.length; j++) {
if (this._frames[j]) {
endFrame = this._frames[j];
break;
}
}
if (endFrame) {
for (var k:int = i + 1; k < j; k++) {
var frame:SSFrame = new SSFrame();
frame.value = SSInterpolation.interpolate(startFrame.ipType, i, j, k, startFrame.value, endFrame.value);
this._frames[k] = frame;
}
i = j - 1;
}
}
}
return this._frames;
}
public function valueAt(time:Number):* {
var prevKeyFrame:SSKeyFrame = null;
var nextKeyFrame:SSKeyFrame = null;
for each (var keyFrame:SSKeyFrame in this.keyFrames) {
if (keyFrame.time <= time) {
if (!prevKeyFrame || keyFrame.time > prevKeyFrame.time) {
prevKeyFrame = keyFrame;
}
} else {
if (!nextKeyFrame || keyFrame.time < nextKeyFrame.time) {
nextKeyFrame = keyFrame;
}
}
}
if (!prevKeyFrame) {
return nextKeyFrame ? nextKeyFrame.value : defaultValue(this.tag);
}
if (!nextKeyFrame) {
return prevKeyFrame.value;
}
return SSInterpolation.interpolate(prevKeyFrame.ipType, prevKeyFrame.time, nextKeyFrame.time, time, prevKeyFrame.value, nextKeyFrame.value);
}
public function SSAttribute() {
super();
this._keyFrames = [];
}
public static function empty(tag:String):SSAttribute {
var result:SSAttribute = new SSAttribute();
result.tag = tag;
return result;
}
public static function fromXML(xml:XML):SSAttribute {
var result:SSAttribute = new SSAttribute();
if (SSProject.DEBUG) {
result._xml = xml;
}
result.tag = xml.@tag;
for each (var key:XML in xml.key) {
var keyFrame:SSKeyFrame = SSKeyFrame.fromXML(key);
result._keyFrames.push(keyFrame);
}
return result;
}
}
}
|
tag warning message
|
tag warning message
|
ActionScript
|
bsd-2-clause
|
promotal/SS5Player,promotal/SS5Player
|
2b12cb53c30b3dbf5d3c9b8de07435d1d94ae52a
|
src/aerys/minko/type/animation/timeline/MatrixSegmentTimeline.as
|
src/aerys/minko/type/animation/timeline/MatrixSegmentTimeline.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;
use namespace minko_animation;
public final class MatrixSegmentTimeline extends AbstractTimeline
{
private var _timeTable : Vector.<uint> = null;
private var _matrices : Vector.<Matrix4x4> = null;
public function MatrixSegmentTimeline(propertyPath : String,
timeTable : Vector.<uint>,
values : Vector.<Matrix4x4>)
{
super(propertyPath, timeTable[int(timeTable.length - 1)]);
_timeTable = timeTable;
_matrices = values;
}
override public function updateAt(t : int, target : Object) : void
{
super.updateAt(t, target);
var reverse : Boolean = t < 0;
var timeId : uint = getIndexForTime(reverse ? duration - t : t);
var timeCount : uint = _timeTable.length;
// change matrix value
var out : Matrix4x4 = currentTarget[propertyName];
if (!out)
{
throw new Error(
"'" + propertyName
+ "' could not be found in '"
+ currentTarget + "'."
);
}
if (timeId == 0)
out.copyFrom(_matrices[0]);
else
out.copyFrom(_matrices[int(timeId - 1)]);
}
private function getIndexForTime(t : uint) : uint
{
// use a dichotomy to find the current frame in the time table.
var timeCount : uint = _timeTable.length;
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(),
_matrices.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;
use namespace minko_animation;
public final class MatrixSegmentTimeline extends AbstractTimeline
{
private var _timeTable : Vector.<uint> = null;
private var _matrices : Vector.<Matrix4x4> = null;
public function MatrixSegmentTimeline(propertyPath : String,
timeTable : Vector.<uint>,
values : Vector.<Matrix4x4>)
{
super(propertyPath, timeTable[uint(timeTable.length - 1)]);
_timeTable = timeTable;
_matrices = values;
}
override public function updateAt(t : int, target : Object) : void
{
super.updateAt(t, target);
var reverse : Boolean = t < 0;
var timeId : uint = getIndexForTime(reverse ? duration - t : t);
var timeCount : uint = _timeTable.length;
// change matrix value
var out : Matrix4x4 = currentTarget[propertyName];
if (!out)
{
throw new Error(
"'" + propertyName
+ "' could not be found in '"
+ currentTarget + "'."
);
}
if (timeId == 0)
out.copyFrom(_matrices[0]);
else
out.copyFrom(_matrices[int(timeId - 1)]);
}
private function getIndexForTime(t : uint) : uint
{
// use a dichotomy to find the current frame in the time table.
var timeCount : uint = _timeTable.length;
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(),
_matrices.slice()
);
}
}
}
|
fix array access cast to uint instead of int in MatrixSegmentTimeline
|
fix array access cast to uint instead of int in MatrixSegmentTimeline
|
ActionScript
|
mit
|
aerys/minko-as3
|
c46d0a4e792a8b81d14175f317e7b284f2b1090e
|
src/org/mangui/hls/stream/HLSNetStream.as
|
src/org/mangui/hls/stream/HLSNetStream.as
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls.stream {
import org.mangui.hls.controller.BufferThresholdController;
import org.mangui.hls.loader.FragmentLoader;
import org.mangui.hls.event.HLSPlayMetrics;
import org.mangui.hls.event.HLSError;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.constant.HLSSeekStates;
import org.mangui.hls.constant.HLSPlayStates;
import org.mangui.hls.flv.FLVTag;
import org.mangui.hls.HLS;
import org.mangui.hls.HLSSettings;
import org.mangui.hls.utils.Hex;
import flash.events.Event;
import flash.events.NetStatusEvent;
import flash.events.TimerEvent;
import flash.net.*;
import flash.utils.*;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
/** Class that overrides standard flash.net.NetStream class, keeps the buffer filled, handles seek and play state
*
* play state transition :
* FROM TO condition
* HLSPlayStates.IDLE HLSPlayStates.PLAYING_BUFFERING play()/play2()/seek() called
* HLSPlayStates.PLAYING_BUFFERING HLSPlayStates.PLAYING buflen > minBufferLength
* HLSPlayStates.PAUSED_BUFFERING HLSPlayStates.PAUSED buflen > minBufferLength
* HLSPlayStates.PLAYING HLSPlayStates.PLAYING_BUFFERING buflen < lowBufferLength
* HLSPlayStates.PAUSED HLSPlayStates.PAUSED_BUFFERING buflen < lowBufferLength
*/
public class HLSNetStream extends NetStream {
/** Reference to the framework controller. **/
private var _hls : HLS;
/** reference to buffer threshold controller */
private var _bufferThresholdController : BufferThresholdController;
/** FLV tags buffer vector **/
private var _flvTagBuffer : Vector.<FLVTag>;
/** FLV tags buffer duration **/
private var _flvTagBufferDuration : Number;
/** The fragment loader. **/
private var _fragmentLoader : FragmentLoader;
/** means that last fragment of a VOD playlist has been loaded */
private var _reached_vod_end : Boolean;
/** Timer used to check buffer and position. **/
private var _timer : Timer;
/** Current playback state. **/
private var _playbackState : String;
/** Current seek state. **/
private var _seekState : String;
/** current playback level **/
private var _playbackLevel : int;
/** Netstream client proxy */
private var _client : HLSNetStreamClient;
/** Create the buffer. **/
public function HLSNetStream(connection : NetConnection, hls : HLS, fragmentLoader : FragmentLoader) : void {
super(connection);
super.bufferTime = 0.1;
_flvTagBufferDuration = 0;
_hls = hls;
_bufferThresholdController = new BufferThresholdController(hls);
_fragmentLoader = fragmentLoader;
_hls.addEventListener(HLSEvent.LAST_VOD_FRAGMENT_LOADED, _lastVODFragmentLoadedHandler);
_playbackState = HLSPlayStates.IDLE;
_seekState = HLSSeekStates.IDLE;
_timer = new Timer(100, 0);
_timer.addEventListener(TimerEvent.TIMER, _checkBuffer);
_client = new HLSNetStreamClient();
_client.registerCallback("onHLSFragmentChange", onHLSFragmentChange);
_client.registerCallback("onID3Data", onID3Data);
super.client = _client;
};
public function onHLSFragmentChange(level : int, seqnum : int, cc : int, audio_only : Boolean, program_date : Number, width : int, height : int, ... tags) : void {
CONFIG::LOGGING {
Log.debug("playing fragment(level/sn/cc):" + level + "/" + seqnum + "/" + cc);
}
_playbackLevel = level;
var tag_list : Array = new Array();
for (var i : uint = 0; i < tags.length; i++) {
tag_list.push(tags[i]);
CONFIG::LOGGING {
Log.debug("custom tag:" + tags[i]);
}
}
_hls.dispatchEvent(new HLSEvent(HLSEvent.FRAGMENT_PLAYING, new HLSPlayMetrics(level, seqnum, cc, audio_only, program_date, width, height, tag_list)));
}
// function is called by SCRIPT in FLV
public function onID3Data(data : ByteArray) : void {
var dump : String = "unset";
// we dump the content as hex to get it to the Javascript in the browser.
// from lots of searching, we could use base64, but even then, the decode would
// not be native, so hex actually seems more efficient
dump = Hex.fromArray(data);
CONFIG::LOGGING {
Log.debug("id3:" + dump);
}
_hls.dispatchEvent(new HLSEvent(HLSEvent.ID3_UPDATED, dump));
}
/** timer function, check/update NetStream state, and append tags if needed **/
private function _checkBuffer(e : Event) : void {
var buffer : Number = this.bufferLength;
// Set playback state. no need to check buffer status if seeking
if (_seekState != HLSSeekStates.SEEKING) {
// check low buffer condition
if (buffer <= 0.1) {
if (_reached_vod_end) {
// reach end of playlist + playback complete (as buffer is empty).
// stop timer, report event and switch to IDLE mode.
_timer.stop();
CONFIG::LOGGING {
Log.debug("reached end of VOD playlist, notify playback complete");
}
_hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYBACK_COMPLETE));
_setPlaybackState(HLSPlayStates.IDLE);
_setSeekState(HLSSeekStates.IDLE);
return;
} else {
// buffer <= 0.1 and not EOS, pause Netstream
super.pause();
}
}
// if buffer len is below lowBufferLength, get into buffering state
if (!_reached_vod_end && buffer < _bufferThresholdController.lowBufferLength) {
if (_playbackState == HLSPlayStates.PLAYING) {
// low buffer condition and play state. switch to play buffering state
_setPlaybackState(HLSPlayStates.PLAYING_BUFFERING);
} else if (_playbackState == HLSPlayStates.PAUSED) {
// low buffer condition and pause state. switch to paused buffering state
_setPlaybackState(HLSPlayStates.PAUSED_BUFFERING);
}
}
// if buffer len is above minBufferLength, get out of buffering state
if (buffer >= _bufferThresholdController.minBufferLength || _reached_vod_end) {
/* after we reach back threshold value, set it buffer low value to avoid
* reporting buffering state to often. using different values for low buffer / min buffer
* allow to fine tune this
*/
// no more in low buffer state
if (_playbackState == HLSPlayStates.PLAYING_BUFFERING) {
CONFIG::LOGGING {
Log.debug("resume playback");
}
super.resume();
_setPlaybackState(HLSPlayStates.PLAYING);
} else if (_playbackState == HLSPlayStates.PAUSED_BUFFERING) {
_setPlaybackState(HLSPlayStates.PAUSED);
}
}
}
// in case any data available in our FLV buffer, append into NetStream
if (_flvTagBuffer.length) {
if (_seekState == HLSSeekStates.SEEKING) {
/* this is our first injection after seek(),
let's flush netstream now
this is to avoid black screen during seek command */
super.close();
CONFIG::FLASH_11_1 {
try {
super.useHardwareDecoder = HLSSettings.useHardwareVideoDecoder;
} catch(e : Error) {
}
}
super.play(null);
super.appendBytesAction(NetStreamAppendBytesAction.RESET_SEEK);
// immediatly pause NetStream, it will be resumed when enough data will be buffered in the NetStream
super.pause();
// dispatch event to mimic NetStream behaviour
dispatchEvent(new NetStatusEvent(NetStatusEvent.NET_STATUS, false, false, {code:"NetStream.Seek.Notify", level:"status"}));
_setSeekState(HLSSeekStates.SEEKED);
}
// CONFIG::LOGGING {
// Log.debug("appending data into NetStream");
// }
while (0 < _flvTagBuffer.length) {
var tagBuffer : FLVTag = _flvTagBuffer.shift();
// append data until we drain our _buffer
try {
if (tagBuffer.type == FLVTag.DISCONTINUITY) {
super.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN);
super.appendBytes(FLVTag.getHeader());
}
super.appendBytes(tagBuffer.data);
} catch (error : Error) {
var hlsError : HLSError = new HLSError(HLSError.TAG_APPENDING_ERROR, null, tagBuffer.type + ": " + error.message);
_hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError));
}
// Last tag done? Then append sequence end.
if (_reached_vod_end && _flvTagBuffer.length == 0) {
super.appendBytesAction(NetStreamAppendBytesAction.END_SEQUENCE);
super.appendBytes(new ByteArray());
}
}
// FLV tag buffer drained, reset its duration
_flvTagBufferDuration = 0;
}
};
/** Return the current playback state. **/
public function get playbackState() : String {
return _playbackState;
};
/** Return the current seek state. **/
public function get seekState() : String {
return _seekState;
};
/** Return the current playback quality level **/
public function get playbackLevel() : int {
return _playbackLevel;
};
/** append tags to NetStream **/
public function appendTags(tags : Vector.<FLVTag>) : void {
_flvTagBufferDuration += (tags[tags.length - 1].pts - tags[0].pts) / 1000;
for each (var tag : FLVTag in tags) {
_flvTagBuffer.push(tag);
}
};
private function _lastVODFragmentLoadedHandler(event : HLSEvent) : void {
CONFIG::LOGGING {
Log.debug("last fragment loaded");
}
_reached_vod_end = true;
}
/** Change playback state. **/
private function _setPlaybackState(state : String) : void {
if (state != _playbackState) {
CONFIG::LOGGING {
Log.debug('[PLAYBACK_STATE] from ' + _playbackState + ' to ' + state);
}
_playbackState = state;
_hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYBACK_STATE, _playbackState));
}
};
/** Change seeking state. **/
private function _setSeekState(state : String) : void {
if (state != _seekState) {
CONFIG::LOGGING {
Log.debug('[SEEK_STATE] from ' + _seekState + ' to ' + state);
}
_seekState = state;
_hls.dispatchEvent(new HLSEvent(HLSEvent.SEEK_STATE, _seekState));
}
};
override public function play(...args) : void {
var _playStart : Number;
if (args.length >= 2) {
_playStart = Number(args[1]);
} else {
_playStart = -1;
}
CONFIG::LOGGING {
Log.info("HLSNetStream:play(" + _playStart + ")");
}
seek(_playStart);
_setPlaybackState(HLSPlayStates.PLAYING_BUFFERING);
}
override public function play2(param : NetStreamPlayOptions) : void {
CONFIG::LOGGING {
Log.info("HLSNetStream:play2(" + param.start + ")");
}
seek(param.start);
_setPlaybackState(HLSPlayStates.PLAYING_BUFFERING);
}
/** Pause playback. **/
override public function pause() : void {
CONFIG::LOGGING {
Log.info("HLSNetStream:pause");
}
if (_playbackState == HLSPlayStates.PLAYING) {
super.pause();
_setPlaybackState(HLSPlayStates.PAUSED);
} else if (_playbackState == HLSPlayStates.PLAYING_BUFFERING) {
super.pause();
_setPlaybackState(HLSPlayStates.PAUSED_BUFFERING);
}
};
/** Resume playback. **/
override public function resume() : void {
CONFIG::LOGGING {
Log.info("HLSNetStream:resume");
}
if (_playbackState == HLSPlayStates.PAUSED) {
super.resume();
_setPlaybackState(HLSPlayStates.PLAYING);
} else if (_playbackState == HLSPlayStates.PAUSED_BUFFERING) {
// dont resume NetStream here, it will be resumed by Timer. this avoids resuming playback while seeking is in progress
_setPlaybackState(HLSPlayStates.PLAYING_BUFFERING);
}
};
/** get Buffer Length **/
override public function get bufferLength() : Number {
/* remaining buffer is total duration buffered since beginning minus playback time */
if (_seekState == HLSSeekStates.SEEKING) {
return _flvTagBufferDuration;
} else {
return super.bufferLength + _flvTagBufferDuration;
}
};
/** Start playing data in the buffer. **/
override public function seek(position : Number) : void {
CONFIG::LOGGING {
Log.info("HLSNetStream:seek(" + position + ")");
}
_fragmentLoader.stop();
_fragmentLoader.seek(position);
_flvTagBuffer = new Vector.<FLVTag>();
_flvTagBufferDuration = 0;
_reached_vod_end = false;
_setSeekState(HLSSeekStates.SEEKING);
/* if HLS was in paused state before seeking,
* switch to paused buffering state
* otherwise, switch to playing buffering state
*/
switch(_playbackState) {
case HLSPlayStates.PAUSED:
case HLSPlayStates.PAUSED_BUFFERING:
_setPlaybackState(HLSPlayStates.PAUSED_BUFFERING);
break;
case HLSPlayStates.PLAYING:
case HLSPlayStates.PLAYING_BUFFERING:
_setPlaybackState(HLSPlayStates.PLAYING_BUFFERING);
break;
default:
break;
}
/* always pause NetStream while seeking, even if we are in play state
* in that case, NetStream will be resumed after first fragment loading
*/
super.pause();
_timer.start();
};
public override function set client(client : Object) : void {
_client.delegate = client;
};
public override function get client() : Object {
return _client.delegate;
}
/** Stop playback. **/
override public function close() : void {
CONFIG::LOGGING {
Log.info("HLSNetStream:close");
}
super.close();
_timer.stop();
_fragmentLoader.stop();
_setPlaybackState(HLSPlayStates.IDLE);
_setSeekState(HLSSeekStates.IDLE);
};
public function dispose_() : void {
close();
_bufferThresholdController.dispose();
_hls.removeEventListener(HLSEvent.LAST_VOD_FRAGMENT_LOADED, _lastVODFragmentLoadedHandler);
}
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls.stream {
import org.mangui.hls.controller.BufferThresholdController;
import org.mangui.hls.loader.FragmentLoader;
import org.mangui.hls.event.HLSPlayMetrics;
import org.mangui.hls.event.HLSError;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.constant.HLSSeekStates;
import org.mangui.hls.constant.HLSPlayStates;
import org.mangui.hls.flv.FLVTag;
import org.mangui.hls.HLS;
import org.mangui.hls.HLSSettings;
import org.mangui.hls.utils.Hex;
import flash.events.Event;
import flash.events.NetStatusEvent;
import flash.events.TimerEvent;
import flash.net.*;
import flash.utils.*;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
/** Class that overrides standard flash.net.NetStream class, keeps the buffer filled, handles seek and play state
*
* play state transition :
* FROM TO condition
* HLSPlayStates.IDLE HLSPlayStates.PLAYING_BUFFERING play()/play2()/seek() called
* HLSPlayStates.PLAYING_BUFFERING HLSPlayStates.PLAYING buflen > minBufferLength
* HLSPlayStates.PAUSED_BUFFERING HLSPlayStates.PAUSED buflen > minBufferLength
* HLSPlayStates.PLAYING HLSPlayStates.PLAYING_BUFFERING buflen < lowBufferLength
* HLSPlayStates.PAUSED HLSPlayStates.PAUSED_BUFFERING buflen < lowBufferLength
*/
public class HLSNetStream extends NetStream {
/** Reference to the framework controller. **/
private var _hls : HLS;
/** reference to buffer threshold controller */
private var _bufferThresholdController : BufferThresholdController;
/** FLV tags buffer vector **/
private var _flvTagBuffer : Vector.<FLVTag>;
/** FLV tags buffer duration **/
private var _flvTagBufferDuration : Number;
/** The fragment loader. **/
private var _fragmentLoader : FragmentLoader;
/** means that last fragment of a VOD playlist has been loaded */
private var _reached_vod_end : Boolean;
/** Timer used to check buffer and position. **/
private var _timer : Timer;
/** Current playback state. **/
private var _playbackState : String;
/** Current seek state. **/
private var _seekState : String;
/** current playback level **/
private var _playbackLevel : int;
/** Netstream client proxy */
private var _client : HLSNetStreamClient;
/** Create the buffer. **/
public function HLSNetStream(connection : NetConnection, hls : HLS, fragmentLoader : FragmentLoader) : void {
super(connection);
super.bufferTime = 0.1;
_flvTagBufferDuration = 0;
_hls = hls;
_bufferThresholdController = new BufferThresholdController(hls);
_fragmentLoader = fragmentLoader;
_hls.addEventListener(HLSEvent.LAST_VOD_FRAGMENT_LOADED, _lastVODFragmentLoadedHandler);
_playbackState = HLSPlayStates.IDLE;
_seekState = HLSSeekStates.IDLE;
_timer = new Timer(100, 0);
_timer.addEventListener(TimerEvent.TIMER, _checkBuffer);
_client = new HLSNetStreamClient();
_client.registerCallback("onHLSFragmentChange", onHLSFragmentChange);
_client.registerCallback("onID3Data", onID3Data);
super.client = _client;
};
public function onHLSFragmentChange(level : int, seqnum : int, cc : int, audio_only : Boolean, program_date : Number, width : int, height : int, ... tags) : void {
CONFIG::LOGGING {
Log.debug("playing fragment(level/sn/cc):" + level + "/" + seqnum + "/" + cc);
}
_playbackLevel = level;
var tag_list : Array = new Array();
for (var i : uint = 0; i < tags.length; i++) {
tag_list.push(tags[i]);
CONFIG::LOGGING {
Log.debug("custom tag:" + tags[i]);
}
}
_hls.dispatchEvent(new HLSEvent(HLSEvent.FRAGMENT_PLAYING, new HLSPlayMetrics(level, seqnum, cc, audio_only, program_date, width, height, tag_list)));
}
// function is called by SCRIPT in FLV
public function onID3Data(data : ByteArray) : void {
var dump : String = "unset";
// we dump the content as hex to get it to the Javascript in the browser.
// from lots of searching, we could use base64, but even then, the decode would
// not be native, so hex actually seems more efficient
dump = Hex.fromArray(data);
CONFIG::LOGGING {
Log.debug("id3:" + dump);
}
_hls.dispatchEvent(new HLSEvent(HLSEvent.ID3_UPDATED, dump));
}
/** timer function, check/update NetStream state, and append tags if needed **/
private function _checkBuffer(e : Event) : void {
var buffer : Number = this.bufferLength;
// Set playback state. no need to check buffer status if seeking
if (_seekState != HLSSeekStates.SEEKING) {
// check low buffer condition
if (buffer <= 0.1) {
if (_reached_vod_end) {
// reach end of playlist + playback complete (as buffer is empty).
// stop timer, report event and switch to IDLE mode.
_timer.stop();
CONFIG::LOGGING {
Log.debug("reached end of VOD playlist, notify playback complete");
}
_hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYBACK_COMPLETE));
_setPlaybackState(HLSPlayStates.IDLE);
_setSeekState(HLSSeekStates.IDLE);
return;
} else {
// buffer <= 0.1 and not EOS, pause playback
super.pause();
}
}
// if buffer len is below lowBufferLength, get into buffering state
if (!_reached_vod_end && buffer < _bufferThresholdController.lowBufferLength) {
if (_playbackState == HLSPlayStates.PLAYING) {
// low buffer condition and play state. switch to play buffering state
_setPlaybackState(HLSPlayStates.PLAYING_BUFFERING);
} else if (_playbackState == HLSPlayStates.PAUSED) {
// low buffer condition and pause state. switch to paused buffering state
_setPlaybackState(HLSPlayStates.PAUSED_BUFFERING);
}
}
// if buffer len is above minBufferLength, get out of buffering state
if (buffer >= _bufferThresholdController.minBufferLength || _reached_vod_end) {
if (_playbackState == HLSPlayStates.PLAYING_BUFFERING) {
CONFIG::LOGGING {
Log.debug("resume playback");
}
// resume playback in case it was paused, this can happen if buffer was in really low condition (less than 0.1s)
super.resume();
_setPlaybackState(HLSPlayStates.PLAYING);
} else if (_playbackState == HLSPlayStates.PAUSED_BUFFERING) {
_setPlaybackState(HLSPlayStates.PAUSED);
}
}
}
// in case any data available in our FLV buffer, append into NetStream
if (_flvTagBuffer.length) {
if (_seekState == HLSSeekStates.SEEKING) {
/* this is our first injection after seek(),
let's flush netstream now
this is to avoid black screen during seek command */
super.close();
CONFIG::FLASH_11_1 {
try {
super.useHardwareDecoder = HLSSettings.useHardwareVideoDecoder;
} catch(e : Error) {
}
}
super.play(null);
super.appendBytesAction(NetStreamAppendBytesAction.RESET_SEEK);
// immediatly pause NetStream, it will be resumed when enough data will be buffered in the NetStream
super.pause();
// dispatch event to mimic NetStream behaviour
dispatchEvent(new NetStatusEvent(NetStatusEvent.NET_STATUS, false, false, {code:"NetStream.Seek.Notify", level:"status"}));
_setSeekState(HLSSeekStates.SEEKED);
}
// CONFIG::LOGGING {
// Log.debug("appending data into NetStream");
// }
while (0 < _flvTagBuffer.length) {
var tagBuffer : FLVTag = _flvTagBuffer.shift();
// append data until we drain our _buffer
try {
if (tagBuffer.type == FLVTag.DISCONTINUITY) {
super.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN);
super.appendBytes(FLVTag.getHeader());
}
super.appendBytes(tagBuffer.data);
} catch (error : Error) {
var hlsError : HLSError = new HLSError(HLSError.TAG_APPENDING_ERROR, null, tagBuffer.type + ": " + error.message);
_hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError));
}
// Last tag done? Then append sequence end.
if (_reached_vod_end && _flvTagBuffer.length == 0) {
super.appendBytesAction(NetStreamAppendBytesAction.END_SEQUENCE);
super.appendBytes(new ByteArray());
}
}
// FLV tag buffer drained, reset its duration
_flvTagBufferDuration = 0;
}
};
/** Return the current playback state. **/
public function get playbackState() : String {
return _playbackState;
};
/** Return the current seek state. **/
public function get seekState() : String {
return _seekState;
};
/** Return the current playback quality level **/
public function get playbackLevel() : int {
return _playbackLevel;
};
/** append tags to NetStream **/
public function appendTags(tags : Vector.<FLVTag>) : void {
_flvTagBufferDuration += (tags[tags.length - 1].pts - tags[0].pts) / 1000;
for each (var tag : FLVTag in tags) {
_flvTagBuffer.push(tag);
}
};
private function _lastVODFragmentLoadedHandler(event : HLSEvent) : void {
CONFIG::LOGGING {
Log.debug("last fragment loaded");
}
_reached_vod_end = true;
}
/** Change playback state. **/
private function _setPlaybackState(state : String) : void {
if (state != _playbackState) {
CONFIG::LOGGING {
Log.debug('[PLAYBACK_STATE] from ' + _playbackState + ' to ' + state);
}
_playbackState = state;
_hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYBACK_STATE, _playbackState));
}
};
/** Change seeking state. **/
private function _setSeekState(state : String) : void {
if (state != _seekState) {
CONFIG::LOGGING {
Log.debug('[SEEK_STATE] from ' + _seekState + ' to ' + state);
}
_seekState = state;
_hls.dispatchEvent(new HLSEvent(HLSEvent.SEEK_STATE, _seekState));
}
};
override public function play(...args) : void {
var _playStart : Number;
if (args.length >= 2) {
_playStart = Number(args[1]);
} else {
_playStart = -1;
}
CONFIG::LOGGING {
Log.info("HLSNetStream:play(" + _playStart + ")");
}
seek(_playStart);
_setPlaybackState(HLSPlayStates.PLAYING_BUFFERING);
}
override public function play2(param : NetStreamPlayOptions) : void {
CONFIG::LOGGING {
Log.info("HLSNetStream:play2(" + param.start + ")");
}
seek(param.start);
_setPlaybackState(HLSPlayStates.PLAYING_BUFFERING);
}
/** Pause playback. **/
override public function pause() : void {
CONFIG::LOGGING {
Log.info("HLSNetStream:pause");
}
if (_playbackState == HLSPlayStates.PLAYING) {
super.pause();
_setPlaybackState(HLSPlayStates.PAUSED);
} else if (_playbackState == HLSPlayStates.PLAYING_BUFFERING) {
super.pause();
_setPlaybackState(HLSPlayStates.PAUSED_BUFFERING);
}
};
/** Resume playback. **/
override public function resume() : void {
CONFIG::LOGGING {
Log.info("HLSNetStream:resume");
}
if (_playbackState == HLSPlayStates.PAUSED) {
super.resume();
_setPlaybackState(HLSPlayStates.PLAYING);
} else if (_playbackState == HLSPlayStates.PAUSED_BUFFERING) {
// dont resume NetStream here, it will be resumed by Timer. this avoids resuming playback while seeking is in progress
_setPlaybackState(HLSPlayStates.PLAYING_BUFFERING);
}
};
/** get Buffer Length **/
override public function get bufferLength() : Number {
/* remaining buffer is total duration buffered since beginning minus playback time */
if (_seekState == HLSSeekStates.SEEKING) {
return _flvTagBufferDuration;
} else {
return super.bufferLength + _flvTagBufferDuration;
}
};
/** Start playing data in the buffer. **/
override public function seek(position : Number) : void {
CONFIG::LOGGING {
Log.info("HLSNetStream:seek(" + position + ")");
}
_fragmentLoader.stop();
_fragmentLoader.seek(position);
_flvTagBuffer = new Vector.<FLVTag>();
_flvTagBufferDuration = 0;
_reached_vod_end = false;
_setSeekState(HLSSeekStates.SEEKING);
/* if HLS was in paused state before seeking,
* switch to paused buffering state
* otherwise, switch to playing buffering state
*/
switch(_playbackState) {
case HLSPlayStates.PAUSED:
case HLSPlayStates.PAUSED_BUFFERING:
_setPlaybackState(HLSPlayStates.PAUSED_BUFFERING);
break;
case HLSPlayStates.PLAYING:
case HLSPlayStates.PLAYING_BUFFERING:
_setPlaybackState(HLSPlayStates.PLAYING_BUFFERING);
break;
default:
break;
}
/* always pause NetStream while seeking, even if we are in play state
* in that case, NetStream will be resumed after first fragment loading
*/
super.pause();
_timer.start();
};
public override function set client(client : Object) : void {
_client.delegate = client;
};
public override function get client() : Object {
return _client.delegate;
}
/** Stop playback. **/
override public function close() : void {
CONFIG::LOGGING {
Log.info("HLSNetStream:close");
}
super.close();
_timer.stop();
_fragmentLoader.stop();
_setPlaybackState(HLSPlayStates.IDLE);
_setSeekState(HLSSeekStates.IDLE);
};
public function dispose_() : void {
close();
_bufferThresholdController.dispose();
_hls.removeEventListener(HLSEvent.LAST_VOD_FRAGMENT_LOADED, _lastVODFragmentLoadedHandler);
}
}
}
|
update comments
|
HLSNetStream.as: update comments
|
ActionScript
|
mpl-2.0
|
mangui/flashls,clappr/flashls,suuhas/flashls,dighan/flashls,Peer5/flashls,clappr/flashls,fixedmachine/flashls,viktorot/flashls,vidible/vdb-flashls,Peer5/flashls,aevange/flashls,Peer5/flashls,NicolasSiver/flashls,codex-corp/flashls,thdtjsdn/flashls,thdtjsdn/flashls,Peer5/flashls,JulianPena/flashls,School-Improvement-Network/flashls,School-Improvement-Network/flashls,jlacivita/flashls,aevange/flashls,tedconf/flashls,vidible/vdb-flashls,suuhas/flashls,viktorot/flashls,jlacivita/flashls,hola/flashls,Corey600/flashls,neilrackett/flashls,suuhas/flashls,Boxie5/flashls,aevange/flashls,hola/flashls,loungelogic/flashls,JulianPena/flashls,NicolasSiver/flashls,aevange/flashls,School-Improvement-Network/flashls,viktorot/flashls,Corey600/flashls,dighan/flashls,fixedmachine/flashls,tedconf/flashls,neilrackett/flashls,loungelogic/flashls,Boxie5/flashls,mangui/flashls,suuhas/flashls,codex-corp/flashls
|
d614cd47b130eb6a5def2b2208ac546f0c621564
|
src/flash/display/DisplayObjectContainer.as
|
src/flash/display/DisplayObjectContainer.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.geom.Point;
import flash.text.TextSnapshot;
[native(cls='DisplayObjectContainerClass')]
public class DisplayObjectContainer extends InteractiveObject {
public function DisplayObjectContainer() {}
public native function get numChildren():int;
public native function get textSnapshot():TextSnapshot;
public native function get tabChildren():Boolean;
public native function set tabChildren(enable:Boolean):void;
public native function get mouseChildren():Boolean;
public native function set mouseChildren(enable:Boolean):void;
public native function addChild(child:DisplayObject):DisplayObject;
public native function addChildAt(child:DisplayObject, index:int):DisplayObject;
public native function removeChild(child:DisplayObject):DisplayObject;
public native function removeChildAt(index:int):DisplayObject;
public native function getChildIndex(child:DisplayObject):int;
public native function setChildIndex(child:DisplayObject, index:int):void;
public native function getChildAt(index:int):DisplayObject;
public native function getChildByName(name:String):DisplayObject;
public native function getObjectsUnderPoint(point:Point):Array;
public native function areInaccessibleObjectsUnderPoint(point:Point):Boolean;
public native function contains(child:DisplayObject):Boolean;
public native function swapChildrenAt(index1:int, index2:int):void;
public native function swapChildren(child1:DisplayObject, child2:DisplayObject):void;
public native function removeChildren(beginIndex:int = 0, endIndex:int = 2147483647):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.geom.Point;
import flash.text.TextSnapshot;
[native(cls='ContainerClass')]
public class DisplayObjectContainer extends InteractiveObject {
public function DisplayObjectContainer() {}
public native function get numChildren():int;
public native function get textSnapshot():TextSnapshot;
public native function get tabChildren():Boolean;
public native function set tabChildren(enable:Boolean):void;
public native function get mouseChildren():Boolean;
public native function set mouseChildren(enable:Boolean):void;
public native function addChild(child:DisplayObject):DisplayObject;
public native function addChildAt(child:DisplayObject, index:int):DisplayObject;
public native function removeChild(child:DisplayObject):DisplayObject;
public native function removeChildAt(index:int):DisplayObject;
public native function getChildIndex(child:DisplayObject):int;
public native function setChildIndex(child:DisplayObject, index:int):void;
public native function getChildAt(index:int):DisplayObject;
public native function getChildByName(name:String):DisplayObject;
public native function getObjectsUnderPoint(point:Point):Array;
public native function areInaccessibleObjectsUnderPoint(point:Point):Boolean;
public native function contains(child:DisplayObject):Boolean;
public native function swapChildrenAt(index1:int, index2:int):void;
public native function swapChildren(child1:DisplayObject, child2:DisplayObject):void;
public native function removeChildren(beginIndex:int = 0, endIndex:int = 2147483647):void;
}
}
|
Fix metadata for DisplayObjectContainer
|
Fix metadata for DisplayObjectContainer
|
ActionScript
|
apache-2.0
|
mozilla/shumway,tschneidereit/shumway,mbebenita/shumway,mbebenita/shumway,mozilla/shumway,mbebenita/shumway,yurydelendik/shumway,tschneidereit/shumway,mbebenita/shumway,mozilla/shumway,yurydelendik/shumway,mozilla/shumway,tschneidereit/shumway,mbebenita/shumway,tschneidereit/shumway,mozilla/shumway,yurydelendik/shumway,mbebenita/shumway,yurydelendik/shumway,mozilla/shumway,yurydelendik/shumway,mozilla/shumway,tschneidereit/shumway,yurydelendik/shumway,mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway,yurydelendik/shumway,tschneidereit/shumway,tschneidereit/shumway,mbebenita/shumway,mozilla/shumway
|
605d113c9ca6f9ef4dd381d89bffd10aa88bfc61
|
Bin/Data/Scripts/Editor.as
|
Bin/Data/Scripts/Editor.as
|
// Urho3D editor
#include "Scripts/Editor/EditorHierarchyWindow.as"
#include "Scripts/Editor/EditorView.as"
#include "Scripts/Editor/EditorScene.as"
#include "Scripts/Editor/EditorActions.as"
#include "Scripts/Editor/EditorUIElement.as"
#include "Scripts/Editor/EditorGizmo.as"
#include "Scripts/Editor/EditorMaterial.as"
#include "Scripts/Editor/EditorSettings.as"
#include "Scripts/Editor/EditorPreferences.as"
#include "Scripts/Editor/EditorToolBar.as"
#include "Scripts/Editor/EditorSecondaryToolbar.as"
#include "Scripts/Editor/EditorUI.as"
#include "Scripts/Editor/EditorImport.as"
#include "Scripts/Editor/EditorResourceBrowser.as"
#include "Scripts/Editor/EditorSpawn.as"
String configFileName;
bool instancingSetting = true;
int shadowQualitySetting = 2;
void Start()
{
// Assign the value ASAP because configFileName is needed on exit, including exit on error
configFileName = fileSystem.GetAppPreferencesDir("urho3d", "Editor") + "Config.xml";
if (engine.headless)
{
ErrorDialog("Urho3D Editor", "Headless mode is not supported. The program will now exit.");
engine.Exit();
return;
}
// Use the first frame to setup when the resolution is initialized
SubscribeToEvent("Update", "FirstFrame");
SubscribeToEvent(input, "ExitRequested", "HandleExitRequested");
// Disable Editor auto exit, check first if it is OK to exit
engine.autoExit = false;
// Enable console commands from the editor script
script.defaultScriptFile = scriptFile;
// Enable automatic resource reloading
cache.autoReloadResources = true;
// Return resources which exist but failed to load due to error, so that we will not lose resource refs
cache.returnFailedResources = true;
// Use OS mouse without grabbing it
input.mouseVisible = true;
// Use system clipboard to allow transport of text in & out from the editor
ui.useSystemClipboard = true;
}
void FirstFrame()
{
// Create root scene node
CreateScene();
// Load editor settings and preferences
LoadConfig();
// Create user interface for the editor
CreateUI();
// Create root UI element where all 'editable' UI elements would be parented to
CreateRootUIElement();
// Load the initial scene if provided
ParseArguments();
// Switch to real frame handler after initialization
SubscribeToEvent("Update", "HandleUpdate");
}
void Stop()
{
SaveConfig();
}
void ParseArguments()
{
Array<String> arguments = GetArguments();
bool loaded = false;
// Scan for a scene to load
for (uint i = 1; i < arguments.length; ++i)
{
if (arguments[i].ToLower() == "-scene")
{
if (++i < arguments.length)
{
loaded = LoadScene(arguments[i]);
break;
}
}
}
if (!loaded)
ResetScene();
}
void HandleUpdate(StringHash eventType, VariantMap& eventData)
{
float timeStep = eventData["TimeStep"].GetFloat();
DoResourceBrowserWork();
UpdateView(timeStep);
UpdateViewports(timeStep);
UpdateStats(timeStep);
UpdateScene(timeStep);
UpdateTestAnimation(timeStep);
UpdateGizmo();
UpdateDirtyUI();
}
void LoadConfig()
{
if (!fileSystem.FileExists(configFileName))
return;
XMLFile config;
config.Load(File(configFileName, FILE_READ));
XMLElement configElem = config.root;
if (configElem.isNull)
return;
XMLElement cameraElem = configElem.GetChild("camera");
XMLElement objectElem = configElem.GetChild("object");
XMLElement renderingElem = configElem.GetChild("rendering");
XMLElement uiElem = configElem.GetChild("ui");
XMLElement hierarchyElem = configElem.GetChild("hierarchy");
XMLElement inspectorElem = configElem.GetChild("attributeinspector");
XMLElement viewElem = configElem.GetChild("view");
XMLElement resourcesElem = configElem.GetChild("resources");
XMLElement consoleElem = configElem.GetChild("console");
if (!cameraElem.isNull)
{
if (cameraElem.HasAttribute("nearclip")) viewNearClip = cameraElem.GetFloat("nearclip");
if (cameraElem.HasAttribute("farclip")) viewFarClip = cameraElem.GetFloat("farclip");
if (cameraElem.HasAttribute("fov")) viewFov = cameraElem.GetFloat("fov");
if (cameraElem.HasAttribute("speed")) cameraBaseSpeed = cameraElem.GetFloat("speed");
if (cameraElem.HasAttribute("limitrotation")) limitRotation = cameraElem.GetBool("limitrotation");
if (cameraElem.HasAttribute("mousewheelcameraposition")) mouseWheelCameraPosition = cameraElem.GetBool("mousewheelcameraposition");
if (cameraElem.HasAttribute("viewportmode")) viewportMode = cameraElem.GetUInt("viewportmode");
UpdateViewParameters();
if (cameraElem.HasAttribute("mouseorbitmode")) mouseOrbitMode = cameraElem.GetInt("mouseorbitmode");
UpdateViewParameters();
}
if (!objectElem.isNull)
{
if (objectElem.HasAttribute("newnodedistance")) newNodeDistance = objectElem.GetFloat("newnodedistance");
if (objectElem.HasAttribute("movestep")) moveStep = objectElem.GetFloat("movestep");
if (objectElem.HasAttribute("rotatestep")) rotateStep = objectElem.GetFloat("rotatestep");
if (objectElem.HasAttribute("scalestep")) scaleStep = objectElem.GetFloat("scalestep");
if (objectElem.HasAttribute("movesnap")) moveSnap = objectElem.GetBool("movesnap");
if (objectElem.HasAttribute("rotatesnap")) rotateSnap = objectElem.GetBool("rotatesnap");
if (objectElem.HasAttribute("scalesnap")) scaleSnap = objectElem.GetBool("scalesnap");
if (objectElem.HasAttribute("applymateriallist")) applyMaterialList = objectElem.GetBool("applymateriallist");
if (objectElem.HasAttribute("importoptions")) importOptions = objectElem.GetAttribute("importoptions");
if (objectElem.HasAttribute("pickmode")) pickMode = objectElem.GetInt("pickmode");
if (objectElem.HasAttribute("axismode")) axisMode = AxisMode(objectElem.GetInt("axismode"));
if (objectElem.HasAttribute("revertonpause")) revertOnPause = objectElem.GetBool("revertonpause");
}
if (!resourcesElem.isNull)
{
if (resourcesElem.HasAttribute("rememberresourcepath")) rememberResourcePath = resourcesElem.GetBool("rememberresourcepath");
if (rememberResourcePath && resourcesElem.HasAttribute("resourcepath"))
{
String newResourcePath = resourcesElem.GetAttribute("resourcepath");
if (fileSystem.DirExists(newResourcePath))
SetResourcePath(resourcesElem.GetAttribute("resourcepath"), false);
}
if (resourcesElem.HasAttribute("importpath"))
{
String newImportPath = resourcesElem.GetAttribute("importpath");
if (fileSystem.DirExists(newImportPath))
uiImportPath = newImportPath;
}
if (resourcesElem.HasAttribute("recentscenes"))
{
uiRecentScenes = resourcesElem.GetAttribute("recentscenes").Split(';');
}
}
if (!renderingElem.isNull)
{
if (renderingElem.HasAttribute("texturequality")) renderer.textureQuality = renderingElem.GetInt("texturequality");
if (renderingElem.HasAttribute("materialquality")) renderer.materialQuality = renderingElem.GetInt("materialquality");
if (renderingElem.HasAttribute("shadowresolution")) SetShadowResolution(renderingElem.GetInt("shadowresolution"));
if (renderingElem.HasAttribute("shadowquality")) renderer.shadowQuality = shadowQualitySetting = renderingElem.GetInt("shadowquality");
if (renderingElem.HasAttribute("maxoccludertriangles")) renderer.maxOccluderTriangles = renderingElem.GetInt("maxoccludertriangles");
if (renderingElem.HasAttribute("specularlighting")) renderer.specularLighting = renderingElem.GetBool("specularlighting");
if (renderingElem.HasAttribute("dynamicinstancing")) renderer.dynamicInstancing = instancingSetting = renderingElem.GetBool("dynamicinstancing");
if (renderingElem.HasAttribute("framelimiter")) engine.maxFps = renderingElem.GetBool("framelimiter") ? 200 : 0;
}
if (!uiElem.isNull)
{
if (uiElem.HasAttribute("minopacity")) uiMinOpacity = uiElem.GetFloat("minopacity");
if (uiElem.HasAttribute("maxopacity")) uiMaxOpacity = uiElem.GetFloat("maxopacity");
}
if (!hierarchyElem.isNull)
{
if (hierarchyElem.HasAttribute("showinternaluielement")) showInternalUIElement = hierarchyElem.GetBool("showinternaluielement");
if (hierarchyElem.HasAttribute("showtemporaryobject")) showTemporaryObject = hierarchyElem.GetBool("showtemporaryobject");
if (inspectorElem.HasAttribute("nodecolor")) nodeTextColor = inspectorElem.GetColor("nodecolor");
if (inspectorElem.HasAttribute("componentcolor")) componentTextColor = inspectorElem.GetColor("componentcolor");
}
if (!inspectorElem.isNull)
{
if (inspectorElem.HasAttribute("originalcolor")) normalTextColor = inspectorElem.GetColor("originalcolor");
if (inspectorElem.HasAttribute("modifiedcolor")) modifiedTextColor = inspectorElem.GetColor("modifiedcolor");
if (inspectorElem.HasAttribute("noneditablecolor")) nonEditableTextColor = inspectorElem.GetColor("noneditablecolor");
if (inspectorElem.HasAttribute("shownoneditable")) showNonEditableAttribute = inspectorElem.GetBool("shownoneditable");
}
if (!viewElem.isNull)
{
if (viewElem.HasAttribute("defaultzoneambientcolor")) renderer.defaultZone.ambientColor = viewElem.GetColor("defaultzoneambientcolor");
if (viewElem.HasAttribute("defaultzonefogcolor")) renderer.defaultZone.fogColor = viewElem.GetColor("defaultzonefogcolor");
if (viewElem.HasAttribute("defaultzonefogstart")) renderer.defaultZone.fogStart = viewElem.GetInt("defaultzonefogstart");
if (viewElem.HasAttribute("defaultzonefogend")) renderer.defaultZone.fogEnd = viewElem.GetInt("defaultzonefogend");
if (viewElem.HasAttribute("showgrid")) showGrid = viewElem.GetBool("showgrid");
if (viewElem.HasAttribute("grid2dmode")) grid2DMode = viewElem.GetBool("grid2dmode");
if (viewElem.HasAttribute("gridsize")) gridSize = viewElem.GetInt("gridsize");
if (viewElem.HasAttribute("gridsubdivisions")) gridSubdivisions = viewElem.GetInt("gridsubdivisions");
if (viewElem.HasAttribute("gridscale")) gridScale = viewElem.GetFloat("gridscale");
if (viewElem.HasAttribute("gridcolor")) gridColor = viewElem.GetColor("gridcolor");
if (viewElem.HasAttribute("gridsubdivisioncolor")) gridSubdivisionColor = viewElem.GetColor("gridsubdivisioncolor");
}
if (!consoleElem.isNull)
{
// Console does not exist yet at this point, so store the string in a global variable
if (consoleElem.HasAttribute("commandinterpreter")) consoleCommandInterpreter = consoleElem.GetAttribute("commandinterpreter");
}
}
void SaveConfig()
{
XMLFile config;
XMLElement configElem = config.CreateRoot("configuration");
XMLElement cameraElem = configElem.CreateChild("camera");
XMLElement objectElem = configElem.CreateChild("object");
XMLElement renderingElem = configElem.CreateChild("rendering");
XMLElement uiElem = configElem.CreateChild("ui");
XMLElement hierarchyElem = configElem.CreateChild("hierarchy");
XMLElement inspectorElem = configElem.CreateChild("attributeinspector");
XMLElement viewElem = configElem.CreateChild("view");
XMLElement resourcesElem = configElem.CreateChild("resources");
XMLElement consoleElem = configElem.CreateChild("console");
cameraElem.SetFloat("nearclip", viewNearClip);
cameraElem.SetFloat("farclip", viewFarClip);
cameraElem.SetFloat("fov", viewFov);
cameraElem.SetFloat("speed", cameraBaseSpeed);
cameraElem.SetBool("limitrotation", limitRotation);
cameraElem.SetBool("mousewheelcameraposition", mouseWheelCameraPosition);
cameraElem.SetUInt("viewportmode", viewportMode);
cameraElem.SetInt("mouseorbitmode", mouseOrbitMode);
objectElem.SetFloat("newnodedistance", newNodeDistance);
objectElem.SetFloat("movestep", moveStep);
objectElem.SetFloat("rotatestep", rotateStep);
objectElem.SetFloat("scalestep", scaleStep);
objectElem.SetBool("movesnap", moveSnap);
objectElem.SetBool("rotatesnap", rotateSnap);
objectElem.SetBool("scalesnap", scaleSnap);
objectElem.SetBool("applymateriallist", applyMaterialList);
objectElem.SetAttribute("importoptions", importOptions);
objectElem.SetInt("pickmode", pickMode);
objectElem.SetInt("axismode", axisMode);
objectElem.SetBool("revertonpause", revertOnPause);
resourcesElem.SetBool("rememberresourcepath", rememberResourcePath);
resourcesElem.SetAttribute("resourcepath", sceneResourcePath);
resourcesElem.SetAttribute("importpath", uiImportPath);
resourcesElem.SetAttribute("recentscenes", Join(uiRecentScenes, ";"));
if (renderer !is null && graphics !is null)
{
renderingElem.SetInt("texturequality", renderer.textureQuality);
renderingElem.SetInt("materialquality", renderer.materialQuality);
renderingElem.SetInt("shadowresolution", GetShadowResolution());
renderingElem.SetInt("maxoccludertriangles", renderer.maxOccluderTriangles);
renderingElem.SetBool("specularlighting", renderer.specularLighting);
// If Shader Model 3 is not supported, save the remembered instancing & quality settings instead of reduced settings
renderingElem.SetInt("shadowquality", graphics.sm3Support ? renderer.shadowQuality : shadowQualitySetting);
renderingElem.SetBool("dynamicinstancing", graphics.sm3Support ? renderer.dynamicInstancing : instancingSetting);
}
renderingElem.SetBool("framelimiter", engine.maxFps > 0);
uiElem.SetFloat("minopacity", uiMinOpacity);
uiElem.SetFloat("maxopacity", uiMaxOpacity);
hierarchyElem.SetBool("showinternaluielement", showInternalUIElement);
hierarchyElem.SetBool("showtemporaryobject", showTemporaryObject);
inspectorElem.SetColor("nodecolor", nodeTextColor);
inspectorElem.SetColor("componentcolor", componentTextColor);
inspectorElem.SetColor("originalcolor", normalTextColor);
inspectorElem.SetColor("modifiedcolor", modifiedTextColor);
inspectorElem.SetColor("noneditablecolor", nonEditableTextColor);
inspectorElem.SetBool("shownoneditable", showNonEditableAttribute);
viewElem.SetBool("showgrid", showGrid);
viewElem.SetBool("grid2dmode", grid2DMode);
viewElem.SetColor("defaultzoneambientcolor", renderer.defaultZone.ambientColor);
viewElem.SetColor("defaultzonefogcolor", renderer.defaultZone.fogColor);
viewElem.SetFloat("defaultzonefogstart", renderer.defaultZone.fogStart);
viewElem.SetFloat("defaultzonefogend", renderer.defaultZone.fogEnd);
viewElem.SetInt("gridsize", gridSize);
viewElem.SetInt("gridsubdivisions", gridSubdivisions);
viewElem.SetFloat("gridscale", gridScale);
viewElem.SetColor("gridcolor", gridColor);
viewElem.SetColor("gridsubdivisioncolor", gridSubdivisionColor);
consoleElem.SetAttribute("commandinterpreter", console.commandInterpreter);
config.Save(File(configFileName, FILE_WRITE));
}
void MakeBackup(const String&in fileName)
{
fileSystem.Rename(fileName, fileName + ".old");
}
void RemoveBackup(bool success, const String&in fileName)
{
if (success)
fileSystem.Delete(fileName + ".old");
}
|
// Urho3D editor
#include "Scripts/Editor/EditorHierarchyWindow.as"
#include "Scripts/Editor/EditorView.as"
#include "Scripts/Editor/EditorScene.as"
#include "Scripts/Editor/EditorActions.as"
#include "Scripts/Editor/EditorUIElement.as"
#include "Scripts/Editor/EditorGizmo.as"
#include "Scripts/Editor/EditorMaterial.as"
#include "Scripts/Editor/EditorSettings.as"
#include "Scripts/Editor/EditorPreferences.as"
#include "Scripts/Editor/EditorToolBar.as"
#include "Scripts/Editor/EditorSecondaryToolbar.as"
#include "Scripts/Editor/EditorUI.as"
#include "Scripts/Editor/EditorImport.as"
#include "Scripts/Editor/EditorResourceBrowser.as"
#include "Scripts/Editor/EditorSpawn.as"
String configFileName;
bool instancingSetting = true;
int shadowQualitySetting = 2;
void Start()
{
// Assign the value ASAP because configFileName is needed on exit, including exit on error
configFileName = fileSystem.GetAppPreferencesDir("urho3d", "Editor") + "Config.xml";
if (engine.headless)
{
ErrorDialog("Urho3D Editor", "Headless mode is not supported. The program will now exit.");
engine.Exit();
return;
}
// Use the first frame to setup when the resolution is initialized
SubscribeToEvent("Update", "FirstFrame");
SubscribeToEvent(input, "ExitRequested", "HandleExitRequested");
// Disable Editor auto exit, check first if it is OK to exit
engine.autoExit = false;
// Enable console commands from the editor script
script.defaultScriptFile = scriptFile;
// Enable automatic resource reloading
cache.autoReloadResources = true;
// Return resources which exist but failed to load due to error, so that we will not lose resource refs
cache.returnFailedResources = true;
// Use OS mouse without grabbing it
input.mouseVisible = true;
// Use system clipboard to allow transport of text in & out from the editor
ui.useSystemClipboard = true;
}
void FirstFrame()
{
// Create root scene node
CreateScene();
// Load editor settings and preferences
LoadConfig();
// Create user interface for the editor
CreateUI();
// Create root UI element where all 'editable' UI elements would be parented to
CreateRootUIElement();
// Load the initial scene if provided
ParseArguments();
// Switch to real frame handler after initialization
SubscribeToEvent("Update", "HandleUpdate");
}
void Stop()
{
SaveConfig();
}
void ParseArguments()
{
Array<String> arguments = GetArguments();
bool loaded = false;
// Scan for a scene to load
for (uint i = 1; i < arguments.length; ++i)
{
if (arguments[i].ToLower() == "-scene")
{
if (++i < arguments.length)
{
loaded = LoadScene(arguments[i]);
break;
}
}
}
if (!loaded)
ResetScene();
}
void HandleUpdate(StringHash eventType, VariantMap& eventData)
{
float timeStep = eventData["TimeStep"].GetFloat();
DoResourceBrowserWork();
UpdateView(timeStep);
UpdateViewports(timeStep);
UpdateStats(timeStep);
UpdateScene(timeStep);
UpdateTestAnimation(timeStep);
UpdateGizmo();
UpdateDirtyUI();
}
void LoadConfig()
{
if (!fileSystem.FileExists(configFileName))
return;
XMLFile config;
config.Load(File(configFileName, FILE_READ));
XMLElement configElem = config.root;
if (configElem.isNull)
return;
XMLElement cameraElem = configElem.GetChild("camera");
XMLElement objectElem = configElem.GetChild("object");
XMLElement renderingElem = configElem.GetChild("rendering");
XMLElement uiElem = configElem.GetChild("ui");
XMLElement hierarchyElem = configElem.GetChild("hierarchy");
XMLElement inspectorElem = configElem.GetChild("attributeinspector");
XMLElement viewElem = configElem.GetChild("view");
XMLElement resourcesElem = configElem.GetChild("resources");
XMLElement consoleElem = configElem.GetChild("console");
if (!cameraElem.isNull)
{
if (cameraElem.HasAttribute("nearclip")) viewNearClip = cameraElem.GetFloat("nearclip");
if (cameraElem.HasAttribute("farclip")) viewFarClip = cameraElem.GetFloat("farclip");
if (cameraElem.HasAttribute("fov")) viewFov = cameraElem.GetFloat("fov");
if (cameraElem.HasAttribute("speed")) cameraBaseSpeed = cameraElem.GetFloat("speed");
if (cameraElem.HasAttribute("limitrotation")) limitRotation = cameraElem.GetBool("limitrotation");
if (cameraElem.HasAttribute("mousewheelcameraposition")) mouseWheelCameraPosition = cameraElem.GetBool("mousewheelcameraposition");
if (cameraElem.HasAttribute("viewportmode")) viewportMode = cameraElem.GetUInt("viewportmode");
if (cameraElem.HasAttribute("mouseorbitmode")) mouseOrbitMode = cameraElem.GetInt("mouseorbitmode");
UpdateViewParameters();
}
if (!objectElem.isNull)
{
if (objectElem.HasAttribute("newnodedistance")) newNodeDistance = objectElem.GetFloat("newnodedistance");
if (objectElem.HasAttribute("movestep")) moveStep = objectElem.GetFloat("movestep");
if (objectElem.HasAttribute("rotatestep")) rotateStep = objectElem.GetFloat("rotatestep");
if (objectElem.HasAttribute("scalestep")) scaleStep = objectElem.GetFloat("scalestep");
if (objectElem.HasAttribute("movesnap")) moveSnap = objectElem.GetBool("movesnap");
if (objectElem.HasAttribute("rotatesnap")) rotateSnap = objectElem.GetBool("rotatesnap");
if (objectElem.HasAttribute("scalesnap")) scaleSnap = objectElem.GetBool("scalesnap");
if (objectElem.HasAttribute("applymateriallist")) applyMaterialList = objectElem.GetBool("applymateriallist");
if (objectElem.HasAttribute("importoptions")) importOptions = objectElem.GetAttribute("importoptions");
if (objectElem.HasAttribute("pickmode")) pickMode = objectElem.GetInt("pickmode");
if (objectElem.HasAttribute("axismode")) axisMode = AxisMode(objectElem.GetInt("axismode"));
if (objectElem.HasAttribute("revertonpause")) revertOnPause = objectElem.GetBool("revertonpause");
}
if (!resourcesElem.isNull)
{
if (resourcesElem.HasAttribute("rememberresourcepath")) rememberResourcePath = resourcesElem.GetBool("rememberresourcepath");
if (rememberResourcePath && resourcesElem.HasAttribute("resourcepath"))
{
String newResourcePath = resourcesElem.GetAttribute("resourcepath");
if (fileSystem.DirExists(newResourcePath))
SetResourcePath(resourcesElem.GetAttribute("resourcepath"), false);
}
if (resourcesElem.HasAttribute("importpath"))
{
String newImportPath = resourcesElem.GetAttribute("importpath");
if (fileSystem.DirExists(newImportPath))
uiImportPath = newImportPath;
}
if (resourcesElem.HasAttribute("recentscenes"))
{
uiRecentScenes = resourcesElem.GetAttribute("recentscenes").Split(';');
}
}
if (!renderingElem.isNull)
{
if (renderingElem.HasAttribute("texturequality")) renderer.textureQuality = renderingElem.GetInt("texturequality");
if (renderingElem.HasAttribute("materialquality")) renderer.materialQuality = renderingElem.GetInt("materialquality");
if (renderingElem.HasAttribute("shadowresolution")) SetShadowResolution(renderingElem.GetInt("shadowresolution"));
if (renderingElem.HasAttribute("shadowquality")) renderer.shadowQuality = shadowQualitySetting = renderingElem.GetInt("shadowquality");
if (renderingElem.HasAttribute("maxoccludertriangles")) renderer.maxOccluderTriangles = renderingElem.GetInt("maxoccludertriangles");
if (renderingElem.HasAttribute("specularlighting")) renderer.specularLighting = renderingElem.GetBool("specularlighting");
if (renderingElem.HasAttribute("dynamicinstancing")) renderer.dynamicInstancing = instancingSetting = renderingElem.GetBool("dynamicinstancing");
if (renderingElem.HasAttribute("framelimiter")) engine.maxFps = renderingElem.GetBool("framelimiter") ? 200 : 0;
}
if (!uiElem.isNull)
{
if (uiElem.HasAttribute("minopacity")) uiMinOpacity = uiElem.GetFloat("minopacity");
if (uiElem.HasAttribute("maxopacity")) uiMaxOpacity = uiElem.GetFloat("maxopacity");
}
if (!hierarchyElem.isNull)
{
if (hierarchyElem.HasAttribute("showinternaluielement")) showInternalUIElement = hierarchyElem.GetBool("showinternaluielement");
if (hierarchyElem.HasAttribute("showtemporaryobject")) showTemporaryObject = hierarchyElem.GetBool("showtemporaryobject");
if (inspectorElem.HasAttribute("nodecolor")) nodeTextColor = inspectorElem.GetColor("nodecolor");
if (inspectorElem.HasAttribute("componentcolor")) componentTextColor = inspectorElem.GetColor("componentcolor");
}
if (!inspectorElem.isNull)
{
if (inspectorElem.HasAttribute("originalcolor")) normalTextColor = inspectorElem.GetColor("originalcolor");
if (inspectorElem.HasAttribute("modifiedcolor")) modifiedTextColor = inspectorElem.GetColor("modifiedcolor");
if (inspectorElem.HasAttribute("noneditablecolor")) nonEditableTextColor = inspectorElem.GetColor("noneditablecolor");
if (inspectorElem.HasAttribute("shownoneditable")) showNonEditableAttribute = inspectorElem.GetBool("shownoneditable");
}
if (!viewElem.isNull)
{
if (viewElem.HasAttribute("defaultzoneambientcolor")) renderer.defaultZone.ambientColor = viewElem.GetColor("defaultzoneambientcolor");
if (viewElem.HasAttribute("defaultzonefogcolor")) renderer.defaultZone.fogColor = viewElem.GetColor("defaultzonefogcolor");
if (viewElem.HasAttribute("defaultzonefogstart")) renderer.defaultZone.fogStart = viewElem.GetInt("defaultzonefogstart");
if (viewElem.HasAttribute("defaultzonefogend")) renderer.defaultZone.fogEnd = viewElem.GetInt("defaultzonefogend");
if (viewElem.HasAttribute("showgrid")) showGrid = viewElem.GetBool("showgrid");
if (viewElem.HasAttribute("grid2dmode")) grid2DMode = viewElem.GetBool("grid2dmode");
if (viewElem.HasAttribute("gridsize")) gridSize = viewElem.GetInt("gridsize");
if (viewElem.HasAttribute("gridsubdivisions")) gridSubdivisions = viewElem.GetInt("gridsubdivisions");
if (viewElem.HasAttribute("gridscale")) gridScale = viewElem.GetFloat("gridscale");
if (viewElem.HasAttribute("gridcolor")) gridColor = viewElem.GetColor("gridcolor");
if (viewElem.HasAttribute("gridsubdivisioncolor")) gridSubdivisionColor = viewElem.GetColor("gridsubdivisioncolor");
}
if (!consoleElem.isNull)
{
// Console does not exist yet at this point, so store the string in a global variable
if (consoleElem.HasAttribute("commandinterpreter")) consoleCommandInterpreter = consoleElem.GetAttribute("commandinterpreter");
}
}
void SaveConfig()
{
XMLFile config;
XMLElement configElem = config.CreateRoot("configuration");
XMLElement cameraElem = configElem.CreateChild("camera");
XMLElement objectElem = configElem.CreateChild("object");
XMLElement renderingElem = configElem.CreateChild("rendering");
XMLElement uiElem = configElem.CreateChild("ui");
XMLElement hierarchyElem = configElem.CreateChild("hierarchy");
XMLElement inspectorElem = configElem.CreateChild("attributeinspector");
XMLElement viewElem = configElem.CreateChild("view");
XMLElement resourcesElem = configElem.CreateChild("resources");
XMLElement consoleElem = configElem.CreateChild("console");
cameraElem.SetFloat("nearclip", viewNearClip);
cameraElem.SetFloat("farclip", viewFarClip);
cameraElem.SetFloat("fov", viewFov);
cameraElem.SetFloat("speed", cameraBaseSpeed);
cameraElem.SetBool("limitrotation", limitRotation);
cameraElem.SetBool("mousewheelcameraposition", mouseWheelCameraPosition);
cameraElem.SetUInt("viewportmode", viewportMode);
cameraElem.SetInt("mouseorbitmode", mouseOrbitMode);
objectElem.SetFloat("newnodedistance", newNodeDistance);
objectElem.SetFloat("movestep", moveStep);
objectElem.SetFloat("rotatestep", rotateStep);
objectElem.SetFloat("scalestep", scaleStep);
objectElem.SetBool("movesnap", moveSnap);
objectElem.SetBool("rotatesnap", rotateSnap);
objectElem.SetBool("scalesnap", scaleSnap);
objectElem.SetBool("applymateriallist", applyMaterialList);
objectElem.SetAttribute("importoptions", importOptions);
objectElem.SetInt("pickmode", pickMode);
objectElem.SetInt("axismode", axisMode);
objectElem.SetBool("revertonpause", revertOnPause);
resourcesElem.SetBool("rememberresourcepath", rememberResourcePath);
resourcesElem.SetAttribute("resourcepath", sceneResourcePath);
resourcesElem.SetAttribute("importpath", uiImportPath);
resourcesElem.SetAttribute("recentscenes", Join(uiRecentScenes, ";"));
if (renderer !is null && graphics !is null)
{
renderingElem.SetInt("texturequality", renderer.textureQuality);
renderingElem.SetInt("materialquality", renderer.materialQuality);
renderingElem.SetInt("shadowresolution", GetShadowResolution());
renderingElem.SetInt("maxoccludertriangles", renderer.maxOccluderTriangles);
renderingElem.SetBool("specularlighting", renderer.specularLighting);
// If Shader Model 3 is not supported, save the remembered instancing & quality settings instead of reduced settings
renderingElem.SetInt("shadowquality", graphics.sm3Support ? renderer.shadowQuality : shadowQualitySetting);
renderingElem.SetBool("dynamicinstancing", graphics.sm3Support ? renderer.dynamicInstancing : instancingSetting);
}
renderingElem.SetBool("framelimiter", engine.maxFps > 0);
uiElem.SetFloat("minopacity", uiMinOpacity);
uiElem.SetFloat("maxopacity", uiMaxOpacity);
hierarchyElem.SetBool("showinternaluielement", showInternalUIElement);
hierarchyElem.SetBool("showtemporaryobject", showTemporaryObject);
inspectorElem.SetColor("nodecolor", nodeTextColor);
inspectorElem.SetColor("componentcolor", componentTextColor);
inspectorElem.SetColor("originalcolor", normalTextColor);
inspectorElem.SetColor("modifiedcolor", modifiedTextColor);
inspectorElem.SetColor("noneditablecolor", nonEditableTextColor);
inspectorElem.SetBool("shownoneditable", showNonEditableAttribute);
viewElem.SetBool("showgrid", showGrid);
viewElem.SetBool("grid2dmode", grid2DMode);
viewElem.SetColor("defaultzoneambientcolor", renderer.defaultZone.ambientColor);
viewElem.SetColor("defaultzonefogcolor", renderer.defaultZone.fogColor);
viewElem.SetFloat("defaultzonefogstart", renderer.defaultZone.fogStart);
viewElem.SetFloat("defaultzonefogend", renderer.defaultZone.fogEnd);
viewElem.SetInt("gridsize", gridSize);
viewElem.SetInt("gridsubdivisions", gridSubdivisions);
viewElem.SetFloat("gridscale", gridScale);
viewElem.SetColor("gridcolor", gridColor);
viewElem.SetColor("gridsubdivisioncolor", gridSubdivisionColor);
consoleElem.SetAttribute("commandinterpreter", console.commandInterpreter);
config.Save(File(configFileName, FILE_WRITE));
}
void MakeBackup(const String&in fileName)
{
fileSystem.Rename(fileName, fileName + ".old");
}
void RemoveBackup(bool success, const String&in fileName)
{
if (success)
fileSystem.Delete(fileName + ".old");
}
|
Remove duplicated call of UpdateViewParameters.[ci skip]
|
Remove duplicated call of UpdateViewParameters.[ci skip]
|
ActionScript
|
mit
|
bacsmar/Urho3D,eugeneko/Urho3D,victorholt/Urho3D,victorholt/Urho3D,henu/Urho3D,luveti/Urho3D,tommy3/Urho3D,codedash64/Urho3D,MonkeyFirst/Urho3D,299299/Urho3D,weitjong/Urho3D,MeshGeometry/Urho3D,SuperWangKai/Urho3D,rokups/Urho3D,SirNate0/Urho3D,PredatorMF/Urho3D,rokups/Urho3D,kostik1337/Urho3D,codedash64/Urho3D,MonkeyFirst/Urho3D,abdllhbyrktr/Urho3D,luveti/Urho3D,helingping/Urho3D,victorholt/Urho3D,tommy3/Urho3D,luveti/Urho3D,c4augustus/Urho3D,orefkov/Urho3D,fire/Urho3D-1,kostik1337/Urho3D,299299/Urho3D,fire/Urho3D-1,299299/Urho3D,kostik1337/Urho3D,codedash64/Urho3D,xiliu98/Urho3D,codemon66/Urho3D,henu/Urho3D,fire/Urho3D-1,c4augustus/Urho3D,codedash64/Urho3D,299299/Urho3D,victorholt/Urho3D,helingping/Urho3D,iainmerrick/Urho3D,SirNate0/Urho3D,c4augustus/Urho3D,carnalis/Urho3D,MeshGeometry/Urho3D,urho3d/Urho3D,bacsmar/Urho3D,codemon66/Urho3D,rokups/Urho3D,MonkeyFirst/Urho3D,tommy3/Urho3D,luveti/Urho3D,MonkeyFirst/Urho3D,cosmy1/Urho3D,fire/Urho3D-1,carnalis/Urho3D,carnalis/Urho3D,iainmerrick/Urho3D,abdllhbyrktr/Urho3D,c4augustus/Urho3D,henu/Urho3D,SirNate0/Urho3D,helingping/Urho3D,weitjong/Urho3D,weitjong/Urho3D,SuperWangKai/Urho3D,urho3d/Urho3D,victorholt/Urho3D,orefkov/Urho3D,SirNate0/Urho3D,PredatorMF/Urho3D,MeshGeometry/Urho3D,weitjong/Urho3D,codedash64/Urho3D,kostik1337/Urho3D,abdllhbyrktr/Urho3D,carnalis/Urho3D,eugeneko/Urho3D,MeshGeometry/Urho3D,codemon66/Urho3D,weitjong/Urho3D,SuperWangKai/Urho3D,tommy3/Urho3D,PredatorMF/Urho3D,rokups/Urho3D,299299/Urho3D,fire/Urho3D-1,orefkov/Urho3D,carnalis/Urho3D,henu/Urho3D,cosmy1/Urho3D,abdllhbyrktr/Urho3D,orefkov/Urho3D,cosmy1/Urho3D,299299/Urho3D,henu/Urho3D,PredatorMF/Urho3D,helingping/Urho3D,xiliu98/Urho3D,cosmy1/Urho3D,iainmerrick/Urho3D,iainmerrick/Urho3D,kostik1337/Urho3D,abdllhbyrktr/Urho3D,luveti/Urho3D,bacsmar/Urho3D,MonkeyFirst/Urho3D,c4augustus/Urho3D,codemon66/Urho3D,helingping/Urho3D,iainmerrick/Urho3D,codemon66/Urho3D,eugeneko/Urho3D,xiliu98/Urho3D,eugeneko/Urho3D,MeshGeometry/Urho3D,cosmy1/Urho3D,SuperWangKai/Urho3D,SirNate0/Urho3D,urho3d/Urho3D,SuperWangKai/Urho3D,rokups/Urho3D,rokups/Urho3D,urho3d/Urho3D,xiliu98/Urho3D,bacsmar/Urho3D,tommy3/Urho3D,xiliu98/Urho3D
|
63181c6fc13b472720fd07a414982c0e7e08ca4b
|
src/as/com/threerings/util/Config.as
|
src/as/com/threerings/util/Config.as
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util {
import flash.events.NetStatusEvent;
import flash.events.EventDispatcher;
import flash.net.SharedObject;
import flash.net.SharedObjectFlushStatus;
/**
* Dispatched when this Config object has a value set on it.
*
* @eventType com.threerings.util.ConfigValueSetEvent.CONFIG_VALUE_SET
*/
[Event(name="ConfigValSet", type="com.threerings.util.ConfigValueSetEvent")]
public class Config extends EventDispatcher
{
/**
* Constructs a new config object which will obtain configuration
* information from the specified path.
*/
public function Config (path :String)
{
_so = SharedObject.getLocal("config_" + path, "/");
}
/**
* Fetches and returns the value for the specified configuration property.
*/
public function getValue (name :String, defValue :Object) :Object
{
var val :* = _so.data[name];
return (val === undefined) ? defValue : val;
}
/**
* Returns the value specified.
*/
public function setValue (name :String, value :Object) :void
{
_so.data[name] = value;
_so.flush(); // flushing is not strictly necessary
// dispatch an event corresponding
dispatchEvent(new ConfigValueSetEvent(name, value));
}
/**
* Remove any set value for the specified preference.
*/
public function remove (name :String) :void
{
delete _so.data[name];
_so.flush(); // flushing is not strictly necessary
}
/**
* Ensure that we can store preferences up to the specified size.
* Note that calling this method may pop up a dialog to the user, asking
* them if it's ok to increase the capacity. The result listener may
* never be called if the user doesn't answer the pop-up.
*
* @param rl an optional listener that will be informed as to whether
* the request succeeded.
*/
public function ensureCapacity (kilobytes :int, rl :ResultListener) :void
{
// flush with the size, see if we're cool
var result :String = _so.flush(1024 * kilobytes);
if (rl == null) {
return;
}
// success
if (result == SharedObjectFlushStatus.FLUSHED) {
rl.requestCompleted(this);
return;
}
// otherwise we'll hear back in a sec
var thisConfig :Config = this;
var listener :Function = function (evt :NetStatusEvent) :void {
// TODO: There is a bug where the status is always
// "SharedObject.Flush.Failed", even on success, if the request
// was for a large enough storage that the player calls it
// "unlimited".
trace("================[" + evt.info.code + "]");
if ("SharedObject.Flush.Success" == evt.info.code) {
rl.requestCompleted(thisConfig);
} else {
rl.requestFailed(new Error(String(evt.info.code)));
}
_so.removeEventListener(NetStatusEvent.NET_STATUS, listener);
};
_so.addEventListener(NetStatusEvent.NET_STATUS, listener);
}
/** The shared object that contains our preferences. */
protected var _so :SharedObject;
}
}
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util {
import flash.events.NetStatusEvent;
import flash.events.EventDispatcher;
import flash.net.SharedObject;
import flash.net.SharedObjectFlushStatus;
/**
* Dispatched when this Config object has a value set on it.
*
* @eventType com.threerings.util.ConfigValueSetEvent.CONFIG_VALUE_SET
*/
[Event(name="ConfigValSet", type="com.threerings.util.ConfigValueSetEvent")]
public class Config extends EventDispatcher
{
/**
* Constructs a new config object which will obtain configuration
* information from the specified path.
*/
public function Config (path :String)
{
setPath(path);
}
public function setPath (path :String) :void
{
_so = (path == null) ? null : SharedObject.getLocal("config_" + path, "/");
_data = (_so == null) ? {} : _so.data;
// dispatch events for all settings
for (var n :String in _data) {
dispatchEvent(new ConfigValueSetEvent(n, _data[n]));
}
}
/**
* Fetches and returns the value for the specified configuration property.
*/
public function getValue (name :String, defValue :Object) :Object
{
var val :* = _data[name];
return (val === undefined) ? defValue : val;
}
/**
* Returns the value specified.
*/
public function setValue (name :String, value :Object) :void
{
_data[name] = value;
if (_so != null) {
_so.flush(); // flushing is not strictly necessary
}
// dispatch an event corresponding
dispatchEvent(new ConfigValueSetEvent(name, value));
}
/**
* Remove any set value for the specified preference.
* This does not dispatch an event because this would only be done to remove an
* obsolete preference.
*/
public function remove (name :String) :void
{
delete _data[name];
if (_so != null) {
_so.flush(); // flushing is not strictly necessary
}
}
/**
* Ensure that we can store preferences up to the specified size.
* Note that calling this method may pop up a dialog to the user, asking
* them if it's ok to increase the capacity. The result listener may
* never be called if the user doesn't answer the pop-up.
*
* @param rl an optional listener that will be informed as to whether
* the request succeeded.
*/
public function ensureCapacity (kilobytes :int, rl :ResultListener) :void
{
if (_so == null) {
if (rl != null) {
rl.requestCompleted(this);
}
return;
}
// flush with the size, see if we're cool
var result :String = _so.flush(1024 * kilobytes);
if (rl == null) {
return;
}
// success
if (result == SharedObjectFlushStatus.FLUSHED) {
rl.requestCompleted(this);
return;
}
// otherwise we'll hear back in a sec
var thisConfig :Config = this;
var listener :Function = function (evt :NetStatusEvent) :void {
// TODO: There is a bug where the status is always
// "SharedObject.Flush.Failed", even on success, if the request
// was for a large enough storage that the player calls it
// "unlimited".
trace("================[" + evt.info.code + "]");
if ("SharedObject.Flush.Success" == evt.info.code) {
rl.requestCompleted(thisConfig);
} else {
rl.requestFailed(new Error(String(evt.info.code)));
}
_so.removeEventListener(NetStatusEvent.NET_STATUS, listener);
};
_so.addEventListener(NetStatusEvent.NET_STATUS, listener);
}
/** The shared object that contains our preferences. */
protected var _so :SharedObject;
/** The object in which we store things, usually _so.data. */
protected var _data :Object;
}
}
|
Allow to be constructed in, and flipped between, storing preferences or just providing a runtime place for them to live.
|
Allow to be constructed in, and flipped between, storing
preferences or just providing a runtime place for them to live.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5671 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
ba78c2cad9b757ac22a23eb71a6b46cd3eb61c19
|
src/aerys/minko/type/clone/CloneOptions.as
|
src/aerys/minko/type/clone/CloneOptions.as
|
package aerys.minko.type.clone
{
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.controller.AnimationController;
import aerys.minko.scene.controller.TransformController;
import aerys.minko.scene.controller.camera.CameraController;
import aerys.minko.scene.controller.light.DirectionalLightController;
import aerys.minko.scene.controller.light.LightController;
import aerys.minko.scene.controller.light.PointLightController;
import aerys.minko.scene.controller.light.SpotLightController;
import aerys.minko.scene.controller.mesh.MeshController;
import aerys.minko.scene.controller.mesh.MeshVisibilityController;
import aerys.minko.scene.controller.mesh.skinning.SkinningController;
public final class CloneOptions
{
private var _clonedControllerTypes : Vector.<Class>;
private var _ignoredControllerTypes : Vector.<Class>;
private var _reassignedControllerTypes : Vector.<Class>;
private var _defaultControllerAction : uint;
public function get defaultControllerAction() : uint
{
return _defaultControllerAction;
}
public function set defaultControllerAction(v : uint) : void
{
if (v != ControllerCloneAction.CLONE
&& v != ControllerCloneAction.IGNORE
&& v != ControllerCloneAction.REASSIGN)
throw new Error('Unknown action type.');
_defaultControllerAction = v;
}
public function CloneOptions()
{
initialize();
}
private function initialize() : void
{
_clonedControllerTypes = new <Class>[];
_ignoredControllerTypes = new <Class>[];
_reassignedControllerTypes = new <Class>[];
_defaultControllerAction = ControllerCloneAction.REASSIGN;
}
public static function get defaultOptions() : CloneOptions
{
var cloneOptions : CloneOptions = new CloneOptions();
cloneOptions._clonedControllerTypes.push(
AnimationController,
SkinningController
);
cloneOptions._ignoredControllerTypes.push(
MeshController,
MeshVisibilityController,
CameraController,
TransformController,
LightController,
DirectionalLightController,
SpotLightController,
PointLightController
);
cloneOptions._defaultControllerAction = ControllerCloneAction.REASSIGN;
return cloneOptions;
}
public static function get cloneAllOptions() : CloneOptions
{
var cloneOptions : CloneOptions = new CloneOptions();
cloneOptions._ignoredControllerTypes.push(
MeshController,
MeshVisibilityController,
CameraController,
TransformController,
LightController,
DirectionalLightController,
SpotLightController,
PointLightController
);
cloneOptions._defaultControllerAction = ControllerCloneAction.CLONE;
return cloneOptions;
}
public function setActionForControllerClass(controllerClass : Class,
action : uint) : CloneOptions
{
var index : int = 0;
if ((index = _clonedControllerTypes.indexOf(controllerClass)) >= 0)
_clonedControllerTypes.splice(index, 1);
else if ((index = _ignoredControllerTypes.indexOf(controllerClass)) >= 0)
_ignoredControllerTypes.splice(index, 1);
else if ((index = _reassignedControllerTypes.indexOf(controllerClass)) >= 0)
_reassignedControllerTypes.splice(index, 1);
switch (action)
{
case ControllerCloneAction.CLONE:
_clonedControllerTypes.push(controllerClass);
break;
case ControllerCloneAction.IGNORE:
_ignoredControllerTypes.push(controllerClass);
break;
case ControllerCloneAction.REASSIGN:
_reassignedControllerTypes.push(controllerClass);
break;
default:
throw new Error('Unknown action type.');
}
return this;
}
public function getActionForController(controller : AbstractController) : uint
{
var numControllersToClone : uint = _clonedControllerTypes.length;
var numControllersToIgnore : uint = _ignoredControllerTypes.length;
var numControllersToReassign : uint = _reassignedControllerTypes.length;
var controllerId : uint;
for (controllerId = 0; controllerId < numControllersToClone; ++controllerId)
if (controller is _clonedControllerTypes[controllerId])
return ControllerCloneAction.CLONE;
for (controllerId = 0; controllerId < numControllersToIgnore; ++controllerId)
if (controller is _ignoredControllerTypes[controllerId])
return ControllerCloneAction.IGNORE;
for (controllerId = 0; controllerId < numControllersToReassign; ++controllerId)
if (controller is _reassignedControllerTypes[controllerId])
return ControllerCloneAction.REASSIGN;
return _defaultControllerAction;
}
}
}
|
package aerys.minko.type.clone
{
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.controller.animation.AnimationController;
import aerys.minko.scene.controller.TransformController;
import aerys.minko.scene.controller.camera.CameraController;
import aerys.minko.scene.controller.light.DirectionalLightController;
import aerys.minko.scene.controller.light.LightController;
import aerys.minko.scene.controller.light.PointLightController;
import aerys.minko.scene.controller.light.SpotLightController;
import aerys.minko.scene.controller.mesh.MeshController;
import aerys.minko.scene.controller.mesh.MeshVisibilityController;
import aerys.minko.scene.controller.mesh.skinning.SkinningController;
public final class CloneOptions
{
private var _clonedControllerTypes : Vector.<Class>;
private var _ignoredControllerTypes : Vector.<Class>;
private var _reassignedControllerTypes : Vector.<Class>;
private var _defaultControllerAction : uint;
public function get defaultControllerAction() : uint
{
return _defaultControllerAction;
}
public function set defaultControllerAction(v : uint) : void
{
if (v != ControllerCloneAction.CLONE
&& v != ControllerCloneAction.IGNORE
&& v != ControllerCloneAction.REASSIGN)
throw new Error('Unknown action type.');
_defaultControllerAction = v;
}
public function CloneOptions()
{
initialize();
}
private function initialize() : void
{
_clonedControllerTypes = new <Class>[];
_ignoredControllerTypes = new <Class>[];
_reassignedControllerTypes = new <Class>[];
_defaultControllerAction = ControllerCloneAction.REASSIGN;
}
public static function get defaultOptions() : CloneOptions
{
var cloneOptions : CloneOptions = new CloneOptions();
cloneOptions._clonedControllerTypes.push(
AnimationController,
SkinningController
);
cloneOptions._ignoredControllerTypes.push(
MeshController,
MeshVisibilityController,
CameraController,
TransformController,
LightController,
DirectionalLightController,
SpotLightController,
PointLightController
);
cloneOptions._defaultControllerAction = ControllerCloneAction.REASSIGN;
return cloneOptions;
}
public static function get cloneAllOptions() : CloneOptions
{
var cloneOptions : CloneOptions = new CloneOptions();
cloneOptions._ignoredControllerTypes.push(
MeshController,
MeshVisibilityController,
CameraController,
TransformController,
LightController,
DirectionalLightController,
SpotLightController,
PointLightController
);
cloneOptions._defaultControllerAction = ControllerCloneAction.CLONE;
return cloneOptions;
}
public function setActionForControllerClass(controllerClass : Class,
action : uint) : CloneOptions
{
var index : int = 0;
if ((index = _clonedControllerTypes.indexOf(controllerClass)) >= 0)
_clonedControllerTypes.splice(index, 1);
else if ((index = _ignoredControllerTypes.indexOf(controllerClass)) >= 0)
_ignoredControllerTypes.splice(index, 1);
else if ((index = _reassignedControllerTypes.indexOf(controllerClass)) >= 0)
_reassignedControllerTypes.splice(index, 1);
switch (action)
{
case ControllerCloneAction.CLONE:
_clonedControllerTypes.push(controllerClass);
break;
case ControllerCloneAction.IGNORE:
_ignoredControllerTypes.push(controllerClass);
break;
case ControllerCloneAction.REASSIGN:
_reassignedControllerTypes.push(controllerClass);
break;
default:
throw new Error('Unknown action type.');
}
return this;
}
public function getActionForController(controller : AbstractController) : uint
{
var numControllersToClone : uint = _clonedControllerTypes.length;
var numControllersToIgnore : uint = _ignoredControllerTypes.length;
var numControllersToReassign : uint = _reassignedControllerTypes.length;
var controllerId : uint;
for (controllerId = 0; controllerId < numControllersToClone; ++controllerId)
if (controller is _clonedControllerTypes[controllerId])
return ControllerCloneAction.CLONE;
for (controllerId = 0; controllerId < numControllersToIgnore; ++controllerId)
if (controller is _ignoredControllerTypes[controllerId])
return ControllerCloneAction.IGNORE;
for (controllerId = 0; controllerId < numControllersToReassign; ++controllerId)
if (controller is _reassignedControllerTypes[controllerId])
return ControllerCloneAction.REASSIGN;
return _defaultControllerAction;
}
}
}
|
fix broken import of AnimationController
|
fix broken import of AnimationController
|
ActionScript
|
mit
|
aerys/minko-as3
|
efe03e7a6ae20d6ce0348c92d1f42368a335e797
|
src/flash/src/Moxie.as
|
src/flash/src/Moxie.as
|
package
{
import com.*;
import com.errors.RuntimeError;
import com.events.*;
import flash.display.LoaderInfo;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.ProgressEvent;
import flash.external.ExternalInterface;
import flash.system.ApplicationDomain;
import flash.system.Security;
import flash.utils.*;
import mxi.Extend;
import mxi.Utils;
import mxi.events.ODataEvent;
import mxi.events.OErrorEvent;
import mxi.events.OProgressEvent;
[SWF(width='500', height='500')]
public class Moxie extends Sprite
{
public static var uid:String;
private var eventDispatcher:String = "moxie.core.EventTarget.instance.dispatchEvent";
public static var compFactory:ComponentFactory;
public static var stageOccupied:Boolean = false; // whether a display facility is already occupied
/**
* Main constructor for the Plupload class.
*/
public function Moxie()
{
if (stage) {
_init();
} else {
addEventListener(Event.ADDED_TO_STAGE, init);
}
}
/**
* Initialization event handler.
*
* @param e Event object.
*/
private function _init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, _init);
// Allow scripting on swf loaded from another domain
if (MXI::EnableCSS) {
Security.allowDomain("*");
}
// Align and scale stage
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.EXACT_FIT;
// use only FlashVars, ignore QueryString
var params:Object, url:String, urlParts:Object, pos:int, query:Object;
params = root.loaderInfo.parameters;
pos = root.loaderInfo.url.indexOf('?');
if (pos !== -1) {
query = Utils.parseStr(root.loaderInfo.url.substr(pos + 1));
for (var key:String in params) {
if (query.hasOwnProperty(Utils.trim(key))) {
delete params[key];
}
}
}
// Setup id
if (!params.hasOwnProperty("uid")) {
return; // we do not have uid, so we cannot fire error event - lets simply wait until it timeouts
}
Moxie.uid = Utils.sanitize(params["uid"]);
// Event dispatcher
if (params.hasOwnProperty("target") && /^[\w\.]+$/.test(params["target"])) {
eventDispatcher = params["target"];
}
//ExternalInterface.marshallExceptions = true; // propagate AS exceptions to JS and vice-versa
ExternalInterface.addCallback('exec', exec);
ExternalInterface.addCallback('isOccupied', isOccupied);
// initialize component factory
Moxie.compFactory = new ComponentFactory;
_fireEvent(Moxie.uid + "::Init");
}
public function exec(uid:String, compName:String, action:String, args:* = null) : *
{
// Moxie.log([uid, compName, action, args]);
uid = Utils.sanitize(uid); // make it safe
var comp:* = Moxie.compFactory.get(uid);
// Moxie.log([compName, action]);
try {
// initialize corresponding com
if (!comp) {
comp = Moxie.compFactory.create(this, uid, compName);
}
// execute the action if available
if (comp.hasOwnProperty(action)) {
return comp[action].apply(comp, args as Array);
}
} catch(err:*) { // re-route exceptions thrown by components (TODO: check marshallExceptions feature)
_fireEvent(Moxie.uid + "::Exception", {
name: err.name,
code: err.errorID,
message: compName + "::" + action
});
}
}
public function isOccupied() : Boolean {
return Moxie.stageOccupied;
}
/**
* Intercept component events and do some operations if required
*
* @param uid String unique identifier of the component throwing the event
* @param e mixed Event object
* @param exType String event type in mOxie format
*/
public function onComponentEvent(uid:String, e:*, exType:String) : void
{
var evt:Object = {};
var data:* = e.hasOwnProperty('data') ? e.data : null;
switch (e.type)
{
case ProgressEvent.PROGRESS:
case OProgressEvent.PROGRESS:
evt.loaded = e.bytesLoaded;
evt.total = e.bytesTotal;
break;
case OErrorEvent.ERROR:
data = e.code;
break;
}
evt.type = [uid, exType].join('::');
_fireEvent(evt, data);
}
/**
* Fires an event from the flash movie out to the page level JS.
*
* @param uid String unique identifier of the component throwing the event
* @param type Name of event to fire.
* @param obj Object with optional data.
*/
private function _fireEvent(evt:*, obj:* = null):void {
try {
ExternalInterface.call(eventDispatcher, evt, obj);
} catch(err:*) {
//_fireEvent("Exception", { name: 'RuntimeError', message: 4 });
// throwing an exception would be better here
}
}
public static function log(obj:*) : void {
ExternalInterface.call('console.info', obj);
}
}
}
|
package
{
import com.*;
import com.errors.RuntimeError;
import com.events.*;
import flash.display.LoaderInfo;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.ProgressEvent;
import flash.external.ExternalInterface;
import flash.system.ApplicationDomain;
import flash.system.Security;
import flash.utils.*;
import mxi.Extend;
import mxi.Utils;
import mxi.events.ODataEvent;
import mxi.events.OErrorEvent;
import mxi.events.OProgressEvent;
[SWF(width='500', height='500')]
public class Moxie extends Sprite
{
public static var uid:String;
private var eventDispatcher:String = "moxie.core.EventTarget.instance.dispatchEvent";
public static var compFactory:ComponentFactory;
public static var stageOccupied:Boolean = false; // whether a display facility is already occupied
/**
* Main constructor for the Plupload class.
*/
public function Moxie()
{
if (stage) {
_init();
} else {
addEventListener(Event.ADDED_TO_STAGE, init);
}
}
/**
* Initialization event handler.
*
* @param e Event object.
*/
private function _init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, _init);
// Allow scripting on swf loaded from another domain
if (MXI::EnableCSS) {
Security.allowDomain("*");
}
// Align and scale stage
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.EXACT_FIT;
// use only FlashVars, ignore QueryString
var params:Object, url:String, urlParts:Object, pos:int, query:Object;
params = root.loaderInfo.parameters;
pos = root.loaderInfo.url.indexOf('?');
if (pos !== -1) {
return; // we do not allow anything from query sring, so if there's anything, we - quit
}
// Setup id
if (!params.hasOwnProperty("uid")) {
return; // we do not have uid, so we cannot fire error event - lets simply wait until it timeouts
}
Moxie.uid = Utils.sanitize(params["uid"]);
// Event dispatcher
if (params.hasOwnProperty("target") && /^[\w\.]+$/.test(params["target"])) {
eventDispatcher = params["target"];
}
//ExternalInterface.marshallExceptions = true; // propagate AS exceptions to JS and vice-versa
ExternalInterface.addCallback('exec', exec);
ExternalInterface.addCallback('isOccupied', isOccupied);
// initialize component factory
Moxie.compFactory = new ComponentFactory;
_fireEvent(Moxie.uid + "::Init");
}
public function exec(uid:String, compName:String, action:String, args:* = null) : *
{
// Moxie.log([uid, compName, action, args]);
uid = Utils.sanitize(uid); // make it safe
var comp:* = Moxie.compFactory.get(uid);
// Moxie.log([compName, action]);
try {
// initialize corresponding com
if (!comp) {
comp = Moxie.compFactory.create(this, uid, compName);
}
// execute the action if available
if (comp.hasOwnProperty(action)) {
return comp[action].apply(comp, args as Array);
}
} catch(err:*) { // re-route exceptions thrown by components (TODO: check marshallExceptions feature)
_fireEvent(Moxie.uid + "::Exception", {
name: err.name,
code: err.errorID,
message: compName + "::" + action
});
}
}
public function isOccupied() : Boolean {
return Moxie.stageOccupied;
}
/**
* Intercept component events and do some operations if required
*
* @param uid String unique identifier of the component throwing the event
* @param e mixed Event object
* @param exType String event type in mOxie format
*/
public function onComponentEvent(uid:String, e:*, exType:String) : void
{
var evt:Object = {};
var data:* = e.hasOwnProperty('data') ? e.data : null;
switch (e.type)
{
case ProgressEvent.PROGRESS:
case OProgressEvent.PROGRESS:
evt.loaded = e.bytesLoaded;
evt.total = e.bytesTotal;
break;
case OErrorEvent.ERROR:
data = e.code;
break;
}
evt.type = [uid, exType].join('::');
_fireEvent(evt, data);
}
/**
* Fires an event from the flash movie out to the page level JS.
*
* @param uid String unique identifier of the component throwing the event
* @param type Name of event to fire.
* @param obj Object with optional data.
*/
private function _fireEvent(evt:*, obj:* = null):void {
try {
ExternalInterface.call(eventDispatcher, evt, obj);
} catch(err:*) {
//_fireEvent("Exception", { name: 'RuntimeError', message: 4 });
// throwing an exception would be better here
}
}
public static function log(obj:*) : void {
ExternalInterface.call('console.info', obj);
}
}
}
|
Address the problem with arguments from query string.
|
Flash: Address the problem with arguments from query string.
|
ActionScript
|
agpl-3.0
|
moxiecode/moxie,moxiecode/moxie,moxiecode/moxie,moxiecode/moxie
|
47388cac329edc12b6a57798a59f27b37b2923b1
|
exporter/src/main/as/flump/xfl/XflLayer.as
|
exporter/src/main/as/flump/xfl/XflLayer.as
|
//
// Flump - Copyright 2013 Flump Authors
package flump.xfl {
import aspire.util.XmlUtil;
import flump.mold.KeyframeMold;
import flump.mold.LayerMold;
public class XflLayer
{
public static const NAME :String = "name";
public static const TYPE :String = "layerType";
public static const TYPE_GUIDE :String = "guide";
public static const TYPE_FOLDER :String = "folder";
public static const TYPE_MASK :String = "mask";
use namespace xflns;
public static function parse (lib :XflLibrary, baseLocation :String, xml :XML, flipbook :Boolean) :LayerMold {
const layer :LayerMold = new LayerMold();
layer.name = XmlUtil.getStringAttr(xml, NAME);
layer.flipbook = flipbook;
// mask
if (mask!=null) layer.mask = mask;
const location :String = baseLocation + ":" + layer.name;
var frameXmlList :XMLList = xml.frames.DOMFrame;
for each (var frameXml :XML in frameXmlList) {
layer.keyframes.push(XflKeyframe.parse(lib, location, frameXml, flipbook));
}
if (layer.keyframes.length == 0) lib.addError(location, ParseError.INFO, "No keyframes on layer");
var ii :int;
var kf :KeyframeMold;
var nextKf :KeyframeMold;
// normalize skews, so that we always skew the shortest distance between
// two angles (we don't want to skew more than Math.PI)
for (ii = 0; ii < layer.keyframes.length - 1; ++ii) {
kf = layer.keyframes[ii];
nextKf = layer.keyframes[ii+1];
frameXml = frameXmlList[ii];
if (kf.skewX + Math.PI < nextKf.skewX) {
nextKf.skewX += -Math.PI * 2;
} else if (kf.skewX - Math.PI > nextKf.skewX) {
nextKf.skewX += Math.PI * 2;
}
if (kf.skewY + Math.PI < nextKf.skewY) {
nextKf.skewY += -Math.PI * 2;
} else if (kf.skewY - Math.PI > nextKf.skewY) {
nextKf.skewY += Math.PI * 2;
}
}
// apply additional rotations
var additionalRotation :Number = 0;
for (ii = 0; ii < layer.keyframes.length - 1; ++ii) {
kf = layer.keyframes[ii];
nextKf = layer.keyframes[ii+1];
frameXml = frameXmlList[ii];
var motionTweenRotate :String = XmlUtil.getStringAttr(frameXml,
XflKeyframe.MOTION_TWEEN_ROTATE, XflKeyframe.MOTION_TWEEN_ROTATE_NONE);
// If a direction is specified, take it into account
if (motionTweenRotate != XflKeyframe.MOTION_TWEEN_ROTATE_NONE) {
var direction :Number = (motionTweenRotate == XflKeyframe.MOTION_TWEEN_ROTATE_CLOCKWISE ? 1 : -1);
// negative scales affect rotation direction
direction *= sign(nextKf.scaleX) * sign(nextKf.scaleY);
while (direction < 0 && kf.skewX < nextKf.skewX) {
nextKf.skewX -= Math.PI * 2;
}
while (direction > 0 && kf.skewX > nextKf.skewX) {
nextKf.skewX += Math.PI * 2;
}
while (direction < 0 && kf.skewY < nextKf.skewY) {
nextKf.skewY -= Math.PI * 2;
}
while (direction > 0 && kf.skewY > nextKf.skewY) {
nextKf.skewY += Math.PI * 2;
}
// additional rotations specified?
var motionTweenRotateTimes :Number =
XmlUtil.getNumberAttr(frameXml, XflKeyframe.MOTION_TWEEN_ROTATE_TIMES, 0);
var thisRotation :Number = motionTweenRotateTimes * Math.PI * 2 * direction;
additionalRotation += thisRotation;
}
nextKf.rotate(additionalRotation);
}
return layer;
}
protected static function sign (n :Number) :Number {
return (n > 0 ? 1 : (n < 0 ? -1 : 0));
}
}
}
|
//
// Flump - Copyright 2013 Flump Authors
package flump.xfl {
import aspire.util.XmlUtil;
import flump.mold.KeyframeMold;
import flump.mold.LayerMold;
public class XflLayer
{
public static const NAME :String = "name";
public static const TYPE :String = "layerType";
public static const TYPE_GUIDE :String = "guide";
public static const TYPE_FOLDER :String = "folder";
public static const TYPE_MASK :String = "mask";
use namespace xflns;
public static function parse (lib :XflLibrary, baseLocation :String, xml :XML, flipbook :Boolean,mask:String=null) :LayerMold {
const layer :LayerMold = new LayerMold();
layer.name = XmlUtil.getStringAttr(xml, NAME);
layer.flipbook = flipbook;
// mask
if (mask!=null) layer.mask = mask;
const location :String = baseLocation + ":" + layer.name;
var frameXmlList :XMLList = xml.frames.DOMFrame;
for each (var frameXml :XML in frameXmlList) {
layer.keyframes.push(XflKeyframe.parse(lib, location, frameXml, flipbook));
}
if (layer.keyframes.length == 0) lib.addError(location, ParseError.INFO, "No keyframes on layer");
var ii :int;
var kf :KeyframeMold;
var nextKf :KeyframeMold;
// normalize skews, so that we always skew the shortest distance between
// two angles (we don't want to skew more than Math.PI)
for (ii = 0; ii < layer.keyframes.length - 1; ++ii) {
kf = layer.keyframes[ii];
nextKf = layer.keyframes[ii+1];
frameXml = frameXmlList[ii];
if (kf.skewX + Math.PI < nextKf.skewX) {
nextKf.skewX += -Math.PI * 2;
} else if (kf.skewX - Math.PI > nextKf.skewX) {
nextKf.skewX += Math.PI * 2;
}
if (kf.skewY + Math.PI < nextKf.skewY) {
nextKf.skewY += -Math.PI * 2;
} else if (kf.skewY - Math.PI > nextKf.skewY) {
nextKf.skewY += Math.PI * 2;
}
}
// apply additional rotations
var additionalRotation :Number = 0;
for (ii = 0; ii < layer.keyframes.length - 1; ++ii) {
kf = layer.keyframes[ii];
nextKf = layer.keyframes[ii+1];
frameXml = frameXmlList[ii];
var motionTweenRotate :String = XmlUtil.getStringAttr(frameXml,
XflKeyframe.MOTION_TWEEN_ROTATE, XflKeyframe.MOTION_TWEEN_ROTATE_NONE);
// If a direction is specified, take it into account
if (motionTweenRotate != XflKeyframe.MOTION_TWEEN_ROTATE_NONE) {
var direction :Number = (motionTweenRotate == XflKeyframe.MOTION_TWEEN_ROTATE_CLOCKWISE ? 1 : -1);
// negative scales affect rotation direction
direction *= sign(nextKf.scaleX) * sign(nextKf.scaleY);
while (direction < 0 && kf.skewX < nextKf.skewX) {
nextKf.skewX -= Math.PI * 2;
}
while (direction > 0 && kf.skewX > nextKf.skewX) {
nextKf.skewX += Math.PI * 2;
}
while (direction < 0 && kf.skewY < nextKf.skewY) {
nextKf.skewY -= Math.PI * 2;
}
while (direction > 0 && kf.skewY > nextKf.skewY) {
nextKf.skewY += Math.PI * 2;
}
// additional rotations specified?
var motionTweenRotateTimes :Number =
XmlUtil.getNumberAttr(frameXml, XflKeyframe.MOTION_TWEEN_ROTATE_TIMES, 0);
var thisRotation :Number = motionTweenRotateTimes * Math.PI * 2 * direction;
additionalRotation += thisRotation;
}
nextKf.rotate(additionalRotation);
}
return layer;
}
protected static function sign (n :Number) :Number {
return (n > 0 ? 1 : (n < 0 ? -1 : 0));
}
}
}
|
fix XflLayer parse signature
|
fix XflLayer parse signature
|
ActionScript
|
mit
|
mathieuanthoine/flump,mathieuanthoine/flump,mathieuanthoine/flump
|
fcfc1597ab28561127b82359bcf498b018f63094
|
src/goplayer/Player.as
|
src/goplayer/Player.as
|
package goplayer
{
import flash.utils.getTimer
import streamio.Stat
public class Player
implements FlashNetConnectionListener, FlashNetStreamListener
{
private const DEFAULT_VOLUME : Number = .8
private const START_BUFFER : Duration = Duration.seconds(3)
private const SMALL_BUFFER : Duration = Duration.seconds(5)
private const LARGE_BUFFER : Duration = Duration.seconds(60)
private const SEEK_GRACE_TIME : Duration = Duration.seconds(2)
private const finishingListeners : Array = []
private var connection : FlashNetConnection
private var _movie : Movie
private var bitratePolicy : BitratePolicy
private var enableRTMP : Boolean
private var _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 = DEFAULT_VOLUME
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)
{
this.connection = connection
_movie = movie
this.bitratePolicy = bitratePolicy
this.enableRTMP = enableRTMP
Stat.view(movie.id)
connection.listener = this
}
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()
Stat.play(movie.id)
}
public function handleConnectionFailed() : void
{
if (movie.rtmpURL.hasPort && !triedStandardRTMP)
handleCustomRTMPUnavailable()
else
handleRTMPUnavailable()
}
private function handleCustomRTMPUnavailable() : void
{
debug("Trying to connect using default RTMP ports.")
connectUsingStandardRTMP()
}
private function handleRTMPUnavailable() : void
{
debug("Could not connect using RTMP; trying plain HTTP.")
connectUsingHTTP()
}
public function get usingRTMP() : Boolean
{ return _usingRTMP }
private function connectUsingRTMP() : void
{ connection.connect(movie.rtmpURL) }
private function connectUsingStandardRTMP() : void
{
triedStandardRTMP = true
connection.connect(movie.rtmpURL.withoutPort)
}
private function connectUsingHTTP() : void
{
_usingRTMP = false
connection.dontConnect()
startPlaying()
}
public function handleConnectionClosed() : void
{}
// -----------------------------------------------------
public function handleConnectionEstablished() : void
{
_usingRTMP = true
if (bandwidthDeterminationNeeded)
connection.determineBandwidth()
else
startPlaying()
}
private function get bandwidthDeterminationNeeded() : Boolean
{ return bitratePolicy == BitratePolicy.BEST }
public function handleBandwidthDetermined
(bandwidth : Bitrate, latency : Duration) : void
{
measuredBandwidth = bandwidth
measuredLatency = latency
startPlaying()
}
private function get bandwidthDetermined() : Boolean
{ return measuredBandwidth != null }
private function startPlaying() : void
{
stream = connection.getNetStream()
stream.listener = this
stream.volume = volume
useStartBuffer()
if (usingRTMP)
playRTMPStream()
else
playHTTPStream()
if (paused)
stream.paused = true
}
private function playRTMPStream() : void
{ stream.playRTMP(streamPicker.first, streamPicker.all) }
private function playHTTPStream() : void
{ stream.playHTTP(movie.httpURL) }
private function get streamPicker() : RTMPStreamPicker
{
return new RTMPStreamPicker
(movie.rtmpStreams, bitratePolicy, measuredBandwidth)
}
// -----------------------------------------------------
public function handleNetStreamMetadata(data : Object) : void
{
metadata = data
if (!usingRTMP)
debug("Video file size: " + stream.httpFileSize)
}
public function handleStreamingStarted() : void
{
useStartBuffer()
_buffering = true
_finished = false
}
public function handleBufferFilled() : void
{ handleBufferingFinished() }
private function handleBufferingFinished() : void
{
_buffering = false
// Give the backend a chance to resume playback before we go
// ahead and raise the buffer size further.
later($handleBufferingFinished)
}
private function $handleBufferingFinished() : void
{
// Make sure playback was not interrupted.
if (!buffering && !finished)
useLargeBuffer()
}
public function handleBufferEmptied() : void
{
if (finishedPlaying)
handleFinishedPlaying()
else
handleBufferingStarted()
}
private function handleBufferingStarted() : void
{
useSmallBuffer()
_buffering = true
_finished = false
}
private function useStartBuffer() : void
{ stream.bufferTime = START_BUFFER }
private function useSmallBuffer() : void
{ stream.bufferTime = SMALL_BUFFER }
private function useLargeBuffer() : void
{ stream.bufferTime = LARGE_BUFFER }
public function get buffering() : Boolean
{ return _buffering }
public function get bufferingUnexpectedly() : Boolean
{ return buffering && !justSeeked }
private function get justSeeked() : Boolean
{ return seekStopwatch.within(SEEK_GRACE_TIME) }
public function handleStreamingStopped() : void
{
if (finishedPlaying)
handleFinishedPlaying()
}
private function handleFinishedPlaying() : void
{
debug("Finished playing.")
_finished = true
for each (var listener : PlayerFinishingListener in finishingListeners)
listener.handleMovieFinishedPlaying()
}
private function get finishedPlaying() : Boolean
{ return timeRemaining.seconds < 1 }
private function get timeRemaining() : Duration
{ return streamLength.minus(playheadPosition) }
// -----------------------------------------------------
public function get paused() : Boolean
{ return _paused }
public function set paused(value : Boolean) : void
{
// Allow pausing before the stream has been created.
_paused = value
if (stream)
stream.paused = value
}
public function togglePaused() : void
{
// Forbid pausing before the stream has been created.
if (stream)
paused = !paused
}
// -----------------------------------------------------
public function get playheadPosition() : Duration
{
return stream != null && stream.playheadPosition != null
? stream.playheadPosition : Duration.ZERO
}
public function get playheadRatio() : Number
{ return getRatio(playheadPosition.seconds, streamLength.seconds) }
public function get bufferRatio() : Number
{ return getRatio(bufferPosition.seconds, streamLength.seconds) }
private function getRatio
(numerator : Number, denominator : Number) : Number
{ return Math.min(1, numerator / denominator) }
private function get bufferPosition() : Duration
{ return playheadPosition.plus(bufferLength) }
public function set playheadPosition(value : Duration) : void
{
if (stream)
$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 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 (stream)
stream.volume = value
}
public function changeVolumeBy(delta : Number) : void
{ volume = volume + delta }
public function mute() : void
{
savedVolume = volume
volume = 0
}
public function unmute() : void
{ volume = savedVolume == 0 ? DEFAULT_VOLUME : savedVolume }
public function get muted() : Boolean
{ return volume == 0 }
// -----------------------------------------------------
public function get aspectRatio() : Number
{ return movie.aspectRatio }
public function get bufferTime() : Duration
{
return stream != null && stream.bufferTime != null
? stream.bufferTime : START_BUFFER
}
public function get bufferLength() : Duration
{
return stream != null && stream.bufferLength != null
? stream.bufferLength : Duration.ZERO
}
public function get bufferFillRatio() : Number
{ return getRatio(bufferLength.seconds, bufferTime.seconds) }
public function get streamLength() : Duration
{
return metadata != null
? Duration.seconds(metadata.duration)
: movie.duration
}
public function get currentBitrate() : Bitrate
{
return stream != null && stream.bitrate != null
? stream.bitrate : Bitrate.ZERO
}
public function get currentBandwidth() : Bitrate
{
return stream != null && stream.bandwidth != null
? stream.bandwidth : Bitrate.ZERO
}
public function get highQualityDimensions() : Dimensions
{
var result : Dimensions = Dimensions.ZERO
for each (var stream : RTMPStream in movie.rtmpStreams)
if (stream.dimensions.isGreaterThan(result))
result = stream.dimensions
return result
}
}
}
|
package goplayer
{
import flash.utils.getTimer
import flash.net.SharedObject
import streamio.Stat
public class Player
implements FlashNetConnectionListener, FlashNetStreamListener
{
private const DEFAULT_VOLUME : Number = .8
private const START_BUFFER : Duration = Duration.seconds(3)
private const SMALL_BUFFER : Duration = Duration.seconds(5)
private const LARGE_BUFFER : Duration = Duration.seconds(60)
private const SEEK_GRACE_TIME : Duration = Duration.seconds(2)
private const finishingListeners : Array = []
private var sharedObject : SharedObject = null
private var connection : FlashNetConnection
private var _movie : Movie
private var bitratePolicy : BitratePolicy
private var enableRTMP : Boolean
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)
{
this.connection = connection
_movie = movie
this.bitratePolicy = bitratePolicy
this.enableRTMP = enableRTMP
connection.listener = this
Stat.view(movie.id)
try
{ sharedObject = SharedObject.getLocal("player") }
catch (error : Error)
{}
if (sharedObject && sharedObject.size > 0)
volume = sharedObject.data["volume"]
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()
Stat.play(movie.id)
}
public function handleConnectionFailed() : void
{
if (movie.rtmpURL.hasPort && !triedStandardRTMP)
handleCustomRTMPUnavailable()
else
handleRTMPUnavailable()
}
private function handleCustomRTMPUnavailable() : void
{
debug("Trying to connect using default RTMP ports.")
connectUsingStandardRTMP()
}
private function handleRTMPUnavailable() : void
{
debug("Could not connect using RTMP; trying plain HTTP.")
connectUsingHTTP()
}
public function get usingRTMP() : Boolean
{ return _usingRTMP }
private function connectUsingRTMP() : void
{ connection.connect(movie.rtmpURL) }
private function connectUsingStandardRTMP() : void
{
triedStandardRTMP = true
connection.connect(movie.rtmpURL.withoutPort)
}
private function connectUsingHTTP() : void
{
_usingRTMP = false
connection.dontConnect()
startPlaying()
}
public function handleConnectionClosed() : void
{}
// -----------------------------------------------------
public function handleConnectionEstablished() : void
{
_usingRTMP = true
if (bandwidthDeterminationNeeded)
connection.determineBandwidth()
else
startPlaying()
}
private function get bandwidthDeterminationNeeded() : Boolean
{ return bitratePolicy == BitratePolicy.BEST }
public function handleBandwidthDetermined
(bandwidth : Bitrate, latency : Duration) : void
{
measuredBandwidth = bandwidth
measuredLatency = latency
startPlaying()
}
private function get bandwidthDetermined() : Boolean
{ return measuredBandwidth != null }
private function startPlaying() : void
{
stream = connection.getNetStream()
stream.listener = this
stream.volume = volume
useStartBuffer()
if (usingRTMP)
playRTMPStream()
else
playHTTPStream()
if (paused)
stream.paused = true
}
private function playRTMPStream() : void
{ stream.playRTMP(streamPicker.first, streamPicker.all) }
private function playHTTPStream() : void
{ stream.playHTTP(movie.httpURL) }
private function get streamPicker() : RTMPStreamPicker
{
return new RTMPStreamPicker
(movie.rtmpStreams, bitratePolicy, measuredBandwidth)
}
// -----------------------------------------------------
public function handleNetStreamMetadata(data : Object) : void
{
metadata = data
if (!usingRTMP)
debug("Video file size: " + stream.httpFileSize)
}
public function handleStreamingStarted() : void
{
useStartBuffer()
_buffering = true
_finished = false
}
public function handleBufferFilled() : void
{ handleBufferingFinished() }
private function handleBufferingFinished() : void
{
_buffering = false
// Give the backend a chance to resume playback before we go
// ahead and raise the buffer size further.
later($handleBufferingFinished)
}
private function $handleBufferingFinished() : void
{
// Make sure playback was not interrupted.
if (!buffering && !finished)
useLargeBuffer()
}
public function handleBufferEmptied() : void
{
if (finishedPlaying)
handleFinishedPlaying()
else
handleBufferingStarted()
}
private function handleBufferingStarted() : void
{
useSmallBuffer()
_buffering = true
_finished = false
}
private function useStartBuffer() : void
{ stream.bufferTime = START_BUFFER }
private function useSmallBuffer() : void
{ stream.bufferTime = SMALL_BUFFER }
private function useLargeBuffer() : void
{ stream.bufferTime = LARGE_BUFFER }
public function get buffering() : Boolean
{ return _buffering }
public function get bufferingUnexpectedly() : Boolean
{ return buffering && !justSeeked }
private function get justSeeked() : Boolean
{ return seekStopwatch.within(SEEK_GRACE_TIME) }
public function handleStreamingStopped() : void
{
if (finishedPlaying)
handleFinishedPlaying()
}
private function handleFinishedPlaying() : void
{
debug("Finished playing.")
_finished = true
for each (var listener : PlayerFinishingListener in finishingListeners)
listener.handleMovieFinishedPlaying()
}
private function get finishedPlaying() : Boolean
{ return timeRemaining.seconds < 1 }
private function get timeRemaining() : Duration
{ return streamLength.minus(playheadPosition) }
// -----------------------------------------------------
public function get paused() : Boolean
{ return _paused }
public function set paused(value : Boolean) : void
{
// Allow pausing before the stream has been created.
_paused = value
if (stream)
stream.paused = value
}
public function togglePaused() : void
{
// Forbid pausing before the stream has been created.
if (stream)
paused = !paused
}
// -----------------------------------------------------
public function get playheadPosition() : Duration
{
return stream != null && stream.playheadPosition != null
? stream.playheadPosition : Duration.ZERO
}
public function get playheadRatio() : Number
{ return getRatio(playheadPosition.seconds, streamLength.seconds) }
public function get bufferRatio() : Number
{ return getRatio(bufferPosition.seconds, streamLength.seconds) }
private function getRatio
(numerator : Number, denominator : Number) : Number
{ return Math.min(1, numerator / denominator) }
private function get bufferPosition() : Duration
{ return playheadPosition.plus(bufferLength) }
public function set playheadPosition(value : Duration) : void
{
if (stream)
$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 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 (sharedObject)
sharedObject.data["volume"] = 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
}
}
}
|
Save volume in local shared object.
|
Save volume in local shared object.
|
ActionScript
|
mit
|
dbrock/goplayer,dbrock/goplayer
|
8fc395ec1ecf89376f21feb054fc4a67bf66bbd1
|
src/aerys/minko/render/shader/compiler/graph/nodes/leaf/Sampler.as
|
src/aerys/minko/render/shader/compiler/graph/nodes/leaf/Sampler.as
|
package aerys.minko.render.shader.compiler.graph.nodes.leaf
{
import aerys.minko.render.resource.texture.ITextureResource;
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.render.shader.compiler.CRC32;
import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode;
/**
* @private
* @author Romain Gilliotte
*
*/
public class Sampler extends AbstractSampler
{
/**
* This vector is only used to compute the hash of the Sampler.
*/
private static const RESOURCES : Vector.<ITextureResource> = new Vector.<ITextureResource>();
private var _textureResource : ITextureResource;
public function get textureResource() : ITextureResource
{
return _textureResource;
}
public function Sampler(textureResource : ITextureResource,
format : uint = 0, // SamplerFormat.RGBA
filter : uint = 1, // SamplerFilter.LINEAR
mipmap : uint = 0, // SamplerMipmap.DISABLE
wrapping : uint = 1, // SamplerWrapping.REPEAT
dimension : uint = 0) // SamplerDimension.FLAT
{
_textureResource = textureResource;
super(format, filter, mipmap, wrapping, dimension);
}
override protected function computeHash() : uint
{
var textureResourceId : int = RESOURCES.indexOf(_textureResource);
if (textureResourceId === -1)
{
RESOURCES.push(textureResource);
textureResourceId = RESOURCES.length - 1;
}
return CRC32.computeForString('Sampler' + textureResourceId)
}
override public function toString() : String
{
return 'Sampler';
}
override public function clone() : AbstractNode
{
return new Sampler(_textureResource, format, filter, mipmap, wrapping, dimension);
}
}
}
|
package aerys.minko.render.shader.compiler.graph.nodes.leaf
{
import aerys.minko.render.resource.texture.ITextureResource;
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.render.shader.compiler.CRC32;
import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode;
import flash.utils.Dictionary;
/**
* @private
* @author Romain Gilliotte
*
*/
public class Sampler extends AbstractSampler
{
/**
* This vector is only used to compute the hash of the Sampler.
*/
private static const RESOURCE_ID : Dictionary = new Dictionary(true);
private static var _lastId : uint = 0;
private var _textureResource : ITextureResource;
public function get textureResource() : ITextureResource
{
return _textureResource;
}
public function Sampler(textureResource : ITextureResource,
format : uint = 0, // SamplerFormat.RGBA
filter : uint = 1, // SamplerFilter.LINEAR
mipmap : uint = 0, // SamplerMipmap.DISABLE
wrapping : uint = 1, // SamplerWrapping.REPEAT
dimension : uint = 0) // SamplerDimension.FLAT
{
_textureResource = textureResource;
super(format, filter, mipmap, wrapping, dimension);
}
override protected function computeHash() : uint
{
var textureResourceId : uint = RESOURCE_ID[_textureResource];
if (!textureResourceId)
{
RESOURCE_ID[_textureResource] = ++_lastId;
textureResourceId = _lastId;
}
return CRC32.computeForString('Sampler' + textureResourceId)
}
override public function toString() : String
{
return 'Sampler';
}
override public function clone() : AbstractNode
{
return new Sampler(_textureResource, format, filter, mipmap, wrapping, dimension);
}
}
}
|
fix memory leak in the Shader ASG node
|
fix memory leak in the Shader ASG node
|
ActionScript
|
mit
|
aerys/minko-as3
|
15171d961146cb2ffcef46c6ddc07d1c50efa36c
|
exporter/src/main/as/flump/export/JSONZipFormat.as
|
exporter/src/main/as/flump/export/JSONZipFormat.as
|
//
// Flump - Copyright 2013 Flump Authors
package flump.export {
import flash.filesystem.File;
import flash.utils.ByteArray;
import flash.utils.IDataOutput;
import deng.fzip.FZip;
import deng.fzip.FZipFile;
import flump.display.LibraryLoader;
import flump.xfl.XflLibrary;
public class JSONZipFormat extends PublishFormat
{
public static const NAME :String = "JSONZip";
public var outputFile :File;
public function JSONZipFormat (destDir :File, libs :Vector.<XflLibrary>, conf :ExportConf,
projectName :String) {
super(destDir, libs, conf, projectName);
if (conf.name != null) {
outputFile = _destDir.resolvePath(conf.name + "/" + location + ".zip");
} else {
outputFile = _destDir.resolvePath(location + ".zip");
}
}
override public function get modified () :Boolean {
if (!outputFile.exists) return true;
const zip :FZip = new FZip();
zip.loadBytes(Files.read(outputFile));
const md5File :FZipFile = zip.getFileByName("md5");
const md5 :String = md5File.content.readUTFBytes(md5File.content.length);
return md5 != md5;
}
override public function publish() :void {
const zip :FZip = new FZip();
function addToZip(name :String, contentWriter :Function) :void {
const bytes :ByteArray = new ByteArray();
contentWriter(bytes);
zip.addFile(name, bytes);
}
const atlases :Vector.<Atlas> = createAtlases();
for each (var atlas :Atlas in atlases) {
addToZip(atlas.filename, function (b :ByteArray) :void { AtlasUtil.writePNG(atlas, b); });
}
addToZip(LibraryLoader.LIBRARY_LOCATION, function (b :ByteArray) :void {
b.writeUTFBytes(toJSONString(createMold(atlases)));
});
addToZip(LibraryLoader.MD5_LOCATION,
function (b :ByteArray) :void { b.writeUTFBytes(md5); });
addToZip(LibraryLoader.VERSION_LOCATION,
function (b :ByteArray) :void { b.writeUTFBytes(LibraryLoader.VERSION); });
Files.write(outputFile, function (out :IDataOutput) :void {
zip.serialize(out, /*includeAdler32=*/true);
});
}
}
}
|
//
// Flump - Copyright 2013 Flump Authors
package flump.export {
import flash.filesystem.File;
import flash.utils.ByteArray;
import flash.utils.IDataOutput;
import deng.fzip.FZip;
import deng.fzip.FZipFile;
import flump.display.LibraryLoader;
import flump.xfl.XflLibrary;
public class JSONZipFormat extends PublishFormat
{
public static const NAME :String = "JSONZip";
public var outputFile :File;
public function JSONZipFormat (destDir :File, libs :Vector.<XflLibrary>, conf :ExportConf,
projectName :String) {
super(destDir, libs, conf, projectName);
if (conf.name != null) {
outputFile = _destDir.resolvePath(conf.name + "/" + location + ".zip");
} else {
outputFile = _destDir.resolvePath(location + ".zip");
}
}
override public function get modified () :Boolean {
if (!outputFile.exists) return true;
const zip :FZip = new FZip();
zip.loadBytes(Files.read(outputFile));
const md5File :FZipFile = zip.getFileByName("md5");
const md5 :String = md5File.content.readUTFBytes(md5File.content.length);
return md5 != this.md5;
}
override public function publish() :void {
const zip :FZip = new FZip();
function addToZip(name :String, contentWriter :Function) :void {
const bytes :ByteArray = new ByteArray();
contentWriter(bytes);
zip.addFile(name, bytes);
}
const atlases :Vector.<Atlas> = createAtlases();
for each (var atlas :Atlas in atlases) {
addToZip(atlas.filename, function (b :ByteArray) :void { AtlasUtil.writePNG(atlas, b); });
}
addToZip(LibraryLoader.LIBRARY_LOCATION, function (b :ByteArray) :void {
b.writeUTFBytes(toJSONString(createMold(atlases)));
});
addToZip(LibraryLoader.MD5_LOCATION,
function (b :ByteArray) :void { b.writeUTFBytes(md5); });
addToZip(LibraryLoader.VERSION_LOCATION,
function (b :ByteArray) :void { b.writeUTFBytes(LibraryLoader.VERSION); });
Files.write(outputFile, function (out :IDataOutput) :void {
zip.serialize(out, /*includeAdler32=*/true);
});
}
}
}
|
Fix the modified column check for combined JSONZip formats.
|
Fix the modified column check for combined JSONZip formats.
I'm surprised this wasn't a compiler warning, but even IDEA wasn't complaining about it.
|
ActionScript
|
mit
|
mathieuanthoine/flump,funkypandagame/flump,tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump,tconkling/flump,funkypandagame/flump
|
436fa7d12a59b3f46d463d729e4707acd0667907
|
src/aerys/minko/scene/node/group/Group.as
|
src/aerys/minko/scene/node/group/Group.as
|
package aerys.minko.scene.node.group
{
import aerys.minko.scene.action.IAction;
import aerys.minko.scene.action.group.GroupAction;
import aerys.minko.scene.node.AbstractScene;
import aerys.minko.scene.node.IScene;
import aerys.minko.scene.node.ISearchableScene;
import aerys.minko.scene.visitor.ISceneVisitor;
import aerys.minko.scene.visitor.RenderingVisitor;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
import flash.utils.getQualifiedClassName;
/**
* The Group3D provides a basic support for scene building.
* A Group3D can contain any object implementing the IScene3D interface.
*
* Group3D objects do not affect their children with any specific behaviour.
*
* @author Jean-Marc Le Roux
*/
public dynamic class Group extends Proxy implements IGroup
{
private static var _id : uint = 0;
private var _name : String = null;
private var _children : Vector.<IScene> = null;
private var _numChildren : int = 0;
private var _actions : Vector.<IAction> = Vector.<IAction>([GroupAction.groupAction]);
public function get actions() : Vector.<IAction> { return _actions; }
public function get name() : String { return _name; }
public function set name(value : String) : void
{
_name = value;
}
protected function get rawChildren() : Vector.<IScene> { return _children; }
protected function set rawChildren(value : Vector.<IScene>) : void
{
_children = value;
_numChildren = _children.length;
}
/**
* The number of children.
*/
public function get numChildren() : uint
{
return _numChildren;
}
public function Group(...children)
{
super();
_name = AbstractScene.getDefaultSceneName(this);
initialize(children);
}
private function initialize(children : Array) : void
{
while (children.length == 1 && children[0] is Array)
children = children[0];
_numChildren = children.length;
_children = _numChildren ? Vector.<IScene>(children)
: new Vector.<IScene>();
}
public function contains(scene : IScene) : Boolean
{
return getChildIndex(scene) >= 0;
}
public function getChildIndex(child : IScene) : int
{
for (var i : int = 0; i < _numChildren; i++)
if (_children[i] === child)
return i;
return -1;
}
public function getChildByName(name : String) : IScene
{
for (var i : int = 0; i < _numChildren; i++)
if (_children[i].name === name)
return _children[i];
return null;
}
/**
* Add a child to the container.
*
* @param scene The child to add.
*/
public function addChild(scene : IScene) : IGroup
{
if (!scene)
throw new Error("Parameter child must be non-null.");
_children.push(scene);
++_numChildren;
//scene.added(this);
return this;
}
public function addChildAt(scene : IScene, position : uint) : IGroup
{
if (!scene)
throw new Error("Parameter child must be non-null.");
var numChildren : int = _children.length;
if (position >= numChildren)
return addChild(scene);
for (var i : int = numChildren; i > position; --i)
_children[i] = _children[int(i - 1)];
_children[position] = scene;
++_numChildren;
return this;
}
/**
* Remove a child from the container.
*
* @param myChild The child to remove.
* @return Whether the child was actually removed or not.
*/
public function removeChild(child : IScene) : IGroup
{
var numChildren : int = _children.length;
var i : int = 0;
while (i < numChildren && _children[i] !== child)
++i;
if (i >= numChildren)
return null;
return removeChildAt(i);
}
public function removeChildAt(position : uint) : IGroup
{
var removed : IScene = null;
if (position < _numChildren)
{
removed = _children[position];
while (position < _numChildren - 1)
_children[position] = _children[int(++position)];
_children.length = --_numChildren;
}
return this;
}
public function removeAllChildren() : IGroup
{
_children.length = 0;
_numChildren = 0;
return this;
}
public function getChildAt(position : uint) : IScene
{
return position < _numChildren ? _children[position] : null;
}
public function swapChildren(child1 : IScene,
child2 : IScene) : IGroup
{
var id1 : int = getChildIndex(child1);
var id2 : int = getChildIndex(child2);
if (id1 == -1 || id2 == -1)
return this;
var tmp : IScene = _children[id2];
_children[id2] = _children[id1];
_children[id1] = tmp;
return this;
}
public function getDescendantByName(name : String) : IScene
{
var descendant : IScene = getChildByName(name);
var numChildren : int = numChildren;
for (var i : int = 0; i < numChildren && !descendant; ++i)
{
var searchable : ISearchableScene = _children[i] as ISearchableScene;
if (searchable)
descendant = searchable.getDescendantByName(name);
}
return descendant;
}
public function toString() : String
{
return "[" + getQualifiedClassName(this) + " " + name + "]";
}
override flash_proxy function getProperty(name : *) : *
{
var index : int = parseInt(name);
return index == name ? getChildAt(index) : getChildByName(name as String);
}
override flash_proxy function setProperty(name : *, value : *) : void
{
var index : int = parseInt(name);
if (index == name)
{
if (index < numChildren)
{
removeChildAt(index);
addChildAt(value, index);
}
}
else
{
var old : IScene = getChildByName(name);
addChild(value);
if (old)
{
swapChildren(value, old);
_children.length = _children.length - 1;
}
}
}
override flash_proxy function getDescendants(name : *) : *
{
return getDescendantByName(name);
}
override flash_proxy function nextNameIndex(index : int) : int
{
return index < numChildren ? index + 1 : 0;
}
override flash_proxy function nextName(index : int) : String
{
return String(index - 1);
}
override flash_proxy function nextValue(index : int) : *
{
return _children[int(index - 1)];
}
}
}
|
package aerys.minko.scene.node.group
{
import aerys.minko.scene.action.IAction;
import aerys.minko.scene.action.group.GroupAction;
import aerys.minko.scene.node.AbstractScene;
import aerys.minko.scene.node.IScene;
import aerys.minko.scene.node.ISearchableScene;
import aerys.minko.scene.visitor.ISceneVisitor;
import aerys.minko.scene.visitor.RenderingVisitor;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
import flash.utils.getQualifiedClassName;
/**
* The Group3D provides a basic support for scene building.
* A Group3D can contain any object implementing the IScene3D interface.
*
* Group3D objects do not affect their children with any specific behaviour.
*
* @author Jean-Marc Le Roux
*/
public dynamic class Group extends Proxy implements IGroup
{
private static var _id : uint = 0;
private var _name : String = null;
private var _children : Vector.<IScene> = null;
private var _numChildren : int = 0;
private var _actions : Vector.<IAction> = Vector.<IAction>([GroupAction.groupAction]);
public function get actions() : Vector.<IAction> { return _actions; }
public function get name() : String { return _name; }
public function set name(value : String) : void
{
_name = value;
}
protected function get rawChildren() : Vector.<IScene> { return _children; }
protected function set rawChildren(value : Vector.<IScene>) : void
{
_children = value;
_numChildren = _children.length;
}
/**
* The number of children.
*/
public function get numChildren() : uint
{
return _numChildren;
}
public function Group(...children)
{
super();
_name = AbstractScene.getDefaultSceneName(this);
initialize(children);
}
private function initialize(children : Array) : void
{
_children = new Vector.<IScene>();
while (children.length == 1 && children[0] is Array)
children = children[0];
var childrenNum : uint = children.length;
for (var childrenIndex : uint = 0; childrenIndex < childrenNum; ++childrenIndex)
{
var child : IScene = children[childrenIndex] as IScene;
if (!child)
throw new Error("Constructor parameters must be IScene objects.");
addChild(child);
}
}
public function contains(scene : IScene) : Boolean
{
return getChildIndex(scene) >= 0;
}
public function getChildIndex(child : IScene) : int
{
for (var i : int = 0; i < _numChildren; i++)
if (_children[i] === child)
return i;
return -1;
}
public function getChildByName(name : String) : IScene
{
for (var i : int = 0; i < _numChildren; i++)
if (_children[i].name === name)
return _children[i];
return null;
}
/**
* Add a child to the container.
*
* @param scene The child to add.
*/
public function addChild(scene : IScene) : IGroup
{
if (!scene)
throw new Error("Parameter child must be non-null.");
_children.push(scene);
++_numChildren;
//scene.added(this);
return this;
}
public function addChildAt(scene : IScene, position : uint) : IGroup
{
if (!scene)
throw new Error("Parameter child must be non-null.");
var numChildren : int = _children.length;
if (position >= numChildren)
return addChild(scene);
for (var i : int = numChildren; i > position; --i)
_children[i] = _children[int(i - 1)];
_children[position] = scene;
++_numChildren;
return this;
}
/**
* Remove a child from the container.
*
* @param myChild The child to remove.
* @return Whether the child was actually removed or not.
*/
public function removeChild(child : IScene) : IGroup
{
var numChildren : int = _children.length;
var i : int = 0;
while (i < numChildren && _children[i] !== child)
++i;
if (i >= numChildren)
return null;
return removeChildAt(i);
}
public function removeChildAt(position : uint) : IGroup
{
var removed : IScene = null;
if (position < _numChildren)
{
removed = _children[position];
while (position < _numChildren - 1)
_children[position] = _children[int(++position)];
_children.length = --_numChildren;
}
return this;
}
public function removeAllChildren() : IGroup
{
_children.length = 0;
_numChildren = 0;
return this;
}
public function getChildAt(position : uint) : IScene
{
return position < _numChildren ? _children[position] : null;
}
public function swapChildren(child1 : IScene,
child2 : IScene) : IGroup
{
var id1 : int = getChildIndex(child1);
var id2 : int = getChildIndex(child2);
if (id1 == -1 || id2 == -1)
return this;
var tmp : IScene = _children[id2];
_children[id2] = _children[id1];
_children[id1] = tmp;
return this;
}
public function getDescendantByName(name : String) : IScene
{
var descendant : IScene = getChildByName(name);
var numChildren : int = numChildren;
for (var i : int = 0; i < numChildren && !descendant; ++i)
{
var searchable : ISearchableScene = _children[i] as ISearchableScene;
if (searchable)
descendant = searchable.getDescendantByName(name);
}
return descendant;
}
public function toString() : String
{
return "[" + getQualifiedClassName(this) + " " + name + "]";
}
override flash_proxy function getProperty(name : *) : *
{
var index : int = parseInt(name);
return index == name ? getChildAt(index) : getChildByName(name as String);
}
override flash_proxy function setProperty(name : *, value : *) : void
{
var index : int = parseInt(name);
if (index == name)
{
if (index < numChildren)
{
removeChildAt(index);
addChildAt(value, index);
}
}
else
{
var old : IScene = getChildByName(name);
addChild(value);
if (old)
{
swapChildren(value, old);
_children.length = _children.length - 1;
}
}
}
override flash_proxy function getDescendants(name : *) : *
{
return getDescendantByName(name);
}
override flash_proxy function nextNameIndex(index : int) : int
{
return index < numChildren ? index + 1 : 0;
}
override flash_proxy function nextName(index : int) : String
{
return String(index - 1);
}
override flash_proxy function nextValue(index : int) : *
{
return _children[int(index - 1)];
}
}
}
|
Add type checking in Group constructor (warn when an object is not an IScene).
|
Add type checking in Group constructor (warn when an object is not an IScene).
|
ActionScript
|
mit
|
aerys/minko-as3
|
25e8afd24f0f621ed6d32776fd2722afff457208
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/utils/UIUtils.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/utils/UIUtils.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.utils
{
import org.apache.flex.core.IPopUpHost;
import org.apache.flex.core.UIBase;
/**
* The UIUtils class is a collection of static functions that provide utility
* features to UIBase objects.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class UIUtils
{
/**
* @private
*/
public function UIUtils()
{
throw new Error("UIUtils should not be instantiated.");
}
/**
* Centers the given item relative to another item. Typically the item being centered is
* a child or sibling of the second item.
*
* @param item The component item being centered.
* @param relativeTo The component used as reference for the centering.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function center( item:UIBase, relativeTo:UIBase ):void
{
var xpos:Number = (relativeTo.width - item.width)/2;
var ypos:Number = (relativeTo.height - item.height)/2;
item.x = xpos;
item.y = ypos;
}
/**
* Given a component starting point, this function walks up the parent chain
* looking for a component that implements the IPopUpHost interface. The function
* either returns that component or null if no IPopUpHost can be found.
*
* @param start A component to start the search.
* @return A component that implements IPopUpHost or null.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function findPopUpHost(start:UIBase):IPopUpHost
{
while( start != null && !(start is IPopUpHost) ) {
start = start.parent as UIBase;
}
return start as IPopUpHost;
}
/**
* Removes the given component from the IPopUpHost.
*
* @param start A component to start the search.
* @return A component that implements IPopUpHost or null.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function removePopUp(popUp:UIBase):void
{
var host:IPopUpHost = popUp.parent as IPopUpHost;
host.removeElement(popUp);
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.utils
{
import org.apache.flex.core.IPopUpHost;
import org.apache.flex.core.IChild;
import org.apache.flex.core.IUIBase;
/**
* The UIUtils class is a collection of static functions that provide utility
* features to UIBase objects.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class UIUtils
{
/**
* @private
*/
public function UIUtils()
{
throw new Error("UIUtils should not be instantiated.");
}
/**
* Centers the given item relative to another item. Typically the item being centered is
* a child or sibling of the second item.
*
* @param item The component item being centered.
* @param relativeTo The component used as reference for the centering.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function center( item:IUIBase, relativeTo:IUIBase ):void
{
var xpos:Number = (relativeTo.width - item.width)/2;
var ypos:Number = (relativeTo.height - item.height)/2;
item.x = xpos;
item.y = ypos;
}
/**
* Given a component starting point, this function walks up the parent chain
* looking for a component that implements the IPopUpHost interface. The function
* either returns that component or null if no IPopUpHost can be found.
*
* @param start A component to start the search.
* @return A component that implements IPopUpHost or null.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function findPopUpHost(start:IUIBase):IPopUpHost
{
while( start != null && !(start is IPopUpHost) && start is IChild ) {
start = IChild(start).parent as IUIBase;
}
return start as IPopUpHost;
}
/**
* Removes the given component from the IPopUpHost.
*
* @param start A component to start the search.
* @return A component that implements IPopUpHost or null.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static function removePopUp(popUp:IChild):void
{
var host:IPopUpHost = popUp.parent as IPopUpHost;
host.removeElement(popUp);
}
}
}
|
switch to interfaces so it works on Buttons
|
switch to interfaces so it works on Buttons
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
468cdf2da947528c77744559fbd6c7a72b18db7b
|
src/main/as/flump/Flump.as
|
src/main/as/flump/Flump.as
|
//
// Flump - Copyright 2012 Three Rings Design
package flump {
import flash.desktop.NativeApplication;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.InvokeEvent;
import flash.filesystem.File;
import deng.fzip.FZip;
import deng.fzip.FZipFile;
import flump.xfl.XflAnimation;
import flump.xfl.XflLibrary;
import starling.core.Starling;
import com.threerings.util.F;
import com.threerings.util.Log;
import com.threerings.util.StringUtil;
public class Flump extends Sprite
{
public static const NA :NativeApplication = NativeApplication.nativeApplication;
public function Flump () {
NA.addEventListener(InvokeEvent.INVOKE, onInvoke);
_starling = new Starling(Preview, stage)
_starling.start();
}
protected function onInvoke (invoke :InvokeEvent) :void {
const file :File = new File(invoke.arguments[0]);
if (!file.exists) {
log.error("Given file doesn't exist", "path", file.nativePath);
NA.exit(1);
return;
}
loadFlashDocument(file);
}
protected function loadFlashDocument (file :File) :void {
if (StringUtil.endsWith(file.nativePath, ".xfl")) file = file.parent;
if (file.isDirectory) new XflLoader().load(file).succeeded.add(function (lib :XflLibrary) :void {
PngExporter.dumpTextures(file, lib);
Preview(_starling.stage.getChildAt(0)).displayAnimation(file, lib, lib.animations[0]);
});
else loadFla(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 anims :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, "anims", F.map(anims, toFn),
"textures", F.map(textures, toFn));
for each (var fz :FZipFile in anims) {
new XflAnimation(bytesToXML(fz.content));
}
NA.exit(0);
});
}
protected var _starling :Starling;
private static const log :Log = Log.getLog(Flump);
}}
|
//
// Flump - Copyright 2012 Three Rings Design
package flump {
import flash.desktop.NativeApplication;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.InvokeEvent;
import flash.filesystem.File;
import deng.fzip.FZip;
import deng.fzip.FZipFile;
import flump.xfl.XflAnimation;
import flump.xfl.XflLibrary;
import starling.core.Starling;
import com.threerings.util.F;
import com.threerings.util.Log;
import com.threerings.util.StringUtil;
public class Flump extends Sprite
{
public static const NA :NativeApplication = NativeApplication.nativeApplication;
public function Flump () {
NA.addEventListener(InvokeEvent.INVOKE, onInvoke);
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
_starling = new Starling(Preview, stage)
_starling.start();
}
protected function onInvoke (invoke :InvokeEvent) :void {
const file :File = new File(invoke.arguments[0]);
if (!file.exists) {
log.error("Given file doesn't exist", "path", file.nativePath);
NA.exit(1);
return;
}
loadFlashDocument(file);
}
protected function loadFlashDocument (file :File) :void {
if (StringUtil.endsWith(file.nativePath, ".xfl")) file = file.parent;
if (file.isDirectory) new XflLoader().load(file).succeeded.add(function (lib :XflLibrary) :void {
PngExporter.dumpTextures(file, lib);
Preview(_starling.stage.getChildAt(0)).displayAnimation(file, lib, lib.animations[0]);
});
else loadFla(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 anims :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, "anims", F.map(anims, toFn),
"textures", F.map(textures, toFn));
for each (var fz :FZipFile in anims) {
new XflAnimation(bytesToXML(fz.content));
}
NA.exit(0);
});
}
protected var _starling :Starling;
private static const log :Log = Log.getLog(Flump);
}}
|
Align the stage properly
|
Align the stage properly
|
ActionScript
|
mit
|
mathieuanthoine/flump,mathieuanthoine/flump,mathieuanthoine/flump,funkypandagame/flump,tconkling/flump,tconkling/flump,funkypandagame/flump
|
cd85cc6458e919a51bb970fe624d54bb97f23f72
|
as3/xobjas3/src/com/rpath/xobj/XSmartURL.as
|
as3/xobjas3/src/com/rpath/xobj/XSmartURL.as
|
/*
# Copyright (c) 2008-2010 rPath, Inc.
#
# This program is distributed under the terms of the MIT License as found
# in a file called LICENSE. If it is not present, the license
# is always available at http://www.opensource.org/licenses/mit-license.php.
#
# This program is distributed in the hope that it will be useful, but
# without any warranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the MIT License for full details.
#
*/
package com.rpath.xobj
{
import mx.collections.Sort;
import flash.utils.Dictionary;
import mx.collections.SortField;
[Bindable]
public class XSmartURL extends URL
{
public function XSmartURL(s:*=null)
{
// unwrap the URL passed in
if (s is XSmartURL)
{
s = (s as XSmartURL).baseURL;
}
super(s);
// keep track of the base URL distinct from
// our current value
baseURL = new URL(this.value);
}
public function get baseURL():URL
{
return _baseURL;
}
private var _baseURL:URL;
public function set baseURL(value:URL):void
{
_baseURL = value;
recomputeQualifiedURL();
}
/** descriptor provides the encoding chars to use
* which is a poor man's metadata right now
*/
[xobjTransient]
private var _descriptor:XSmartURLDescriptor;
public function get descriptor():XSmartURLDescriptor
{
return _descriptor;
}
public function set descriptor(value:XSmartURLDescriptor):void
{
_descriptor = value;
recomputeQualifiedURL();
}
/** paging support
*/
[xobjTransient]
public var rangeRequest:Boolean;
[xobjTransient]
private var _startIndex:Number;
public function get startIndex():Number
{
return _startIndex;
}
public function set startIndex(value:Number):void
{
_startIndex = value;
rangeRequest = true;
recomputeQualifiedURL();
}
[xobjTransient]
private var _limit:Number;
public function get limit():Number
{
return _limit;
}
public function set limit(value:Number):void
{
_limit = value;
rangeRequest = true;
recomputeQualifiedURL();
}
/** filterTerms is an array of (field, operator, value) clauses
* that are assumed to be AND clauses
*/
private var _filterTerms:Array;
[xobjTransient]
public function get filterTerms():Array
{
return _filterTerms;
}
[xobjTransient]
public function set filterTerms(value:Array):void
{
_filterTerms = value;
recomputeQualifiedURL();
}
/** sortTerms are an ordered set of (asc, desc) fields to order by
*/
private var _sortTerms:Sort;
[xobjTransient]
public function get sortTerms():Sort
{
return _sortTerms;
}
[xobjTransient]
public function set sortTerms(value:Sort):void
{
_sortTerms = value;
recomputeQualifiedURL();
}
/** freeSearch is for google-like full text searching
*/
private var _freeSearch:String;
[xobjTransient]
public function get freeSearch():String
{
return _freeSearch;
}
[xobjTransient]
public function set freeSearch(value:String):void
{
_freeSearch = value;
recomputeQualifiedURL();
}
/** url takes the baseURL and modifies it to encode the query,
* page, etc. params requested
*/
// TODO: optimize this via setter/getter pairs on query terms
[xobjTransient]
public function get qualifiedURL():String
{
return _qualifiedURL;
}
private var _qualifiedURL:String;
[xobjTransient]
public function set qualifiedURL(s:String):void
{
_qualifiedURL = s;
}
[xobjTransient]
public function recomputeQualifiedURL():void
{
if (!baseURL)
return;
var fullURL:String = baseURL.value;
var queryFrag:String = queryFragment();
if (queryFrag)
{
if (fullURL.indexOf(descriptor.paramDelimiter) != -1)
{
fullURL = fullURL + descriptor.paramDelimiter + queryFrag;
}
else
{
fullURL = fullURL + descriptor.paramMarker + queryFrag;
}
}
qualifiedURL = fullURL;
}
[xobjTransient]
public function queryFragment():String
{
var params:Dictionary = new Dictionary();
var query:String = "";
if (!descriptor)
return query;
if (rangeRequest)
{
if (descriptor.startKey)
params[descriptor.startKey] = startIndex;
if (descriptor.limitKey)
params[descriptor.limitKey] = limit;
}
// TODO: use descriptor to tell us how to express sort
if (sortTerms)
{
var terms:String = "";
if (sortTerms.fields && sortTerms.fields.length > 0)
{
var first:Boolean = true;
for each (var term:SortField in sortTerms.fields)
{
if (!term || !term.name)
continue;
terms = terms
+ (first ? "": descriptor.sortConjunction)
+ (term.descending ? descriptor.sortDescMarker: descriptor.sortAscMarker)
+ term.name;
first = false;
}
if (terms)
{
params[descriptor.sortKey] = terms;
}
}
}
if (filterTerms)
{
var search:String = "";
first = true;
for each (var searchTerm:FilterTerm in filterTerms)
{
search = search
+ (first ? "": descriptor.filterTermConjunction)
+ descriptor.filterTermStart
+ searchTerm.name + descriptor.filterTermSeperator+ searchTerm.operator +descriptor.filterTermSeperator + searchTerm.value
+ descriptor.filterTermEnd;
first = false;
}
if (search)
{
params[descriptor.filterKey] = search;
}
}
// Google like full text searching
if (freeSearch)
{
params[descriptor.searchKey] = freeSearch;
}
first = true;
for (var param:String in params)
{
query = query + (first ? "" : descriptor.paramDelimiter) + param + "=" + params[param];
first = false;
}
return query;
}
[xobjTransient]
public function addSearchTerm(term:FilterTerm):void
{
if (!filterTerms)
filterTerms = [];
filterTerms.push(term);
recomputeQualifiedURL();
}
/* TODO: decide if headers really belong on resource spec */
[xobjTransient]
public var headers:Dictionary;
[xobjTransient]
public var hasHeaders:Boolean;
[xobjTransient]
public function setHeader(name:String, value:String):void
{
headers[name] = value;
hasHeaders = true;
}
}
}
|
/*
# Copyright (c) 2008-2010 rPath, Inc.
#
# This program is distributed under the terms of the MIT License as found
# in a file called LICENSE. If it is not present, the license
# is always available at http://www.opensource.org/licenses/mit-license.php.
#
# This program is distributed in the hope that it will be useful, but
# without any warranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the MIT License for full details.
#
*/
package com.rpath.xobj
{
import flash.utils.Dictionary;
import mx.collections.Sort;
import mx.collections.SortField;
[Bindable]
public class XSmartURL extends URL
{
public function XSmartURL(s:*=null)
{
// unwrap the URL passed in
if (s is XSmartURL)
{
s = (s as XSmartURL).baseURL;
}
super(s);
// keep track of the base URL distinct from
// our current value
baseURL = new URL(this.value);
}
public function get baseURL():URL
{
return _baseURL;
}
private var _baseURL:URL;
public function set baseURL(value:URL):void
{
_baseURL = value;
recomputeQualifiedURL();
}
/** descriptor provides the encoding chars to use
* which is a poor man's metadata right now
*/
[xobjTransient]
private var _descriptor:XSmartURLDescriptor;
public function get descriptor():XSmartURLDescriptor
{
return _descriptor;
}
public function set descriptor(value:XSmartURLDescriptor):void
{
_descriptor = value;
recomputeQualifiedURL();
}
/** paging support
*/
[xobjTransient]
public var rangeRequest:Boolean;
[xobjTransient]
private var _startIndex:Number;
public function get startIndex():Number
{
return _startIndex;
}
public function set startIndex(value:Number):void
{
_startIndex = value;
rangeRequest = true;
recomputeQualifiedURL();
}
[xobjTransient]
private var _limit:Number;
public function get limit():Number
{
return _limit;
}
public function set limit(value:Number):void
{
_limit = value;
rangeRequest = true;
recomputeQualifiedURL();
}
/** filterTerms is an array of (field, operator, value) clauses
* that are assumed to be AND clauses
*/
private var _filterTerms:Array;
[xobjTransient]
public function get filterTerms():Array
{
return _filterTerms;
}
[xobjTransient]
public function set filterTerms(value:Array):void
{
_filterTerms = value;
recomputeQualifiedURL();
}
/** sortTerms are an ordered set of (asc, desc) fields to order by
*/
private var _sortTerms:Sort;
[xobjTransient]
public function get sortTerms():Sort
{
return _sortTerms;
}
[xobjTransient]
public function set sortTerms(value:Sort):void
{
_sortTerms = value;
recomputeQualifiedURL();
}
/** freeSearch is for google-like full text searching
*/
private var _freeSearch:String;
[xobjTransient]
public function get freeSearch():String
{
return _freeSearch;
}
[xobjTransient]
public function set freeSearch(value:String):void
{
_freeSearch = value;
recomputeQualifiedURL();
}
/** url takes the baseURL and modifies it to encode the query,
* page, etc. params requested
*/
// TODO: optimize this via setter/getter pairs on query terms
[xobjTransient]
public function get qualifiedURL():String
{
return _qualifiedURL;
}
private var _qualifiedURL:String;
[xobjTransient]
public function set qualifiedURL(s:String):void
{
_qualifiedURL = s;
}
[xobjTransient]
public function recomputeQualifiedURL():void
{
if (!baseURL)
return;
var fullURL:String = baseURL.value;
if (!fullURL)
return;
var queryFrag:String = queryFragment();
if (queryFrag)
{
if (fullURL.indexOf(descriptor.paramDelimiter) != -1)
{
fullURL = fullURL + descriptor.paramDelimiter + queryFrag;
}
else
{
fullURL = fullURL + descriptor.paramMarker + queryFrag;
}
}
qualifiedURL = fullURL;
}
[xobjTransient]
public function queryFragment():String
{
var params:Dictionary = new Dictionary();
var query:String = "";
if (!descriptor)
return query;
if (rangeRequest)
{
if (descriptor.startKey)
params[descriptor.startKey] = startIndex;
if (descriptor.limitKey)
params[descriptor.limitKey] = limit;
}
// TODO: use descriptor to tell us how to express sort
if (sortTerms)
{
var terms:String = "";
if (sortTerms.fields && sortTerms.fields.length > 0)
{
var first:Boolean = true;
for each (var term:SortField in sortTerms.fields)
{
if (!term || !term.name)
continue;
terms = terms
+ (first ? "": descriptor.sortConjunction)
+ (term.descending ? descriptor.sortDescMarker: descriptor.sortAscMarker)
+ term.name;
first = false;
}
if (terms)
{
params[descriptor.sortKey] = terms;
}
}
}
if (filterTerms)
{
var search:String = "";
first = true;
for each (var searchTerm:FilterTerm in filterTerms)
{
search = search
+ (first ? "": descriptor.filterTermConjunction)
+ descriptor.filterTermStart
+ searchTerm.name + descriptor.filterTermSeperator+ searchTerm.operator +descriptor.filterTermSeperator + searchTerm.value
+ descriptor.filterTermEnd;
first = false;
}
if (search)
{
params[descriptor.filterKey] = search;
}
}
// Google like full text searching
if (freeSearch)
{
params[descriptor.searchKey] = freeSearch;
}
first = true;
for (var param:String in params)
{
query = query + (first ? "" : descriptor.paramDelimiter) + param + "=" + params[param];
first = false;
}
return query;
}
public function addSearchTerm(term:FilterTerm):void
{
if (!filterTerms)
filterTerms = [];
filterTerms.push(term);
recomputeQualifiedURL();
}
public function removeSearchTerm(term:FilterTerm):void
{
var index:int = filterTerms.indexOf(term);
if (index != -1)
{
filterTerms.splice(index,1);
}
recomputeQualifiedURL();
}
/* TODO: decide if headers really belong on resource spec */
[xobjTransient]
public var headers:Dictionary;
[xobjTransient]
public var hasHeaders:Boolean;
[xobjTransient]
public function setHeader(name:String, value:String):void
{
headers[name] = value;
hasHeaders = true;
}
}
}
|
Remove searchTerms as well as add...
|
Remove searchTerms as well as add...
|
ActionScript
|
apache-2.0
|
sassoftware/xobj,sassoftware/xobj,sassoftware/xobj,sassoftware/xobj
|
909c1f41892f4715395e8096fe4ef94427f2d678
|
src/as/com/threerings/flash/TextFieldUtil.as
|
src/as/com/threerings/flash/TextFieldUtil.as
|
//
// $Id$
//
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/nenya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.flash {
import flash.events.Event;
import flash.events.MouseEvent;
import flash.filters.GlowFilter;
import flash.system.Capabilities;
import flash.system.System;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFieldType;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;
public class TextFieldUtil
{
/** A fudge factor that must be added to a TextField's textWidth when setting the width. */
public static const WIDTH_PAD :int = 5;
/** A fudge factor that must be added to a TextField's textHeight when setting the height. */
public static const HEIGHT_PAD :int = 4;
/**
* Create a TextField.
*
* args: contains properties with which to initialize the TextField
*/
public static function createField (
text :String, args :Object = null, clazz :Class = null) :TextField
{
var tf :TextField = (clazz == null) ? new TextField() : TextField(new clazz());
tf.background = getArg(args, "background", false);
tf.border = getArg(args, "border", false);
tf.multiline = getArg(args, "multiline", false);
tf.type = getArg(args, "type", TextFieldType.DYNAMIC);
var format :* = getArg(args, "format");
if (format !== undefined) {
tf.defaultTextFormat = format;
}
var outColor :* = getArg(args, "outlineColor");
if (outColor !== undefined) {
tf.filters = [ new GlowFilter(uint(outColor), 1, 2, 2, 255) ];
}
tf.autoSize = getArg(args, "autoSize", TextFieldAutoSize.LEFT);
tf.text = text;
if (tf.autoSize != null) {
tf.width = tf.textWidth + 5;
tf.height = tf.textHeight + 4;
}
return tf;
}
/**
* Create a TextFormat.
*/
public static function createFormat (args :Object) :TextFormat
{
var f :TextFormat = new TextFormat();
f.align = getArg(args, "align", TextFormatAlign.LEFT);
f.blockIndent = getArg(args, "blockIndent", null);
f.bold = getArg(args, "bold", false);
f.bullet = getArg(args, "bullet", null);
f.size = getArg(args, "size", 18);
f.font = getArg(args, "font", "Arial");
f.color = getArg(args, "color", 0x000000);
return f;
}
/**
* Include the specified TextField in a set of TextFields in which only
* one may have a selection at a time.
*/
public static function trackSingleSelectable (textField :TextField) :void
{
textField.addEventListener(MouseEvent.MOUSE_MOVE, handleTrackedSelection);
// immediately put the kibosh on any selection
textField.setSelection(0, 0);
}
/**
* Internal method related to tracking a single selectable TextField.
*/
protected static function handleTrackedSelection (event :MouseEvent) :void
{
if (event.buttonDown) {
var field :TextField = event.target as TextField;
if (field == _lastSelected) {
updateSelection(field);
} else if (field.selectionBeginIndex != field.selectionEndIndex) {
// clear the last one..
if (_lastSelected != null) {
handleLastSelectedRemoved();
}
_lastSelected = field;
_lastSelected.addEventListener(Event.REMOVED_FROM_STAGE, handleLastSelectedRemoved);
updateSelection(field);
}
}
}
/**
* Process the selection.
*/
protected static function updateSelection (field :TextField) :void
{
if (-1 != Capabilities.os.indexOf("Linux")) {
var str :String = field.text.substring(
field.selectionBeginIndex, field.selectionEndIndex);
System.setClipboard(str);
}
}
/**
* Internal method related to tracking a single selectable TextField.
*/
protected static function handleLastSelectedRemoved (... ignored) :void
{
_lastSelected.setSelection(0, 0);
_lastSelected.removeEventListener(Event.REMOVED_FROM_STAGE, handleLastSelectedRemoved);
_lastSelected = null;
}
/**
* Utility function for createTextField() and createFormat().
*/
protected static function getArg (args :Object, name :String, defVal :* = undefined) :*
{
if (args != null && (name in args)) {
return args[name];
}
return defVal;
}
/** The last tracked TextField to be selected. */
protected static var _lastSelected :TextField;
}
}
|
//
// $Id$
//
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/nenya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.flash {
import flash.events.Event;
import flash.events.MouseEvent;
import flash.filters.GlowFilter;
import flash.system.Capabilities;
import flash.system.System;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFieldType;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;
import com.threerings.util.Util;
public class TextFieldUtil
{
/** A fudge factor that must be added to a TextField's textWidth when setting the width. */
public static const WIDTH_PAD :int = 5;
/** A fudge factor that must be added to a TextField's textHeight when setting the height. */
public static const HEIGHT_PAD :int = 4;
/**
* Create a TextField.
*
* @param initProps contains properties with which to initialize the TextField.
* Additionally it may contain the following properties:
* outlineColor: uint
*
* initProps may be destructively modified.
*/
public static function createField (
text :String, initProps :Object = null, clazz :Class = null) :TextField
{
var tf :TextField = (clazz == null) ? new TextField() : TextField(new clazz());
if ("outlineColor" in initProps) {
tf.filters = [ new GlowFilter(uint(initProps["outlineColor"]), 1, 2, 2, 255) ];
}
Util.init(tf, initProps, null, MASK_FIELD_PROPS);
tf.text = text;
if (tf.autoSize != null) {
tf.width = tf.textWidth + WIDTH_PAD;
tf.height = tf.textHeight + HEIGHT_PAD;
}
return tf;
}
/**
* Create a TextFormat using initProps.
* If unspecified, the following properties have default values:
* size: 18
* font: _sans
*/
public static function createFormat (initProps :Object) :TextFormat
{
var f :TextFormat = new TextFormat();
Util.init(f, initProps, DEFAULT_FORMAT_PROPS);
return f;
}
/**
* Include the specified TextField in a set of TextFields in which only
* one may have a selection at a time.
*/
public static function trackSingleSelectable (textField :TextField) :void
{
textField.addEventListener(MouseEvent.MOUSE_MOVE, handleTrackedSelection);
// immediately put the kibosh on any selection
textField.setSelection(0, 0);
}
/**
* Internal method related to tracking a single selectable TextField.
*/
protected static function handleTrackedSelection (event :MouseEvent) :void
{
if (event.buttonDown) {
var field :TextField = event.target as TextField;
if (field == _lastSelected) {
updateSelection(field);
} else if (field.selectionBeginIndex != field.selectionEndIndex) {
// clear the last one..
if (_lastSelected != null) {
handleLastSelectedRemoved();
}
_lastSelected = field;
_lastSelected.addEventListener(Event.REMOVED_FROM_STAGE, handleLastSelectedRemoved);
updateSelection(field);
}
}
}
/**
* Process the selection.
*/
protected static function updateSelection (field :TextField) :void
{
if (-1 != Capabilities.os.indexOf("Linux")) {
var str :String = field.text.substring(
field.selectionBeginIndex, field.selectionEndIndex);
System.setClipboard(str);
}
}
/**
* Internal method related to tracking a single selectable TextField.
*/
protected static function handleLastSelectedRemoved (... ignored) :void
{
_lastSelected.setSelection(0, 0);
_lastSelected.removeEventListener(Event.REMOVED_FROM_STAGE, handleLastSelectedRemoved);
_lastSelected = null;
}
/** The last tracked TextField to be selected. */
protected static var _lastSelected :TextField;
protected static const MASK_FIELD_PROPS :Object = { outlineColor: true };
protected static const DEFAULT_FORMAT_PROPS :Object = { size: 18, font: "_sans" };
}
}
|
Use Util.init() to initialize TextFields and TextFormats.
|
Use Util.init() to initialize TextFields and TextFormats.
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@381 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
e649880f9024e907b0b1396e113ff647fc33bef5
|
src/as/com/threerings/util/Log.as
|
src/as/com/threerings/util/Log.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.getQualifiedClassName;
/**
* A simple logging mechanism.
*
* Log instances are created for modules, and the logging level can be configured per
* module in a hierarchical fashion.
*
* Typically, you should create a module name based on the full path to a class:
* calling getLog() and passing an object or Class will do this. Alternattely, you
* may create a Log to share in several classes in a package, in which case the
* module name can be like "com.foocorp.games.bunnywar". Finally, you can just
* create made-up module names like "mygame" or "util", but this is not recommended.
* You really should name things based on your packages, and your packages should be
* named according to Sun's recommendations for Java packages.
*
* Typical usage for creating a Log to be used by the entire class would be:
* public class MyClass
* {
* private static const log :Log = Log.getLog(MyClass);
* ...
*
* OR, if you just need a one-off Log:
* protected function doStuff (thingy :Thingy) :void
* {
* if (!isValid(thingy)) {
* Log.getLog(this).warn("Invalid thingy specified", "thingy", thingy);
* ....
*/
public class Log
{
/** Log level constants. */
public static const DEBUG :int = 0;
public static const INFO :int = 1;
public static const WARNING :int = 2;
public static const ERROR :int = 3;
public static const OFF :int = 4;
// if you add to this, update LEVEL_NAMES and stringToLevel() at the bottom...
/**
* Retrieve a Log for the specified module.
*
* @param moduleSpec can be a String of the module name, or any Object or Class to
* have the module name be the full package and name of the class (recommended).
*/
public static function getLog (moduleSpec :*) :Log
{
const module :String = (moduleSpec is String) ? String(moduleSpec)
: getQualifiedClassName(moduleSpec).replace("::", ".");
return new Log(module);
}
/**
* A convenience function for quickly and easily inserting printy
* statements during application development.
*/
public static function testing (... params) :void
{
var log :Log = new Log("testing");
log.debug.apply(log, params);
}
/**
* A convenience function for quickly printing a stack trace
* to the log, useful for debugging.
*/
public static function dumpStack () :void
{
testing(new Error("dumpStack").getStackTrace());
}
/**
* Add a logging target.
*/
public static function addTarget (target :LogTarget) :void
{
_targets.push(target);
}
/**
* Remove a logging target.
*/
public static function removeTarget (target :LogTarget) :void
{
var dex :int = _targets.indexOf(target);
if (dex != -1) {
_targets.splice(dex, 1);
}
}
/**
* Set the log level for the specified module.
*
* @param module The smallest prefix desired to configure a log level.
* For example, you can set the global level with Log.setLevel("", Log.INFO);
* Then you can Log.setLevel("com.foo.game", Log.DEBUG). Now, everything
* logs at INFO level except for modules within com.foo.game, which is at DEBUG.
*/
public static function setLevel (module :String, level :int) :void
{
_setLevels[module] = level;
_levels = {}; // reset cached levels
}
/**
* Parses a String in the form of ":info;com.foo.game:debug;com.bar.util:warning"
*
* Semicolons separate modules, colons separate a module name from the log level.
* An empty string specifies the top-level (global) module.
*/
public static function setLevels (settingString :String) :void
{
for each (var module :String in settingString.split(";")) {
var setting :Array = module.split(":");
_setLevels[setting[0]] = stringToLevel(String(setting[1]));
}
_levels = {}; // reset cached levels
}
/**
* Use Log.getLog();
*
* @private
*/
public function Log (module :String)
{
if (module == null) module = "";
_module = module;
}
/**
* Log a message with 'debug' priority.
*
* @param args The first argument is the actual message to log. After that, each pair
* of parameters is printed in key/value form, the benefit being that if no log
* message is generated then toString() will not be called on the values.
* A final parameter may be an Error, in which case the stack trace is printed.
*
* @example
* <listing version="3.0">
* log.debug("Message", "key1", value1, "key2", value2, optionalError);
* </listing>
*/
public function debug (... args) :void
{
doLog(DEBUG, args);
}
/**
* Log a message with 'info' priority.
*
* @param args The first argument is the actual message to log. After that, each pair
* of parameters is printed in key/value form, the benefit being that if no log
* message is generated then toString() will not be called on the values.
* A final parameter may be an Error, in which case the stack trace is printed.
*
* @example
* <listing version="3.0">
* log.info("Message", "key1", value1, "key2", value2, optionalError);
* </listing>
*/
public function info (... args) :void
{
doLog(INFO, args);
}
/**
* Log a message with 'warning' priority.
*
* @param args The first argument is the actual message to log. After that, each pair
* of parameters is printed in key/value form, the benefit being that if no log
* message is generated then toString() will not be called on the values.
* A final parameter may be an Error, in which case the stack trace is printed.
*
* @example
* <listing version="3.0">
* log.warning("Message", "key1", value1, "key2", value2, optionalError);
* </listing>
*/
public function warning (... args) :void
{
doLog(WARNING, args);
}
/**
* Log a message with 'error' priority.
*
* @param args The first argument is the actual message to log. After that, each pair
* of parameters is printed in key/value form, the benefit being that if no log
* message is generated then toString() will not be called on the values.
* A final parameter may be an Error, in which case the stack trace is printed.
*
* @example
* <listing version="3.0">
* log.error("Message", "key1", value1, "key2", value2, optionalError);
* </listing>
*/
public function error (... args) :void
{
doLog(ERROR, args);
}
/**
* Log just a stack trace with 'warning' priority.
* Deprecated, sorta. Just use warning("Message", error);
*/
public function logStackTrace (error :Error) :void
{
warning(error.getStackTrace());
}
protected function doLog (level :int, args :Array) :void
{
if (level < getLevel(_module)) {
return; // we don't want to log it!
}
var logMessage :String = formatMessage(level, args);
trace(logMessage);
// possibly also dispatch to any other log targets.
for each (var target :LogTarget in _targets) {
target.log(logMessage);
}
}
protected function formatMessage (level :int, args :Array) :String
{
var msg :String = getTimeStamp() + " " + LEVEL_NAMES[level] + ": " + _module;
if (args.length > 0) {
msg += " " + String(args[0]); // the primary log message
var err :Error = null;
if (args.length % 2 == 0) { // there's one extra arg
var lastArg :Object = args.pop();
if (lastArg is Error) {
err = lastArg as Error; // ok, it's an error, we like those
} else {
args.push(lastArg, ""); // what? Well, cope by pushing it back with a ""
}
}
if (args.length > 1) {
for (var ii :int = 1; ii < args.length; ii += 2) {
msg += (ii == 1) ? " [" : ", ";
msg += String(args[ii]) + "=" + String(args[ii + 1]);
}
msg += "]";
}
if (err != null) {
msg += "\n" + err.getStackTrace();
}
}
return msg;
}
protected function getTimeStamp () :String
{
var d :Date = new Date();
// return d.toLocaleTimeString();
// format it like the date format in our java logs
return d.fullYear + "-" +
StringUtil.prepad(String(d.month + 1), 2, "0") + "-" +
StringUtil.prepad(String(d.date), 2, "0") + " " +
StringUtil.prepad(String(d.hours), 2, "0") + ":" +
StringUtil.prepad(String(d.minutes), 2, "0") + ":" +
StringUtil.prepad(String(d.seconds), 2, "0") + "," +
StringUtil.prepad(String(d.milliseconds), 3, "0");
}
/**
* Get the logging level for the specified module.
*/
protected static function getLevel (module :String) :int
{
// we probably already have the level cached for this module
var lev :Object = _levels[module];
if (lev == null) {
// cache miss- copy some parent module's level...
var ancestor :String = module;
while (true) {
lev = _setLevels[ancestor];
if (lev != null || ancestor == "") {
// bail if we found a setting or get to the top level,
// but always save the level from _setLevels into _levels
_levels[module] = int(lev); // if lev was null, this will become 0 (DEBUG)
break;
}
var dex :int = ancestor.lastIndexOf(".");
ancestor = (dex == -1) ? "" : ancestor.substring(0, dex);
}
}
return int(lev);
}
protected static function stringToLevel (s :String) :int
{
switch (s.toLowerCase()) {
default: // default to DEBUG
case "debug": return DEBUG;
case "info": return INFO;
case "warning": case "warn": return WARNING;
case "error": return ERROR;
case "off": return OFF;
}
}
/** The module to which this log instance applies. */
protected var _module :String;
/** Other registered LogTargets, besides the trace log. */
protected static var _targets :Array = [];
/** A cache of log levels, copied from _setLevels. */
protected static var _levels :Object = {};
/** The configured log levels. */
protected static var _setLevels :Object = { "": DEBUG }; // global: debug
/** The outputted names of each level. The last one isn't used, it corresponds with OFF. */
protected static const LEVEL_NAMES :Array = [ "debug", "INFO", "WARN", "ERROR", false ];
}
}
|
//
// $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.getQualifiedClassName;
/**
* A simple logging mechanism.
*
* Log instances are created for modules, and the logging level can be configured per
* module in a hierarchical fashion.
*
* Typically, you should create a module name based on the full path to a class:
* calling getLog() and passing an object or Class will do this. Alternattely, you
* may create a Log to share in several classes in a package, in which case the
* module name can be like "com.foocorp.games.bunnywar". Finally, you can just
* create made-up module names like "mygame" or "util", but this is not recommended.
* You really should name things based on your packages, and your packages should be
* named according to Sun's recommendations for Java packages.
*
* Typical usage for creating a Log to be used by the entire class would be:
* public class MyClass
* {
* private static const log :Log = Log.getLog(MyClass);
* ...
*
* OR, if you just need a one-off Log:
* protected function doStuff (thingy :Thingy) :void
* {
* if (!isValid(thingy)) {
* Log.getLog(this).warn("Invalid thingy specified", "thingy", thingy);
* ....
*/
public class Log
{
/** Log level constants. */
public static const DEBUG :int = 0;
public static const INFO :int = 1;
public static const WARNING :int = 2;
public static const ERROR :int = 3;
public static const OFF :int = 4;
// if you add to this, update LEVEL_NAMES and stringToLevel() at the bottom...
/**
* Retrieve a Log for the specified module.
*
* @param moduleSpec can be a String of the module name, or any Object or Class to
* have the module name be the full package and name of the class (recommended).
*/
public static function getLog (moduleSpec :*) :Log
{
const module :String = (moduleSpec is String) ? String(moduleSpec)
: getQualifiedClassName(moduleSpec).replace("::", ".");
return new Log(module);
}
/**
* A convenience function for quickly and easily inserting printy
* statements during application development.
*/
public static function testing (... params) :void
{
var log :Log = new Log("testing");
log.debug.apply(log, params);
}
/**
* A convenience function for quickly printing a stack trace
* to the log, useful for debugging.
*/
public static function dumpStack (msg :String = "dumpStack") :void
{
testing(new Error(msg).getStackTrace());
}
/**
* Add a logging target.
*/
public static function addTarget (target :LogTarget) :void
{
_targets.push(target);
}
/**
* Remove a logging target.
*/
public static function removeTarget (target :LogTarget) :void
{
var dex :int = _targets.indexOf(target);
if (dex != -1) {
_targets.splice(dex, 1);
}
}
/**
* Set the log level for the specified module.
*
* @param module The smallest prefix desired to configure a log level.
* For example, you can set the global level with Log.setLevel("", Log.INFO);
* Then you can Log.setLevel("com.foo.game", Log.DEBUG). Now, everything
* logs at INFO level except for modules within com.foo.game, which is at DEBUG.
*/
public static function setLevel (module :String, level :int) :void
{
_setLevels[module] = level;
_levels = {}; // reset cached levels
}
/**
* Parses a String in the form of ":info;com.foo.game:debug;com.bar.util:warning"
*
* Semicolons separate modules, colons separate a module name from the log level.
* An empty string specifies the top-level (global) module.
*/
public static function setLevels (settingString :String) :void
{
for each (var module :String in settingString.split(";")) {
var setting :Array = module.split(":");
_setLevels[setting[0]] = stringToLevel(String(setting[1]));
}
_levels = {}; // reset cached levels
}
/**
* Use Log.getLog();
*
* @private
*/
public function Log (module :String)
{
if (module == null) module = "";
_module = module;
}
/**
* Log a message with 'debug' priority.
*
* @param args The first argument is the actual message to log. After that, each pair
* of parameters is printed in key/value form, the benefit being that if no log
* message is generated then toString() will not be called on the values.
* A final parameter may be an Error, in which case the stack trace is printed.
*
* @example
* <listing version="3.0">
* log.debug("Message", "key1", value1, "key2", value2, optionalError);
* </listing>
*/
public function debug (... args) :void
{
doLog(DEBUG, args);
}
/**
* Log a message with 'info' priority.
*
* @param args The first argument is the actual message to log. After that, each pair
* of parameters is printed in key/value form, the benefit being that if no log
* message is generated then toString() will not be called on the values.
* A final parameter may be an Error, in which case the stack trace is printed.
*
* @example
* <listing version="3.0">
* log.info("Message", "key1", value1, "key2", value2, optionalError);
* </listing>
*/
public function info (... args) :void
{
doLog(INFO, args);
}
/**
* Log a message with 'warning' priority.
*
* @param args The first argument is the actual message to log. After that, each pair
* of parameters is printed in key/value form, the benefit being that if no log
* message is generated then toString() will not be called on the values.
* A final parameter may be an Error, in which case the stack trace is printed.
*
* @example
* <listing version="3.0">
* log.warning("Message", "key1", value1, "key2", value2, optionalError);
* </listing>
*/
public function warning (... args) :void
{
doLog(WARNING, args);
}
/**
* Log a message with 'error' priority.
*
* @param args The first argument is the actual message to log. After that, each pair
* of parameters is printed in key/value form, the benefit being that if no log
* message is generated then toString() will not be called on the values.
* A final parameter may be an Error, in which case the stack trace is printed.
*
* @example
* <listing version="3.0">
* log.error("Message", "key1", value1, "key2", value2, optionalError);
* </listing>
*/
public function error (... args) :void
{
doLog(ERROR, args);
}
/**
* Log just a stack trace with 'warning' priority.
* Deprecated, sorta. Just use warning("Message", error);
*/
public function logStackTrace (error :Error) :void
{
warning(error.getStackTrace());
}
protected function doLog (level :int, args :Array) :void
{
if (level < getLevel(_module)) {
return; // we don't want to log it!
}
var logMessage :String = formatMessage(level, args);
trace(logMessage);
// possibly also dispatch to any other log targets.
for each (var target :LogTarget in _targets) {
target.log(logMessage);
}
}
protected function formatMessage (level :int, args :Array) :String
{
var msg :String = getTimeStamp() + " " + LEVEL_NAMES[level] + ": " + _module;
if (args.length > 0) {
msg += " " + String(args[0]); // the primary log message
var err :Error = null;
if (args.length % 2 == 0) { // there's one extra arg
var lastArg :Object = args.pop();
if (lastArg is Error) {
err = lastArg as Error; // ok, it's an error, we like those
} else {
args.push(lastArg, ""); // what? Well, cope by pushing it back with a ""
}
}
if (args.length > 1) {
for (var ii :int = 1; ii < args.length; ii += 2) {
msg += (ii == 1) ? " [" : ", ";
msg += String(args[ii]) + "=" + String(args[ii + 1]);
}
msg += "]";
}
if (err != null) {
msg += "\n" + err.getStackTrace();
}
}
return msg;
}
protected function getTimeStamp () :String
{
var d :Date = new Date();
// return d.toLocaleTimeString();
// format it like the date format in our java logs
return d.fullYear + "-" +
StringUtil.prepad(String(d.month + 1), 2, "0") + "-" +
StringUtil.prepad(String(d.date), 2, "0") + " " +
StringUtil.prepad(String(d.hours), 2, "0") + ":" +
StringUtil.prepad(String(d.minutes), 2, "0") + ":" +
StringUtil.prepad(String(d.seconds), 2, "0") + "," +
StringUtil.prepad(String(d.milliseconds), 3, "0");
}
/**
* Get the logging level for the specified module.
*/
protected static function getLevel (module :String) :int
{
// we probably already have the level cached for this module
var lev :Object = _levels[module];
if (lev == null) {
// cache miss- copy some parent module's level...
var ancestor :String = module;
while (true) {
lev = _setLevels[ancestor];
if (lev != null || ancestor == "") {
// bail if we found a setting or get to the top level,
// but always save the level from _setLevels into _levels
_levels[module] = int(lev); // if lev was null, this will become 0 (DEBUG)
break;
}
var dex :int = ancestor.lastIndexOf(".");
ancestor = (dex == -1) ? "" : ancestor.substring(0, dex);
}
}
return int(lev);
}
protected static function stringToLevel (s :String) :int
{
switch (s.toLowerCase()) {
default: // default to DEBUG
case "debug": return DEBUG;
case "info": return INFO;
case "warning": case "warn": return WARNING;
case "error": return ERROR;
case "off": return OFF;
}
}
/** The module to which this log instance applies. */
protected var _module :String;
/** Other registered LogTargets, besides the trace log. */
protected static var _targets :Array = [];
/** A cache of log levels, copied from _setLevels. */
protected static var _levels :Object = {};
/** The configured log levels. */
protected static var _setLevels :Object = { "": DEBUG }; // global: debug
/** The outputted names of each level. The last one isn't used, it corresponds with OFF. */
protected static const LEVEL_NAMES :Array = [ "debug", "INFO", "WARN", "ERROR", false ];
}
}
|
Allow a message to be passed to happy testing dumpStack()
|
Allow a message to be passed to happy testing dumpStack()
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5566 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
9a262df8fc9c68589b85b834de33a21fb1ea024f
|
src/org/mangui/hls/HLSSettings.as
|
src/org/mangui/hls/HLSSettings.as
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls {
import org.mangui.hls.constant.HLSSeekMode;
import org.mangui.hls.constant.HLSMaxLevelCappingMode;
public final class HLSSettings extends Object {
/**
* Limit levels usable in auto-quality by the stage dimensions (width and height).
* true - level width and height (defined in m3u8 playlist) will be compared with the player width and height (stage.stageWidth and stage.stageHeight).
* Max level will be set depending on the maxLevelCappingMode option.
* false - levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration.
*
* Note: this setting is ignored in manual mode so all the levels could be selected manually.
*
* Default is false
*/
public static var capLevelToStage : Boolean = false;
/**
* Defines the max level capping mode to the one available in HLSMaxLevelCappingMode
* HLSMaxLevelCappingMode.DOWNSCALE - max capped level should be the one with the dimensions equal or greater than the stage dimensions (so the video will be downscaled)
* HLSMaxLevelCappingMode.UPSCALE - max capped level should be the one with the dimensions equal or lower than the stage dimensions (so the video will be upscaled)
*
* Default is HLSMaxLevelCappingMode.DOWNSCALE
*/
public static var maxLevelCappingMode : String = HLSMaxLevelCappingMode.DOWNSCALE;
// // // // // ///////////////////////////////////
//
// org.mangui.hls.stream.HLSNetStream
//
// // // // // ///////////////////////////////////
/**
* Defines minimum buffer length in seconds before playback can start, after seeking or buffer stalling.
*
* Default is -1 = auto
*/
public static var minBufferLength : Number = -1;
/**
* Defines maximum buffer length in seconds.
* (0 means infinite buffering)
*
* Default is 60.
*/
public static var maxBufferLength : Number = 60;
/**
* Defines low buffer length in seconds.
* When crossing down this threshold, HLS will switch to buffering state.
*
* Default is 3.
*/
public static var lowBufferLength : Number = 3;
/**
* Defines seek mode to one form available in HLSSeekMode class:
* HLSSeekMode.ACCURATE_SEEK - accurate seeking to exact requested position
* HLSSeekMode.KEYFRAME_SEEK - key-frame based seeking (seek to nearest key frame before requested seek position)
* HLSSeekMode.SEGMENT_SEEK - segment based seeking (seek to beginning of segment containing requested seek position)
*
* Default is HLSSeekMode.ACCURATE_SEEK.
*/
public static var seekMode : String = HLSSeekMode.ACCURATE_SEEK;
/** max nb of retries for Key Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var keyLoadMaxRetry : int = -1;
/** keyLoadMaxRetryTimeout
* Maximum key retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on key request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until keyLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var keyLoadMaxRetryTimeout : Number = 64000;
/** max nb of retries for Fragment Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var fragmentLoadMaxRetry : int = -1;
/** fragmentLoadMaxRetryTimeout
* Maximum Fragment retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until fragmentLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var fragmentLoadMaxRetryTimeout : Number = 64000;
/**
* If set to true, live playlist will be flushed from URL cache before reloading
* (this is to workaround some cache issues with some combination of Flash Player / IE version)
*
* Default is false
*/
public static var flushLiveURLCache : Boolean = false;
/** max nb of retries for Manifest Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var manifestLoadMaxRetry : int = -1;
/** manifestLoadMaxRetryTimeout
* Maximum Manifest retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until manifestLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var manifestLoadMaxRetryTimeout : Number = 64000;
/**
* If greater than 0, specifies the preferred bitrate.
* If -1, and startFromLevel is not specified, automatic start level selection will be used.
* This parameter, if set, will take priority over startFromLevel.
*/
public static var startFromBitrate : Number = -1;
/** start level :
* from 0 to 1 : indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
*/
public static var startFromLevel : Number = -1;
/** seek level :
* from 0 to 1 : indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, keep previous level matching previous download bandwidth
*/
public static var seekFromLevel : Number = -1;
/** use hardware video decoder :
* it will set NetStream.useHardwareDecoder
* refer to http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#useHardwareDecoder
*/
public static var useHardwareVideoDecoder : Boolean = false;
/**
* Defines whether INFO level log messages will will appear in the console
* Default is true.
*/
public static var logInfo : Boolean = true;
/**
* Defines whether DEBUG level log messages will will appear in the console
* Default is false.
*/
public static var logDebug : Boolean = false;
/**
* Defines whether DEBUG2 level log messages will will appear in the console
* Default is false.
*/
public static var logDebug2 : Boolean = false;
/**
* Defines whether WARN level log messages will will appear in the console
* Default is true.
*/
public static var logWarn : Boolean = true;
/**
* Defines whether ERROR level log messages will will appear in the console
* Default is true.
*/
public static var logError : Boolean = true;
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls {
import org.mangui.hls.constant.HLSSeekMode;
import org.mangui.hls.constant.HLSMaxLevelCappingMode;
public final class HLSSettings extends Object {
/**
* Limit levels usable in auto-quality by the stage dimensions (width and height).
* true - level width and height (defined in m3u8 playlist) will be compared with the player width and height (stage.stageWidth and stage.stageHeight).
* Max level will be set depending on the maxLevelCappingMode option.
* false - levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration.
*
* Note: this setting is ignored in manual mode so all the levels could be selected manually.
*
* Default is false
*/
public static var capLevelToStage : Boolean = false;
/**
* Defines the max level capping mode to the one available in HLSMaxLevelCappingMode
* HLSMaxLevelCappingMode.DOWNSCALE - max capped level should be the one with the dimensions equal or greater than the stage dimensions (so the video will be downscaled)
* HLSMaxLevelCappingMode.UPSCALE - max capped level should be the one with the dimensions equal or lower than the stage dimensions (so the video will be upscaled)
*
* Default is HLSMaxLevelCappingMode.DOWNSCALE
*/
public static var maxLevelCappingMode : String = HLSMaxLevelCappingMode.DOWNSCALE;
// // // // // ///////////////////////////////////
//
// org.mangui.hls.stream.HLSNetStream
//
// // // // // ///////////////////////////////////
/**
* Defines minimum buffer length in seconds before playback can start, after seeking or buffer stalling.
*
* Default is -1 = auto
*/
public static var minBufferLength : Number = -1;
/**
* Defines maximum buffer length in seconds.
* (0 means infinite buffering)
*
* Default is 300.
*/
public static var maxBufferLength : Number = 300;
/**
* Defines low buffer length in seconds.
* When crossing down this threshold, HLS will switch to buffering state.
*
* Default is 3.
*/
public static var lowBufferLength : Number = 3;
/**
* Defines seek mode to one form available in HLSSeekMode class:
* HLSSeekMode.ACCURATE_SEEK - accurate seeking to exact requested position
* HLSSeekMode.KEYFRAME_SEEK - key-frame based seeking (seek to nearest key frame before requested seek position)
* HLSSeekMode.SEGMENT_SEEK - segment based seeking (seek to beginning of segment containing requested seek position)
*
* Default is HLSSeekMode.ACCURATE_SEEK.
*/
public static var seekMode : String = HLSSeekMode.ACCURATE_SEEK;
/** max nb of retries for Key Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var keyLoadMaxRetry : int = -1;
/** keyLoadMaxRetryTimeout
* Maximum key retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on key request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until keyLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var keyLoadMaxRetryTimeout : Number = 64000;
/** max nb of retries for Fragment Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var fragmentLoadMaxRetry : int = -1;
/** fragmentLoadMaxRetryTimeout
* Maximum Fragment retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until fragmentLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var fragmentLoadMaxRetryTimeout : Number = 64000;
/**
* If set to true, live playlist will be flushed from URL cache before reloading
* (this is to workaround some cache issues with some combination of Flash Player / IE version)
*
* Default is false
*/
public static var flushLiveURLCache : Boolean = false;
/** max nb of retries for Manifest Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var manifestLoadMaxRetry : int = -1;
/** manifestLoadMaxRetryTimeout
* Maximum Manifest retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until manifestLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var manifestLoadMaxRetryTimeout : Number = 64000;
/**
* If greater than 0, specifies the preferred bitrate.
* If -1, and startFromLevel is not specified, automatic start level selection will be used.
* This parameter, if set, will take priority over startFromLevel.
*/
public static var startFromBitrate : Number = -1;
/** start level :
* from 0 to 1 : indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
*/
public static var startFromLevel : Number = -1;
/** seek level :
* from 0 to 1 : indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, keep previous level matching previous download bandwidth
*/
public static var seekFromLevel : Number = -1;
/** use hardware video decoder :
* it will set NetStream.useHardwareDecoder
* refer to http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#useHardwareDecoder
*/
public static var useHardwareVideoDecoder : Boolean = false;
/**
* Defines whether INFO level log messages will will appear in the console
* Default is true.
*/
public static var logInfo : Boolean = true;
/**
* Defines whether DEBUG level log messages will will appear in the console
* Default is false.
*/
public static var logDebug : Boolean = false;
/**
* Defines whether DEBUG2 level log messages will will appear in the console
* Default is false.
*/
public static var logDebug2 : Boolean = false;
/**
* Defines whether WARN level log messages will will appear in the console
* Default is true.
*/
public static var logWarn : Boolean = true;
/**
* Defines whether ERROR level log messages will will appear in the console
* Default is true.
*/
public static var logError : Boolean = true;
}
}
|
increase default max buffer length to 300s
|
increase default max buffer length to 300s
|
ActionScript
|
mpl-2.0
|
aevange/flashls,tedconf/flashls,suuhas/flashls,JulianPena/flashls,fixedmachine/flashls,vidible/vdb-flashls,School-Improvement-Network/flashls,fixedmachine/flashls,aevange/flashls,NicolasSiver/flashls,Boxie5/flashls,suuhas/flashls,hola/flashls,tedconf/flashls,vidible/vdb-flashls,Boxie5/flashls,Peer5/flashls,mangui/flashls,loungelogic/flashls,jlacivita/flashls,thdtjsdn/flashls,jlacivita/flashls,suuhas/flashls,Peer5/flashls,neilrackett/flashls,clappr/flashls,mangui/flashls,suuhas/flashls,viktorot/flashls,aevange/flashls,codex-corp/flashls,dighan/flashls,thdtjsdn/flashls,Peer5/flashls,hola/flashls,clappr/flashls,School-Improvement-Network/flashls,aevange/flashls,loungelogic/flashls,JulianPena/flashls,viktorot/flashls,dighan/flashls,viktorot/flashls,codex-corp/flashls,School-Improvement-Network/flashls,Corey600/flashls,neilrackett/flashls,Corey600/flashls,Peer5/flashls,NicolasSiver/flashls
|
6f41602665d2c76ab371b9c956a15813b8ebf19d
|
src/org/openPyro/managers/OverlayManager.as
|
src/org/openPyro/managers/OverlayManager.as
|
package org.openPyro.managers
{
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.Sprite;
import flash.events.Event;
import flash.geom.Point;
public class OverlayManager
{
public function OverlayManager()
{
super();
}
protected var _overlayDisplayObject:DisplayObjectContainer
/**
* The overlay layer on which the popups are rendered. If a new layer
* is set as the overlayContainer, the old one is removed from the
* stage, so please set displayobjects for this value to be dedicated
* to just displaying overlays.
*/
public function set overlayContainer(dp:DisplayObjectContainer):void{
/*
If there already was an overlay created, remove
it and all its children
*/
if(_overlayDisplayObject){
while(_overlayDisplayObject.numChildren > 0){
_overlayDisplayObject.removeChildAt(0)
}
bgSprite = null;
if(_overlayDisplayObject.parent){
_overlayDisplayObject.parent.removeChild(_overlayDisplayObject);
}
}
_overlayDisplayObject = dp;
}
public function get overlayContainer():DisplayObjectContainer{
return _overlayDisplayObject;
}
private static var instance:OverlayManager
public static function getInstance():OverlayManager{
if(!instance){
instance = new OverlayManager()
}
return instance;
}
private var bgSprite:Sprite;
private var centeredPopup:DisplayObject
public function showPopUp(popupObject:DisplayObject, modal:Boolean=false, center:Boolean=true):void{
if(!_overlayDisplayObject){
throw new Error("No overlay displayObject defined on which to draw")
}
if(modal){
if(!bgSprite){
bgSprite = new Sprite()
bgSprite.graphics.beginFill(0x00000, .5)
bgSprite.graphics.drawRect(0,0,50,50);
_overlayDisplayObject.addChild(bgSprite);
_overlayDisplayObject.stage.addEventListener(Event.RESIZE, onBaseStageResize)
// capture mouse interactions here.
}
bgSprite.width = _overlayDisplayObject.stage.stageWidth;
bgSprite.height = _overlayDisplayObject.stage.stageHeight
bgSprite.visible = true;
}
_overlayDisplayObject.addChild(popupObject);
if(center){
centeredPopup = popupObject
popupObject.x = (_overlayDisplayObject.stage.stageWidth-popupObject.width)/2;
popupObject.y = (_overlayDisplayObject.stage.stageHeight-popupObject.height)/2;
}
}
/**
* Shows the object DisplayObject at the x and y coordinates of the target DisplayObject.
* If the target is not supplied, the object is positioned at 0,0.
*/
public function showOnOverlay(object:DisplayObject, target:DisplayObject=null):void{
_overlayDisplayObject.addChild(object);
if(target){
var orig:Point = new Point(0,0)
var pt:Point = target.localToGlobal(orig)
pt = _overlayDisplayObject.globalToLocal(pt);
object.x = pt.x
object.y = pt.y
}
var xp:Number = object.stage.stageWidth - (object.x+object.width+10);
if(xp < 0){
object.x += xp;
}
}
public function remove(popup:DisplayObject):void{
if(!popup || !popup.parent) return;
popup.parent.removeChild(popup);
bgSprite.visible = false;
}
public function removeAll():void{
while(_overlayDisplayObject.numChildren > 1){
_overlayDisplayObject.removeChildAt(1);
}
if(bgSprite){
bgSprite.visible = false;
}
}
private function onBaseStageResize(event:Event):void{
if(bgSprite){
bgSprite.width = _overlayDisplayObject.stage.stageWidth
bgSprite.height = _overlayDisplayObject.stage.stageHeight
}
if(centeredPopup){
centeredPopup.x = (_overlayDisplayObject.stage.stageWidth-centeredPopup.width)/2;
centeredPopup.y = (_overlayDisplayObject.stage.stageHeight-centeredPopup.height)/2;
}
}
}
}
|
package org.openPyro.managers
{
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.Sprite;
import flash.events.Event;
import flash.geom.Point;
public class OverlayManager
{
public function OverlayManager()
{
super();
}
protected var _overlayDisplayObject:DisplayObjectContainer
/**
* The overlay layer on which the popups are rendered. If a new layer
* is set as the overlayContainer, the old one is removed from the
* stage, so please set displayobjects for this value to be dedicated
* to just displaying overlays.
*/
public function set overlayContainer(dp:DisplayObjectContainer):void{
/*
If there already was an overlay created, remove
it and all its children
*/
if(_overlayDisplayObject){
while(_overlayDisplayObject.numChildren > 0){
_overlayDisplayObject.removeChildAt(0)
}
bgSprite = null;
if(_overlayDisplayObject.parent){
_overlayDisplayObject.parent.removeChild(_overlayDisplayObject);
}
}
_overlayDisplayObject = dp;
}
public function get overlayContainer():DisplayObjectContainer{
return _overlayDisplayObject;
}
private static var instance:OverlayManager
public static function getInstance():OverlayManager{
if(!instance){
instance = new OverlayManager()
}
return instance;
}
private var bgSprite:Sprite;
private var centeredPopup:DisplayObject
public function showPopUp(popupObject:DisplayObject, modal:Boolean=false, center:Boolean=true):void{
if(!_overlayDisplayObject){
throw new Error("No overlay displayObject defined on which to draw")
}
if(modal){
if(!bgSprite){
bgSprite = new Sprite()
bgSprite.graphics.beginFill(0x00000, .5)
bgSprite.graphics.drawRect(0,0,50,50);
_overlayDisplayObject.addChild(bgSprite);
_overlayDisplayObject.stage.addEventListener(Event.RESIZE, onBaseStageResize)
// capture mouse interactions here.
}
bgSprite.width = _overlayDisplayObject.stage.stageWidth;
bgSprite.height = _overlayDisplayObject.stage.stageHeight
bgSprite.visible = true;
}
_overlayDisplayObject.addChild(popupObject);
if(center){
centeredPopup = popupObject
popupObject.x = (_overlayDisplayObject.stage.stageWidth-popupObject.width)/2;
popupObject.y = (_overlayDisplayObject.stage.stageHeight-popupObject.height)/2;
}
}
/**
* Shows the object DisplayObject at the x and y coordinates of the target DisplayObject.
* If the target is not supplied, the object is positioned at 0,0.
*/
public function showOnOverlay(object:DisplayObject, target:DisplayObject=null):void{
_overlayDisplayObject.addChild(object);
if(target){
var orig:Point = new Point(0,0)
var pt:Point = target.localToGlobal(orig)
pt = _overlayDisplayObject.globalToLocal(pt);
object.x = pt.x
object.y = pt.y
}
var xp:Number = object.stage.stageWidth - (object.x+object.width+10);
if(xp < 0){
object.x += xp;
}
}
public function remove(popup:DisplayObject):void{
if(!popup || !popup.parent) return;
popup.parent.removeChild(popup);
if(bgSprite){
bgSprite.visible = false;
}
}
public function removeAll():void{
while(_overlayDisplayObject.numChildren > 1){
_overlayDisplayObject.removeChildAt(1);
}
if(bgSprite){
bgSprite.visible = false;
}
}
private function onBaseStageResize(event:Event):void{
if(bgSprite){
bgSprite.width = _overlayDisplayObject.stage.stageWidth
bgSprite.height = _overlayDisplayObject.stage.stageHeight
}
if(centeredPopup){
centeredPopup.x = (_overlayDisplayObject.stage.stageWidth-centeredPopup.width)/2;
centeredPopup.y = (_overlayDisplayObject.stage.stageHeight-centeredPopup.height)/2;
}
}
}
}
|
check that could cause null object reference in OverlayManager
|
check that could cause null object reference in OverlayManager
|
ActionScript
|
mit
|
arpit/openpyro
|
d8ae0c7877231aff09611b62de6fa80c28fa4a03
|
src/as/com/threerings/flex/ChatDisplayBox.as
|
src/as/com/threerings/flex/ChatDisplayBox.as
|
//
// $Id$
//
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/nenya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.flex {
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import mx.controls.TextArea;
import com.threerings.crowd.chat.client.ChatDirector;
import com.threerings.crowd.chat.client.ChatDisplay;
import com.threerings.crowd.chat.data.ChatMessage;
import com.threerings.crowd.chat.data.UserMessage;
import com.threerings.crowd.util.CrowdContext;
/**
* A very simple chat display.
*/
public class ChatDisplayBox extends TextArea
implements ChatDisplay
{
public function ChatDisplayBox (ctx :CrowdContext)
{
_ctx = ctx;
this.editable = false;
// TODO
width = 400;
height = 150;
addEventListener(Event.ADDED_TO_STAGE, handleAddRemove);
addEventListener(Event.REMOVED_FROM_STAGE, handleAddRemove);
}
// documentation inherited from interface ChatDisplay
public function clear () :void
{
this.htmlText = "";
}
// documentation inherited from interface ChatDisplay
public function displayMessage (
msg :ChatMessage, alreadyDisplayed :Boolean) :Boolean
{
if (!_scrollBot) {
_scrollBot = (verticalScrollPosition == maxVerticalScrollPosition);
}
// display the message
if (msg is UserMessage) {
this.htmlText += "<font color=\"red\"><" +
(msg as UserMessage).speaker + "></font> ";
}
this.htmlText += msg.message;
return true;
}
// handle us being added or removed from the stage
protected function handleAddRemove (event :Event) :void
{
var chatdir :ChatDirector = _ctx.getChatDirector();
if (event.type == Event.ADDED_TO_STAGE) {
chatdir.addChatDisplay(this);
} else {
chatdir.removeChatDisplay(this);
}
}
// documentation inherited
override protected function updateDisplayList (uw :Number, uh :Number) :void
{
super.updateDisplayList(uw, uh);
if (_scrollBot) {
verticalScrollPosition = maxVerticalScrollPosition;
_scrollBot = false;
}
}
/** The giver of life. */
protected var _ctx :CrowdContext;
protected var _scrollBot :Boolean;
}
}
|
//
// $Id$
//
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/nenya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.flex {
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import mx.controls.TextArea;
import com.threerings.crowd.chat.client.ChatDirector;
import com.threerings.crowd.chat.client.ChatDisplay;
import com.threerings.crowd.chat.data.ChatMessage;
import com.threerings.crowd.chat.data.UserMessage;
import com.threerings.crowd.util.CrowdContext;
/**
* A very simple chat display.
*/
public class ChatDisplayBox extends TextArea
implements ChatDisplay
{
public function ChatDisplayBox (ctx :CrowdContext)
{
_ctx = ctx;
this.editable = false;
// TODO
width = 400;
height = 150;
addEventListener(Event.ADDED_TO_STAGE, handleAddRemove);
addEventListener(Event.REMOVED_FROM_STAGE, handleAddRemove);
}
// documentation inherited from interface ChatDisplay
public function clear () :void
{
this.htmlText = "";
}
// documentation inherited from interface ChatDisplay
public function displayMessage (msg :ChatMessage) :void
{
if (!_scrollBot) {
_scrollBot = (verticalScrollPosition == maxVerticalScrollPosition);
}
// display the message
if (msg is UserMessage) {
this.htmlText += "<font color=\"red\"><" +
(msg as UserMessage).speaker + "></font> ";
}
this.htmlText += msg.message;
}
// handle us being added or removed from the stage
protected function handleAddRemove (event :Event) :void
{
var chatdir :ChatDirector = _ctx.getChatDirector();
if (event.type == Event.ADDED_TO_STAGE) {
chatdir.addChatDisplay(this);
} else {
chatdir.removeChatDisplay(this);
}
}
// documentation inherited
override protected function updateDisplayList (uw :Number, uh :Number) :void
{
super.updateDisplayList(uw, uh);
if (_scrollBot) {
verticalScrollPosition = maxVerticalScrollPosition;
_scrollBot = false;
}
}
/** The giver of life. */
protected var _ctx :CrowdContext;
protected var _scrollBot :Boolean;
}
}
|
Update to match change to ChatDisplay interface.
|
Update to match change to ChatDisplay interface.
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@847 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
3f5638d30632f4a8638d11eb6859b9e0c288b3c1
|
frameworks/projects/framework/tests/ListCollectionView_FLEX_34837_Tests.as
|
frameworks/projects/framework/tests/ListCollectionView_FLEX_34837_Tests.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 mx.collections.ArrayList;
import mx.collections.ComplexSortField;
import mx.collections.IList;
import mx.collections.ListCollectionView;
import mx.collections.Sort;
import mx.collections.SortField;
import mx.utils.ObjectUtil;
import mx.core.mx_internal;
import org.flexunit.asserts.assertEquals;
public class ListCollectionView_FLEX_34837_Tests {
private var _sut:ListCollectionView;
[Before]
public function setUp():void
{
_sut = new ListCollectionView(new ArrayList());
}
[After]
public function tearDown():void
{
_sut = null;
}
[Test]
public function test_sort_by_complex_fields_with_custom_compare_function_for_sort():void
{
function compareByStreet(a:ListCollectionView_FLEX_34837_VO, b:ListCollectionView_FLEX_34837_VO, fields:Array):int
{
var streetA:String = a.address ? a.address.street : null;
var streetB:String = b.address ? b.address.street : null;
return ObjectUtil.stringCompare(streetA, streetB, true);
}
//given
var from4To0:IList = generateVOs(5, true);
_sut.addAll(from4To0); //values["address.street"]: Street4, Street3, Street2, Street1, Street0
const sortByStreetAscending:Sort = new Sort();
sortByStreetAscending.fields = [new ComplexSortField("address.street", false, false, false)]; //should make no difference
sortByStreetAscending.compareFunction = compareByStreet;
_sut.sort = sortByStreetAscending;
//when
_sut.refresh(); //should be: Street0, Street1, Street2, Street3, Street4
//then
assertIndexesAre([0, 1, 2, 3, 4]);
}
[Test]
public function test_sort_by_complex_fields_with_custom_compare_function_for_sort_field():void
{
function compareByStreet(a:ListCollectionView_FLEX_34837_VO, b:ListCollectionView_FLEX_34837_VO):int
{
var streetA:String = a.address ? a.address.street : null;
var streetB:String = b.address ? b.address.street : null;
return ObjectUtil.stringCompare(streetA, streetB, true);
}
//given
var from4To0:IList = generateVOs(5, true);
_sut.addAll(from4To0); //values["address.street"]: Street4, Street3, Street2, Street1, Street0
const sortByStreetAscending:Sort = new Sort();
var sortField:SortField = new ComplexSortField("address.street", false, false, false);
sortField.mx_internal::compareFunction_ = compareByStreet;
sortByStreetAscending.fields = [sortField];
_sut.sort = sortByStreetAscending;
//when
_sut.refresh(); //should be: Street0, Street1, Street2, Street3, Street4
//then
assertIndexesAre([0, 1, 2, 3, 4]);
}
[Test]
public function test_changing_simple_sort_field_value_places_it_correctly_according_to_collection_sort():void
{
//given
var from1To4:IList = generateVOs(5);
from1To4.removeItemAt(0);
_sut.addAll(from1To4);
const sortByNameAscending:Sort = new Sort();
sortByNameAscending.fields = [new SortField("name", false, false, false)];
_sut.sort = sortByNameAscending;
_sut.refresh(); //values: Object1, Object2, Object3, Object4
//when
const newItem:ListCollectionView_FLEX_34837_VO = generateOneObject(5);
_sut.addItem(newItem); //values: Object1, Object2, Object3, Object4, Object5
newItem.name = "Object0"; //this should immediately place the newItem at position 0
//then
const newItemIndex:int = _sut.getItemIndex(newItem);
assertEquals("the new item should have been placed at the beginning of the list as soon as its name was changed", 0, newItemIndex);
}
private function assertIndexesAre(indexes:Array):void
{
assertEquals(indexes.length, _sut.length);
for(var i:int = 0; i < _sut.length; i++)
{
assertEquals(ListCollectionView_FLEX_34837_VO(_sut.getItemAt(i)).index, indexes[i]);
}
}
private static function generateVOs(no:int, reverse:Boolean = false):IList
{
return generateObjects(no, reverse, generateOneObject);
}
private static function generateObjects(no:int, reverse:Boolean, generator:Function):IList
{
var result:Array = [];
for(var i:int = 0; i < no; i++)
{
result.push(generator(i));
}
if(reverse)
result.reverse();
return new ArrayList(result);
}
private static function generateOneObject(index:Number):ListCollectionView_FLEX_34837_VO
{
return new ListCollectionView_FLEX_34837_VO(index, "Object", "Street");
}
}
}
[Bindable]
class ListCollectionView_FLEX_34837_VO
{
public var name:String;
public var address:ListCollectionView_FLEX_34837_AddressVO;
public var index:Number;
public function ListCollectionView_FLEX_34837_VO(index:Number, namePrefix:String, streetPrefix:String)
{
this.index = index;
this.name = namePrefix + index;
this.address = new ListCollectionView_FLEX_34837_AddressVO(streetPrefix + index);
}
}
[Bindable]
class ListCollectionView_FLEX_34837_AddressVO
{
public var street:String;
public function ListCollectionView_FLEX_34837_AddressVO(street:String)
{
this.street = street;
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 mx.collections.ArrayList;
import mx.collections.ComplexSortField;
import mx.collections.IList;
import mx.collections.ListCollectionView;
import mx.collections.Sort;
import mx.collections.SortField;
import mx.utils.ObjectUtil;
import org.flexunit.asserts.assertEquals;
public class ListCollectionView_FLEX_34837_Tests {
private var _sut:ListCollectionView;
[Before]
public function setUp():void
{
_sut = new ListCollectionView(new ArrayList());
}
[After]
public function tearDown():void
{
_sut = null;
}
[Test]
public function test_sort_by_complex_fields_with_custom_compare_function_for_sort():void
{
function compareByStreet(a:ListCollectionView_FLEX_34837_VO, b:ListCollectionView_FLEX_34837_VO, fields:Array):int
{
var streetA:String = a.address ? a.address.street : null;
var streetB:String = b.address ? b.address.street : null;
return ObjectUtil.stringCompare(streetA, streetB, true);
}
//given
var from4To0:IList = generateVOs(5, true);
_sut.addAll(from4To0); //values["address.street"]: Street4, Street3, Street2, Street1, Street0
const sortByStreetAscending:Sort = new Sort();
sortByStreetAscending.fields = [new ComplexSortField("address.street", false, false, false)]; //should make no difference
sortByStreetAscending.compareFunction = compareByStreet;
_sut.sort = sortByStreetAscending;
//when
_sut.refresh(); //should be: Street0, Street1, Street2, Street3, Street4
//then
assertIndexesAre([0, 1, 2, 3, 4]);
}
[Test]
public function test_sort_by_complex_fields_with_custom_compare_function_for_sort_field():void
{
function compareByStreet(a:ListCollectionView_FLEX_34837_VO, b:ListCollectionView_FLEX_34837_VO):int
{
var streetA:String = a.address ? a.address.street : null;
var streetB:String = b.address ? b.address.street : null;
return ObjectUtil.stringCompare(streetA, streetB, true);
}
//given
var from4To0:IList = generateVOs(5, true);
_sut.addAll(from4To0); //values["address.street"]: Street4, Street3, Street2, Street1, Street0
const sortByStreetAscending:Sort = new Sort();
var sortField:SortField = new ComplexSortField("address.street", false, false, false);
sortField.compareFunction = compareByStreet;
sortByStreetAscending.fields = [sortField];
_sut.sort = sortByStreetAscending;
//when
_sut.refresh(); //should be: Street0, Street1, Street2, Street3, Street4
//then
assertIndexesAre([0, 1, 2, 3, 4]);
}
[Test]
public function test_changing_simple_sort_field_value_places_it_correctly_according_to_collection_sort():void
{
//given
var from1To4:IList = generateVOs(5);
from1To4.removeItemAt(0);
_sut.addAll(from1To4);
const sortByNameAscending:Sort = new Sort();
sortByNameAscending.fields = [new SortField("name", false, false, false)];
_sut.sort = sortByNameAscending;
_sut.refresh(); //values: Object1, Object2, Object3, Object4
//when
const newItem:ListCollectionView_FLEX_34837_VO = generateOneObject(5);
_sut.addItem(newItem); //values: Object1, Object2, Object3, Object4, Object5
newItem.name = "Object0"; //this should immediately place the newItem at position 0
//then
const newItemIndex:int = _sut.getItemIndex(newItem);
assertEquals("the new item should have been placed at the beginning of the list as soon as its name was changed", 0, newItemIndex);
}
private function assertIndexesAre(indexes:Array):void
{
assertEquals(indexes.length, _sut.length);
for(var i:int = 0; i < _sut.length; i++)
{
assertEquals(ListCollectionView_FLEX_34837_VO(_sut.getItemAt(i)).index, indexes[i]);
}
}
private static function generateVOs(no:int, reverse:Boolean = false):IList
{
return generateObjects(no, reverse, generateOneObject);
}
private static function generateObjects(no:int, reverse:Boolean, generator:Function):IList
{
var result:Array = [];
for(var i:int = 0; i < no; i++)
{
result.push(generator(i));
}
if(reverse)
result.reverse();
return new ArrayList(result);
}
private static function generateOneObject(index:Number):ListCollectionView_FLEX_34837_VO
{
return new ListCollectionView_FLEX_34837_VO(index, "Object", "Street");
}
}
}
[Bindable]
class ListCollectionView_FLEX_34837_VO
{
public var name:String;
public var address:ListCollectionView_FLEX_34837_AddressVO;
public var index:Number;
public function ListCollectionView_FLEX_34837_VO(index:Number, namePrefix:String, streetPrefix:String)
{
this.index = index;
this.name = namePrefix + index;
this.address = new ListCollectionView_FLEX_34837_AddressVO(streetPrefix + index);
}
}
[Bindable]
class ListCollectionView_FLEX_34837_AddressVO
{
public var street:String;
public function ListCollectionView_FLEX_34837_AddressVO(street:String)
{
this.street = street;
}
}
|
Revert FLEX-34880 part 2
|
Revert FLEX-34880 part 2
This reverts commit ff4067f56651082cecbe062f9cfd2aedbe44bf60.
|
ActionScript
|
apache-2.0
|
apache/flex-sdk,apache/flex-sdk,apache/flex-sdk,apache/flex-sdk,apache/flex-sdk,apache/flex-sdk
|
f53050a9c9f12da7070f2b60a5a077602faeda54
|
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 = null;
private var _providers : Vector.<IDataProvider> = new <IDataProvider>[];
private var _bindingNames : Vector.<String> = new Vector.<String>();
private var _bindingNameToValue : Object = {};
private var _bindingNameToChangedSignal : Object = {};
private var _bindingNameToProvider : Object = {};
private var _providerToBindingNames : Dictionary = new Dictionary(); // dic[Vector.<String>[]]
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;
}
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 providerBindingNames : Vector.<String> = new <String>[];
var dataDescriptor : Object = provider.dataDescriptor;
provider.changed.add(providerChangedHandler);
_providerToBindingNames[provider] = providerBindingNames;
_providers.push(provider);
for (var attrName : String in dataDescriptor)
{
// if this provider attribute is also a dataprovider, let's also bind it
var bindingName : String = dataDescriptor[attrName];
var attribute : Object = provider[attrName];
if (_bindingNames.indexOf(bindingName) != -1)
throw new Error(
'Another data provider is already declaring the \'' + bindingName + '\' property.'
);
_bindingNameToProvider[bindingName] = provider;
_bindingNameToValue[bindingName] = attribute;
providerBindingNames.push(bindingName);
_bindingNames.push(bindingName);
if (_bindingNameToChangedSignal[bindingName])
_bindingNameToChangedSignal[bindingName].execute(this, bindingName, null, attribute);
}
}
public function removeProvider(provider : IDataProvider) : void
{
var providerBindingsNames : Vector.<String> = _providerToBindingNames[provider];
var tmpValues : Object = {};
if (providerBindingsNames == null)
throw new ArgumentError('Unkown provider.');
var numBindings : uint = _bindingNames.length;
for (var indexRead : uint = 0, indexWrite : uint = 0; indexRead < numBindings; ++indexRead)
{
var bindingName : String = _bindingNames[indexRead];
if (providerBindingsNames.indexOf(bindingName) != -1)
{
tmpValues[bindingName] = _bindingNameToValue[bindingName];
delete _bindingNameToValue[bindingName];
delete _bindingNameToProvider[bindingName];
}
else
_bindingNames[indexWrite++] = _bindingNames[indexRead];
}
_bindingNames.length = indexWrite;
provider.changed.remove(providerChangedHandler);
_providers.splice(_providers.indexOf(provider), 1);
delete _providerToBindingNames[provider];
for each (bindingName in providerBindingsNames)
{
var changedSignal : Signal = _bindingNameToChangedSignal[bindingName] as Signal;
if (changedSignal != null)
{
changedSignal.execute(
this, bindingName, tmpValues[bindingName], 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) : *
{
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 providerChangedHandler(source : IDataProvider, attributeName : String) : void
{
if (attributeName == null)
{
throw new Error('DataProviders must change one property at a time.');
}
else if (attributeName == 'dataDescriptor')
{
removeProvider(source);
addProvider(source);
}
else
{
var bindingName : String = source.dataDescriptor[attributeName];
var oldValue : Object = _bindingNameToValue[bindingName];
var newValue : Object = source[attributeName];
_bindingNameToValue[bindingName] = newValue;
if (_bindingNameToChangedSignal[bindingName])
_bindingNameToChangedSignal[bindingName].execute(this, bindingName, oldValue, newValue);
}
}
}
}
|
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 = null;
private var _providers : Vector.<IDataProvider> = new <IDataProvider>[];
private var _bindingNames : Vector.<String> = new Vector.<String>();
private var _bindingNameToValue : Object = {};
private var _bindingNameToChangedSignal : Object = {};
private var _bindingNameToProvider : Object = {};
private var _providerToBindingNames : Dictionary = new Dictionary(); // dic[Vector.<String>[]]
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;
}
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 providerBindingNames : Vector.<String> = new <String>[];
var dataDescriptor : Object = provider.dataDescriptor;
provider.changed.add(providerChangedHandler);
_providerToBindingNames[provider] = providerBindingNames;
_providers.push(provider);
for (var attrName : String in dataDescriptor)
{
// if this provider attribute is also a dataprovider, let's also bind it
var bindingName : String = dataDescriptor[attrName];
var attribute : Object = provider[attrName];
if (_bindingNames.indexOf(bindingName) != -1)
throw new Error(
'Another data provider is already declaring the \'' + bindingName + '\' property.'
);
_bindingNameToProvider[bindingName] = provider;
_bindingNameToValue[bindingName] = attribute;
providerBindingNames.push(bindingName);
_bindingNames.push(bindingName);
if (_bindingNameToChangedSignal[bindingName])
_bindingNameToChangedSignal[bindingName].execute(this, bindingName, null, attribute);
}
}
public function removeProvider(provider : IDataProvider) : void
{
var providerBindingsNames : Vector.<String> = _providerToBindingNames[provider];
var tmpValues : Object = {};
if (providerBindingsNames == null)
throw new ArgumentError('Unkown provider.');
var numBindings : uint = _bindingNames.length;
for (var indexRead : uint = 0, indexWrite : uint = 0; indexRead < numBindings; ++indexRead)
{
var bindingName : String = _bindingNames[indexRead];
if (providerBindingsNames.indexOf(bindingName) != -1)
{
tmpValues[bindingName] = _bindingNameToValue[bindingName];
delete _bindingNameToValue[bindingName];
delete _bindingNameToProvider[bindingName];
}
else
_bindingNames[indexWrite++] = _bindingNames[indexRead];
}
_bindingNames.length = indexWrite;
provider.changed.remove(providerChangedHandler);
_providers.splice(_providers.indexOf(provider), 1);
delete _providerToBindingNames[provider];
for each (bindingName in providerBindingsNames)
{
var changedSignal : Signal = _bindingNameToChangedSignal[bindingName] as Signal;
if (changedSignal != null)
{
changedSignal.execute(
this, bindingName, tmpValues[bindingName], 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 providerChangedHandler(source : IDataProvider, attributeName : String) : void
{
if (attributeName == null)
{
throw new Error('DataProviders must change one property at a time.');
}
else if (attributeName == 'dataDescriptor')
{
removeProvider(source);
addProvider(source);
}
else
{
var bindingName : String = source.dataDescriptor[attributeName];
var oldValue : Object = _bindingNameToValue[bindingName];
var newValue : Object = source[attributeName];
_bindingNameToValue[bindingName] = newValue;
if (_bindingNameToChangedSignal[bindingName])
_bindingNameToChangedSignal[bindingName].execute(this, bindingName, oldValue, newValue);
}
}
}
}
|
fix DataBindings.getProperty() to throw an error when attempting to read a property that does not exist
|
fix DataBindings.getProperty() to throw an error when attempting to read a property that does not exist
|
ActionScript
|
mit
|
aerys/minko-as3
|
fcb827ea56bc0d42f2e366cd3f4362e68a2630f5
|
src/org/httpclient/io/HttpResponseBuffer.as
|
src/org/httpclient/io/HttpResponseBuffer.as
|
/**
* Copyright (c) 2007 Gabriel Handford
* See LICENSE.txt for full license information.
*/
package org.httpclient.io {
import com.adobe.utils.StringUtil;
import flash.utils.ByteArray;
import org.httpclient.HttpResponse;
import org.httpclient.HttpHeader;
import flash.errors.*;
/**
* Bytes from response are placed in this buffer, and parsed according to transfer encoding.
*/
public class HttpResponseBuffer {
// Data buffer
private var _buffer:HttpBuffer = new HttpBuffer();
// Bytes read of body content
private var _bodyBytesRead:Number = 0;
// Response header data parsed from bytes
private var _headerData:Array = [];
// The response header, after we parsed it
private var _responseHeader:HttpResponse;
// For special transfer encodings (like Chunks); Typically data is streamed directly
private var _responseBody:HttpBuffer = new HttpBuffer();
// Notified of response header: function(response:HttpResponse):void { }
private var _onResponseHeader:Function;
// Notified of response body data: function(bytes:ByteArray):void { }
private var _onResponseData:Function;
// Notified when response is complete: function(bytesRead:Number):void { }
private var _onResponseComplete:Function
// If we expect response body
private var _hasResponseBody:Boolean;
// If response buffer is done
private var _isPayloadDone:Boolean = false;
/**
* Create response buffer.
* @param onResponseHeader
* @param onResponseData
* @param onResponseComplete
*/
public function HttpResponseBuffer(hasResponseBody:Boolean, onResponseHeader:Function, onResponseData:Function, onResponseComplete:Function) {
super();
_hasResponseBody = hasResponseBody;
_onResponseHeader = onResponseHeader;
_onResponseData = onResponseData;
_onResponseComplete = onResponseComplete;
}
/**
* Write bytes to the buffer.
* Parse lines for header, or send to onPayload.
*
* @param bytes Data
*/
public function writeBytes(bytes:ByteArray):void {
if (_isPayloadDone) throw new IllegalOperationError("Response is finished; can't accept more bytes");
// If we don't have the full header yet
if (!_responseHeader) {
_buffer.write(bytes);
var line:String = _buffer.readLine(true);
while (line != null) {
// If empty line, then we reached the end of the header
if (line == "") {
_responseHeader = parseHeader(_headerData);
Log.debug("Response header:\n" + _responseHeader);
// Notify
_onResponseHeader(_responseHeader);
// On information responses, get next response header
if (_responseHeader.isInformation) {
_buffer.truncate();
_responseHeader = null;
_isPayloadDone = false;
} else {
// Pass any extra as payload
var payload:ByteArray = _buffer.readAvailable();
Log.debug("Response payload (from parsing header): " + payload.length);
_isPayloadDone = handlePayload(payload);
break;
}
} else {
_headerData.push(line);
}
line = _buffer.readLine(true);
}
} else {
Log.debug("Response payload: " + bytes.length);
_isPayloadDone = handlePayload(bytes);
}
// Check if complete
Log.debug("Payload done? " + _isPayloadDone);
if (!_hasResponseBody) _onResponseComplete(0);
else if (_isPayloadDone) _onResponseComplete(_responseHeader.contentLength);
}
/**
* Get header, if its been reached.
*/
public function get header():HttpResponse { return _responseHeader; }
/**
* Notify with response data.
* Check for transfer encodings, otherwise stream it direct.
* @param bytes The data
* @return True if we don't expect any more data, false otherwise
*/
private function handlePayload(bytes:ByteArray):Boolean {
if (_responseHeader.isChunked) {
_responseBody.write(bytes);
_bodyBytesRead += bytes.length;
return _responseBody.readChunks(_onResponseData);
} else {
if (bytes.bytesAvailable > 0) {
_onResponseData(bytes);
_bodyBytesRead += bytes.length;
}
Log.debug("Bytes read (body): " + _bodyBytesRead + ", content length: " + _responseHeader.contentLength);
return (_bodyBytesRead >= _responseHeader.contentLength);
}
}
/**
* Parse HTTP response header.
* @param lines Lines in header
* @return The HTTP response so far
*/
protected function parseHeader(lines:Array):HttpResponse {
var line:String = lines[0];
// Regex courtesy of ruby 1.8 Net::HTTP
// Example, HTTP/1.1 200 OK
var matches:Array = line.match(/\AHTTP(?:\/(\d+\.\d+))?\s+(\d\d\d)\s*(.*)\z/);
if (!matches)
throw new Error("Invalid header: " + line + ", matches: " + matches);
var version:String = matches[1];
var code:String = matches[2];
var message:String = matches[3];
var headers:Array = [];
for(var i:Number = 1; i < lines.length; i++) {
line = lines[i];
var index:int = line.indexOf(":");
if (index != -1) {
var name:String = line.substring(0, index);
var value:String = line.substring(index + 1, line.length);
headers.push({ name: name, value: value });
} else {
Log.warn("Invalid header: " + line);
}
}
return new HttpResponse(version, code, message, new HttpHeader(headers));
}
}
}
|
/**
* Copyright (c) 2007 Gabriel Handford
* See LICENSE.txt for full license information.
*/
package org.httpclient.io {
import com.adobe.utils.StringUtil;
import flash.utils.ByteArray;
import org.httpclient.HttpResponse;
import org.httpclient.HttpHeader;
import flash.errors.*;
/**
* Bytes from response are placed in this buffer, and parsed according to transfer encoding.
*/
public class HttpResponseBuffer {
// Data buffer
private var _buffer:HttpBuffer = new HttpBuffer();
// Bytes read of body content
private var _bodyBytesRead:Number = 0;
// Response header data parsed from bytes
private var _headerData:Array = [];
// The response header, after we parsed it
private var _responseHeader:HttpResponse;
// For special transfer encodings (like Chunks); Typically data is streamed directly
private var _responseBody:HttpBuffer = new HttpBuffer();
// Notified of response header: function(response:HttpResponse):void { }
private var _onResponseHeader:Function;
// Notified of response body data: function(bytes:ByteArray):void { }
private var _onResponseData:Function;
// Notified when response is complete: function(bytesRead:Number):void { }
private var _onResponseComplete:Function
// If we expect response body
private var _hasResponseBody:Boolean;
// If response buffer is done
private var _isPayloadDone:Boolean = false;
/**
* Create response buffer.
* @param onResponseHeader
* @param onResponseData
* @param onResponseComplete
*/
public function HttpResponseBuffer(hasResponseBody:Boolean, onResponseHeader:Function, onResponseData:Function, onResponseComplete:Function) {
super();
_hasResponseBody = hasResponseBody;
_onResponseHeader = onResponseHeader;
_onResponseData = onResponseData;
_onResponseComplete = onResponseComplete;
}
/**
* Write bytes to the buffer.
* Parse lines for header, or send to onPayload.
*
* @param bytes Data
*/
public function writeBytes(bytes:ByteArray):void {
//if (_isPayloadDone) throw new IllegalOperationError("Response is finished; can't accept more bytes");
if (_isPayloadDone) return; // TODO: Figure out why on some TLS chunked encoding this happens (oh maybe chunked encoding footer?)
// If we don't have the full header yet
if (!_responseHeader) {
_buffer.write(bytes);
var line:String = _buffer.readLine(true);
while (line != null) {
// If empty line, then we reached the end of the header
if (line == "") {
_responseHeader = parseHeader(_headerData);
Log.debug("Response header:\n" + _responseHeader);
// Notify
_onResponseHeader(_responseHeader);
// On information responses, get next response header
if (_responseHeader.isInformation) {
_buffer.truncate();
_responseHeader = null;
_isPayloadDone = false;
} else {
// Pass any extra as payload
var payload:ByteArray = _buffer.readAvailable();
Log.debug("Response payload (from parsing header): " + payload.length);
_isPayloadDone = handlePayload(payload);
break;
}
} else {
_headerData.push(line);
}
line = _buffer.readLine(true);
}
} else {
Log.debug("Response payload: " + bytes.length);
_isPayloadDone = handlePayload(bytes);
}
// Check if complete
Log.debug("Payload done? " + _isPayloadDone);
if (!_hasResponseBody) _onResponseComplete(0);
else if (_isPayloadDone) _onResponseComplete(_responseHeader.contentLength);
}
/**
* Get header, if its been reached.
*/
public function get header():HttpResponse { return _responseHeader; }
/**
* Notify with response data.
* Check for transfer encodings, otherwise stream it direct.
* @param bytes The data
* @return True if we don't expect any more data, false otherwise
*/
private function handlePayload(bytes:ByteArray):Boolean {
if (_responseHeader.isChunked) {
_responseBody.write(bytes);
_bodyBytesRead += bytes.length;
return _responseBody.readChunks(_onResponseData);
} else {
if (bytes.bytesAvailable > 0) {
_onResponseData(bytes);
_bodyBytesRead += bytes.length;
}
Log.debug("Bytes read (body): " + _bodyBytesRead + ", content length: " + _responseHeader.contentLength);
return (_bodyBytesRead >= _responseHeader.contentLength);
}
}
/**
* Parse HTTP response header.
* @param lines Lines in header
* @return The HTTP response so far
*/
protected function parseHeader(lines:Array):HttpResponse {
var line:String = lines[0];
// Regex courtesy of ruby 1.8 Net::HTTP
// Example, HTTP/1.1 200 OK
var matches:Array = line.match(/\AHTTP(?:\/(\d+\.\d+))?\s+(\d\d\d)\s*(.*)\z/);
if (!matches)
throw new Error("Invalid header: " + line + ", matches: " + matches);
var version:String = matches[1];
var code:String = matches[2];
var message:String = matches[3];
var headers:Array = [];
for(var i:Number = 1; i < lines.length; i++) {
line = lines[i];
var index:int = line.indexOf(":");
if (index != -1) {
var name:String = line.substring(0, index);
var value:String = line.substring(index + 1, line.length);
headers.push({ name: name, value: value });
} else {
Log.warn("Invalid header: " + line);
}
}
return new HttpResponse(version, code, message, new HttpHeader(headers));
}
}
}
|
change from error to ignore.. i think i need to handle chunked footer
|
change from error to ignore.. i think i need to handle chunked footer
|
ActionScript
|
mit
|
gabriel/as3httpclient
|
5038219c4e827727f3c78058d1d8b99b633583d9
|
plugins/akamaiMediaAnalyticsPlugin/src/com/kaltura/kdpfl/plugin/akamaiMediaAnalyticsMediator.as
|
plugins/akamaiMediaAnalyticsPlugin/src/com/kaltura/kdpfl/plugin/akamaiMediaAnalyticsMediator.as
|
package com.kaltura.kdpfl.plugin
{
import com.akamai.playeranalytics.AnalyticsPluginLoader;
import com.kaltura.kdpfl.model.ConfigProxy;
import com.kaltura.kdpfl.model.MediaProxy;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.model.type.StreamerType;
import com.kaltura.types.KalturaMediaType;
import com.kaltura.vo.KalturaBaseEntry;
import com.kaltura.vo.KalturaFlavorAsset;
import com.kaltura.vo.KalturaMediaEntry;
import flash.system.Capabilities;
import org.puremvc.as3.interfaces.INotification;
import org.puremvc.as3.patterns.mediator.Mediator;
public class akamaiMediaAnalyticsMediator extends Mediator
{
public static const NAME:String = "akamaiMediaAnalyticsMediator";
private var _mediaProxy:MediaProxy;
public function akamaiMediaAnalyticsMediator(viewComponent:Object=null)
{
super(NAME, viewComponent);
}
override public function onRegister():void
{
_mediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy;
super.onRegister();
}
override public function listNotificationInterests():Array
{
return [NotificationType.MEDIA_READY, NotificationType.MEDIA_ELEMENT_READY];
}
override public function handleNotification(notification:INotification):void
{
switch (notification.getName())
{
case NotificationType.MEDIA_READY:
//populate analytics metadata
var configProxy:ConfigProxy = facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy;
var entry:KalturaBaseEntry = _mediaProxy.vo.entry;
AnalyticsPluginLoader.setData("title", entry.name);
AnalyticsPluginLoader.setData("entryId", entry.id);
AnalyticsPluginLoader.setData("category", entry.categories);
AnalyticsPluginLoader.setData("publisherId", configProxy.vo.flashvars.partnerId);
//find content type
if (entry is KalturaMediaEntry)
{
var mediaEntry:KalturaMediaEntry = entry as KalturaMediaEntry;
AnalyticsPluginLoader.setData("contentLength", mediaEntry.duration);
var contentType:String;
switch (mediaEntry.mediaType)
{
case KalturaMediaType.VIDEO:
contentType = "video";
break;
case KalturaMediaType.AUDIO:
contentType = "audio";
break;
case KalturaMediaType.IMAGE:
contentType = "image";
break;
default:
contentType = "live";
}
AnalyticsPluginLoader.setData("contentType", contentType);
}
AnalyticsPluginLoader.setData("device", Capabilities.os );
AnalyticsPluginLoader.setData("playerId", configProxy.vo.flashvars.uiConfId);
break;
case NotificationType.MEDIA_ELEMENT_READY:
//find starting flavor ID
var flavorAssetId:String;
var flavorParamsId:String;
if (_mediaProxy.vo.deliveryType == StreamerType.HTTP)
{
flavorAssetId = _mediaProxy.vo.selectedFlavorId;
}
else if (_mediaProxy.vo.deliveryType == StreamerType.RTMP)
{
flavorAssetId = getFlavorIdByIndex(_mediaProxy.startingIndex);
}
for each (var kfa:KalturaFlavorAsset in _mediaProxy.vo.kalturaMediaFlavorArray) {
if (kfa.id == flavorAssetId) {
flavorParamsId = kfa.flavorParamsId.toString();
break;
}
}
if (flavorParamsId)
AnalyticsPluginLoader.setData("flavorId", flavorParamsId);
break;
}
}
/**
* returns the id of the flavor asset in the given index. null if index is invalid.
* @param index
* @return
*
*/
private function getFlavorIdByIndex(index:int):String
{
var flavorId:String;
if (index >= 0 &&
_mediaProxy.vo.kalturaMediaFlavorArray &&
index < _mediaProxy.vo.kalturaMediaFlavorArray.length) {
flavorId = (_mediaProxy.vo.kalturaMediaFlavorArray[index] as KalturaFlavorAsset).id;
}
return flavorId;
}
}
}
|
package com.kaltura.kdpfl.plugin
{
import com.akamai.playeranalytics.AnalyticsPluginLoader;
import com.kaltura.kdpfl.model.ConfigProxy;
import com.kaltura.kdpfl.model.MediaProxy;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.model.type.StreamerType;
import com.kaltura.types.KalturaMediaType;
import com.kaltura.vo.KalturaBaseEntry;
import com.kaltura.vo.KalturaFlavorAsset;
import com.kaltura.vo.KalturaMediaEntry;
import flash.system.Capabilities;
import org.puremvc.as3.interfaces.INotification;
import org.puremvc.as3.patterns.mediator.Mediator;
public class akamaiMediaAnalyticsMediator extends Mediator
{
public static const NAME:String = "akamaiMediaAnalyticsMediator";
private var _mediaProxy:MediaProxy;
public function akamaiMediaAnalyticsMediator(viewComponent:Object=null)
{
super(NAME, viewComponent);
}
override public function onRegister():void
{
_mediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy;
super.onRegister();
}
override public function listNotificationInterests():Array
{
return [NotificationType.MEDIA_READY, NotificationType.MEDIA_ELEMENT_READY];
}
override public function handleNotification(notification:INotification):void
{
switch (notification.getName())
{
case NotificationType.MEDIA_READY:
//populate analytics metadata
var configProxy:ConfigProxy = facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy;
var entry:KalturaBaseEntry = _mediaProxy.vo.entry;
AnalyticsPluginLoader.setData("title", entry.name);
AnalyticsPluginLoader.setData("entryId", entry.id);
AnalyticsPluginLoader.setData("category", entry.categories);
AnalyticsPluginLoader.setData("publisherId", configProxy.vo.flashvars.partnerId);
//find content type
if (entry is KalturaMediaEntry)
{
var mediaEntry:KalturaMediaEntry = entry as KalturaMediaEntry;
AnalyticsPluginLoader.setData("contentLength", mediaEntry.msDuration);
var contentType:String;
switch (mediaEntry.mediaType)
{
case KalturaMediaType.VIDEO:
contentType = "video";
break;
case KalturaMediaType.AUDIO:
contentType = "audio";
break;
case KalturaMediaType.IMAGE:
contentType = "image";
break;
default:
contentType = "live";
}
AnalyticsPluginLoader.setData("contentType", contentType);
}
AnalyticsPluginLoader.setData("device", Capabilities.os );
AnalyticsPluginLoader.setData("playerId", configProxy.vo.flashvars.uiConfId);
break;
case NotificationType.MEDIA_ELEMENT_READY:
//find starting flavor ID
var flavorAssetId:String;
var flavorParamsId:String;
if (_mediaProxy.vo.deliveryType == StreamerType.HTTP)
{
flavorAssetId = _mediaProxy.vo.selectedFlavorId;
}
else if (_mediaProxy.vo.deliveryType == StreamerType.RTMP)
{
flavorAssetId = getFlavorIdByIndex(_mediaProxy.startingIndex);
}
for each (var kfa:KalturaFlavorAsset in _mediaProxy.vo.kalturaMediaFlavorArray) {
if (kfa.id == flavorAssetId) {
flavorParamsId = kfa.flavorParamsId.toString();
break;
}
}
if (flavorParamsId)
AnalyticsPluginLoader.setData("flavorId", flavorParamsId);
break;
}
}
/**
* returns the id of the flavor asset in the given index. null if index is invalid.
* @param index
* @return
*
*/
private function getFlavorIdByIndex(index:int):String
{
var flavorId:String;
if (index >= 0 &&
_mediaProxy.vo.kalturaMediaFlavorArray &&
index < _mediaProxy.vo.kalturaMediaFlavorArray.length) {
flavorId = (_mediaProxy.vo.kalturaMediaFlavorArray[index] as KalturaFlavorAsset).id;
}
return flavorId;
}
}
}
|
change duration to milliseconds
|
qnd: change duration to milliseconds
git-svn-id: 3f608e5a9a704dd448217c0a64c508e7f145cfa1@91935 6b8eccd3-e8c5-4e7d-8186-e12b5326b719
|
ActionScript
|
agpl-3.0
|
kaltura/kdp,shvyrev/kdp,shvyrev/kdp,kaltura/kdp,shvyrev/kdp,kaltura/kdp
|
a648b6eac9aecc98b4dd5139e6fdf190eaf13a49
|
actionscript/src/com/freshplanet/ane/AirMediaPlayer/AirMediaPlayer.as
|
actionscript/src/com/freshplanet/ane/AirMediaPlayer/AirMediaPlayer.as
|
//////////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2012 Freshplanet (http://freshplanet.com | [email protected])
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//////////////////////////////////////////////////////////////////////////////////////
package com.freshplanet.ane.AirMediaPlayer
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.system.Capabilities;
public class AirMediaPlayer extends EventDispatcher
{
// --------------------------------------------------------------------------------------//
// //
// PUBLIC API //
// //
// --------------------------------------------------------------------------------------//
/** AirMediaPlayer is supported on iOS and Android devices. */
public static function get isSupported():Boolean
{
var isIOS:Boolean = (Capabilities.manufacturer.indexOf("iOS") != -1);
var isAndroid:Boolean = (Capabilities.manufacturer.indexOf("Android") != -1)
return isIOS || isAndroid;
}
public function AirMediaPlayer()
{
if (!_instance)
{
_context = ExtensionContext.createExtensionContext(EXTENSION_ID, null);
if (!_context)
{
log("ERROR - Extension context is null. Please check if extension.xml is setup correctly.");
return;
}
_context.addEventListener(StatusEvent.STATUS, onStatus);
_instance = this;
}
else
{
throw Error("This is a singleton, use getInstance(), do not call the constructor directly.");
}
}
public static function getInstance():AirMediaPlayer
{
return _instance ? _instance:new AirMediaPlayer();
}
public var logEnabled:Boolean = true;
/**
*
*/
public function loadUrl(url:String):void
{
_context.call("loadUrl", url);
}
/**
*
*/
public function play(startTime:int=0):void
{
_context.call("play", startTime);
}
/**
*
*/
public function pause():void
{
_context.call("pause");
}
/**
*
*/
public function close():void
{
_context.call("close");
}
/**
* Length in milliseconds
*/
public function get length():int
{
return _context.call("getLength") as int;
}
/**
* Progress in milliseconds
*/
public function get progress():int
{
return _context.call("getProgress") as int;
}
// --------------------------------------------------------------------------------------//
// //
// PRIVATE API //
// //
// --------------------------------------------------------------------------------------//
private static const EXTENSION_ID:String = "com.freshplanet.AirMediaPlayer";
private static var _instance:AirMediaPlayer;
private var _context:ExtensionContext;
private function onStatus( event:StatusEvent ):void
{
if (event.code == "LOGGING") // Simple log message
{
log(event.level);
}
}
private function log( message:String ):void
{
if (logEnabled) trace("[AirMediaPlayer] " + message);
}
}
}
|
//////////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2012 Freshplanet (http://freshplanet.com | [email protected])
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//////////////////////////////////////////////////////////////////////////////////////
package com.freshplanet.ane.AirMediaPlayer
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.system.Capabilities;
public class AirMediaPlayer extends EventDispatcher
{
// --------------------------------------------------------------------------------------//
// //
// PUBLIC API //
// //
// --------------------------------------------------------------------------------------//
/** AirMediaPlayer is supported on iOS and Android devices. */
public static function get isSupported():Boolean
{
var isIOS:Boolean = (Capabilities.manufacturer.indexOf("iOS") != -1);
var isAndroid:Boolean = (Capabilities.manufacturer.indexOf("Android") != -1)
return isIOS || isAndroid;
}
public function AirMediaPlayer()
{
if (!_instance)
{
_context = ExtensionContext.createExtensionContext(EXTENSION_ID, null);
if (!_context)
{
log("ERROR - Extension context is null. Please check if extension.xml is setup correctly.");
return;
}
_context.addEventListener(StatusEvent.STATUS, onStatus);
_instance = this;
}
else
{
throw Error("This is a singleton, use getInstance(), do not call the constructor directly.");
}
}
public static function getInstance():AirMediaPlayer
{
return _instance ? _instance:new AirMediaPlayer();
}
public var logEnabled:Boolean = true;
/**
* Load a music stream url
* @param url:String
*/
public function loadUrl(url:String):void
{
_context.call("loadUrl", url);
}
/**
* Start playing the stream.
* If the playback has been paused before, it will continue from this point.
* @param startTime:int the start time in milliseconds
*/
public function play(startTime:int=0):void
{
_context.call("play", startTime);
}
/**
* Pause the playback
*/
public function pause():void
{
_context.call("pause");
}
/**
* Close the stream and release.
* Note that loadUrl() has to be called again before replaying if close has been called.
*/
public function close():void
{
_context.call("close");
}
/**
* Length in milliseconds
*/
public function get length():int
{
return _context.call("getLength") as int;
}
/**
* Progress in milliseconds
*/
public function get progress():int
{
return _context.call("getProgress") as int;
}
// --------------------------------------------------------------------------------------//
// //
// PRIVATE API //
// //
// --------------------------------------------------------------------------------------//
private static const EXTENSION_ID:String = "com.freshplanet.AirMediaPlayer";
private static var _instance:AirMediaPlayer;
private var _context:ExtensionContext;
private function onStatus( event:StatusEvent ):void
{
if (event.code == "LOGGING") // Simple log message
{
log(event.level);
}
}
private function log( message:String ):void
{
if (logEnabled) trace("[AirMediaPlayer] " + message);
}
}
}
|
Add documentation
|
Add documentation
|
ActionScript
|
apache-2.0
|
freshplanet/ANE-AACPlayer,freshplanet/ANE-AACPlayer,freshplanet/ANE-AACPlayer
|
eb1e8ab5c8a4cbeda5df86d0e9c16fe118e0c248
|
src/org/mangui/chromeless/ChromelessPlayer.as
|
src/org/mangui/chromeless/ChromelessPlayer.as
|
package org.mangui.chromeless {
import org.mangui.HLS.parsing.Level;
import org.mangui.HLS.*;
import flash.display.*;
import flash.events.*;
import flash.external.ExternalInterface;
import flash.geom.Rectangle;
import flash.media.Video;
import flash.media.SoundTransform;
import flash.media.StageVideo;
import flash.media.StageVideoAvailability;
import flash.utils.setTimeout;
public class ChromelessPlayer extends Sprite {
/** reference to the framework. **/
private var _hls:HLS;
/** Sheet to place on top of the video. **/
private var _sheet:Sprite;
/** Reference to the video element. **/
private var _video:StageVideo;
/** current media position */
private var _media_position:Number;
/** Initialization. **/
public function ChromelessPlayer():void {
// Set stage properties
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
stage.fullScreenSourceRect = new Rectangle(0,0,stage.stageWidth,stage.stageHeight);
stage.addEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, _onStageVideoState);
// Draw sheet for catching clicks
_sheet = new Sprite();
_sheet.graphics.beginFill(0x000000,0);
_sheet.graphics.drawRect(0,0,stage.stageWidth,stage.stageHeight);
_sheet.addEventListener(MouseEvent.CLICK,_clickHandler);
_sheet.buttonMode = true;
addChild(_sheet);
// Connect getters to JS.
ExternalInterface.addCallback("getLevel",_getLevel);
ExternalInterface.addCallback("getLevels",_getLevels);
ExternalInterface.addCallback("getMetrics",_getMetrics);
ExternalInterface.addCallback("getPosition",_getPosition);
ExternalInterface.addCallback("getState",_getState);
ExternalInterface.addCallback("getType",_getType);
ExternalInterface.addCallback("getmaxBufferLength",_getmaxBufferLength);
ExternalInterface.addCallback("getbufferLength",_getbufferLength);
// Connect calls to JS.
ExternalInterface.addCallback("playerLoad",_load);
ExternalInterface.addCallback("playerPlay",_play);
ExternalInterface.addCallback("playerPause",_pause);
ExternalInterface.addCallback("playerResume",_resume);
ExternalInterface.addCallback("playerSeek",_seek);
ExternalInterface.addCallback("playerStop",_stop);
ExternalInterface.addCallback("playerVolume",_volume);
ExternalInterface.addCallback("playerSetLevel",_setLevel);
ExternalInterface.addCallback("playerSetmaxBufferLength",_setmaxBufferLength);
setTimeout(_pingJavascript,50);
};
/** Notify javascript the framework is ready. **/
private function _pingJavascript():void {
ExternalInterface.call("onHLSReady",ExternalInterface.objectID);
};
/** Forward events from the framework. **/
private function _completeHandler(event:HLSEvent):void {
if (ExternalInterface.available) {
ExternalInterface.call("onComplete");
}
};
private function _errorHandler(event:HLSEvent):void {
if (ExternalInterface.available) {
ExternalInterface.call("onError",event.message);
}
};
private function _fragmentHandler(event:HLSEvent):void {
if (ExternalInterface.available) {
ExternalInterface.call("onFragment",event.metrics.bandwidth,event.metrics.level,event.metrics.screenwidth);
}
};
private function _manifestHandler(event:HLSEvent):void {
if (ExternalInterface.available) {
ExternalInterface.call("onManifest",event.levels[0].duration);
}
};
private function _mediaTimeHandler(event:HLSEvent):void {
if (ExternalInterface.available) {
_media_position = event.mediatime.position;
ExternalInterface.call("onPosition",event.mediatime.position,event.mediatime.duration);
}
};
private function _stateHandler(event:HLSEvent):void {
if (ExternalInterface.available) {
ExternalInterface.call("onState",event.state);
}
};
private function _switchHandler(event:HLSEvent):void {
if (ExternalInterface.available) {
ExternalInterface.call("onSwitch",event.level);
}
};
/** Javascript getters. **/
private function _getLevel():Number { return _hls.getLevel(); };
private function _getLevels():Vector.<Level> { return _hls.getLevels(); };
private function _getMetrics():Object { return _hls.getMetrics(); };
private function _getPosition():Number { return _hls.getPosition(); };
private function _getState():String { return _hls.getState(); };
private function _getType():String { return _hls.getType(); };
private function _getbufferLength():Number { return _hls.getBufferLength(); };
private function _getmaxBufferLength():Number { return _hls.maxBufferLength; };
/** Javascript calls. **/
private function _load(url:String):void { _hls.load(url); };
private function _play():void { _hls.stream.play(); };
private function _pause():void { _hls.stream.pause(); };
private function _resume():void { _hls.stream.resume(); };
private function _seek(position:Number):void { _hls.stream.seek(position); };
private function _stop():void { _hls.stream.close(); };
private function _volume(percent:Number):void { _hls.stream.soundTransform = new SoundTransform(percent/100);};
private function _setLevel(level:Number):void { _hls.setPlaybackQuality(level); if (!isNaN(_media_position)) {_hls.stream.seek(_media_position);}};
private function _setmaxBufferLength(new_len:Number):void { _hls.maxBufferLength = new_len;};
/** Mouse click handler. **/
private function _clickHandler(event:MouseEvent):void {
if(stage.displayState == StageDisplayState.FULL_SCREEN_INTERACTIVE || stage.displayState==StageDisplayState.FULL_SCREEN) {
stage.displayState = StageDisplayState.NORMAL;
} else {
stage.displayState = StageDisplayState.FULL_SCREEN;
}
_hls.setWidth(stage.stageWidth);
};
/** StageVideo detector. **/
private function _onStageVideoState(event:StageVideoAvailabilityEvent):void {
var available:Boolean = (event.availability == StageVideoAvailability.AVAILABLE);
if (available && stage.stageVideos.length > 0) {
_video = stage.stageVideos[0];
_video.viewPort = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
_hls = new HLS();
_video.attachNetStream(_hls.stream);
} else {
var video:Video = new Video(stage.stageWidth, stage.stageHeight);
addChild(video);
_hls = new HLS();
video.smoothing = true;
video.attachNetStream(_hls.stream);
}
_hls.setWidth(stage.stageWidth);
_hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE,_completeHandler);
_hls.addEventListener(HLSEvent.ERROR,_errorHandler);
_hls.addEventListener(HLSEvent.FRAGMENT_LOADED,_fragmentHandler);
_hls.addEventListener(HLSEvent.MANIFEST_LOADED,_manifestHandler);
_hls.addEventListener(HLSEvent.MEDIA_TIME,_mediaTimeHandler);
_hls.addEventListener(HLSEvent.STATE,_stateHandler);
_hls.addEventListener(HLSEvent.QUALITY_SWITCH,_switchHandler);
};
}
}
|
package org.mangui.chromeless {
import org.mangui.HLS.parsing.Level;
import org.mangui.HLS.*;
import flash.display.*;
import flash.events.*;
import flash.external.ExternalInterface;
import flash.geom.Rectangle;
import flash.media.Video;
import flash.media.SoundTransform;
import flash.media.StageVideo;
import flash.media.StageVideoAvailability;
import flash.utils.setTimeout;
public class ChromelessPlayer extends Sprite {
/** reference to the framework. **/
private var _hls:HLS;
/** Sheet to place on top of the video. **/
private var _sheet:Sprite;
/** Reference to the video element. **/
private var _video:StageVideo;
/** current media position */
private var _media_position:Number;
/** Initialization. **/
public function ChromelessPlayer():void {
// Set stage properties
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
stage.fullScreenSourceRect = new Rectangle(0,0,stage.stageWidth,stage.stageHeight);
stage.addEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, _onStageVideoState);
// Draw sheet for catching clicks
_sheet = new Sprite();
_sheet.graphics.beginFill(0x000000,0);
_sheet.graphics.drawRect(0,0,stage.stageWidth,stage.stageHeight);
_sheet.addEventListener(MouseEvent.CLICK,_clickHandler);
_sheet.buttonMode = true;
addChild(_sheet);
// Connect getters to JS.
ExternalInterface.addCallback("getLevel",_getLevel);
ExternalInterface.addCallback("getLevels",_getLevels);
ExternalInterface.addCallback("getMetrics",_getMetrics);
ExternalInterface.addCallback("getPosition",_getPosition);
ExternalInterface.addCallback("getState",_getState);
ExternalInterface.addCallback("getType",_getType);
ExternalInterface.addCallback("getmaxBufferLength",_getmaxBufferLength);
ExternalInterface.addCallback("getbufferLength",_getbufferLength);
ExternalInterface.addCallback("getPlayerVersion",_getPlayerVersion);
// Connect calls to JS.
ExternalInterface.addCallback("playerLoad",_load);
ExternalInterface.addCallback("playerPlay",_play);
ExternalInterface.addCallback("playerPause",_pause);
ExternalInterface.addCallback("playerResume",_resume);
ExternalInterface.addCallback("playerSeek",_seek);
ExternalInterface.addCallback("playerStop",_stop);
ExternalInterface.addCallback("playerVolume",_volume);
ExternalInterface.addCallback("playerSetLevel",_setLevel);
ExternalInterface.addCallback("playerSetmaxBufferLength",_setmaxBufferLength);
setTimeout(_pingJavascript,50);
};
/** Notify javascript the framework is ready. **/
private function _pingJavascript():void {
ExternalInterface.call("onHLSReady",ExternalInterface.objectID);
};
/** Forward events from the framework. **/
private function _completeHandler(event:HLSEvent):void {
if (ExternalInterface.available) {
ExternalInterface.call("onComplete");
}
};
private function _errorHandler(event:HLSEvent):void {
if (ExternalInterface.available) {
ExternalInterface.call("onError",event.message);
}
};
private function _fragmentHandler(event:HLSEvent):void {
if (ExternalInterface.available) {
ExternalInterface.call("onFragment",event.metrics.bandwidth,event.metrics.level,event.metrics.screenwidth);
}
};
private function _manifestHandler(event:HLSEvent):void {
if (ExternalInterface.available) {
ExternalInterface.call("onManifest",event.levels[0].duration);
}
};
private function _mediaTimeHandler(event:HLSEvent):void {
if (ExternalInterface.available) {
_media_position = event.mediatime.position;
ExternalInterface.call("onPosition",event.mediatime.position,event.mediatime.duration);
}
};
private function _stateHandler(event:HLSEvent):void {
if (ExternalInterface.available) {
ExternalInterface.call("onState",event.state);
}
};
private function _switchHandler(event:HLSEvent):void {
if (ExternalInterface.available) {
ExternalInterface.call("onSwitch",event.level);
}
};
/** Javascript getters. **/
private function _getLevel():Number { return _hls.getLevel(); };
private function _getLevels():Vector.<Level> { return _hls.getLevels(); };
private function _getMetrics():Object { return _hls.getMetrics(); };
private function _getPosition():Number { return _hls.getPosition(); };
private function _getState():String { return _hls.getState(); };
private function _getType():String { return _hls.getType(); };
private function _getbufferLength():Number { return _hls.getBufferLength(); };
private function _getmaxBufferLength():Number { return _hls.maxBufferLength; };
private function _getPlayerVersion():Number { return 2; };
/** Javascript calls. **/
private function _load(url:String):void { _hls.load(url); };
private function _play():void { _hls.stream.play(); };
private function _pause():void { _hls.stream.pause(); };
private function _resume():void { _hls.stream.resume(); };
private function _seek(position:Number):void { _hls.stream.seek(position); };
private function _stop():void { _hls.stream.close(); };
private function _volume(percent:Number):void { _hls.stream.soundTransform = new SoundTransform(percent/100);};
private function _setLevel(level:Number):void { _hls.setPlaybackQuality(level); if (!isNaN(_media_position)) {_hls.stream.seek(_media_position);}};
private function _setmaxBufferLength(new_len:Number):void { _hls.maxBufferLength = new_len;};
/** Mouse click handler. **/
private function _clickHandler(event:MouseEvent):void {
if(stage.displayState == StageDisplayState.FULL_SCREEN_INTERACTIVE || stage.displayState==StageDisplayState.FULL_SCREEN) {
stage.displayState = StageDisplayState.NORMAL;
} else {
stage.displayState = StageDisplayState.FULL_SCREEN;
}
_hls.setWidth(stage.stageWidth);
};
/** StageVideo detector. **/
private function _onStageVideoState(event:StageVideoAvailabilityEvent):void {
var available:Boolean = (event.availability == StageVideoAvailability.AVAILABLE);
if (available && stage.stageVideos.length > 0) {
_video = stage.stageVideos[0];
_video.viewPort = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
_hls = new HLS();
_video.attachNetStream(_hls.stream);
} else {
var video:Video = new Video(stage.stageWidth, stage.stageHeight);
addChild(video);
_hls = new HLS();
video.smoothing = true;
video.attachNetStream(_hls.stream);
}
_hls.setWidth(stage.stageWidth);
_hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE,_completeHandler);
_hls.addEventListener(HLSEvent.ERROR,_errorHandler);
_hls.addEventListener(HLSEvent.FRAGMENT_LOADED,_fragmentHandler);
_hls.addEventListener(HLSEvent.MANIFEST_LOADED,_manifestHandler);
_hls.addEventListener(HLSEvent.MEDIA_TIME,_mediaTimeHandler);
_hls.addEventListener(HLSEvent.STATE,_stateHandler);
_hls.addEventListener(HLSEvent.QUALITY_SWITCH,_switchHandler);
};
}
}
|
add a getPlayerVersion method.
|
add a getPlayerVersion method.
|
ActionScript
|
mpl-2.0
|
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
|
21e9f345838f5598c7069c4c710875204b81cf24
|
src/aerys/minko/type/loader/TextureLoader.as
|
src/aerys/minko/type/loader/TextureLoader.as
|
package aerys.minko.type.loader
{
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.type.Signal;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.getQualifiedClassName;
public class TextureLoader implements ILoader
{
private var _progress : Signal;
private var _error : Signal;
private var _complete : Signal;
private var _isComplete : Boolean;
private var _mipmap : Boolean;
protected var _textureResource : TextureResource;
public function get progress() : Signal
{
return _progress;
}
public function get error() : Signal
{
return _error;
}
public function get complete() : Signal
{
return _complete;
}
public function get isComplete() : Boolean
{
return _isComplete;
}
public function get textureResource() : TextureResource
{
return _textureResource;
}
public function TextureLoader(enableMipmapping : Boolean = true)
{
_mipmap = enableMipmapping;
_textureResource = new TextureResource();
_isComplete = false;
_error = new Signal('TextureLoader.error');
_progress = new Signal('TextureLoader.progress');
_complete = new Signal('TextureLoader.complete');
}
public function load(request : URLRequest) : void
{
var loader : URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener(ProgressEvent.PROGRESS, loadProgressHandler);
loader.addEventListener(Event.COMPLETE, loadCompleteHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR, loadIoErrorHandler);
loader.load(request);
}
private function loadIoErrorHandler(e : IOErrorEvent) : void
{
_textureResource = null;
_error.execute(this, e.errorID, e.text);
}
private function loadProgressHandler(e : ProgressEvent) : void
{
_progress.execute(this, e.bytesLoaded, e.bytesTotal);
}
private function loadCompleteHandler(e : Event) : void
{
loadBytes(URLLoader(e.currentTarget).data);
}
public function loadClass(classObject : Class) : void
{
var assetObject : Object = new classObject();
if (assetObject is Bitmap || assetObject is BitmapData)
{
var bitmapData : BitmapData = assetObject as BitmapData;
if (bitmapData == null)
bitmapData = Bitmap(assetObject).bitmapData;
_textureResource.setContentFromBitmapData(bitmapData, _mipmap);
_isComplete = true;
_complete.execute(this, _textureResource);
}
else if (assetObject is ByteArray)
{
loadBytes(ByteArray(assetObject));
}
else
{
var className : String = getQualifiedClassName(classObject);
className = className.substr(className.lastIndexOf(':') + 1);
_isComplete = true;
throw new Error('No texture can be created from an object of type \'' + className + '\'');
}
}
public function loadBytes(bytes : ByteArray) : void
{
bytes.position = 0;
if (bytes.readByte() == 'A'.charCodeAt(0) &&
bytes.readByte() == 'T'.charCodeAt(0) &&
bytes.readByte() == 'F'.charCodeAt(0))
{
bytes.position = 0;
_textureResource.setContentFromATF(bytes);
_isComplete = true;
_complete.execute(this, _textureResource);
}
else
{
bytes.position = 0;
var loader : Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadBytesCompleteHandler);
loader.loadBytes(bytes);
}
}
private function loadBytesCompleteHandler(e : Event) : void
{
var displayObject : DisplayObject = LoaderInfo(e.currentTarget).content;
if (displayObject is Bitmap)
{
_textureResource.setContentFromBitmapData(Bitmap(displayObject).bitmapData, _mipmap);
_isComplete = true;
_complete.execute(this, _textureResource);
}
else
{
var className : String = getQualifiedClassName(displayObject);
className = className.substr(className.lastIndexOf(':') + 1);
_isComplete = true;
throw new Error('No texture can be created from an object of type \'' + className + '\'');
}
}
public static function loadClass(classObject : Class,
enableMipMapping : Boolean = true) : TextureResource
{
var textureLoader : TextureLoader = new TextureLoader(enableMipMapping);
textureLoader.loadClass(classObject);
return textureLoader.textureResource;
}
public static function load(request : URLRequest,
enableMipMapping : Boolean = true) : TextureResource
{
var textureLoader : TextureLoader = new TextureLoader(enableMipMapping);
textureLoader.load(request);
return textureLoader.textureResource;
}
public static function loadBytes(bytes : ByteArray,
enableMipMapping : Boolean = true) : TextureResource
{
var textureLoader : TextureLoader = new TextureLoader(enableMipMapping);
textureLoader.loadBytes(bytes);
return textureLoader.textureResource;
}
}
}
|
package aerys.minko.type.loader
{
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.type.Signal;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.getQualifiedClassName;
public class TextureLoader implements ILoader
{
private var _progress : Signal;
private var _error : Signal;
private var _complete : Signal;
private var _isComplete : Boolean;
private var _mipmap : Boolean;
protected var _textureResource : TextureResource;
public function get progress() : Signal
{
return _progress;
}
public function get error() : Signal
{
return _error;
}
public function get complete() : Signal
{
return _complete;
}
public function get isComplete() : Boolean
{
return _isComplete;
}
public function get textureResource() : TextureResource
{
return _textureResource;
}
public function TextureLoader(enableMipmapping : Boolean = true)
{
_mipmap = enableMipmapping;
_textureResource = new TextureResource();
_isComplete = false;
_error = new Signal('TextureLoader.error');
_progress = new Signal('TextureLoader.progress');
_complete = new Signal('TextureLoader.complete');
}
public function load(request : URLRequest) : void
{
var loader : URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener(ProgressEvent.PROGRESS, loadProgressHandler);
loader.addEventListener(Event.COMPLETE, loadCompleteHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR, loadIoErrorHandler);
loader.load(request);
}
private function loadIoErrorHandler(e : IOErrorEvent) : void
{
_textureResource = null;
_error.execute(this, e.errorID, e.text);
}
private function loadProgressHandler(e : ProgressEvent) : void
{
_progress.execute(this, e.bytesLoaded, e.bytesTotal);
}
private function loadCompleteHandler(e : Event) : void
{
loadBytes(URLLoader(e.currentTarget).data);
}
public function loadClass(classObject : Class) : void
{
var assetObject : Object = new classObject();
if (assetObject is Bitmap || assetObject is BitmapData)
{
var bitmapData : BitmapData = assetObject as BitmapData;
if (bitmapData == null)
bitmapData = Bitmap(assetObject).bitmapData;
_textureResource.setContentFromBitmapData(bitmapData, _mipmap);
bitmapData.dispose();
_isComplete = true;
_complete.execute(this, _textureResource);
}
else if (assetObject is ByteArray)
{
loadBytes(ByteArray(assetObject));
}
else
{
var className : String = getQualifiedClassName(classObject);
className = className.substr(className.lastIndexOf(':') + 1);
_isComplete = true;
throw new Error('No texture can be created from an object of type \'' + className + '\'');
}
}
public function loadBytes(bytes : ByteArray) : void
{
bytes.position = 0;
if (bytes.readByte() == 'A'.charCodeAt(0) &&
bytes.readByte() == 'T'.charCodeAt(0) &&
bytes.readByte() == 'F'.charCodeAt(0))
{
bytes.position = 0;
_textureResource.setContentFromATF(bytes);
_isComplete = true;
_complete.execute(this, _textureResource);
}
else
{
bytes.position = 0;
var loader : Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadBytesCompleteHandler);
loader.loadBytes(bytes);
}
}
private function loadBytesCompleteHandler(e : Event) : void
{
var displayObject : DisplayObject = LoaderInfo(e.currentTarget).content;
if (displayObject is Bitmap)
{
var bitmapData : BitmapData = Bitmap(displayObject).bitmapData;
_textureResource.setContentFromBitmapData(bitmapData, _mipmap);
bitmapData.dispose();
_isComplete = true;
_complete.execute(this, _textureResource);
}
else
{
var className : String = getQualifiedClassName(displayObject);
className = className.substr(className.lastIndexOf(':') + 1);
_isComplete = true;
throw new Error(
'No texture can be created from an object of type \'' + className + '\''
);
}
}
public static function loadClass(classObject : Class,
enableMipMapping : Boolean = true) : TextureResource
{
var textureLoader : TextureLoader = new TextureLoader(enableMipMapping);
textureLoader.loadClass(classObject);
return textureLoader.textureResource;
}
public static function load(request : URLRequest,
enableMipMapping : Boolean = true) : TextureResource
{
var textureLoader : TextureLoader = new TextureLoader(enableMipMapping);
textureLoader.load(request);
return textureLoader.textureResource;
}
public static function loadBytes(bytes : ByteArray,
enableMipMapping : Boolean = true) : TextureResource
{
var textureLoader : TextureLoader = new TextureLoader(enableMipMapping);
textureLoader.loadBytes(bytes);
return textureLoader.textureResource;
}
}
}
|
call BitmapData.dispose() to dispose each temporary bitmap data object when TextureResource.setContentFromBitmapData() has been called to free the memory as soon as possible
|
call BitmapData.dispose() to dispose each temporary bitmap data object when TextureResource.setContentFromBitmapData() has been called to free the memory as soon as possible
|
ActionScript
|
mit
|
aerys/minko-as3
|
2d62a97e15af1630da843c3942caed2865a155fe
|
WEB-INF/lps/lfc/kernel/swf/LzSoundMC.as
|
WEB-INF/lps/lfc/kernel/swf/LzSoundMC.as
|
/**
* LzSoundMC.as
*
* @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic AS2
*/
/**
* Wraps the streaming MP3 loader in a movieclip-like API.
* Used for proxyless mp3 audio loading.
*
* @access private
*/
var SoundMC = function (mc) {
this.init(mc);
}
SoundMC.prototype = new MovieClip();
// the attached flash Sound object
SoundMC.prototype._sound = null;
// flag required for loader
SoundMC.prototype.isaudio = true;
// tracks the loading progress
SoundMC.prototype.loadstate = 0;
// next frame to be played
SoundMC.prototype._nextframe = -1;
SoundMC.prototype.addProperty("_totalframes", function () {
return Math.floor(this._sound.duration * .001 * canvas.framerate) || 0;
}, null);
SoundMC.prototype.addProperty("_currentframe", function () {
if (this._nextframe != -1) {
return this._nextframe;
} else {
return Math.floor(this._sound.position * .001 * canvas.framerate) || 0;
}
}, null);
SoundMC.prototype.addProperty("_framesloaded", function () {
return Math.floor((this._sound.getBytesLoaded() / this._sound.getBytesTotal()) * this._totalframes) || 0;
}, null);
/**
* @access private
*/
SoundMC.prototype.play = function (direct=false) {
// if we're not seeking to a specific frame and we're at the end already, start at the beginning
if (direct != true && this._currentframe == this._totalframes) {
var t = 0;
} else {
var t = this._currentframe / canvas.framerate;
if (t < 0) t = 0;
}
this._nextframe = -1;
this._sound.stop();
this._sound.start(t);
}
/**
* @access private
*/
SoundMC.prototype.gotoAndPlay = function (f) {
this._nextframe = f;
this.play(true);
}
/**
* @access private
*/
SoundMC.prototype.stop = function () {
this._sound.stop();
}
/**
* @access private
*/
SoundMC.prototype.gotoAndStop = function (f) {
this.stop();
this._nextframe = f;
}
/**
* @access private
*/
SoundMC.prototype.loadMovie = function (reqstr) {
this.init();
this._sound.loadSound(reqstr, true);
this.loadstate = 1;
}
/**
* @access private
*/
SoundMC.prototype.getBytesLoaded = function () {
return this._sound.getBytesLoaded();
}
/**
* @access private
*/
SoundMC.prototype.getBytesTotal = function () {
return this._sound.getBytesTotal();
}
/**
* @access private
*/
SoundMC.prototype.unload = function () {
this.stop();
delete this._sound;
this.loadstate = 0;
}
/**
* @access private
*/
SoundMC.prototype.setPan = function (p) {
this._sound.setPan(p);
}
/**
* @access private
*/
SoundMC.prototype.setVolume = function (v) {
this._sound.setVolume(v);
}
/**
* @access private
*/
SoundMC.prototype.getPan = function () {
return this._sound.getPan();
}
/**
* @access private
*/
SoundMC.prototype.getVolume = function () {
return this._sound.getVolume();
}
/**
* @access private
*/
SoundMC.prototype.loadDone = function (success) {
if (success != true) {
// LzLoader -> LzSprite -> LzView
this.loader.owner.owner.resourceloaderror();
if ($debug) {
Debug.warn("failed to load %w", this.reqobj.url);
}
} else {
this.loadstate = 2;
}
}
/**
* @access private
*/
SoundMC.prototype.init = function (mc) {
this._sound.stop();
delete this._sound;
if (mc != null) {
this._sound = new Sound(mc);
} else {
this._sound = new Sound();
}
this._sound.checkPolicyFile = true;
this._sound.mc = this;
/** @access private */
this._sound.onLoad = function (success) {
this.mc.loadDone(success);
}
/** @access private */
this._sound.onSoundComplete = function () {
}
this.loadstate = 0;
}
/**
* @access private
*/
SoundMC.prototype.getTotalTime = function () {
return this._sound.duration * .001;
}
/**
* @access private
*/
SoundMC.prototype.getCurrentTime = function () {
// use _nextframe if the sound was stopped at a specific frame, cf. gotoAndStop
if (this._nextframe != -1) {
return this._nextframe / canvas.framerate;
} else {
return this._sound.position * .001;
}
}
/**
* @access private
*/
SoundMC.prototype.seek = function (secs, playing) {
this._sound.stop();
this._sound.start(this.getCurrentTime() + secs);
if (playing != true) {
this._sound.stop();
// LzLoader -> LzSprite
this.loader.owner.updatePlayStatus();
}
}
/**
* @access private
*/
SoundMC.prototype.getID3 = function () {
return this._sound.id3;
}
|
/**
* LzSoundMC.as
*
* @copyright Copyright 2001-2009 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic AS2
*/
/**
* Wraps the streaming MP3 loader in a movieclip-like API.
* Used for proxyless mp3 audio loading.
*
* @access private
*/
var SoundMC = function (mc) {
this.init(mc);
}
SoundMC.prototype = new MovieClip();
// the attached flash Sound object
SoundMC.prototype._sound = null;
// flag required for loader
SoundMC.prototype.isaudio = true;
// tracks the loading progress
SoundMC.prototype.loadstate = 0;
// next frame to be played
SoundMC.prototype._nextframe = -1;
SoundMC.prototype.addProperty("_totalframes", function () {
return Math.floor(this._sound.duration * .001 * canvas.framerate) || 0;
}, null);
SoundMC.prototype.addProperty("_currentframe", function () {
if (this._nextframe != -1) {
return this._nextframe;
} else {
return Math.floor(this._sound.position * .001 * canvas.framerate) || 0;
}
}, null);
SoundMC.prototype.addProperty("_framesloaded", function () {
return Math.floor((this._sound.getBytesLoaded() / this._sound.getBytesTotal()) * this._totalframes) || 0;
}, null);
/**
* @access private
*/
SoundMC.prototype.play = function (direct=false) {
// if we're not seeking to a specific frame and we're at the end already, start at the beginning
if (direct != true && this._currentframe == this._totalframes) {
var t = 0;
} else {
var t = this._currentframe / canvas.framerate;
if (t < 0) t = 0;
}
this._nextframe = -1;
this._sound.stop();
this._sound.start(t);
}
/**
* @access private
*/
SoundMC.prototype.gotoAndPlay = function (f) {
this._nextframe = f;
this.play(true);
}
/**
* @access private
*/
SoundMC.prototype.stop = function () {
this._sound.stop();
}
/**
* @access private
*/
SoundMC.prototype.gotoAndStop = function (f) {
this.stop();
this._nextframe = f;
}
/**
* @access private
*/
SoundMC.prototype.loadMovie = function (reqstr) {
this.init();
this._sound.loadSound(reqstr, true);
this.loadstate = 1;
}
/**
* @access private
*/
SoundMC.prototype.getBytesLoaded = function () {
return this._sound.getBytesLoaded();
}
/**
* @access private
*/
SoundMC.prototype.getBytesTotal = function () {
return this._sound.getBytesTotal();
}
/**
* @access private
*/
SoundMC.prototype.unload = function () {
this.stop();
delete this._sound;
this.loadstate = 0;
}
/**
* @access private
*/
SoundMC.prototype.setPan = function (p) {
this._sound.setPan(p);
}
/**
* @access private
*/
SoundMC.prototype.setVolume = function (v) {
this._sound.setVolume(v);
}
/**
* @access private
*/
SoundMC.prototype.getPan = function () {
return this._sound.getPan();
}
/**
* @access private
*/
SoundMC.prototype.getVolume = function () {
return this._sound.getVolume();
}
/**
* @access private
*/
SoundMC.prototype.loadDone = function (success) {
// @devnote Loading invalid files still results in a successful load,
// therefore check duration to identify valid mp3-files (LPP-7880)
if (success != true || this._sound.duration == 0) {
this.loader.doError(this.loader.mc);
if ($debug) {
Debug.warn("failed to load %w", this.reqobj.url);
}
} else {
this.loadstate = 2;
}
}
/**
* @access private
*/
SoundMC.prototype.init = function (mc) {
this._sound.stop();
delete this._sound;
if (mc != null) {
this._sound = new Sound(mc);
} else {
this._sound = new Sound();
}
this._sound.checkPolicyFile = true;
this._sound.mc = this;
/** @access private */
this._sound.onLoad = function (success) {
this.mc.loadDone(success);
}
/** @access private */
this._sound.onSoundComplete = function () {
}
this.loadstate = 0;
}
/**
* @access private
*/
SoundMC.prototype.getTotalTime = function () {
return this._sound.duration * .001;
}
/**
* @access private
*/
SoundMC.prototype.getCurrentTime = function () {
// use _nextframe if the sound was stopped at a specific frame, cf. gotoAndStop
if (this._nextframe != -1) {
return this._nextframe / canvas.framerate;
} else {
return this._sound.position * .001;
}
}
/**
* @access private
*/
SoundMC.prototype.seek = function (secs, playing) {
this._sound.stop();
this._sound.start(this.getCurrentTime() + secs);
if (playing != true) {
this._sound.stop();
// LzLoader -> LzSprite
this.loader.owner.updatePlayStatus();
}
}
/**
* @access private
*/
SoundMC.prototype.getID3 = function () {
return this._sound.id3;
}
|
Change 20090309-bargull-tGm by bargull@dell--p4--2-53 on 2009-03-09 02:14:09 in /home/Admin/src/svn/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk
|
Change 20090309-bargull-tGm by bargull@dell--p4--2-53 on 2009-03-09 02:14:09
in /home/Admin/src/svn/openlaszlo/trunk
for http://svn.openlaszlo.org/openlaszlo/trunk
Summary: handle invalid files in SoundMC
New Features:
Bugs Fixed: LPP-7880 (SWF8: mp3 loading responds with error-swf / onerror not dispatched) (partial)
Technical Reviewer: hminsky
QA Reviewer: (pending)
Doc Reviewer: (pending)
Documentation:
Release Notes:
Details:
Invalid files still send onLoad(true), so check Sound.duration as a simple means to identify valid mp3-files.
Also call LzLoader#doError() instead of LzView#resourceloaderror() in order to remove requests properly from load-queue.
Tests:
testcase at bugreport
examples/music/music.lzx
git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@13220 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
|
ActionScript
|
epl-1.0
|
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
|
a54c66942ee4e36bfb1edaf0c97b4667f2fe4abc
|
src/aerys/minko/type/animation/Animation.as
|
src/aerys/minko/type/animation/Animation.as
|
package aerys.minko.type.animation
{
import aerys.minko.scene.node.IScene;
import aerys.minko.scene.node.ITransformable;
import aerys.minko.scene.node.group.Group;
import aerys.minko.type.animation.timeline.ITimeline;
import flash.utils.getTimer;
import org.osmf.elements.DurationElement;
public class Animation
{
private var _id : String;
private var _beginTime : uint;
private var _lastTime : uint;
private var _playingOn : IScene;
private var _timelines : Vector.<ITimeline>;
private var _duration : uint;
public function get id() : String { return _id; }
public function Animation(id : String,
timelines : Vector.<ITimeline>)
{
_id = id;
_timelines = timelines;
_lastTime = 0;
_duration = 0;
for each (var timeline : ITimeline in timelines)
if (_duration < timeline.duration)
_duration = timeline.duration;
}
public function tick() : void
{
var time : uint = (getTimer() - _beginTime) % _duration;
transformNodes(time);
}
public function step(deltaTime : uint = 80) : void
{
var time : uint = (_lastTime + deltaTime) % _duration;
transformNodes(time);
}
public function stepReverse(deltaTime : uint = 80) : void
{
var time : int = (_lastTime - deltaTime) % _duration;
if (time < 0)
time = time + _duration;
transformNodes(time);
}
private function transformNodes(time : uint) : void
{
_lastTime = time;
var timelinesCount : uint = _timelines.length;
for (var i : uint = 0; i < timelinesCount; ++i)
{
var timeline : ITimeline = _timelines[i];
var timelineTarget : String = timeline.target;
var target : ITransformable;
if (_playingOn.name == timelineTarget)
target = ITransformable(_playingOn);
else if (_playingOn is Group)
target = ITransformable(Group(_playingOn).getDescendantByName(timelineTarget));
if (!target)
continue;
timeline.updateAt(time, target);
}
}
public function playOn(node : IScene) : void
{
_beginTime = getTimer();
_playingOn = node;
_lastTime = 0;
}
public function stop() : void
{
_playingOn = null;
}
}
}
|
package aerys.minko.type.animation
{
import aerys.minko.scene.node.IScene;
import aerys.minko.scene.node.ITransformable;
import aerys.minko.scene.node.group.Group;
import aerys.minko.type.animation.timeline.ITimeline;
import flash.utils.getTimer;
public class Animation
{
private var _id : String;
private var _beginTime : uint;
private var _lastTime : uint;
private var _playingOn : IScene;
private var _timelines : Vector.<ITimeline>;
private var _duration : uint;
public function get id() : String { return _id; }
public function Animation(id : String,
timelines : Vector.<ITimeline>)
{
_id = id;
_timelines = timelines;
_lastTime = 0;
_duration = 0;
for each (var timeline : ITimeline in timelines)
if (_duration < timeline.duration)
_duration = timeline.duration;
}
public function tick() : void
{
var time : uint = (getTimer() - _beginTime) % _duration;
transformNodes(time);
}
public function step(deltaTime : uint = 80) : void
{
var time : uint = (_lastTime + deltaTime) % _duration;
transformNodes(time);
}
public function stepReverse(deltaTime : uint = 80) : void
{
var time : int = (_lastTime - deltaTime) % _duration;
if (time < 0)
time = time + _duration;
transformNodes(time);
}
private function transformNodes(time : uint) : void
{
_lastTime = time;
var timelinesCount : uint = _timelines.length;
for (var i : uint = 0; i < timelinesCount; ++i)
{
var timeline : ITimeline = _timelines[i];
var timelineTarget : String = timeline.target;
var target : ITransformable;
if (_playingOn.name == timelineTarget)
target = ITransformable(_playingOn);
else if (_playingOn is Group)
target = ITransformable(Group(_playingOn).getDescendantByName(timelineTarget));
if (!target)
continue;
timeline.updateAt(time, target);
}
}
public function playOn(node : IScene) : void
{
_beginTime = getTimer();
_playingOn = node;
_lastTime = 0;
}
public function stop() : void
{
_playingOn = null;
}
}
}
|
Remove usused import
|
Remove usused import
|
ActionScript
|
mit
|
aerys/minko-as3
|
452864c0ae84b774cd61d205a09b9dfcd9038fea
|
WEB-INF/lps/lfc/kernel/swf9/LzMouseKernel.as
|
WEB-INF/lps/lfc/kernel/swf9/LzMouseKernel.as
|
/**
* LzMouseKernel.as
*
* @copyright Copyright 2001-2010 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic swf9
*/
// Receives mouse events from the runtime
class LzMouseKernel {
#passthrough (toplevel:true) {
import flash.display.Sprite;
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.ui.*;
import flash.utils.getDefinitionByName;
}#
//////////////////
// MOUSE EVENTS //
//////////////////
// sends mouse events to the callback
static function handleMouseEvent (view:*, eventname:String) :void {
if (__callback) __scope[__callback](eventname, view);
//Debug.write('LzMouseKernel event', eventname);
}
static var __callback:String = null;
static var __scope:* = null;
static var __lastMouseDown:LzSprite = null;
static var __mouseLeft:Boolean = false;
static var __listeneradded:Boolean = false;
/**
* Shows or hides the hand cursor for all clickable views.
*/
static var showhandcursor:Boolean = true;
static function setCallback (scope:*, funcname:String) :void {
__scope = scope;
__callback = funcname;
if (__listeneradded == false) {
/* TODO [hqm 2008-01] Do we want to do anything with other
* events, like click?
stage.addEventListener(MouseEvent.CLICK, reportClick);
*/
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_MOVE, __mouseHandler);
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_UP, __mouseHandler);
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_DOWN, __mouseHandler);
// handled by lz.embed.mousewheel for Windows LFCApplication.stage.addEventListener(MouseEvent.MOUSE_WHEEL, __mouseWheelHandler);
LFCApplication.stage.addEventListener(Event.MOUSE_LEAVE, __mouseLeaveHandler);
__listeneradded = true;
}
}
// Handles global mouse events
static function __mouseHandler (event:MouseEvent) :void {
var eventname:String = 'on' + event.type.toLowerCase();
if (eventname == 'onmouseup' && __lastMouseDown != null) {
// call mouseup on the sprite that got the last mouse down
__lastMouseDown.__globalmouseup(event);
__lastMouseDown = null;
} else {
if (__mouseLeft) {
__mouseLeft = false;
// Mouse reentered the app.
if (event.buttonDown) __mouseUpOutsideHandler();
if (lz.embed.browser.isFirefox && lz.embed.browser.OS == 'mac' && lz.embed.browser.version < 3.5) {
// TODO [hqm 2009-04] LPP-7957 -- this works
// around Firefox bug; if you are making a text
// selection, and then drag the mouse outside of
// the app while the left button is down, and then
// release it. When you bring the mouse back into
// the app, the selection is stuck dragging
// because Flash plugin never gets the mouse up.
LFCApplication.stage.focus = null;
}
// generate a 'onmouseenter' event
handleMouseEvent(null, 'onmouseenter');
}
handleMouseEvent(null, eventname);
}
}
// sends mouseup and calls __globalmouseup when the mouse goes up outside the app - see LPP-7724
static function __mouseUpOutsideHandler () :void {
if (__lastMouseDown != null) {
var ev:MouseEvent = new MouseEvent('mouseup');
__lastMouseDown.__globalmouseup(ev);
__lastMouseDown = null;
}
}
// handles MOUSE_LEAVE event
static function __mouseLeaveHandler (event:Event = null) :void {
__mouseLeft = true;
handleMouseEvent(null, 'onmouseleave');
}
static function __mouseWheelHandler (event:MouseEvent) :void {
lz.Keys.__mousewheelEvent(event.delta);
}
//////////////////
// MOUSE CURSOR //
//////////////////
/**
* Shows or hides the hand cursor for all clickable views.
* @param Boolean show: true shows the hand cursor for buttons, false hides it
*/
static function showHandCursor (show:Boolean) :void {
showhandcursor = show;
LzSprite.rootSprite.setGlobalHandCursor(show);
}
static var __amLocked:Boolean = false;
static var useBuiltinCursor:Boolean = false;
static var cursorSprite:Sprite = null;
static var cursorOffsetX:int = 0;
static var cursorOffsetY:int = 0;
static var globalCursorResource:String = null;
static var lastCursorResource:String = null;
#passthrough {
private static var __MouseCursor:Object = null;
private static function get MouseCursor () :Object {
if (__MouseCursor == null) {
__MouseCursor = getDefinitionByName('flash.ui.MouseCursor');
}
return __MouseCursor;
}
private static var __builtinCursors:Object = null;
static function get builtinCursors () :Object {
if (__builtinCursors == null) {
var cursors:Object = {};
if ($swf10) {
cursors[MouseCursor.ARROW] = true;
cursors[MouseCursor.AUTO] = true;
cursors[MouseCursor.BUTTON] = true;
cursors[MouseCursor.HAND] = true;
cursors[MouseCursor.IBEAM] = true;
}
__builtinCursors = cursors;
}
return __builtinCursors;
}
static function get hasGlobalCursor () :Boolean {
var gcursor:String = globalCursorResource;
if ($swf10) {
return ! (gcursor == null || (gcursor == MouseCursor.AUTO && useBuiltinCursor));
} else {
return ! (gcursor == null);
}
}
}#
/**
* Sets the cursor to a resource
* @param String what: The resource to use as the cursor.
*/
static function setCursorGlobal (what:String) :void {
globalCursorResource = what;
setCursorLocal(what);
}
static function setCursorLocal (what:String) :void {
if ( __amLocked ) { return; }
if (what == null) {
// null is invalid, maybe call restoreCursor()?
return;
} else if (lastCursorResource != what) {
var resourceSprite:DisplayObject = getCursorResource(what);
if (resourceSprite != null) {
if (cursorSprite.numChildren > 0) {
cursorSprite.removeChildAt(0);
}
cursorSprite.addChild( resourceSprite );
useBuiltinCursor = false;
} else if (builtinCursors[what] != null) {
useBuiltinCursor = true;
} else {
// invalid cursor?
return;
}
lastCursorResource = what;
}
if (useBuiltinCursor) {
if ($swf10) { Mouse['cursor'] = what; }
cursorSprite.stopDrag();
cursorSprite.visible = false;
LFCApplication.stage.removeEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
LFCApplication.stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
Mouse.show();
} else {
// you can only hide the Mouse when Mouse.cursor is AUTO
if ($swf10) { Mouse['cursor'] = MouseCursor.AUTO; }
Mouse.hide();
cursorSprite.x = LFCApplication.stage.mouseX + cursorOffsetX;
cursorSprite.y = LFCApplication.stage.mouseY + cursorOffsetY;
LFCApplication.setChildIndex(cursorSprite, LFCApplication._sprite.numChildren-1);
// respond to mouse move events
cursorSprite.startDrag();
LFCApplication.stage.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
cursorSprite.visible = true;
}
}
/**
* Triggered when cursor leaves screen or context-menu is opened, in both
* cases we must display the system cursor
*/
private static function mouseLeaveHandler (event:Event) :void {
cursorSprite.visible = false;
Mouse.show();
// use capture-phase because most sprites call stopPropagation() for mouse-events
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_OVER, mouseEnterHandler, true);
}
/**
* Triggered when cursor enters screen or context-menu is closed
*/
private static function mouseEnterHandler (event:Event) :void {
cursorSprite.visible = true;
Mouse.hide();
LFCApplication.stage.removeEventListener(MouseEvent.MOUSE_OVER, mouseEnterHandler, true);
}
/**
* Hide custom cursor over selectable TextFields otherwise both the ibeam-cursor
* and the custom cursor are displayed
*/
private static function mouseMoveHandler (event:MouseEvent) :void {
var target:Object = event.target;
if (target is TextField && target.selectable) {
cursorSprite.visible = false;
Mouse.show();
} else {
Mouse.hide();
cursorSprite.visible = true;
}
}
private static function getCursorResource (resource:String) :DisplayObject {
var resinfo:Object = LzResourceLibrary[resource];
var assetclass:Class;
if (resinfo == null) {
return null;
}
// single frame resources get an entry in LzResourceLibrary which has
// 'assetclass' pointing to the resource Class object.
if (resinfo.assetclass is Class) {
assetclass = resinfo.assetclass;
} else {
// Multiframe resources have an array of Class objects in frames[]
var frames:Array = resinfo.frames;
assetclass = frames[0];
}
var asset:DisplayObject = new assetclass();
asset.scaleX = 1.0;
asset.scaleY = 1.0;
if (resinfo['offsetx'] != null) { cursorOffsetX = resinfo['offsetx']; }
if (resinfo['offsety'] != null) { cursorOffsetY = resinfo['offsety']; }
return asset;
}
/**
* This function restores the default cursor if there is no locked cursor on
* the screen.
*
* @access private
*/
static function restoreCursor () :void {
if ( __amLocked ) { return; }
cursorSprite.stopDrag();
cursorSprite.visible = false;
LFCApplication.stage.removeEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
LFCApplication.stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
globalCursorResource = null;
if ($swf10) { Mouse['cursor'] = MouseCursor.AUTO; }
Mouse.show();
}
/** Called by LzSprite to restore cursor to global value.
*/
static function restoreCursorLocal () :void {
if ( __amLocked ) { return; }
if (globalCursorResource == null) {
// Restore to system default pointer
restoreCursor();
} else {
// Restore to the last value set by setCursorGlobal
setCursorLocal(globalCursorResource);
}
}
/**
* Prevents the cursor from being changed until unlock is called.
*
*/
static function lock () :void {
__amLocked = true;
}
/**
* Restores the default cursor.
*
*/
static function unlock () :void {
__amLocked = false;
restoreCursor();
}
static function initCursor () :void {
cursorSprite = new Sprite();
cursorSprite.mouseChildren = false;
cursorSprite.mouseEnabled = false;
cursorSprite.visible = false;
// Add the cursor DisplayObject to the root sprite
LFCApplication.addChild(cursorSprite);
cursorSprite.x = -10000;
cursorSprite.y = -10000;
}
}
|
/**
* LzMouseKernel.as
*
* @copyright Copyright 2001-2010 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic swf9
*/
// Receives mouse events from the runtime
class LzMouseKernel {
#passthrough (toplevel:true) {
import flash.display.Sprite;
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.ui.*;
import flash.utils.getDefinitionByName;
}#
//////////////////
// MOUSE EVENTS //
//////////////////
// sends mouse events to the callback
static function handleMouseEvent (view:*, eventname:String) :void {
if (__callback) __scope[__callback](eventname, view);
//Debug.write('LzMouseKernel event', eventname);
}
static var __callback:String = null;
static var __scope:* = null;
static var __lastMouseDown:LzSprite = null;
static var __mouseLeft:Boolean = false;
static var __listeneradded:Boolean = false;
/**
* Shows or hides the hand cursor for all clickable views.
*/
static var showhandcursor:Boolean = true;
static function setCallback (scope:*, funcname:String) :void {
__scope = scope;
__callback = funcname;
if (__listeneradded == false) {
/* TODO [hqm 2008-01] Do we want to do anything with other
* events, like click?
stage.addEventListener(MouseEvent.CLICK, reportClick);
*/
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_MOVE, __mouseHandler);
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_UP, __mouseHandler);
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_DOWN, __mouseHandler);
// handled by lz.embed.mousewheel for Windows LFCApplication.stage.addEventListener(MouseEvent.MOUSE_WHEEL, __mouseWheelHandler);
LFCApplication.stage.addEventListener(Event.MOUSE_LEAVE, __mouseLeaveHandler);
__listeneradded = true;
}
}
// Handles global mouse events
static function __mouseHandler (event:MouseEvent) :void {
var eventname:String = 'on' + event.type.toLowerCase();
if (eventname == 'onmouseup' && __lastMouseDown != null) {
// call mouseup on the sprite that got the last mouse down
__lastMouseDown.__globalmouseup(event);
__lastMouseDown = null;
} else {
if (__mouseLeft) {
__mouseLeft = false;
// Mouse reentered the app.
if (event.buttonDown) __mouseUpOutsideHandler();
if (lz.embed.browser && lz.embed.browser.isFirefox && lz.embed.browser.OS == 'Mac' && lz.embed.browser.version < 3.5) {
// TODO [hqm 2009-04] LPP-7957 -- this works
// around Firefox bug; if you are making a text
// selection, and then drag the mouse outside of
// the app while the left button is down, and then
// release it. When you bring the mouse back into
// the app, the selection is stuck dragging
// because Flash plugin never gets the mouse up.
LFCApplication.stage.focus = null;
}
// generate a 'onmouseenter' event
handleMouseEvent(null, 'onmouseenter');
}
handleMouseEvent(null, eventname);
}
}
// sends mouseup and calls __globalmouseup when the mouse goes up outside the app - see LPP-7724
static function __mouseUpOutsideHandler () :void {
if (__lastMouseDown != null) {
var ev:MouseEvent = new MouseEvent('mouseup');
__lastMouseDown.__globalmouseup(ev);
__lastMouseDown = null;
}
}
// handles MOUSE_LEAVE event
static function __mouseLeaveHandler (event:Event = null) :void {
__mouseLeft = true;
handleMouseEvent(null, 'onmouseleave');
}
static function __mouseWheelHandler (event:MouseEvent) :void {
lz.Keys.__mousewheelEvent(event.delta);
}
//////////////////
// MOUSE CURSOR //
//////////////////
/**
* Shows or hides the hand cursor for all clickable views.
* @param Boolean show: true shows the hand cursor for buttons, false hides it
*/
static function showHandCursor (show:Boolean) :void {
showhandcursor = show;
LzSprite.rootSprite.setGlobalHandCursor(show);
}
static var __amLocked:Boolean = false;
static var useBuiltinCursor:Boolean = false;
static var cursorSprite:Sprite = null;
static var cursorOffsetX:int = 0;
static var cursorOffsetY:int = 0;
static var globalCursorResource:String = null;
static var lastCursorResource:String = null;
#passthrough {
private static var __MouseCursor:Object = null;
private static function get MouseCursor () :Object {
if (__MouseCursor == null) {
__MouseCursor = getDefinitionByName('flash.ui.MouseCursor');
}
return __MouseCursor;
}
private static var __builtinCursors:Object = null;
static function get builtinCursors () :Object {
if (__builtinCursors == null) {
var cursors:Object = {};
if ($swf10) {
cursors[MouseCursor.ARROW] = true;
cursors[MouseCursor.AUTO] = true;
cursors[MouseCursor.BUTTON] = true;
cursors[MouseCursor.HAND] = true;
cursors[MouseCursor.IBEAM] = true;
}
__builtinCursors = cursors;
}
return __builtinCursors;
}
static function get hasGlobalCursor () :Boolean {
var gcursor:String = globalCursorResource;
if ($swf10) {
return ! (gcursor == null || (gcursor == MouseCursor.AUTO && useBuiltinCursor));
} else {
return ! (gcursor == null);
}
}
}#
/**
* Sets the cursor to a resource
* @param String what: The resource to use as the cursor.
*/
static function setCursorGlobal (what:String) :void {
globalCursorResource = what;
setCursorLocal(what);
}
static function setCursorLocal (what:String) :void {
if ( __amLocked ) { return; }
if (what == null) {
// null is invalid, maybe call restoreCursor()?
return;
} else if (lastCursorResource != what) {
var resourceSprite:DisplayObject = getCursorResource(what);
if (resourceSprite != null) {
if (cursorSprite.numChildren > 0) {
cursorSprite.removeChildAt(0);
}
cursorSprite.addChild( resourceSprite );
useBuiltinCursor = false;
} else if (builtinCursors[what] != null) {
useBuiltinCursor = true;
} else {
// invalid cursor?
return;
}
lastCursorResource = what;
}
if (useBuiltinCursor) {
if ($swf10) { Mouse['cursor'] = what; }
cursorSprite.stopDrag();
cursorSprite.visible = false;
LFCApplication.stage.removeEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
LFCApplication.stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
Mouse.show();
} else {
// you can only hide the Mouse when Mouse.cursor is AUTO
if ($swf10) { Mouse['cursor'] = MouseCursor.AUTO; }
Mouse.hide();
cursorSprite.x = LFCApplication.stage.mouseX + cursorOffsetX;
cursorSprite.y = LFCApplication.stage.mouseY + cursorOffsetY;
LFCApplication.setChildIndex(cursorSprite, LFCApplication._sprite.numChildren-1);
// respond to mouse move events
cursorSprite.startDrag();
LFCApplication.stage.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
cursorSprite.visible = true;
}
}
/**
* Triggered when cursor leaves screen or context-menu is opened, in both
* cases we must display the system cursor
*/
private static function mouseLeaveHandler (event:Event) :void {
cursorSprite.visible = false;
Mouse.show();
// use capture-phase because most sprites call stopPropagation() for mouse-events
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_OVER, mouseEnterHandler, true);
}
/**
* Triggered when cursor enters screen or context-menu is closed
*/
private static function mouseEnterHandler (event:Event) :void {
cursorSprite.visible = true;
Mouse.hide();
LFCApplication.stage.removeEventListener(MouseEvent.MOUSE_OVER, mouseEnterHandler, true);
}
/**
* Hide custom cursor over selectable TextFields otherwise both the ibeam-cursor
* and the custom cursor are displayed
*/
private static function mouseMoveHandler (event:MouseEvent) :void {
var target:Object = event.target;
if (target is TextField && target.selectable) {
cursorSprite.visible = false;
Mouse.show();
} else {
Mouse.hide();
cursorSprite.visible = true;
}
}
private static function getCursorResource (resource:String) :DisplayObject {
var resinfo:Object = LzResourceLibrary[resource];
var assetclass:Class;
if (resinfo == null) {
return null;
}
// single frame resources get an entry in LzResourceLibrary which has
// 'assetclass' pointing to the resource Class object.
if (resinfo.assetclass is Class) {
assetclass = resinfo.assetclass;
} else {
// Multiframe resources have an array of Class objects in frames[]
var frames:Array = resinfo.frames;
assetclass = frames[0];
}
var asset:DisplayObject = new assetclass();
asset.scaleX = 1.0;
asset.scaleY = 1.0;
if (resinfo['offsetx'] != null) { cursorOffsetX = resinfo['offsetx']; }
if (resinfo['offsety'] != null) { cursorOffsetY = resinfo['offsety']; }
return asset;
}
/**
* This function restores the default cursor if there is no locked cursor on
* the screen.
*
* @access private
*/
static function restoreCursor () :void {
if ( __amLocked ) { return; }
cursorSprite.stopDrag();
cursorSprite.visible = false;
LFCApplication.stage.removeEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
LFCApplication.stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
globalCursorResource = null;
if ($swf10) { Mouse['cursor'] = MouseCursor.AUTO; }
Mouse.show();
}
/** Called by LzSprite to restore cursor to global value.
*/
static function restoreCursorLocal () :void {
if ( __amLocked ) { return; }
if (globalCursorResource == null) {
// Restore to system default pointer
restoreCursor();
} else {
// Restore to the last value set by setCursorGlobal
setCursorLocal(globalCursorResource);
}
}
/**
* Prevents the cursor from being changed until unlock is called.
*
*/
static function lock () :void {
__amLocked = true;
}
/**
* Restores the default cursor.
*
*/
static function unlock () :void {
__amLocked = false;
restoreCursor();
}
static function initCursor () :void {
cursorSprite = new Sprite();
cursorSprite.mouseChildren = false;
cursorSprite.mouseEnabled = false;
cursorSprite.visible = false;
// Add the cursor DisplayObject to the root sprite
LFCApplication.addChild(cursorSprite);
cursorSprite.x = -10000;
cursorSprite.y = -10000;
}
}
|
Change 20100224-maxcarlson-n by maxcarlson@bank on 2010-02-24 11:14:21 PST in /Users/maxcarlson/openlaszlo/trunk-clean for http://svn.openlaszlo.org/openlaszlo/trunk
|
Change 20100224-maxcarlson-n by maxcarlson@bank on 2010-02-24 11:14:21 PST
in /Users/maxcarlson/openlaszlo/trunk-clean
for http://svn.openlaszlo.org/openlaszlo/trunk
Summary: UPDATED: Conditionalize textfield focus workaround from LPP-7957
Bugs Fixed: LPP-8783 - Text field loses focus when mousing out of canvas and then mousing back in (SWF9)
Technical Reviewer: ptw
QA Reviewer: [email protected]
Details: Test for lz.embed.browser, and correct case in test for 'Mac'. Conditionalize workaround to only happen for FF < 3.5 on OS X.
Tests: See LPP-8783.
git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@15803 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
|
ActionScript
|
epl-1.0
|
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
|
23cc6105f96c7cc481b3bc6940f572450a606b55
|
src/flash/htmlelements/YouTubeElement.as
|
src/flash/htmlelements/YouTubeElement.as
|
package htmlelements
{
import flash.display.Sprite;
import flash.events.*;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.media.Video;
import flash.media.SoundTransform;
import flash.utils.Timer;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLVariables;
import flash.net.URLRequestMethod;
import flash.display.MovieClip;
import flash.display.Loader;
import flash.display.DisplayObject;
import FlashMediaElement;
import HtmlMediaEvent;
public class YouTubeElement extends Sprite implements IMediaElement
{
private var _currentUrl:String = "";
private var _autoplay:Boolean = true;
private var _preload:String = "";
private var _element:FlashMediaElement;
// event values
private var _currentTime:Number = 0;
private var _duration:Number = 0;
private var _framerate:Number;
private var _isPaused:Boolean = true;
private var _isEnded:Boolean = false;
private var _volume:Number = 1;
private var _isMuted:Boolean = false;
private var _bytesLoaded:Number = 0;
private var _bytesTotal:Number = 0;
private var _bufferedTime:Number = 0;
private var _bufferEmpty:Boolean = false;
private var _videoWidth:Number = -1;
private var _videoHeight:Number = -1;
private var _timer:Timer;
// YouTube stuff
private var _playerLoader:Loader;
private var _player:Object = null;
private var _playerIsLoaded:Boolean = false;
private var _youTubeId:String = "";
//http://code.google.com/p/gdata-samples/source/browse/trunk/ytplayer/actionscript3/com/google/youtube/examples/AS3Player.as
private static const WIDESCREEN_ASPECT_RATIO:String = "widescreen";
private static const QUALITY_TO_PLAYER_WIDTH:Object = {
small: 320,
medium: 640,
large: 854,
hd720: 1280
};
private static const STATE_ENDED:Number = 0;
private static const STATE_PLAYING:Number = 1;
private static const STATE_PAUSED:Number = 2;
private static const STATE_CUED:Number = 5;
public function get player():DisplayObject {
return _player;
}
public function setSize(width:Number, height:Number):void {
if (_player != null) {
_player.setSize(width, height);
}
}
public function get videoHeight():Number {
return _videoHeight;
}
public function get videoWidth():Number {
return _videoWidth;
}
public function duration():Number {
return _duration;
}
public function currentProgress():Number {
if(_bytesTotal> 0) {
return Math.round(_bytesLoaded/_bytesTotal*100);
} else {
return 0;
}
}
public function currentTime():Number {
return _currentTime;
}
public var initHeight:Number;
public var initWidth:Number;
// (1) load()
// calls _connection.connect();
// waits for NetConnection.Connect.Success
// _stream gets created
public function YouTubeElement(element:FlashMediaElement, autoplay:Boolean, preload:String, timerRate:Number, startVolume:Number)
{
_element = element;
_autoplay = autoplay;
_volume = startVolume;
_preload = preload;
initHeight = 0;
initWidth = 0;
_playerLoader = new Loader();
_playerLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, playerLoaderInitHandler);
_playerLoader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3"));
_timer = new Timer(timerRate);
_timer.addEventListener("timer", timerHandler);
_timer.start();
}
private function playerLoaderInitHandler(event:Event):void {
_element.addChild(_playerLoader.content);
_element.setControlDepth();
_playerLoader.content.addEventListener("onReady", onPlayerReady);
_playerLoader.content.addEventListener("onError", onPlayerError);
_playerLoader.content.addEventListener("onStateChange", onPlayerStateChange);
_playerLoader.content.addEventListener("onPlaybackQualityChange", onVideoPlaybackQualityChange);
}
private function onPlayerReady(event:Event):void {
_playerIsLoaded = true;
_player = _playerLoader.content;
if (initHeight > 0 && initWidth > 0)
_player.setSize(initWidth, initHeight);
if (_youTubeId != "") {
if (_autoplay) {
player.loadVideoById(_youTubeId);
} else {
player.cueVideoById(_youTubeId);
}
_timer.start();
}
}
private function onPlayerError(event:Event):void {
// trace("Player error:", Object(event).data);
}
private function onPlayerStateChange(event:Event):void {
trace("State is", Object(event).data);
_duration = _player.getDuration();
switch (Object(event).data) {
case STATE_ENDED:
_isEnded = true;
_isPaused = false;
sendEvent(HtmlMediaEvent.ENDED);
break;
case STATE_PLAYING:
_isEnded = false;
_isPaused = false;
sendEvent(HtmlMediaEvent.PLAY);
sendEvent(HtmlMediaEvent.PLAYING);
break;
case STATE_PAUSED:
_isEnded = false;
_isPaused = true;
sendEvent(HtmlMediaEvent.PAUSE);
break;
case STATE_CUED:
sendEvent(HtmlMediaEvent.CANPLAY);
// resize?
break;
}
}
private function onVideoPlaybackQualityChange(event:Event):void {
trace("Current video quality:", Object(event).data);
//resizePlayer(Object(event).data);
}
private function timerHandler(e:TimerEvent) {
if (_playerIsLoaded) {
_bytesLoaded = _player.getVideoBytesLoaded();
_bytesTotal = _player.getVideoBytesTotal();
_currentTime = player.getCurrentTime();
if (!_isPaused)
sendEvent(HtmlMediaEvent.TIMEUPDATE);
if (_bytesLoaded < _bytesTotal)
sendEvent(HtmlMediaEvent.PROGRESS);
}
}
private function getYouTubeId(url:String):String {
// http://www.youtube.com/watch?feature=player_embedded&v=yyWWXSwtPP0
// http://www.youtube.com/v/VIDEO_ID?version=3
// http://youtu.be/Djd6tPrxc08
url = unescape(url);
var youTubeId:String = "";
if (url.indexOf("?") > 0) {
// assuming: http://www.youtube.com/watch?feature=player_embedded&v=yyWWXSwtPP0
youTubeId = getYouTubeIdFromParam(url);
// if it's http://www.youtube.com/v/VIDEO_ID?version=3
if (youTubeId == "") {
youTubeId = getYouTubeIdFromUrl(url);
}
} else {
youTubeId = getYouTubeIdFromUrl(url);
}
return youTubeId;
}
// http://www.youtube.com/watch?feature=player_embedded&v=yyWWXSwtPP0
private function getYouTubeIdFromParam(url:String):String {
var youTubeId:String = "";
var parts:Array = url.split('?');
var parameters:Array = parts[1].split('&');
for (var i:Number=0; i<parameters.length; i++) {
var paramParts = parameters[i].split('=');
if (paramParts[0] == "v") {
youTubeId = paramParts[1];
break;
}
}
return youTubeId;
}
// http://www.youtube.com/v/VIDEO_ID?version=3
// http://youtu.be/Djd6tPrxc08
private function getYouTubeIdFromUrl(url:String):String {
var youTubeId:String = "";
// remove any querystring elements
var parts:Array = url.split('?');
url = parts[0];
youTubeId = url.substring(url.lastIndexOf("/")+1);
return youTubeId;
}
// interface members
public function setSrc(url:String):void {
_currentUrl = url;
_youTubeId = getYouTubeId(url);
}
public function load():void {
// do nothing
if (_playerIsLoaded) {
player.loadVideoById(_youTubeId);
_timer.start();
}
}
public function play():void {
if (_playerIsLoaded) {
_player.playVideo();
}
}
public function pause():void {
if (_playerIsLoaded) {
_player.pauseVideo();
}
}
public function stop():void {
if (_playerIsLoaded) {
_player.pauseVideo();
}
}
public function setCurrentTime(pos:Number):void {
_player.seekTo(pos, false);
}
public function setVolume(volume:Number):void {
_player.setVolume(volume*100);
_volume = volume;
}
public function getVolume():Number {
return _player.getVolume()*100;
}
public function setMuted(muted:Boolean):void {
if (muted) {
_player.mute();
} else {
_player.unMute();
}
_muted = _player.isMuted();
sendEvent(HtmlMediaEvent.VOLUMECHANGE);
}
private function sendEvent(eventName:String) {
// calculate this to mimic HTML5
_bufferedTime = _bytesLoaded / _bytesTotal * _duration;
// build JSON
var values:String =
"duration:" + _duration +
",framerate:" + _framerate +
",currentTime:" + _currentTime +
",muted:" + _isMuted +
",paused:" + _isPaused +
",ended:" + _isEnded +
",volume:" + _volume +
",src:\"" + _currentUrl + "\"" +
",bytesTotal:" + _bytesTotal +
",bufferedBytes:" + _bytesLoaded +
",bufferedTime:" + _bufferedTime +
",videoWidth:" + _videoWidth +
",videoHeight:" + _videoHeight +
"";
_element.sendEvent(eventName, values);
}
}
}
|
package htmlelements
{
import flash.display.Sprite;
import flash.events.*;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.media.Video;
import flash.media.SoundTransform;
import flash.utils.Timer;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLVariables;
import flash.net.URLRequestMethod;
import flash.display.MovieClip;
import flash.display.Loader;
import flash.display.DisplayObject;
import FlashMediaElement;
import HtmlMediaEvent;
public class YouTubeElement extends Sprite implements IMediaElement
{
private var _currentUrl:String = "";
private var _autoplay:Boolean = true;
private var _preload:String = "";
private var _element:FlashMediaElement;
// event values
private var _currentTime:Number = 0;
private var _duration:Number = 0;
private var _framerate:Number;
private var _isPaused:Boolean = true;
private var _isEnded:Boolean = false;
private var _volume:Number = 1;
private var _isMuted:Boolean = false;
private var _bytesLoaded:Number = 0;
private var _bytesTotal:Number = 0;
private var _bufferedTime:Number = 0;
private var _bufferEmpty:Boolean = false;
private var _videoWidth:Number = -1;
private var _videoHeight:Number = -1;
private var _timer:Timer;
// YouTube stuff
private var _playerLoader:Loader;
private var _player:Object = null;
private var _playerIsLoaded:Boolean = false;
private var _youTubeId:String = "";
//http://code.google.com/p/gdata-samples/source/browse/trunk/ytplayer/actionscript3/com/google/youtube/examples/AS3Player.as
private static const WIDESCREEN_ASPECT_RATIO:String = "widescreen";
private static const QUALITY_TO_PLAYER_WIDTH:Object = {
small: 320,
medium: 640,
large: 854,
hd720: 1280
};
private static const STATE_ENDED:Number = 0;
private static const STATE_PLAYING:Number = 1;
private static const STATE_PAUSED:Number = 2;
private static const STATE_CUED:Number = 5;
public function get player():DisplayObject {
return _player;
}
public function setSize(width:Number, height:Number):void {
if (_player != null) {
_player.setSize(width, height);
}
}
public function get videoHeight():Number {
return _videoHeight;
}
public function get videoWidth():Number {
return _videoWidth;
}
public function duration():Number {
return _duration;
}
public function currentProgress():Number {
if(_bytesTotal> 0) {
return Math.round(_bytesLoaded/_bytesTotal*100);
} else {
return 0;
}
}
public function currentTime():Number {
return _currentTime;
}
public var initHeight:Number;
public var initWidth:Number;
// (1) load()
// calls _connection.connect();
// waits for NetConnection.Connect.Success
// _stream gets created
private var _isChromeless:Boolean = false;
public function YouTubeElement(element:FlashMediaElement, autoplay:Boolean, preload:String, timerRate:Number, startVolume:Number)
{
_element = element;
_autoplay = autoplay;
_volume = startVolume;
_preload = preload;
initHeight = 0;
initWidth = 0;
_playerLoader = new Loader();
_playerLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, playerLoaderInitHandler);
// chromeless
if (_isChromeless) {
_playerLoader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3&controls=1&rel=0&showinfo=0&iv_load_policy=1"));
}
_timer = new Timer(timerRate);
_timer.addEventListener("timer", timerHandler);
_timer.start();
}
private function playerLoaderInitHandler(event:Event):void {
trace("yt player init");
_element.addChild(_playerLoader.content);
_element.setControlDepth();
_playerLoader.content.addEventListener("onReady", onPlayerReady);
_playerLoader.content.addEventListener("onError", onPlayerError);
_playerLoader.content.addEventListener("onStateChange", onPlayerStateChange);
_playerLoader.content.addEventListener("onPlaybackQualityChange", onVideoPlaybackQualityChange);
}
private function onPlayerReady(event:Event):void {
_playerIsLoaded = true;
_player = _playerLoader.content;
if (initHeight > 0 && initWidth > 0)
_player.setSize(initWidth, initHeight);
if (_youTubeId != "") { // && _isChromeless) {
if (_autoplay) {
player.loadVideoById(_youTubeId);
} else {
player.cueVideoById(_youTubeId);
}
_timer.start();
}
}
private function onPlayerError(event:Event):void {
// trace("Player error:", Object(event).data);
}
private function onPlayerStateChange(event:Event):void {
trace("State is", Object(event).data);
_duration = _player.getDuration();
switch (Object(event).data) {
case STATE_ENDED:
_isEnded = true;
_isPaused = false;
sendEvent(HtmlMediaEvent.ENDED);
break;
case STATE_PLAYING:
_isEnded = false;
_isPaused = false;
sendEvent(HtmlMediaEvent.PLAY);
sendEvent(HtmlMediaEvent.PLAYING);
break;
case STATE_PAUSED:
_isEnded = false;
_isPaused = true;
sendEvent(HtmlMediaEvent.PAUSE);
break;
case STATE_CUED:
sendEvent(HtmlMediaEvent.CANPLAY);
// resize?
break;
}
}
private function onVideoPlaybackQualityChange(event:Event):void {
trace("Current video quality:", Object(event).data);
//resizePlayer(Object(event).data);
}
private function timerHandler(e:TimerEvent) {
if (_playerIsLoaded) {
_bytesLoaded = _player.getVideoBytesLoaded();
_bytesTotal = _player.getVideoBytesTotal();
_currentTime = player.getCurrentTime();
if (!_isPaused)
sendEvent(HtmlMediaEvent.TIMEUPDATE);
if (_bytesLoaded < _bytesTotal)
sendEvent(HtmlMediaEvent.PROGRESS);
}
}
private function getYouTubeId(url:String):String {
// http://www.youtube.com/watch?feature=player_embedded&v=yyWWXSwtPP0
// http://www.youtube.com/v/VIDEO_ID?version=3
// http://youtu.be/Djd6tPrxc08
url = unescape(url);
var youTubeId:String = "";
if (url.indexOf("?") > 0) {
// assuming: http://www.youtube.com/watch?feature=player_embedded&v=yyWWXSwtPP0
youTubeId = getYouTubeIdFromParam(url);
// if it's http://www.youtube.com/v/VIDEO_ID?version=3
if (youTubeId == "") {
youTubeId = getYouTubeIdFromUrl(url);
}
} else {
youTubeId = getYouTubeIdFromUrl(url);
}
return youTubeId;
}
// http://www.youtube.com/watch?feature=player_embedded&v=yyWWXSwtPP0
private function getYouTubeIdFromParam(url:String):String {
var youTubeId:String = "";
var parts:Array = url.split('?');
var parameters:Array = parts[1].split('&');
for (var i:Number=0; i<parameters.length; i++) {
var paramParts = parameters[i].split('=');
if (paramParts[0] == "v") {
youTubeId = paramParts[1];
break;
}
}
return youTubeId;
}
// http://www.youtube.com/v/VIDEO_ID?version=3
// http://youtu.be/Djd6tPrxc08
private function getYouTubeIdFromUrl(url:String):String {
var youTubeId:String = "";
// remove any querystring elements
var parts:Array = url.split('?');
url = parts[0];
youTubeId = url.substring(url.lastIndexOf("/")+1);
return youTubeId;
}
// interface members
public function setSrc(url:String):void {
trace("yt setSrc()" + url );
_currentUrl = url;
_youTubeId = getYouTubeId(url);
if (!_playerIsLoaded && !_isChromeless) {
_playerLoader.load(new URLRequest("http://www.youtube.com/v/" + _youTubeId + "?version=3&controls=0&rel=0&showinfo=0&iv_load_policy=1"));
}
}
public function load():void {
// do nothing
trace("yt load()");
if (_playerIsLoaded) {
player.loadVideoById(_youTubeId);
_timer.start();
} else {
/*
if (!_isChromless && _youTubeId != "") {
_playerLoader.load(new URLRequest("http://www.youtube.com/v/" + _youTubeId + "?version=3&controls=0&rel=0&showinfo=0&iv_load_policy=1"));
}
*/
}
}
public function play():void {
if (_playerIsLoaded) {
_player.playVideo();
}
}
public function pause():void {
if (_playerIsLoaded) {
_player.pauseVideo();
}
}
public function stop():void {
if (_playerIsLoaded) {
_player.pauseVideo();
}
}
public function setCurrentTime(pos:Number):void {
_player.seekTo(pos, false);
}
public function setVolume(volume:Number):void {
_player.setVolume(volume*100);
_volume = volume;
}
public function getVolume():Number {
return _player.getVolume()*100;
}
public function setMuted(muted:Boolean):void {
if (muted) {
_player.mute();
} else {
_player.unMute();
}
_muted = _player.isMuted();
sendEvent(HtmlMediaEvent.VOLUMECHANGE);
}
private function sendEvent(eventName:String) {
// calculate this to mimic HTML5
_bufferedTime = _bytesLoaded / _bytesTotal * _duration;
// build JSON
var values:String =
"duration:" + _duration +
",framerate:" + _framerate +
",currentTime:" + _currentTime +
",muted:" + _isMuted +
",paused:" + _isPaused +
",ended:" + _isEnded +
",volume:" + _volume +
",src:\"" + _currentUrl + "\"" +
",bytesTotal:" + _bytesTotal +
",bufferedBytes:" + _bytesLoaded +
",bufferedTime:" + _bufferedTime +
",videoWidth:" + _videoWidth +
",videoHeight:" + _videoHeight +
"";
_element.sendEvent(eventName, values);
}
}
}
|
Update from Chromeless to normal player to support anntations
|
Update from Chromeless to normal player to support anntations
|
ActionScript
|
agpl-3.0
|
libeo/Vibeo,libeo/Vibeo,libeo/Vibeo,libeo/Vibeo
|
8111aa3f7e1c22ecc1961e5070de842842406366
|
runtime/src/main/as/flump/xfl/XflKeyframe.as
|
runtime/src/main/as/flump/xfl/XflKeyframe.as
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.xfl {
import flash.geom.Matrix;
import flash.geom.Point;
public class XflKeyframe extends XflComponent
{
use namespace xflns;
public var index :int;
/** The length of this keyframe in frames. */
public var duration :Number;
/** The name of the libraryItem in this keyframe, or null if there is no libraryItem. */
public var libraryItem :String;
/** The name of the symbol in this keyframe, or null if there is no symbol. */
public var symbol :String;
/** The transform of the symbol in this keyframe, or null if libraryName is null. */
public var matrix :Matrix;
/** The label on this keyframe, or null if there isn't one */
public var label :String;
/** Exploded values from matrix */
public var x :Number = 0.0, y :Number = 0.0, scaleX :Number = 1.0, scaleY :Number = 1.0,
rotation :Number = 0.0;
public function XflKeyframe (baseLocation :String, xml :XML, errors :Vector.<ParseError>,
flipbook :Boolean) {
const converter :XmlConverter = new XmlConverter(xml);
index = converter.getIntAttr("index");
super(baseLocation + ":" + index, errors);
duration = converter.getNumberAttr("duration", 1);
label = converter.getStringAttr("name", null);
if (flipbook) return;
var symbolXml :XML;
for each (var frameEl :XML in xml.elements.elements()) {
if (frameEl.name().localName == "DOMSymbolInstance") {
if (symbolXml != null) {
addError(ParseError.CRIT, "There can be only one symbol instance at " +
"a time in a keyframe.");
} else symbolXml = frameEl;
} else {
addError(ParseError.CRIT, "Non-symbols may not be in exported movie " +
"layers");
}
}
if (symbolXml == null) return; // Purely labelled frame
if (!isClassicTween(xml)) {
addError(ParseError.WARN, "Motion and Shape tweens are not supported");
}
libraryItem = new XmlConverter(symbolXml).getStringAttr("libraryItemName");
const matrixXml :XML = symbolXml.matrix.Matrix[0];
const matrixConverter :XmlConverter =
matrixXml == null ? null : new XmlConverter(matrixXml);
function m (name :String, def :Number) :Number {
return matrixConverter == null ? def : matrixConverter.getNumberAttr(name, def);
}
matrix = new Matrix(m("a", 1), m("b", 0), m("c", 0), m("d", 1), m("tx", 0), m("ty", 0));
x = matrix.tx;
y = matrix.ty;
var py :Point = matrix.deltaTransformPoint(new Point(1, 0));
rotation = Math.atan2(py.y, py.x);
scaleX = Math.sqrt((matrix.a * matrix.a) + (matrix.b * matrix.b));
scaleY = Math.sqrt((matrix.c * matrix.c) + (matrix.d * matrix.d));
}
public function checkSymbols (lib :XflLibrary) :void {
if (symbol != null && !lib.hasSymbol(symbol)) {
addError(ParseError.CRIT, "Symbol '" + symbol + "' not exported");
}
}
public function toJSON (_:*) :Object {
var json :Object = {
index: index,
duration: duration
};
if (libraryItem != null) {
json.ref = symbol;
json.t = [ x, y, scaleX, scaleY, rotation ];
// json.alpha = 1;
}
if (label != null) {
json.label = label;
}
return json;
}
protected static function isClassicTween (xml :XML) :Boolean {
const converter :XmlConverter = new XmlConverter(xml);
if (converter.hasAttr("motionTweenRotate") ||
converter.hasAttr("motionTweenRotateTimes")) {
return false;
}
return true;
}
}
}
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.xfl {
import flash.geom.Matrix;
import flash.geom.Point;
import com.threerings.util.MatrixUtil;
public class XflKeyframe extends XflComponent
{
use namespace xflns;
public var index :int;
/** The length of this keyframe in frames. */
public var duration :Number;
/** The name of the libraryItem in this keyframe, or null if there is no libraryItem. */
public var libraryItem :String;
/** The name of the symbol in this keyframe, or null if there is no symbol. */
public var symbol :String;
/** The transform of the symbol in this keyframe, or null if libraryName is null. */
public var matrix :Matrix;
/** The label on this keyframe, or null if there isn't one */
public var label :String;
/** Exploded values from matrix */
public var x :Number = 0.0, y :Number = 0.0, scaleX :Number = 1.0, scaleY :Number = 1.0,
rotation :Number = 0.0;
public function XflKeyframe (baseLocation :String, xml :XML, errors :Vector.<ParseError>,
flipbook :Boolean) {
const converter :XmlConverter = new XmlConverter(xml);
index = converter.getIntAttr("index");
super(baseLocation + ":" + index, errors);
duration = converter.getNumberAttr("duration", 1);
label = converter.getStringAttr("name", null);
if (flipbook) return;
var symbolXml :XML;
for each (var frameEl :XML in xml.elements.elements()) {
if (frameEl.name().localName == "DOMSymbolInstance") {
if (symbolXml != null) {
addError(ParseError.CRIT, "There can be only one symbol instance at " +
"a time in a keyframe.");
} else symbolXml = frameEl;
} else {
addError(ParseError.CRIT, "Non-symbols may not be in exported movie " +
"layers");
}
}
if (symbolXml == null) return; // Purely labelled frame
if (!isClassicTween(xml)) {
addError(ParseError.WARN, "Motion and Shape tweens are not supported");
}
libraryItem = new XmlConverter(symbolXml).getStringAttr("libraryItemName");
const matrixXml :XML = symbolXml.matrix.Matrix[0];
const matrixConverter :XmlConverter =
matrixXml == null ? null : new XmlConverter(matrixXml);
function m (name :String, def :Number) :Number {
return matrixConverter == null ? def : matrixConverter.getNumberAttr(name, def);
}
matrix = new Matrix(m("a", 1), m("b", 0), m("c", 0), m("d", 1), m("tx", 0), m("ty", 0));
x = matrix.tx;
y = matrix.ty;
rotation = MatrixUtil.rotation(matrix);
scaleX = MatrixUtil.scaleX(matrix);
scaleY = MatrixUtil.scaleY(matrix);
}
public function checkSymbols (lib :XflLibrary) :void {
if (symbol != null && !lib.hasSymbol(symbol)) {
addError(ParseError.CRIT, "Symbol '" + symbol + "' not exported");
}
}
public function toJSON (_:*) :Object {
var json :Object = {
index: index,
duration: duration
};
if (libraryItem != null) {
json.ref = symbol;
json.t = [ x, y, scaleX, scaleY, rotation ];
// json.alpha = 1;
}
if (label != null) {
json.label = label;
}
return json;
}
protected static function isClassicTween (xml :XML) :Boolean {
const converter :XmlConverter = new XmlConverter(xml);
if (converter.hasAttr("motionTweenRotate") ||
converter.hasAttr("motionTweenRotateTimes")) {
return false;
}
return true;
}
}
}
|
Use MatrixUtil
|
Use MatrixUtil
|
ActionScript
|
mit
|
mathieuanthoine/flump,mathieuanthoine/flump,funkypandagame/flump,tconkling/flump,mathieuanthoine/flump,tconkling/flump,funkypandagame/flump
|
192fa89ae544a10e755914e6cc523025bdae7128
|
src/aerys/minko/scene/controller/AbstractController.as
|
src/aerys/minko/scene/controller/AbstractController.as
|
package aerys.minko.scene.controller
{
import aerys.minko.ns.minko_scene;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.type.Signal;
import flash.utils.getQualifiedClassName;
/**
* Controllers work on scene nodes to modify and update them. They offer the best
* way to add any kind of behavior on one or multiple scene nodes. They can be used
* to create animations, add physics, artificial intelligence...
*
* @author Jean-Marc Le Roux
*
*/
public class AbstractController
{
private var _targetType : Class = null;
private var _targets : Vector.<ISceneNode> = new <ISceneNode>[];
private var _targetAdded : Signal = new Signal('AbstractController.targetAdded');
private var _targetRemoved : Signal = new Signal('AbstractController.targetRemoved');
/**
* The number of scene nodes targeted by this very controller.
* @return
*
*/
public function get numTargets() : uint
{
return _targets.length;
}
/**
* The signal executed when a target is added to the controller.
* @return
*
*/
public function get targetAdded() : Signal
{
return _targetAdded;
}
/**
* The signal executed when a target is removed from the controller.
* @return
*
*/
public function get targetRemoved() : Signal
{
return _targetRemoved;
}
public function AbstractController(targetType : Class = null)
{
_targetType = targetType || ISceneNode;
}
/**
* Add a target to the controller.
* @param target
*
*/
minko_scene function addTarget(target : ISceneNode) : void
{
if (_targetType && !(target is _targetType))
{
throw new Error(
'Controller \'' + getQualifiedClassName(this)
+ ' cannot target objects from class \''
+ getQualifiedClassName(target) + '\'.'
);
}
_targets.push(target);
_targetAdded.execute(this, target);
}
/**
* Remove a target from the controller.
* @param target
*
*/
minko_scene function removeTarget(target : ISceneNode) : void
{
var index : int = _targets.indexOf(target);
var numTargets : int = _targets.length - 1;
if (index < 0)
throw new Error();
_targets[index] = _targets[numTargets];
_targets.length = numTargets;
_targetRemoved.execute(this, target);
}
/**
* Get the target at the specified index.
* @param index
* @return
*
*/
public function getTarget(index : uint) : ISceneNode
{
return _targets[index];
}
public function clone() : AbstractController
{
throw new Error('The method AbstractController.clone() must be overriden.');
}
}
}
|
package aerys.minko.scene.controller
{
import aerys.minko.ns.minko_scene;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.type.Signal;
import flash.utils.getQualifiedClassName;
use namespace minko_scene;
/**
* Controllers work on scene nodes to modify and update them. They offer the best
* way to add any kind of behavior on one or multiple scene nodes. They can be used
* to create animations, add physics, artificial intelligence...
*
* @author Jean-Marc Le Roux
*
*/
public class AbstractController
{
private var _targetType : Class = null;
private var _targets : Vector.<ISceneNode> = new <ISceneNode>[];
private var _targetAdded : Signal = new Signal('AbstractController.targetAdded');
private var _targetRemoved : Signal = new Signal('AbstractController.targetRemoved');
/**
* The number of scene nodes targeted by this very controller.
* @return
*
*/
public function get numTargets() : uint
{
return _targets.length;
}
/**
* The signal executed when a target is added to the controller.
* @return
*
*/
public function get targetAdded() : Signal
{
return _targetAdded;
}
/**
* The signal executed when a target is removed from the controller.
* @return
*
*/
public function get targetRemoved() : Signal
{
return _targetRemoved;
}
public function AbstractController(targetType : Class = null)
{
_targetType = targetType || ISceneNode;
}
/**
* Add a target to the controller.
* @param target
*
*/
minko_scene function addTarget(target : ISceneNode) : void
{
if (_targetType && !(target is _targetType))
{
throw new Error(
'Controller \'' + getQualifiedClassName(this)
+ ' cannot target objects from class \''
+ getQualifiedClassName(target) + '\'.'
);
}
_targets.push(target);
_targetAdded.execute(this, target);
}
/**
* Remove a target from the controller.
* @param target
*
*/
minko_scene function removeTarget(target : ISceneNode) : void
{
var index : int = _targets.indexOf(target);
var numTargets : int = _targets.length - 1;
if (index < 0)
throw new Error();
_targets[index] = _targets[numTargets];
_targets.length = numTargets;
_targetRemoved.execute(this, target);
}
/**
* Get the target at the specified index.
* @param index
* @return
*
*/
public function getTarget(index : uint) : ISceneNode
{
return _targets[index];
}
public function clone() : AbstractController
{
throw new Error('The method AbstractController.clone() must be overriden.');
}
}
}
|
add missing use namespace minko_scene to allow the override of AbstractController.minko_scene::addTarget() and AbstractController.minko_scene::removeTarget()
|
add missing use namespace minko_scene to allow the override of AbstractController.minko_scene::addTarget() and AbstractController.minko_scene::removeTarget()
|
ActionScript
|
mit
|
aerys/minko-as3
|
77c2158f7539c373afad8dba80f922f2487ba878
|
WEB-INF/lps/lfc/kernel/swf9/LFCApplication.as
|
WEB-INF/lps/lfc/kernel/swf9/LFCApplication.as
|
/**
* LFCApplication.as
*
* @copyright Copyright 2007, 2008 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic swf9
* @author Henry Minsky <[email protected]>
*/
public class LFCApplication extends Sprite {
// This serves as the superclass of DefaultApplication, currently that is where
// the compiler puts top level code to run.
#passthrough (toplevel:true) {
import flash.display.*;
import flash.events.*;
import flash.utils.*;
import flash.text.*;
import flash.system.*;
import flash.net.*;
import flash.ui.*;
import flash.text.Font;
}#
public function LFCApplication () {
// Start up idle service timer. LzIdle is a global
LzIdle = new LzIdleClass ();
LzIdleKernel.addCallback( this, '__idleupdate' );
var idleTimerPeriod = 14; // msecs
//var idleTimerPeriod = 31; // msecs
trace('idle timer period = ', idleTimerPeriod , 'msecs');
LzIdleKernel.startTimer( idleTimerPeriod );
stage.addEventListener(KeyboardEvent.KEY_DOWN,reportKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP,reportKeyUp);
// necessary for consistent behavior - in netscape browsers HTML is ignored
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
//Stage.align = ('canvassalign' in global && global.canvassalign != null) ? global.canvassalign : "LT";
//Stage.scaleMode = ('canvasscale' in global && global.canvasscale != null) ? global.canvasscale : "noScale";
stage.addEventListener(Event.RESIZE, resizeHandler);
/* TODO [hqm 2008-01] Do we want to do anything with other
* events, like click, or mousewheel ?
stage.addEventListener(MouseEvent.CLICK, reportClick);
stage.addEventListener(MouseEvent.MOUSE_WHEEL, reportWheel);
*/
LzKeyboardKernel.setCallback(LzKeys, '__keyEvent');
////////////////////////////////////////////////////////////////
// cheapo debug console
lzconsole = this;
var tfield:TextField = new TextField();
tfield.background = true;
tfield.backgroundColor = 0xcccccc;
tfield.x = 0;
tfield.y = 400;
tfield.wordWrap = true;
tfield.multiline = true;
tfield.width = 800;
tfield.height = 160;
tfield.border = true;
consoletext = tfield;
var ci:TextField = new TextField();
consoleinputtext = ci;
ci.background = true;
ci.backgroundColor = 0xffcccc;
ci.x = 0;
ci.y = 560;
ci.wordWrap = false;
ci.multiline = false;
ci.width = 800;
ci.height = 20;
ci.border = true;
ci.type = TextFieldType.INPUT;
ci.addEventListener(KeyboardEvent.KEY_DOWN, consoleInputHandler);
/* var allFonts:Array = Font.enumerateFonts(true);
allFonts.sortOn("fontName", Array.CASEINSENSITIVE);
var embeddedFonts:Array = Font.enumerateFonts(false);
embeddedFonts.sortOn("fontName", Array.CASEINSENSITIVE);
*/
var newFormat:TextFormat = new TextFormat();
newFormat.size = 11;
newFormat.font = "Verdana";
ci.defaultTextFormat = newFormat;
consoletext.defaultTextFormat = newFormat;
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
// Testing runtime code loading
////////////////////////////////////////////////////////////////
}
var debugloader:Loader;
// Debugger loader completion handler
function debugEvalListener (e:Event):void {
debugloader.unload();
//DebugExec(e.target.content).doit();
}
function consoleInputHandler (event:KeyboardEvent ){
if (event.charCode == Keyboard.ENTER) {
var expr = consoleinputtext.text;
write(expr);
consoleinputtext.text = "";
debugloader = new Loader();
debugloader.contentLoaderInfo.addEventListener(Event.INIT, debugEvalListener);
// Send EVAL request to LPS server
// It doesn't matter what path/filename we use, as long as it has ".lzx" suffix, so it is
// handled by the LPS. The lzt=eval causes the request to be served by the EVAL Responder.
var url = "hello.lzx?lzr=swf9&lz_load=false&lzt=eval&lz_script=" + encodeURIComponent(expr)+"&lzbc=" +(new Date()).getTime();
debugloader.load(new URLRequest(url),
new LoaderContext(false,
new ApplicationDomain(ApplicationDomain.currentDomain)));
}
}
////////////////////////////////////////////////////////////////
// A crude debugger output window for now
public var consoletext:TextField;
public var consoleinputtext:TextField;
public function write (...args) {
consoletext.appendText( "\n" + args.join(" "));
consoletext.scrollV = consoletext.maxScrollV;
}
////////////////////////////////////////////////////////////////
function reportWheel(event:MouseEvent):void
{
trace(event.currentTarget.toString() +
" dispatches MouseWheelEvent. delta = " + event.delta);
// LzKeys.__mousewheelEvent(event.delta);
}
function reportClick(event:MouseEvent):void
{
/*
trace(event.currentTarget.toString() +
" dispatches MouseEvent. Local coords [" +
event.localX + "," + event.localY + "] Stage coords [" +
event.stageX + "," + event.stageY + "]");
*/
}
function resizeHandler(event:Event):void {
// event.target is a pointer to the stage
LzScreenKernel.handleResizeEvent(event.target);
}
function reportKeyUp(event:KeyboardEvent):void {
/*
trace("Key Released: " + String.fromCharCode(event.charCode) +
" (key code: " + event.keyCode + " character code: " +
event.charCode + ")");
*/
LzKeyboardKernel.__keyboardEvent(event.charCode, 'onkeyup');
}
function reportKeyDown(event:KeyboardEvent):void {
/*
trace("Key Pressed: " + String.fromCharCode(event.charCode) +
" (key code: " + event.keyCode + " character code: "
+ event.charCode + ")");
*/
LzKeyboardKernel.__keyboardEvent(event.charCode, 'onkeydown');
}
/**
* __idleupdate is a callback function from LzIdleKernel.
* Treat it as a static function (ie. Don't reference 'this')
* @access private
*/
public function __idleupdate (etime) {
var oi = LzIdle.onidle;
if (oi.ready) {
oi.sendEvent( etime );
}
}
}
// Resource library
// contains {ptype, class, frames, width, height}
// ptype is one of "ar" (app relative) or "sr" (system relative)
var LzResourceLibrary = {};
var lzconsole;
|
/**
* LFCApplication.as
*
* @copyright Copyright 2007, 2008 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic swf9
* @author Henry Minsky <[email protected]>
*/
public class LFCApplication extends Sprite {
// This serves as the superclass of DefaultApplication, currently that is where
// the compiler puts top level code to run.
#passthrough (toplevel:true) {
import flash.display.*;
import flash.events.*;
import flash.utils.*;
import flash.text.*;
import flash.system.*;
import flash.net.*;
import flash.ui.*;
import flash.text.Font;
}#
public function LFCApplication () {
// Start up idle service timer. LzIdle is a global
LzIdle = new LzIdleClass ();
LzIdleKernel.addCallback( this, '__idleupdate' );
var idleTimerPeriod = 14; // msecs
//var idleTimerPeriod = 31; // msecs
trace('idle timer period = ', idleTimerPeriod , 'msecs');
LzIdleKernel.startTimer( idleTimerPeriod );
stage.addEventListener(KeyboardEvent.KEY_DOWN,reportKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP,reportKeyUp);
// necessary for consistent behavior - in netscape browsers HTML is ignored
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
//Stage.align = ('canvassalign' in global && global.canvassalign != null) ? global.canvassalign : "LT";
//Stage.scaleMode = ('canvasscale' in global && global.canvasscale != null) ? global.canvasscale : "noScale";
stage.addEventListener(Event.RESIZE, resizeHandler);
/* TODO [hqm 2008-01] Do we want to do anything with other
* events, like click, or mousewheel ?
stage.addEventListener(MouseEvent.CLICK, reportClick);
stage.addEventListener(MouseEvent.MOUSE_WHEEL, reportWheel);
*/
LzKeyboardKernel.setCallback(LzKeys, '__keyEvent');
////////////////////////////////////////////////////////////////
// cheapo debug console
lzconsole = this;
var tfield:TextField = new TextField();
tfield.background = true;
tfield.backgroundColor = 0xcccccc;
tfield.x = 0;
tfield.y = 400;
tfield.wordWrap = true;
tfield.multiline = true;
tfield.width = 800;
tfield.height = 160;
tfield.border = true;
consoletext = tfield;
var ci:TextField = new TextField();
consoleinputtext = ci;
ci.background = true;
ci.backgroundColor = 0xffcccc;
ci.x = 0;
ci.y = 560;
ci.wordWrap = false;
ci.multiline = false;
ci.width = 800;
ci.height = 20;
ci.border = true;
ci.type = TextFieldType.INPUT;
ci.addEventListener(KeyboardEvent.KEY_DOWN, consoleInputHandler);
/* var allFonts:Array = Font.enumerateFonts(true);
allFonts.sortOn("fontName", Array.CASEINSENSITIVE);
var embeddedFonts:Array = Font.enumerateFonts(false);
embeddedFonts.sortOn("fontName", Array.CASEINSENSITIVE);
*/
var newFormat:TextFormat = new TextFormat();
newFormat.size = 11;
newFormat.font = "Verdana";
ci.defaultTextFormat = newFormat;
consoletext.defaultTextFormat = newFormat;
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
// Testing runtime code loading
////////////////////////////////////////////////////////////////
}
var debugloader:Loader;
// Debugger loader completion handler
function debugEvalListener (e:Event):void {
debugloader.unload();
//DebugExec(e.target.content).doit();
}
function consoleInputHandler (event:KeyboardEvent ){
if (event.charCode == Keyboard.ENTER) {
var expr = consoleinputtext.text;
write(expr);
consoleinputtext.text = "";
debugloader = new Loader();
debugloader.contentLoaderInfo.addEventListener(Event.INIT, debugEvalListener);
// Send EVAL request to LPS server
// It doesn't matter what path/filename we use, as long as it has ".lzx" suffix, so it is
// handled by the LPS. The lzt=eval causes the request to be served by the EVAL Responder.
var url = "hello.lzx?lzr=swf9&lz_load=false&lzt=eval&lz_script=" + encodeURIComponent(expr)+"&lzbc=" +(new Date()).getTime();
debugloader.load(new URLRequest(url),
new LoaderContext(false,
new ApplicationDomain(ApplicationDomain.currentDomain)));
}
}
////////////////////////////////////////////////////////////////
// A crude debugger output window for now
public var consoletext:TextField;
public var consoleinputtext:TextField;
public function write (...args) {
consoletext.appendText( "\n" + args.join(" "));
consoletext.scrollV = consoletext.maxScrollV;
}
////////////////////////////////////////////////////////////////
function reportWheel(event:MouseEvent):void
{
trace(event.currentTarget.toString() +
" dispatches MouseWheelEvent. delta = " + event.delta);
// LzKeys.__mousewheelEvent(event.delta);
}
function reportClick(event:MouseEvent):void
{
/*
trace(event.currentTarget.toString() +
" dispatches MouseEvent. Local coords [" +
event.localX + "," + event.localY + "] Stage coords [" +
event.stageX + "," + event.stageY + "]");
*/
}
function resizeHandler(event:Event):void {
// event.target is a pointer to the stage
//LzScreenKernel.handleResizeEvent(event.target);
}
function reportKeyUp(event:KeyboardEvent):void {
/*
trace("Key Released: " + String.fromCharCode(event.charCode) +
" (key code: " + event.keyCode + " character code: " +
event.charCode + ")");
*/
LzKeyboardKernel.__keyboardEvent(event.charCode, 'onkeyup');
}
function reportKeyDown(event:KeyboardEvent):void {
/*
trace("Key Pressed: " + String.fromCharCode(event.charCode) +
" (key code: " + event.keyCode + " character code: "
+ event.charCode + ")");
*/
LzKeyboardKernel.__keyboardEvent(event.charCode, 'onkeydown');
}
/**
* __idleupdate is a callback function from LzIdleKernel.
* Treat it as a static function (ie. Don't reference 'this')
* @access private
*/
public function __idleupdate (etime) {
var oi = LzIdle.onidle;
if (oi.ready) {
oi.sendEvent( etime );
}
}
}
// Resource library
// contains {ptype, class, frames, width, height}
// ptype is one of "ar" (app relative) or "sr" (system relative)
var LzResourceLibrary = {};
var lzconsole;
|
revert until LzScreenKernel gets checked in
|
revert until LzScreenKernel gets checked in
git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@8582 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
|
ActionScript
|
epl-1.0
|
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
|
54050c1f4fd0f3052dd076c1537eb4d5808a6504
|
src/aerys/minko/render/shader/compiler/visitor/allocator/VertexAllocator.as
|
src/aerys/minko/render/shader/compiler/visitor/allocator/VertexAllocator.as
|
package aerys.minko.render.shader.compiler.visitor.allocator
{
import aerys.minko.render.shader.compiler.allocator.Allocator;
import aerys.minko.render.shader.node.INode;
import aerys.minko.render.shader.node.leaf.AbstractConstant;
import aerys.minko.render.shader.node.leaf.Attribute;
import aerys.minko.render.shader.node.operation.AbstractOperation;
import aerys.minko.render.shader.node.operation.manipulation.Combine;
import aerys.minko.render.shader.node.operation.manipulation.Interpolate;
import aerys.minko.render.shader.node.operation.manipulation.Extract;
public class VertexAllocator extends AbstractAllocator
{
protected var _attrAlloc : Allocator;
protected var _visited : Vector.<INode>;
protected var _stack : Vector.<INode>;
public function VertexAllocator(attrAlloc : Allocator,
tmpAlloc : Allocator,
constAlloc : Allocator)
{
_operationId = 0;
_attrAlloc = attrAlloc;
_tmpAlloc = tmpAlloc;
_constAlloc = constAlloc;
_visited = new Vector.<INode>();
_stack = new Vector.<INode>();
}
public function processVertexShader(nodes:Vector.<INode>):void
{
for each (var node:INode in nodes)
visit(node);
}
override public function visit(shaderNode : INode):void
{
if (_visited.indexOf(shaderNode) !== -1)
return;
_visited.push(shaderNode);
_stack.push(shaderNode);
shaderNode.accept(this);
++_operationId;
if (shaderNode is Interpolate || shaderNode is Extract)
{
reportOperationArgumentsUsage(AbstractOperation(shaderNode));
}
else if (shaderNode is Combine)
{
var combineNode : Combine = shaderNode as Combine;
reportArgumentUsage(combineNode.arg1, false);
_tmpAlloc.allocate(combineNode, _operationId);
++_operationId;
reportArgumentUsage(combineNode.arg2, false);
}
else if (shaderNode is AbstractOperation)
{
var operationNode : AbstractOperation = AbstractOperation(shaderNode);
reportOperationArgumentsUsage(operationNode);
// on ne traite pas le noeud final.
if (_stack.length > 1)
_tmpAlloc.allocate(operationNode, _operationId);
}
else if (shaderNode is Attribute)
_attrAlloc.allocate(shaderNode);
else if (shaderNode is AbstractConstant)
_constAlloc.allocate(shaderNode);
_stack.pop();
}
override protected function reportArgumentUsage(arg:INode, aligned : Boolean) : void
{
if (arg is Attribute)
_attrAlloc.reportUsage(arg, _operationId, aligned);
else if (arg is AbstractConstant)
_constAlloc.reportUsage(arg, _operationId, aligned);
else if (arg is Extract)
reportArgumentUsage((arg as Extract).arg1, aligned);
else if (arg is AbstractOperation)
_tmpAlloc.reportUsage(arg, _operationId, aligned);
}
}
}
|
package aerys.minko.render.shader.compiler.visitor.allocator
{
import aerys.minko.render.shader.compiler.allocator.Allocator;
import aerys.minko.render.shader.node.INode;
import aerys.minko.render.shader.node.leaf.AbstractConstant;
import aerys.minko.render.shader.node.leaf.Attribute;
import aerys.minko.render.shader.node.operation.AbstractOperation;
import aerys.minko.render.shader.node.operation.manipulation.Combine;
import aerys.minko.render.shader.node.operation.manipulation.Interpolate;
import aerys.minko.render.shader.node.operation.manipulation.Extract;
public class VertexAllocator extends AbstractAllocator
{
protected var _attrAlloc : Allocator;
protected var _visited : Vector.<INode>;
protected var _stack : Vector.<INode>;
public function VertexAllocator(attrAlloc : Allocator,
tmpAlloc : Allocator,
constAlloc : Allocator)
{
_operationId = 0;
_attrAlloc = attrAlloc;
_tmpAlloc = tmpAlloc;
_constAlloc = constAlloc;
_visited = new Vector.<INode>();
_stack = new Vector.<INode>();
}
public function processVertexShader(nodes:Vector.<INode>):void
{
for each (var node:INode in nodes)
visit(node);
}
override public function visit(shaderNode : INode):void
{
if (_visited.indexOf(shaderNode) !== -1)
return;
_visited.push(shaderNode);
_stack.push(shaderNode);
shaderNode.accept(this);
if (shaderNode is Interpolate)
{
++_operationId;
reportOperationArgumentsUsage(AbstractOperation(shaderNode));
}
else if (shaderNode is Extract)
{
reportOperationArgumentsUsage(AbstractOperation(shaderNode));
}
else if (shaderNode is Combine)
{
var combineNode : Combine = shaderNode as Combine;
++_operationId;
reportArgumentUsage(combineNode.arg1, false);
_tmpAlloc.allocate(combineNode, _operationId);
++_operationId;
reportArgumentUsage(combineNode.arg2, false);
}
else if (shaderNode is AbstractOperation)
{
var operationNode : AbstractOperation = AbstractOperation(shaderNode);
++_operationId;
reportOperationArgumentsUsage(operationNode);
// on ne traite pas le noeud final.
if (_stack.length > 1)
_tmpAlloc.allocate(operationNode, _operationId);
}
else if (shaderNode is Attribute)
_attrAlloc.allocate(shaderNode);
else if (shaderNode is AbstractConstant)
_constAlloc.allocate(shaderNode);
_stack.pop();
}
override protected function reportArgumentUsage(arg:INode, aligned : Boolean) : void
{
if (arg is Attribute)
_attrAlloc.reportUsage(arg, _operationId, aligned);
else if (arg is AbstractConstant)
_constAlloc.reportUsage(arg, _operationId, aligned);
else if (arg is Extract)
reportArgumentUsage((arg as Extract).arg1, aligned);
else if (arg is AbstractOperation)
_tmpAlloc.reportUsage(arg, _operationId, aligned);
}
}
}
|
Change numerotation system for operations in VertexAllocator. Allows to display a more pertinent debug information if needed.
|
Change numerotation system for operations in VertexAllocator. Allows to display a more pertinent debug information if needed.
|
ActionScript
|
mit
|
aerys/minko-as3
|
f887589f89104fbe588381fd5928bda7d7a03a25
|
exporter/src/main/as/flump/xfl/XflKeyframe.as
|
exporter/src/main/as/flump/xfl/XflKeyframe.as
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.xfl {
import flash.geom.Matrix;
import flash.geom.Point;
import flump.mold.KeyframeMold;
import com.threerings.util.XmlUtil;
public class XflKeyframe
{
use namespace xflns;
public static function parse (lib :XflLibrary, baseLocation :String, xml :XML,
flipbook :Boolean) :KeyframeMold {
const kf :KeyframeMold = new KeyframeMold();
kf.index = XmlUtil.getIntAttr(xml, "index");
const location :String = baseLocation + ":" + kf.index;
kf.duration = XmlUtil.getNumberAttr(xml, "duration", 1);
kf.label = XmlUtil.getStringAttr(xml, "name", null);
kf.ease = XmlUtil.getNumberAttr(xml, "acceleration", 0) / 100;
if (flipbook) return kf;
var symbolXml :XML;
for each (var frameEl :XML in xml.elements.elements()) {
if (frameEl.name().localName == "DOMSymbolInstance") {
if (symbolXml != null) {
lib.addError(location, ParseError.CRIT, "There can be only one symbol instance at " +
"a time in a keyframe.");
} else symbolXml = frameEl;
} else {
lib.addError(location, ParseError.CRIT, "Non-symbols may not be in movie layers");
}
}
if (symbolXml == null) return kf; // Purely labelled frame
if (XmlUtil.getBooleanAttr(xml, "motionTweenOrientToPath", false)) {
lib.addError(location, ParseError.CRIT, "motion paths are not supported");
}
if (XmlUtil.getBooleanAttr(xml, "hasCustomEase", false)) {
lib.addError(location, ParseError.WARN, "Custom easing is not supported");
}
// Fill this in with the library name for now. XflLibrary.finishLoading will swap in the
// symbol or implicit symbol the library item corresponds to.
kf.ref = XmlUtil.getStringAttr(symbolXml, "libraryItemName");
kf.visible = XmlUtil.getBooleanAttr(symbolXml, "isVisible", true);
var matrix :Matrix = new Matrix();
// Read the matrix transform
if (symbolXml.matrix != null) {
const matrixXml :XML = symbolXml.matrix.Matrix[0];
function m (name :String, def :Number) :Number {
return matrixXml == null ? def : XmlUtil.getNumberAttr(matrixXml, name, def);
}
matrix = new Matrix(m("a", 1), m("b", 0), m("c", 0), m("d", 1), m("tx", 0), m("ty", 0));
// Back out of translation
var rewound :Matrix = matrix.clone();
rewound.tx = rewound.ty = 0;
var p :Point = rewound.transformPoint(new Point(1, 0));
kf.rotation = Math.atan2(p.y, p.x);
// Back out of rotation
rewound.rotate(-kf.rotation);
p = rewound.transformPoint(new Point(1, 1));
kf.scaleX = p.x;
kf.scaleY = p.y;
const skewX :Number = Math.atan(rewound.c);
const skewY :Number = Math.atan(rewound.b);
if (Math.abs(skewX) > 0.0001 || Math.abs(skewY) > 0.0001) {
lib.addError(location, ParseError.WARN, "Skewing is not supported");
}
}
// Read the pivot point
if (symbolXml.transformationPoint != null) {
var pivotXml :XML = symbolXml.transformationPoint.Point[0];
if (pivotXml != null) {
kf.pivotX = XmlUtil.getNumberAttr(pivotXml, "x", 0);
kf.pivotY = XmlUtil.getNumberAttr(pivotXml, "y", 0);
// Translate to the pivot point
const orig :Matrix = matrix.clone();
matrix.identity();
matrix.translate(kf.pivotX, kf.pivotY);
matrix.concat(orig);
}
}
// Now that the matrix and pivot point have been read, apply translation
kf.x = matrix.tx;
kf.y = matrix.ty;
// Read the alpha
if (symbolXml.color != null) {
const colorXml :XML = symbolXml.color.Color[0];
if (colorXml != null) {
kf.alpha = XmlUtil.getNumberAttr(colorXml, "alphaMultiplier", 1);
}
}
return kf;
}
}
}
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.xfl {
import flash.geom.Matrix;
import flash.geom.Point;
import flump.mold.KeyframeMold;
import com.threerings.util.XmlUtil;
public class XflKeyframe
{
use namespace xflns;
public static function parse (lib :XflLibrary, baseLocation :String, xml :XML,
flipbook :Boolean) :KeyframeMold {
const kf :KeyframeMold = new KeyframeMold();
kf.index = XmlUtil.getIntAttr(xml, "index");
const location :String = baseLocation + ":" + kf.index;
kf.duration = XmlUtil.getNumberAttr(xml, "duration", 1);
kf.label = XmlUtil.getStringAttr(xml, "name", null);
kf.ease = XmlUtil.getNumberAttr(xml, "acceleration", 0) / 100;
if (flipbook) return kf;
var symbolXml :XML;
for each (var frameEl :XML in xml.elements.elements()) {
if (frameEl.name().localName == "DOMSymbolInstance") {
if (symbolXml != null) {
lib.addError(location, ParseError.CRIT, "There can be only one symbol instance at " +
"a time in a keyframe.");
} else symbolXml = frameEl;
} else {
lib.addError(location, ParseError.CRIT, "Non-symbols may not be in movie layers");
}
}
if (symbolXml == null) return kf; // Purely labelled frame
if (XmlUtil.getBooleanAttr(xml, "motionTweenOrientToPath", false)) {
lib.addError(location, ParseError.WARN, "motion paths are not supported");
}
if (XmlUtil.getBooleanAttr(xml, "hasCustomEase", false)) {
lib.addError(location, ParseError.WARN, "Custom easing is not supported");
}
// Fill this in with the library name for now. XflLibrary.finishLoading will swap in the
// symbol or implicit symbol the library item corresponds to.
kf.ref = XmlUtil.getStringAttr(symbolXml, "libraryItemName");
kf.visible = XmlUtil.getBooleanAttr(symbolXml, "isVisible", true);
var matrix :Matrix = new Matrix();
// Read the matrix transform
if (symbolXml.matrix != null) {
const matrixXml :XML = symbolXml.matrix.Matrix[0];
function m (name :String, def :Number) :Number {
return matrixXml == null ? def : XmlUtil.getNumberAttr(matrixXml, name, def);
}
matrix = new Matrix(m("a", 1), m("b", 0), m("c", 0), m("d", 1), m("tx", 0), m("ty", 0));
// Back out of translation
var rewound :Matrix = matrix.clone();
rewound.tx = rewound.ty = 0;
var p :Point = rewound.transformPoint(new Point(1, 0));
kf.rotation = Math.atan2(p.y, p.x);
// Back out of rotation
rewound.rotate(-kf.rotation);
p = rewound.transformPoint(new Point(1, 1));
kf.scaleX = p.x;
kf.scaleY = p.y;
const skewX :Number = Math.atan(rewound.c);
const skewY :Number = Math.atan(rewound.b);
if (Math.abs(skewX) > 0.0001 || Math.abs(skewY) > 0.0001) {
lib.addError(location, ParseError.WARN, "Skewing is not supported");
}
}
// Read the pivot point
if (symbolXml.transformationPoint != null) {
var pivotXml :XML = symbolXml.transformationPoint.Point[0];
if (pivotXml != null) {
kf.pivotX = XmlUtil.getNumberAttr(pivotXml, "x", 0);
kf.pivotY = XmlUtil.getNumberAttr(pivotXml, "y", 0);
// Translate to the pivot point
const orig :Matrix = matrix.clone();
matrix.identity();
matrix.translate(kf.pivotX, kf.pivotY);
matrix.concat(orig);
}
}
// Now that the matrix and pivot point have been read, apply translation
kf.x = matrix.tx;
kf.y = matrix.ty;
// Read the alpha
if (symbolXml.color != null) {
const colorXml :XML = symbolXml.color.Color[0];
if (colorXml != null) {
kf.alpha = XmlUtil.getNumberAttr(colorXml, "alphaMultiplier", 1);
}
}
return kf;
}
}
}
|
make this a warning
|
make this a warning
|
ActionScript
|
mit
|
tconkling/flump,mathieuanthoine/flump,funkypandagame/flump,mathieuanthoine/flump,funkypandagame/flump,tconkling/flump,mathieuanthoine/flump
|
a3cfd80c0b50d6f6c24fd528da519582196e85df
|
www/demos/welcome.as
|
www/demos/welcome.as
|
; Write some assembly code here.
; Then click 'Assemble and Run' to run it on the P3 simulator.
; For more information check 'About P3JS'.
; Try the Demos -----> -----> -----> -----> -----> -----> -----> ----->
; This is a very short program that fills the memory with ac5fh!
; Click 'Assemble and Run' to test.
ORIG 8000h
MOV R1, M[PC]
MOV M[PC], R1
; How does it work? Why is the value at the address 8000h not ac5fh?
; HINT
; ||
; ||
; \/
; HINT: Notice that ac5fh is the binary code for 'MOV M[PC], R1'.
|
; Write some assembly code here.
; Then click 'Assemble and Run' to run it on the P3 simulator.
; Comments start with ';'.
; For more information check 'About P3JS'.
; ------------- ;
; Try the Demos -----> -----> -----> -----> -----> -----> -----> ----->
; ------------- ;
; This is a simple program that counts to ffffh and shows the result in binary
; on the LEDS.
; Click 'Assemble and Run' then check the tab 'Input/Output'.
LEDS EQU fff8h ; constant with the I/O address to
; control the LEDS
ORIG 0000h ; indication that we want to put the
; code at position 0000h
; the CPU starts running code at the address 0000h
; the first instruction is to jump to the Main code
JMP Main ; jump to the Main code
; this next code is a simple delay routine
; uses R7 to count to 0000h then returns, this is not the ideal
; way to make delays, you should use the timer and interrupts
Delay: MOV R7, f000h ; initialize R7 with f000h
DelayInc: INC R7 ; increment R7
BR.NZ DelayInc ; if R7 is not 0000h, jump to DelayInc
RET ; else return from the routine
; the Main code starts here
Main: MOV R1, R0 ; initialize R1 with 0 (R0 is always 0)
Loop: INC R1 ; increment R1
MOV M[LEDS], R1 ; write the value of R1 to the LEDS
CALL Delay ; call the Delay routine
BR Loop ; branch jump back to Loop
|
Improve the 'welcome.as' demo to include a proper simple program
|
Improve the 'welcome.as' demo to include a proper simple program
|
ActionScript
|
mit
|
goncalomb/p3js,goncalomb/p3js
|
c61e3cf02380ee57256f176cf0064f8ab9b83ded
|
lib/src/com/amanitadesign/steam/FRESteamWorks.as
|
lib/src/com/amanitadesign/steam/FRESteamWorks.as
|
/*
* FRESteamWorks.as
* 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 com.amanitadesign.steam
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.utils.ByteArray;
import flash.utils.clearInterval;
import flash.utils.setInterval;
public class FRESteamWorks extends EventDispatcher
{
[Event(name="steam_response", type="com.amanitadesign.steam.SteamEvent")]
private var _ExtensionContext:ExtensionContext;
private var _tm:int;
public var isReady:Boolean = false;
public function FRESteamWorks(target:IEventDispatcher=null)
{
_ExtensionContext = ExtensionContext.createExtensionContext("com.amanitadesign.steam.FRESteamWorks", null);
_ExtensionContext.addEventListener(StatusEvent.STATUS, handleStatusEvent);
super(target);
}
private function handleStatusEvent(event:StatusEvent):void{
//_ExtensionContext.removeEventListener(StatusEvent.STATUS, handleStatusEvent);
var req_type:int = new int(event.code);
var response:int = new int(event.level);
var sEvent:SteamEvent = new SteamEvent(SteamEvent.STEAM_RESPONSE, req_type, response);
trace("handleStatusEvent: "+req_type+" "+response);
dispatchEvent(sEvent);
}
public function dispose():void
{
clearInterval(_tm);
_ExtensionContext.removeEventListener(StatusEvent.STATUS, handleStatusEvent);
_ExtensionContext.dispose();
}
public function init():Boolean
{
isReady = _ExtensionContext.call("AIRSteam_Init") as Boolean;
if(isReady) _tm = setInterval(runCallbacks, 100);
return isReady;
}
public function requestStats():Boolean
{
return _ExtensionContext.call("AIRSteam_RequestStats") as Boolean;
}
public function runCallbacks():Boolean
{
return _ExtensionContext.call("AIRSteam_RunCallbacks") as Boolean;
}
public function getUserID():String
{
return _ExtensionContext.call("AIRSteam_GetUserID") as String;
}
public function getPersonaName():String
{
return _ExtensionContext.call("AIRSteam_GetPersonaName") as String;
}
public function useCrashHandler():Boolean
{
return _ExtensionContext.call("AIRSteam_UseCrashHandler") as Boolean;
}
public function setAchievement(id:String):Boolean
{
return _ExtensionContext.call("AIRSteam_SetAchievement", id) as Boolean;
}
public function clearAchievement(id:String):Boolean
{
return _ExtensionContext.call("AIRSteam_ClearAchievement", id) as Boolean;
}
public function isAchievement(id:String):Boolean
{
return _ExtensionContext.call("AIRSteam_IsAchievement", id) as Boolean;
}
public function getStatInt(id:String):int
{
return _ExtensionContext.call("AIRSteam_GetStatInt", id) as int;
}
public function getStatFloat(id:String):Number
{
return _ExtensionContext.call("AIRSteam_GetStatFloat", id) as Number;
}
public function setStatInt(id:String, value:int):Boolean
{
return _ExtensionContext.call("AIRSteam_SetStatInt", id, value) as Boolean;
}
public function setStatFloat(id:String, value:Number):Boolean
{
return _ExtensionContext.call("AIRSteam_SetStatFloat", id, value) as Boolean;
}
public function storeStats():Boolean
{
return _ExtensionContext.call("AIRSteam_StoreStats") as Boolean;
}
public function resetAllStats(bAchievementsToo:Boolean):Boolean
{
return _ExtensionContext.call("AIRSteam_ResetAllStats", bAchievementsToo) as Boolean;
}
public function getFileCount():int
{
return _ExtensionContext.call("AIRSteam_GetFileCount") as int;
}
public function getFileSize(fileName:String):int
{
return _ExtensionContext.call("AIRSteam_GetFileSize", fileName) as int;
}
public function fileExists(fileName:String):Boolean
{
return _ExtensionContext.call("AIRSteam_FileExists", fileName) as Boolean;
}
public function fileWrite(fileName:String, data:ByteArray):Boolean
{
return _ExtensionContext.call("AIRSteam_FileWrite", fileName, data) as Boolean;
}
public function fileRead(fileName:String, data:ByteArray):Boolean
{
return _ExtensionContext.call("AIRSteam_FileRead", fileName, data) as Boolean;
}
public function fileDelete(fileName:String):Boolean
{
return _ExtensionContext.call("AIRSteam_FileDelete", fileName) as Boolean;
}
public function isCloudEnabledForApp():Boolean
{
return _ExtensionContext.call("AIRSteam_IsCloudEnabledForApp") as Boolean;
}
public function setCloudEnabledForApp(enabled:Boolean):Boolean
{
return _ExtensionContext.call("AIRSteam_SetCloudEnabledForApp", enabled) as Boolean;
}
}
}
|
/*
* FRESteamWorks.as
* 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 com.amanitadesign.steam
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.utils.ByteArray;
import flash.utils.clearInterval;
import flash.utils.setInterval;
public class FRESteamWorks extends EventDispatcher
{
[Event(name="steam_response", type="com.amanitadesign.steam.SteamEvent")]
private var _ExtensionContext:ExtensionContext;
private var _tm:int;
public var isReady:Boolean = false;
public function FRESteamWorks(target:IEventDispatcher=null)
{
_ExtensionContext = ExtensionContext.createExtensionContext("com.amanitadesign.steam.FRESteamWorks", null);
_ExtensionContext.addEventListener(StatusEvent.STATUS, handleStatusEvent);
super(target);
}
private function handleStatusEvent(event:StatusEvent):void{
//_ExtensionContext.removeEventListener(StatusEvent.STATUS, handleStatusEvent);
var req_type:int = new int(event.code);
var response:int = new int(event.level);
var sEvent:SteamEvent = new SteamEvent(SteamEvent.STEAM_RESPONSE, req_type, response);
trace("handleStatusEvent: "+req_type+" "+response);
dispatchEvent(sEvent);
}
public function dispose():void
{
clearInterval(_tm);
_ExtensionContext.removeEventListener(StatusEvent.STATUS, handleStatusEvent);
_ExtensionContext.dispose();
}
public function init():Boolean
{
isReady = _ExtensionContext.call("AIRSteam_Init") as Boolean;
if(isReady) _tm = setInterval(runCallbacks, 100);
return isReady;
}
public function requestStats():Boolean
{
return _ExtensionContext.call("AIRSteam_RequestStats") as Boolean;
}
public function runCallbacks():Boolean
{
return _ExtensionContext.call("AIRSteam_RunCallbacks") as Boolean;
}
public function getUserID():String
{
return _ExtensionContext.call("AIRSteam_GetUserID") as String;
}
public function getPersonaName():String
{
return _ExtensionContext.call("AIRSteam_GetPersonaName") as String;
}
public function useCrashHandler(version:String, date:String, time:String):Boolean
{
return _ExtensionContext.call("AIRSteam_UseCrashHandler", version, date, time) as Boolean;
}
public function setAchievement(id:String):Boolean
{
return _ExtensionContext.call("AIRSteam_SetAchievement", id) as Boolean;
}
public function clearAchievement(id:String):Boolean
{
return _ExtensionContext.call("AIRSteam_ClearAchievement", id) as Boolean;
}
public function isAchievement(id:String):Boolean
{
return _ExtensionContext.call("AIRSteam_IsAchievement", id) as Boolean;
}
public function getStatInt(id:String):int
{
return _ExtensionContext.call("AIRSteam_GetStatInt", id) as int;
}
public function getStatFloat(id:String):Number
{
return _ExtensionContext.call("AIRSteam_GetStatFloat", id) as Number;
}
public function setStatInt(id:String, value:int):Boolean
{
return _ExtensionContext.call("AIRSteam_SetStatInt", id, value) as Boolean;
}
public function setStatFloat(id:String, value:Number):Boolean
{
return _ExtensionContext.call("AIRSteam_SetStatFloat", id, value) as Boolean;
}
public function storeStats():Boolean
{
return _ExtensionContext.call("AIRSteam_StoreStats") as Boolean;
}
public function resetAllStats(bAchievementsToo:Boolean):Boolean
{
return _ExtensionContext.call("AIRSteam_ResetAllStats", bAchievementsToo) as Boolean;
}
public function getFileCount():int
{
return _ExtensionContext.call("AIRSteam_GetFileCount") as int;
}
public function getFileSize(fileName:String):int
{
return _ExtensionContext.call("AIRSteam_GetFileSize", fileName) as int;
}
public function fileExists(fileName:String):Boolean
{
return _ExtensionContext.call("AIRSteam_FileExists", fileName) as Boolean;
}
public function fileWrite(fileName:String, data:ByteArray):Boolean
{
return _ExtensionContext.call("AIRSteam_FileWrite", fileName, data) as Boolean;
}
public function fileRead(fileName:String, data:ByteArray):Boolean
{
return _ExtensionContext.call("AIRSteam_FileRead", fileName, data) as Boolean;
}
public function fileDelete(fileName:String):Boolean
{
return _ExtensionContext.call("AIRSteam_FileDelete", fileName) as Boolean;
}
public function isCloudEnabledForApp():Boolean
{
return _ExtensionContext.call("AIRSteam_IsCloudEnabledForApp") as Boolean;
}
public function setCloudEnabledForApp(enabled:Boolean):Boolean
{
return _ExtensionContext.call("AIRSteam_SetCloudEnabledForApp", enabled) as Boolean;
}
}
}
|
Add missing arguments for useCrashHandler
|
Add missing arguments for useCrashHandler
|
ActionScript
|
bsd-2-clause
|
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
|
ca4f8844f2f93a6b80d406cfb7e3440461f6287b
|
frameworks/as/src/org/apache/flex/html/staticControls/beads/controllers/DropDownListController.as
|
frameworks/as/src/org/apache/flex/html/staticControls/beads/controllers/DropDownListController.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.staticControls.beads.controllers
{
import flash.display.DisplayObject;
import flash.events.MouseEvent;
import org.apache.flex.core.IBead;
import org.apache.flex.core.ISelectionModel;
import org.apache.flex.core.IStrand;
import org.apache.flex.html.staticControls.beads.IDropDownListBead;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
public class DropDownListController implements IBead
{
public function DropDownListController()
{
}
private var _strand:IStrand;
public function set strand(value:IStrand):void
{
_strand = value;
IEventDispatcher(value).addEventListener(MouseEvent.CLICK, clickHandler);
}
private function clickHandler(event:Event):void
{
var viewBead:IDropDownListBead = _strand.getBeadByType(IDropDownListBead) as IDropDownListBead;
viewBead.popUpVisible = true;
var selectionModel:ISelectionModel = _strand.getBeadByType(ISelectionModel) as ISelectionModel;
var popUpModel:ISelectionModel = viewBead.popUp.getBeadByType(ISelectionModel) as ISelectionModel;
popUpModel.dataProvider = selectionModel.dataProvider;
popUpModel.selectedIndex = selectionModel.selectedIndex;
DisplayObject(viewBead.popUp).width = DisplayObject(_strand).width;
DisplayObject(viewBead.popUp).height = 200;
DisplayObject(viewBead.popUp).x = DisplayObject(_strand).x;
DisplayObject(viewBead.popUp).y = DisplayObject(_strand).y;
IEventDispatcher(viewBead.popUp).addEventListener("change", changeHandler);
}
private function changeHandler(event:Event):void
{
var viewBead:IDropDownListBead = _strand.getBeadByType(IDropDownListBead) as IDropDownListBead;
viewBead.popUpVisible = false;
var selectionModel:ISelectionModel = _strand.getBeadByType(ISelectionModel) as ISelectionModel;
var popUpModel:ISelectionModel = viewBead.popUp.getBeadByType(ISelectionModel) as ISelectionModel;
selectionModel.selectedIndex = popUpModel.selectedIndex;
IEventDispatcher(_strand).dispatchEvent(new Event("change"));
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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.staticControls.beads.controllers
{
import flash.display.DisplayObject;
import flash.events.MouseEvent;
import org.apache.flex.core.IBead;
import org.apache.flex.core.ISelectionModel;
import org.apache.flex.core.IStrand;
import org.apache.flex.html.staticControls.beads.IDropDownListBead;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
public class DropDownListController implements IBead
{
public function DropDownListController()
{
}
private var _strand:IStrand;
public function set strand(value:IStrand):void
{
_strand = value;
IEventDispatcher(value).addEventListener(MouseEvent.CLICK, clickHandler);
}
private function clickHandler(event:MouseEvent):void
{
var viewBead:IDropDownListBead = _strand.getBeadByType(IDropDownListBead) as IDropDownListBead;
viewBead.popUpVisible = true;
var selectionModel:ISelectionModel = _strand.getBeadByType(ISelectionModel) as ISelectionModel;
var popUpModel:ISelectionModel = viewBead.popUp.getBeadByType(ISelectionModel) as ISelectionModel;
popUpModel.dataProvider = selectionModel.dataProvider;
popUpModel.selectedIndex = selectionModel.selectedIndex;
DisplayObject(viewBead.popUp).width = DisplayObject(_strand).width;
DisplayObject(viewBead.popUp).height = 200;
DisplayObject(viewBead.popUp).x = DisplayObject(_strand).x;
DisplayObject(viewBead.popUp).y = DisplayObject(_strand).y;
IEventDispatcher(viewBead.popUp).addEventListener("change", changeHandler);
}
private function changeHandler(event:Event):void
{
var viewBead:IDropDownListBead = _strand.getBeadByType(IDropDownListBead) as IDropDownListBead;
viewBead.popUpVisible = false;
var selectionModel:ISelectionModel = _strand.getBeadByType(ISelectionModel) as ISelectionModel;
var popUpModel:ISelectionModel = viewBead.popUp.getBeadByType(ISelectionModel) as ISelectionModel;
selectionModel.selectedIndex = popUpModel.selectedIndex;
IEventDispatcher(_strand).dispatchEvent(new Event("change"));
}
}
}
|
fix type error
|
fix type error
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
f8ad9e1823b74a0766c533ebe61347941dc61444
|
swfcat.as
|
swfcat.as
|
package
{
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.text.TextField;
import flash.net.Socket;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.utils.ByteArray;
import flash.utils.setTimeout;
public class swfcat extends Sprite
{
/* David's bridge (nickname eRYaZuvY02FpExln) that also serves a
crossdomain policy. */
private const DEFAULT_TOR_ADDR:Object = {
// host: "173.255.221.44", 3VXRyxz67OeRoqHn
host: "69.164.193.231",
port: 9001
};
private const DEFAULT_FACILITATOR_ADDR:Object = {
host: "173.255.221.44",
port: 9002
};
// Milliseconds.
private const FACILITATOR_POLL_INTERVAL:int = 10000;
// Socket to facilitator.
private var s_f:Socket;
private var output_text:TextField;
private var fac_addr:Object;
[Embed(source="badge.png")]
private var BadgeImage:Class;
public function puts(s:String):void
{
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
public function swfcat()
{
// Absolute positioning.
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
output_text = new TextField();
output_text.width = stage.stageWidth;
output_text.height = stage.stageHeight;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44cc44;
puts("Starting.");
// Wait until the query string parameters are loaded.
this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
}
private function loaderinfo_complete(e:Event):void
{
var fac_spec:String;
puts("Parameters loaded.");
if (this.loaderInfo.parameters["debug"])
addChild(output_text);
else
addChild(new BadgeImage());
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
{
s_f = new Socket();
s_f.addEventListener(Event.CONNECT, fac_connected);
s_f.addEventListener(Event.CLOSE, function (e:Event):void {
puts("Facilitator: closed connection.");
setTimeout(main, FACILITATOR_POLL_INTERVAL);
});
s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
});
s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
});
puts("Facilitator: connecting to " + fac_addr.host + ":" + fac_addr.port + ".");
s_f.connect(fac_addr.host, fac_addr.port);
}
private function fac_connected(e:Event):void
{
puts("Facilitator: connected.");
s_f.addEventListener(ProgressEvent.SOCKET_DATA, fac_data);
s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n");
}
private function fac_data(e:ProgressEvent):void
{
var client_spec:String;
var client_addr:Object;
var proxy_pair:Object;
client_spec = s_f.readMultiByte(e.bytesLoaded, "utf-8");
puts("Facilitator: got \"" + client_spec + "\".");
client_addr = parse_addr_spec(client_spec);
if (!client_addr) {
puts("Error: Client spec must be in the form \"host:port\".");
return;
}
if (client_addr.host == "0.0.0.0" && client_addr.port == 0) {
puts("Error: Facilitator has no clients.");
return;
}
proxy_pair = new ProxyPair(this, client_addr, DEFAULT_TOR_ADDR);
proxy_pair.connect();
}
/* Parse an address in the form "host:port". Returns an Object with
keys "host" (String) and "port" (int). Returns null on error. */
private static function parse_addr_spec(spec:String):Object
{
var parts:Array;
var addr:Object;
parts = spec.split(":", 2);
if (parts.length != 2 || !parseInt(parts[1]))
return null;
addr = {}
addr.host = parts[0];
addr.port = parseInt(parts[1]);
return addr;
}
}
}
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
/* An instance of a client-relay connection. */
class ProxyPair
{
// Address ({host, port}) of client.
private var addr_c:Object;
// Address ({host, port}) of relay.
private var addr_r:Object;
// Socket to client.
private var s_c:Socket;
// Socket to relay.
private var s_r:Socket;
// Parent swfcat, for UI updates.
private var ui:swfcat;
private function log(msg:String):void
{
ui.puts(id() + ": " + msg)
}
// String describing this pair for output.
private function id():String
{
return "<" + this.addr_c.host + ":" + this.addr_c.port +
"," + this.addr_r.host + ":" + this.addr_r.port + ">";
}
public function ProxyPair(ui:swfcat, addr_c:Object, addr_r:Object)
{
this.ui = ui;
this.addr_c = addr_c;
this.addr_r = addr_r;
}
public function connect():void
{
s_r = new Socket();
s_r.addEventListener(Event.CONNECT, tor_connected);
s_r.addEventListener(Event.CLOSE, function (e:Event):void {
log("Tor: closed.");
if (s_c.connected)
s_c.close();
});
s_r.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Tor: I/O error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
s_r.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Tor: security error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
log("Tor: connecting to " + addr_r.host + ":" + addr_r.port + ".");
s_r.connect(addr_r.host, addr_r.port);
}
private function tor_connected(e:Event):void
{
log("Tor: connected.");
s_c = new Socket();
s_c.addEventListener(Event.CONNECT, client_connected);
s_c.addEventListener(Event.CLOSE, function (e:Event):void {
log("Client: closed.");
if (s_r.connected)
s_r.close();
});
s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Client: I/O error: " + e.text + ".");
if (s_r.connected)
s_r.close();
});
s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Client: security error: " + e.text + ".");
if (s_r.connected)
s_r.close();
});
log("Client: connecting to " + addr_c.host + ":" + addr_c.port + ".");
s_c.connect(addr_c.host, addr_c.port);
}
private function client_connected(e:Event):void
{
log("Client: connected.");
s_r.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_r.readBytes(bytes, 0, e.bytesLoaded);
log("Tor: read " + bytes.length + ".");
s_c.writeBytes(bytes);
});
s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_c.readBytes(bytes, 0, e.bytesLoaded);
log("Client: read " + bytes.length + ".");
s_r.writeBytes(bytes);
});
}
}
|
package
{
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.text.TextField;
import flash.net.Socket;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.utils.ByteArray;
import flash.utils.setTimeout;
public class swfcat extends Sprite
{
/* David's relay (nickname 3VXRyxz67OeRoqHn) that also serves a
crossdomain policy. */
private const DEFAULT_TOR_ADDR:Object = {
host: "173.255.221.44",
port: 9001
};
private const DEFAULT_FACILITATOR_ADDR:Object = {
host: "173.255.221.44",
port: 9002
};
// Milliseconds.
private const FACILITATOR_POLL_INTERVAL:int = 10000;
// Socket to facilitator.
private var s_f:Socket;
private var output_text:TextField;
private var fac_addr:Object;
[Embed(source="badge.png")]
private var BadgeImage:Class;
public function puts(s:String):void
{
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
public function swfcat()
{
// Absolute positioning.
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
output_text = new TextField();
output_text.width = stage.stageWidth;
output_text.height = stage.stageHeight;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44cc44;
puts("Starting.");
// Wait until the query string parameters are loaded.
this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
}
private function loaderinfo_complete(e:Event):void
{
var fac_spec:String;
puts("Parameters loaded.");
if (this.loaderInfo.parameters["debug"])
addChild(output_text);
else
addChild(new BadgeImage());
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
{
s_f = new Socket();
s_f.addEventListener(Event.CONNECT, fac_connected);
s_f.addEventListener(Event.CLOSE, function (e:Event):void {
puts("Facilitator: closed connection.");
setTimeout(main, FACILITATOR_POLL_INTERVAL);
});
s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
});
s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
});
puts("Facilitator: connecting to " + fac_addr.host + ":" + fac_addr.port + ".");
s_f.connect(fac_addr.host, fac_addr.port);
}
private function fac_connected(e:Event):void
{
puts("Facilitator: connected.");
s_f.addEventListener(ProgressEvent.SOCKET_DATA, fac_data);
s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n");
}
private function fac_data(e:ProgressEvent):void
{
var client_spec:String;
var client_addr:Object;
var proxy_pair:Object;
client_spec = s_f.readMultiByte(e.bytesLoaded, "utf-8");
puts("Facilitator: got \"" + client_spec + "\".");
client_addr = parse_addr_spec(client_spec);
if (!client_addr) {
puts("Error: Client spec must be in the form \"host:port\".");
return;
}
if (client_addr.host == "0.0.0.0" && client_addr.port == 0) {
puts("Error: Facilitator has no clients.");
return;
}
proxy_pair = new ProxyPair(this, client_addr, DEFAULT_TOR_ADDR);
proxy_pair.connect();
}
/* Parse an address in the form "host:port". Returns an Object with
keys "host" (String) and "port" (int). Returns null on error. */
private static function parse_addr_spec(spec:String):Object
{
var parts:Array;
var addr:Object;
parts = spec.split(":", 2);
if (parts.length != 2 || !parseInt(parts[1]))
return null;
addr = {}
addr.host = parts[0];
addr.port = parseInt(parts[1]);
return addr;
}
}
}
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
/* An instance of a client-relay connection. */
class ProxyPair
{
// Address ({host, port}) of client.
private var addr_c:Object;
// Address ({host, port}) of relay.
private var addr_r:Object;
// Socket to client.
private var s_c:Socket;
// Socket to relay.
private var s_r:Socket;
// Parent swfcat, for UI updates.
private var ui:swfcat;
private function log(msg:String):void
{
ui.puts(id() + ": " + msg)
}
// String describing this pair for output.
private function id():String
{
return "<" + this.addr_c.host + ":" + this.addr_c.port +
"," + this.addr_r.host + ":" + this.addr_r.port + ">";
}
public function ProxyPair(ui:swfcat, addr_c:Object, addr_r:Object)
{
this.ui = ui;
this.addr_c = addr_c;
this.addr_r = addr_r;
}
public function connect():void
{
s_r = new Socket();
s_r.addEventListener(Event.CONNECT, tor_connected);
s_r.addEventListener(Event.CLOSE, function (e:Event):void {
log("Tor: closed.");
if (s_c.connected)
s_c.close();
});
s_r.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Tor: I/O error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
s_r.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Tor: security error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
log("Tor: connecting to " + addr_r.host + ":" + addr_r.port + ".");
s_r.connect(addr_r.host, addr_r.port);
}
private function tor_connected(e:Event):void
{
log("Tor: connected.");
s_c = new Socket();
s_c.addEventListener(Event.CONNECT, client_connected);
s_c.addEventListener(Event.CLOSE, function (e:Event):void {
log("Client: closed.");
if (s_r.connected)
s_r.close();
});
s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Client: I/O error: " + e.text + ".");
if (s_r.connected)
s_r.close();
});
s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Client: security error: " + e.text + ".");
if (s_r.connected)
s_r.close();
});
log("Client: connecting to " + addr_c.host + ":" + addr_c.port + ".");
s_c.connect(addr_c.host, addr_c.port);
}
private function client_connected(e:Event):void
{
log("Client: connected.");
s_r.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_r.readBytes(bytes, 0, e.bytesLoaded);
log("Tor: read " + bytes.length + ".");
s_c.writeBytes(bytes);
});
s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_c.readBytes(bytes, 0, e.bytesLoaded);
log("Client: read " + bytes.length + ".");
s_r.writeBytes(bytes);
});
}
}
|
Change back to my relay, not an alternative bridge, now that hibernation is turned off on the relay.
|
Change back to my relay, not an alternative bridge, now that hibernation
is turned off on the relay.
|
ActionScript
|
mit
|
infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,infinity0/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,glamrock/flashproxy,glamrock/flashproxy,glamrock/flashproxy,arlolra/flashproxy
|
f30415c135d1112fefaf99e22c9cfae4fd88c250
|
src/com/google/analytics/utils/Environment.as
|
src/com/google/analytics/utils/Environment.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.utils
{
import com.google.analytics.core.ga_internal;
import com.google.analytics.debug.DebugConfiguration;
import com.google.analytics.external.HTMLDOM;
import core.strings.userAgent;
import core.uri;
import flash.system.Capabilities;
import flash.system.Security;
import flash.system.System;
/**
* Environment provides informations for the local environment.
*/
public class Environment
{
private var _debug:DebugConfiguration;
private var _dom:HTMLDOM;
private var _protocol:String;
private var _appName:String;
private var _appVersion:Version;
private var _userAgent:String;
private var _url:String;
/**
* Creates a new Environment instance.
* @param url The URL of the SWF.
* @param app The application name
* @param version The application version
* @param dom the HTMLDOM reference.
*/
public function Environment( url:String = "", app:String = "", version:String = "",
debug:DebugConfiguration = null, dom:HTMLDOM = null )
{
var v:Version;
if( app == "" )
{
if( isAIR() )
{
app = "AIR";
}
else
{
app = "Flash";
}
}
if( version == "" )
{
v = flashVersion;
}
else
{
v = Version.fromString( version );
}
_url = url;
_appName = app;
_appVersion = v;
_debug = debug;
_dom = dom;
}
/**
* @private
*/
private function _findProtocol():void
{
_protocol = "";
if( _url != "" )
{
var url:uri = new uri( _url );
_protocol = url.scheme;
}
}
/**
* Indicates the name of the application.
*/
public function get appName():String
{
return _appName;
}
/**
* @private
*/
public function set appName( value:String ):void
{
_appName = value;
_defineUserAgent();
}
/**
* Indicates the version of the application.
*/
public function get appVersion():Version
{
return _appVersion;
}
/**
* @private
*/
public function set appVersion( value:Version ):void
{
_appVersion = value;
_defineUserAgent();
}
/**
* Sets the stage reference value of the application.
*/
ga_internal function set url( value:String ):void
{
_url = value;
}
/**
* Indicates the location of swf.
*/
public function get locationSWFPath():String
{
return _url;
}
/**
* Indicates the referrer value.
*/
public function get referrer():String
{
var _referrer:String = _dom.referrer;
if( _referrer )
{
return _referrer;
}
if( protocol == "file" )
{
return "localhost";
}
return "";
}
/**
* Indicates the title of the document.
*/
public function get documentTitle():String
{
var _title:String = _dom.title;
if( _title )
{
return _title;
}
return "";
}
/**
* Indicates the local domain name value.
*/
public function get domainName():String
{
if( (protocol == "http") ||
(protocol == "https") )
{
var url:uri = new uri( _url.toLowerCase() );
return url.host;
}
if( protocol == "file" )
{
return "localhost";
}
return "";
}
/**
* Indicates if the application is running in AIR.
*/
public function isAIR():Boolean
{
return Security.sandboxType == "application";
}
/**
* Indicates if the SWF is embeded in an HTML page.
* @return <code class="prettyprint">true</code> if the SWF is embeded in an HTML page.
*/
public function isInHTML():Boolean
{
return Capabilities.playerType == "PlugIn" ;
}
/**
* Indicates the locationPath value.
*/
public function get locationPath():String
{
var _pathname:String = _dom.pathname;
if( _pathname )
{
return _pathname;
}
return "";
}
/**
* Indicates the locationSearch value.
*/
public function get locationSearch():String
{
var _search:String = _dom.search;
if( _search )
{
return _search;
}
return "";
}
/**
* Returns the flash version object representation of the application.
* <p>This object contains the attributes major, minor, build and revision :</p>
* <p><b>Example :</b></p>
* <pre class="prettyprint">
* import com.google.analytics.utils.Environment ;
*
* var info:Environment = new Environment( "http://www.domain.com" ) ;
* var version:Object = info.flashVersion ;
*
* trace( version.major ) ; // 9
* trace( version.minor ) ; // 0
* trace( version.build ) ; // 124
* trace( version.revision ) ; // 0
* </pre>
* @return the flash version object representation of the application.
*/
public function get flashVersion():Version
{
var v:Version = Version.fromString( Capabilities.version.split( " " )[1], "," ) ;
return v ;
}
/**
* Returns the language string as a lowercase two-letter language code from ISO 639-1.
* @see Capabilities.language
*/
public function get language():String
{
var _lang:String = _dom.language;
var lang:String = Capabilities.language;
if( _lang )
{
if( (_lang.length > lang.length) &&
(_lang.substr(0,lang.length) == lang) )
{
lang = _lang;
}
}
return lang;
}
/**
* Returns the internal character set used by the flash player
* <p>Logic : by default flash player use unicode internally so we return UTF-8.</p>
* <p>If the player use the system code page then we try to return the char set of the browser.</p>
* @return the internal character set used by the flash player
*/
public function get languageEncoding():String
{
if( System.useCodePage )
{
var _charset:String = _dom.characterSet;
if( _charset )
{
return _charset;
}
return "-"; //not found
}
//default
return "UTF-8" ;
}
/**
* Returns the operating system string.
* <p><b>Note:</b> The flash documentation indicate those strings</p>
* <li>"Windows XP"</li>
* <li>"Windows 2000"</li>
* <li>"Windows NT"</li>
* <li>"Windows 98/ME"</li>
* <li>"Windows 95"</li>
* <li>"Windows CE" (available only in Flash Player SDK, not in the desktop version)</li>
* <li>"Linux"</li>
* <li>"MacOS"</li>
* <p>Other strings we can obtain ( not documented : "Mac OS 10.5.4" , "Windows Vista")</p>
* @return the operating system string.
* @see Capabilities.os
*/
public function get operatingSystem():String
{
return Capabilities.os ;
}
/**
* Returns the player type.
* <p><b>Note :</b> The flash documentation indicate those strings.</p>
* <li><b>"ActiveX"</b> : for the Flash Player ActiveX control used by Microsoft Internet Explorer.</li>
* <li><b>"Desktop"</b> : for the Adobe AIR runtime (except for SWF content loaded by an HTML page, which has Capabilities.playerType set to "PlugIn").</li>
* <li><b>"External"</b> : for the external Flash Player "PlugIn" for the Flash Player browser plug-in (and for SWF content loaded by an HTML page in an AIR application).</li>
* <li><b>"StandAlone"</b> : for the stand-alone Flash Player.</li>
* @return the player type.
* @see Capabilities.playerType
*/
public function get playerType():String
{
return Capabilities.playerType;
}
/**
* Returns the platform, can be "Windows", "Macintosh" or "Linux"
* @see Capabilities.manufacturer
*/
public function get platform():String
{
var p:String = Capabilities.manufacturer;
return p.split( "Adobe " )[1];
}
/**
* Indicates the Protocols object of this local info.
*/
public function get protocol():String
{
if(!_protocol)
{
_findProtocol();
}
return _protocol;
}
/**
* Indicates the height of the screen.
* @see Capabilities.screenResolutionY
*/
public function get screenHeight():Number
{
return Capabilities.screenResolutionY;
}
/**
* Indicates the width of the screen.
* @see Capabilities.screenResolutionX
*/
public function get screenWidth():Number
{
return Capabilities.screenResolutionX;
}
/**
* In AIR we can use flash.display.Screen to directly get the colorDepth property
* in flash player we can only access screenColor in flash.system.Capabilities.
* <p>Some ref : <a href="http://en.wikipedia.org/wiki/Color_depth">http://en.wikipedia.org/wiki/Color_depth</a></p>
* <li>"color" -> 16-bit or 24-bit or 32-bit</li>
* <li>"gray" -> 2-bit</li>
* <li>"bw" -> 1-bit</li>
*/
public function get screenColorDepth():String
{
var color:String;
switch( Capabilities.screenColor )
{
case "bw":
{
color = "1";
break;
}
case "gray":
{
color = "2";
break;
}
/* note:
as we have no way to know if
we are in 16-bit, 24-bit or 32-bit
we gives 24-bit by default
*/
case "color" :
default :
{
color = "24" ;
}
}
var _colorDepth:String = _dom.colorDepth;
if( _colorDepth )
{
color = _colorDepth;
}
return color;
}
private function _defineUserAgent():void
{
_userAgent = core.strings.userAgent( appName + "/" + appVersion.toString(4) );
}
/**
* Defines a custom user agent.
* <p>For case where the user would want to define its own application name and version
* it is possible to change appName and appVersion which are in sync with
* applicationProduct and applicationVersion properties.</p>
*/
public function get userAgent():String
{
if( !_userAgent )
{
_defineUserAgent();
}
return _userAgent;
}
/**
* @private
*/
public function set userAgent( custom:String ):void
{
_userAgent = 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.utils
{
import com.google.analytics.core.ga_internal;
import com.google.analytics.debug.DebugConfiguration;
import com.google.analytics.external.HTMLDOM;
import core.strings.userAgent;
import core.uri;
import core.version;
import flash.system.Capabilities;
import flash.system.Security;
import flash.system.System;
/**
* Environment provides informations for the local environment.
*/
public class Environment
{
private var _debug:DebugConfiguration;
private var _dom:HTMLDOM;
private var _protocol:String;
private var _appName:String;
private var _appVersion:version;
private var _userAgent:String;
private var _url:String;
/**
* Creates a new Environment instance.
* @param url The URL of the SWF.
* @param app The application name
* @param version The application version
* @param dom the HTMLDOM reference.
*/
public function Environment( url:String = "", app:String = "", version:String = "",
debug:DebugConfiguration = null, dom:HTMLDOM = null )
{
var v:core.version;
if( app == "" )
{
if( isAIR() )
{
app = "AIR";
}
else
{
app = "Flash";
}
}
if( version == "" )
{
v = flashVersion;
}
else
{
v = getVersionFromString( version );
}
_url = url;
_appName = app;
_appVersion = v;
_debug = debug;
_dom = dom;
}
/**
* @private
*/
private function _findProtocol():void
{
_protocol = "";
if( _url != "" )
{
var url:uri = new uri( _url );
_protocol = url.scheme;
}
}
/**
* Indicates the name of the application.
*/
public function get appName():String
{
return _appName;
}
/**
* @private
*/
public function set appName( value:String ):void
{
_appName = value;
_defineUserAgent();
}
/**
* Indicates the version of the application.
*/
public function get appVersion():version
{
return _appVersion;
}
/**
* @private
*/
public function set appVersion( value:version ):void
{
_appVersion = value;
_defineUserAgent();
}
/**
* Sets the stage reference value of the application.
*/
ga_internal function set url( value:String ):void
{
_url = value;
}
/**
* Indicates the location of swf.
*/
public function get locationSWFPath():String
{
return _url;
}
/**
* Indicates the referrer value.
*/
public function get referrer():String
{
var _referrer:String = _dom.referrer;
if( _referrer )
{
return _referrer;
}
if( protocol == "file" )
{
return "localhost";
}
return "";
}
/**
* Indicates the title of the document.
*/
public function get documentTitle():String
{
var _title:String = _dom.title;
if( _title )
{
return _title;
}
return "";
}
/**
* Indicates the local domain name value.
*/
public function get domainName():String
{
if( (protocol == "http") ||
(protocol == "https") )
{
var url:uri = new uri( _url.toLowerCase() );
return url.host;
}
if( protocol == "file" )
{
return "localhost";
}
return "";
}
/**
* Indicates if the application is running in AIR.
*/
public function isAIR():Boolean
{
return Security.sandboxType == "application";
}
/**
* Indicates if the SWF is embeded in an HTML page.
* @return <code class="prettyprint">true</code> if the SWF is embeded in an HTML page.
*/
public function isInHTML():Boolean
{
return Capabilities.playerType == "PlugIn" ;
}
/**
* Indicates the locationPath value.
*/
public function get locationPath():String
{
var _pathname:String = _dom.pathname;
if( _pathname )
{
return _pathname;
}
return "";
}
/**
* Indicates the locationSearch value.
*/
public function get locationSearch():String
{
var _search:String = _dom.search;
if( _search )
{
return _search;
}
return "";
}
/**
* Returns the flash version object representation of the application.
* <p>This object contains the attributes major, minor, build and revision :</p>
* <p><b>Example :</b></p>
* <pre class="prettyprint">
* import com.google.analytics.utils.Environment ;
*
* var info:Environment = new Environment( "http://www.domain.com" ) ;
* var version:Object = info.flashVersion ;
*
* trace( version.major ) ; // 9
* trace( version.minor ) ; // 0
* trace( version.build ) ; // 124
* trace( version.revision ) ; // 0
* </pre>
* @return the flash version object representation of the application.
*/
public function get flashVersion():version
{
var v:version = getVersionFromString( Capabilities.version.split( " " )[1], "," ) ;
return v ;
}
/**
* Returns the language string as a lowercase two-letter language code from ISO 639-1.
* @see Capabilities.language
*/
public function get language():String
{
var _lang:String = _dom.language;
var lang:String = Capabilities.language;
if( _lang )
{
if( (_lang.length > lang.length) &&
(_lang.substr(0,lang.length) == lang) )
{
lang = _lang;
}
}
return lang;
}
/**
* Returns the internal character set used by the flash player
* <p>Logic : by default flash player use unicode internally so we return UTF-8.</p>
* <p>If the player use the system code page then we try to return the char set of the browser.</p>
* @return the internal character set used by the flash player
*/
public function get languageEncoding():String
{
if( System.useCodePage )
{
var _charset:String = _dom.characterSet;
if( _charset )
{
return _charset;
}
return "-"; //not found
}
//default
return "UTF-8" ;
}
/**
* Returns the operating system string.
* <p><b>Note:</b> The flash documentation indicate those strings</p>
* <li>"Windows XP"</li>
* <li>"Windows 2000"</li>
* <li>"Windows NT"</li>
* <li>"Windows 98/ME"</li>
* <li>"Windows 95"</li>
* <li>"Windows CE" (available only in Flash Player SDK, not in the desktop version)</li>
* <li>"Linux"</li>
* <li>"MacOS"</li>
* <p>Other strings we can obtain ( not documented : "Mac OS 10.5.4" , "Windows Vista")</p>
* @return the operating system string.
* @see Capabilities.os
*/
public function get operatingSystem():String
{
return Capabilities.os ;
}
/**
* Returns the player type.
* <p><b>Note :</b> The flash documentation indicate those strings.</p>
* <li><b>"ActiveX"</b> : for the Flash Player ActiveX control used by Microsoft Internet Explorer.</li>
* <li><b>"Desktop"</b> : for the Adobe AIR runtime (except for SWF content loaded by an HTML page, which has Capabilities.playerType set to "PlugIn").</li>
* <li><b>"External"</b> : for the external Flash Player "PlugIn" for the Flash Player browser plug-in (and for SWF content loaded by an HTML page in an AIR application).</li>
* <li><b>"StandAlone"</b> : for the stand-alone Flash Player.</li>
* @return the player type.
* @see Capabilities.playerType
*/
public function get playerType():String
{
return Capabilities.playerType;
}
/**
* Returns the platform, can be "Windows", "Macintosh" or "Linux"
* @see Capabilities.manufacturer
*/
public function get platform():String
{
var p:String = Capabilities.manufacturer;
return p.split( "Adobe " )[1];
}
/**
* Indicates the Protocols object of this local info.
*/
public function get protocol():String
{
if(!_protocol)
{
_findProtocol();
}
return _protocol;
}
/**
* Indicates the height of the screen.
* @see Capabilities.screenResolutionY
*/
public function get screenHeight():Number
{
return Capabilities.screenResolutionY;
}
/**
* Indicates the width of the screen.
* @see Capabilities.screenResolutionX
*/
public function get screenWidth():Number
{
return Capabilities.screenResolutionX;
}
/**
* In AIR we can use flash.display.Screen to directly get the colorDepth property
* in flash player we can only access screenColor in flash.system.Capabilities.
* <p>Some ref : <a href="http://en.wikipedia.org/wiki/Color_depth">http://en.wikipedia.org/wiki/Color_depth</a></p>
* <li>"color" -> 16-bit or 24-bit or 32-bit</li>
* <li>"gray" -> 2-bit</li>
* <li>"bw" -> 1-bit</li>
*/
public function get screenColorDepth():String
{
var color:String;
switch( Capabilities.screenColor )
{
case "bw":
{
color = "1";
break;
}
case "gray":
{
color = "2";
break;
}
/* note:
as we have no way to know if
we are in 16-bit, 24-bit or 32-bit
we gives 24-bit by default
*/
case "color" :
default :
{
color = "24" ;
}
}
var _colorDepth:String = _dom.colorDepth;
if( _colorDepth )
{
color = _colorDepth;
}
return color;
}
private function _defineUserAgent():void
{
_userAgent = core.strings.userAgent( appName + "/" + appVersion.toString(4) );
}
/**
* Defines a custom user agent.
* <p>For case where the user would want to define its own application name and version
* it is possible to change appName and appVersion which are in sync with
* applicationProduct and applicationVersion properties.</p>
*/
public function get userAgent():String
{
if( !_userAgent )
{
_defineUserAgent();
}
return _userAgent;
}
/**
* @private
*/
public function set userAgent( custom:String ):void
{
_userAgent = custom;
}
}
}
|
replace class Version by core.version
|
replace class Version by core.version
|
ActionScript
|
apache-2.0
|
nsdevaraj/gaforflash,minimedj/gaforflash,nsdevaraj/gaforflash,minimedj/gaforflash
|
20eb66a97097d8f2ffa122fcda7c3e8ff5e6c106
|
media/as3/ZeroClipboardPdf.as
|
media/as3/ZeroClipboardPdf.as
|
/* Compile using: mxmlc --target-player=10.0.0 -library-path+=lib ZeroClipboard.as */
package {
import flash.display.Stage;
import flash.display.Sprite;
import flash.display.LoaderInfo;
import flash.display.StageScaleMode;
import flash.events.*;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.external.ExternalInterface;
import flash.system.Security;
import flash.utils.*;
import flash.system.System;
import flash.net.FileReference;
import flash.net.FileFilter;
/* PDF imports */
import org.alivepdf.pdf.PDF;
import org.alivepdf.data.Grid;
import org.alivepdf.data.GridColumn;
import org.alivepdf.layout.Orientation;
import org.alivepdf.layout.Size;
import org.alivepdf.layout.Unit;
import org.alivepdf.display.Display;
import org.alivepdf.saving.Method;
import org.alivepdf.fonts.FontFamily;
import org.alivepdf.fonts.Style;
import org.alivepdf.fonts.CoreFont;
import org.alivepdf.colors.RGBColor;
public class ZeroClipboard extends Sprite {
private var domId:String = '';
private var button:Sprite;
private var clipText:String = 'blank';
private var fileName:String = '';
private var action:String = 'copy';
private var incBom:Boolean = true;
private var charSet:String = 'utf8';
public function ZeroClipboard() {
// constructor, setup event listeners and external interfaces
stage.scaleMode = StageScaleMode.EXACT_FIT;
flash.system.Security.allowDomain("*");
// import flashvars
var flashvars:Object = LoaderInfo( this.root.loaderInfo ).parameters;
domId = flashvars.id;
// invisible button covers entire stage
button = new Sprite();
button.buttonMode = true;
button.useHandCursor = true;
button.graphics.beginFill(0x00FF00);
button.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
button.alpha = 0.0;
addChild(button);
button.addEventListener(MouseEvent.CLICK, clickHandler);
button.addEventListener(MouseEvent.MOUSE_OVER, function(event:Event):void {
ExternalInterface.call( 'ZeroClipboard.dispatch', domId, 'mouseOver', null );
} );
button.addEventListener(MouseEvent.MOUSE_OUT, function(event:Event):void {
ExternalInterface.call( 'ZeroClipboard.dispatch', domId, 'mouseOut', null );
} );
button.addEventListener(MouseEvent.MOUSE_DOWN, function(event:Event):void {
ExternalInterface.call( 'ZeroClipboard.dispatch', domId, 'mouseDown', null );
} );
button.addEventListener(MouseEvent.MOUSE_UP, function(event:Event):void {
ExternalInterface.call( 'ZeroClipboard.dispatch', domId, 'mouseUp', null );
} );
// external functions
ExternalInterface.addCallback("setHandCursor", setHandCursor);
ExternalInterface.addCallback("clearText", clearText);
ExternalInterface.addCallback("setText", setText);
ExternalInterface.addCallback("appendText", appendText);
ExternalInterface.addCallback("setFileName", setFileName);
ExternalInterface.addCallback("setAction", setAction);
ExternalInterface.addCallback("setCharSet", setCharSet);
ExternalInterface.addCallback("setBomInc", setBomInc);
// signal to the browser that we are ready
ExternalInterface.call( 'ZeroClipboard.dispatch', domId, 'load', null );
}
public function setCharSet(newCharSet:String):void {
if ( newCharSet == 'UTF16LE' ) {
charSet = newCharSet;
} else {
charSet = 'UTF8';
}
}
public function setBomInc(newBomInc:Boolean):void {
incBom = newBomInc;
}
public function clearText():void {
clipText = '';
}
public function appendText(newText:String):void {
clipText += newText;
}
public function setText(newText:String):void {
clipText = newText;
}
public function setFileName(newFileName:String):void {
fileName = newFileName;
}
public function setAction(newAction:String):void {
action = newAction;
}
public function setHandCursor(enabled:Boolean):void {
// control whether the hand cursor is shown on rollover (true)
// or the default arrow cursor (false)
button.useHandCursor = enabled;
}
private function clickHandler(event:Event):void {
var fileRef:FileReference = new FileReference();
if ( action == "save" ) {
/* Save as a file */
if ( charSet == 'UTF16LE' ) {
fileRef.save( strToUTF16LE(clipText), fileName );
} else {
fileRef.save( strToUTF8(clipText), fileName );
}
} else if ( action == "pdf" ) {
/* Save as a PDF */
var pdf:PDF = configPdf();
fileRef.save( pdf.save( Method.LOCAL ), fileName );
} else {
/* Copy the text to the clipboard. Note charset and BOM have no effect here */
System.setClipboard( clipText );
}
ExternalInterface.call( 'ZeroClipboard.dispatch', domId, 'complete', clipText );
}
private function getProp( prop:String, opts:Array ):String
{
var i:int, iLen:int;
for ( i=0, iLen=opts.length ; i<iLen ; i++ )
{
if ( opts[i].indexOf( prop+":" ) != -1 )
{
return opts[i].replace( prop+":", "" );
}
}
return "";
}
private function configPdf():PDF
{
var
pdf:PDF,
i:int, iLen:int,
splitText:Array = clipText.split("--/TableToolsOpts--\n"),
opts:Array = splitText[0].split("\n"),
dataIn:Array = splitText[1].split("\n"),
aColRatio:Array = getProp( 'colWidth', opts ).split('\t'),
title:String = getProp( 'title', opts ),
message:String = getProp( 'message', opts ),
iPageWidth:int = 0,
dataOut:Array = [],
columns:Array = [],
headers:Array,
y:int = 0;
/* Create the PDF */
pdf = new PDF( Orientation.PORTRAIT, Unit.MM, Size.A4 );
pdf.setDisplayMode( Display.FULL_WIDTH );
pdf.addPage();
iPageWidth = pdf.getCurrentPage().w-20
/* Data setup. Split up the headers, and then construct the columns */
for ( i=0, iLen=dataIn.length ; i<iLen ; i++ )
{
dataOut.push( dataIn[i].split("\t") );
}
headers = dataOut.shift();
for ( i=0, iLen=headers.length ; i<iLen ; i++ )
{
columns.push( new GridColumn( headers[i], i.toString(), aColRatio[i]*iPageWidth ) );
}
pdf.textStyle( new RGBColor(0), 1 );
pdf.setFont( new CoreFont(FontFamily.HELVETICA), 11 );
var grid:Grid = new Grid(
dataOut, /* 1. data */
iPageWidth, /* 2. width */
100, /* 3. height */
new RGBColor (0x00CCFF), /* 4. headerColor */
new RGBColor (0xFFFFFF), /* 5. backgroundColor */
true, /* 6. alternateRowColor */
new RGBColor ( 0x0 ), /* 7. borderColor */
.1, /* 8. border alpha */
null, /* 9. joins */
columns /* 10. columns */
);
pdf.addGrid( grid, 0, y );
return pdf;
}
/*
* Function: strToUTF8
* Purpose: Convert a string to the output utf-8
* Returns: ByteArray
* Inputs: String
*/
private function strToUTF8( str:String ):ByteArray {
var utf8:ByteArray = new ByteArray();
/* BOM first */
if ( incBom ) {
utf8.writeByte( 0xEF );
utf8.writeByte( 0xBB );
utf8.writeByte( 0xBF );
}
utf8.writeUTFBytes( str );
return utf8;
}
/*
* Function: strToUTF16LE
* Purpose: Convert a string to the output utf-16
* Returns: ByteArray
* Inputs: String
* Notes: The fact that this function is needed is a little annoying. Basically, strings in
* AS3 are UTF-16 (with surrogate pairs and everything), but characters which take up less
* than 8 bytes appear to be stored as only 8 bytes. This function effective adds the
* padding required, and the BOM
*/
private function strToUTF16LE( str:String ):ByteArray {
var utf16:ByteArray = new ByteArray();
var iChar:uint;
var i:uint=0, iLen:uint = str.length;
/* BOM first */
if ( incBom ) {
utf16.writeByte( 0xFF );
utf16.writeByte( 0xFE );
}
while ( i < iLen ) {
iChar = str.charCodeAt(i);
if ( iChar < 0xFF ) {
/* one byte char */
utf16.writeByte( iChar );
utf16.writeByte( 0 );
} else {
/* two byte char */
utf16.writeByte( iChar & 0x00FF );
utf16.writeByte( iChar >> 8 );
}
i++;
}
return utf16;
}
}
}
|
/* Compile using: mxmlc --target-player=10.0.0 -library-path+=lib ZeroClipboardPdf.as */
package {
import flash.display.Stage;
import flash.display.Sprite;
import flash.display.LoaderInfo;
import flash.display.StageScaleMode;
import flash.events.*;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.external.ExternalInterface;
import flash.system.Security;
import flash.utils.*;
import flash.system.System;
import flash.net.FileReference;
import flash.net.FileFilter;
/* PDF imports */
import org.alivepdf.pdf.PDF;
import org.alivepdf.data.Grid;
import org.alivepdf.data.GridColumn;
import org.alivepdf.layout.Orientation;
import org.alivepdf.layout.Size;
import org.alivepdf.layout.Unit;
import org.alivepdf.display.Display;
import org.alivepdf.saving.Method;
import org.alivepdf.fonts.FontFamily;
import org.alivepdf.fonts.Style;
import org.alivepdf.fonts.CoreFont;
import org.alivepdf.colors.RGBColor;
public class ZeroClipboard extends Sprite {
private var domId:String = '';
private var button:Sprite;
private var clipText:String = 'blank';
private var fileName:String = '';
private var action:String = 'copy';
private var incBom:Boolean = true;
private var charSet:String = 'utf8';
public function ZeroClipboard() {
// constructor, setup event listeners and external interfaces
stage.scaleMode = StageScaleMode.EXACT_FIT;
flash.system.Security.allowDomain("*");
// import flashvars
var flashvars:Object = LoaderInfo( this.root.loaderInfo ).parameters;
domId = flashvars.id;
// invisible button covers entire stage
button = new Sprite();
button.buttonMode = true;
button.useHandCursor = true;
button.graphics.beginFill(0x00FF00);
button.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
button.alpha = 0.0;
addChild(button);
button.addEventListener(MouseEvent.CLICK, clickHandler);
button.addEventListener(MouseEvent.MOUSE_OVER, function(event:Event):void {
ExternalInterface.call( 'ZeroClipboard.dispatch', domId, 'mouseOver', null );
} );
button.addEventListener(MouseEvent.MOUSE_OUT, function(event:Event):void {
ExternalInterface.call( 'ZeroClipboard.dispatch', domId, 'mouseOut', null );
} );
button.addEventListener(MouseEvent.MOUSE_DOWN, function(event:Event):void {
ExternalInterface.call( 'ZeroClipboard.dispatch', domId, 'mouseDown', null );
} );
button.addEventListener(MouseEvent.MOUSE_UP, function(event:Event):void {
ExternalInterface.call( 'ZeroClipboard.dispatch', domId, 'mouseUp', null );
} );
// external functions
ExternalInterface.addCallback("setHandCursor", setHandCursor);
ExternalInterface.addCallback("clearText", clearText);
ExternalInterface.addCallback("setText", setText);
ExternalInterface.addCallback("appendText", appendText);
ExternalInterface.addCallback("setFileName", setFileName);
ExternalInterface.addCallback("setAction", setAction);
ExternalInterface.addCallback("setCharSet", setCharSet);
ExternalInterface.addCallback("setBomInc", setBomInc);
// signal to the browser that we are ready
ExternalInterface.call( 'ZeroClipboard.dispatch', domId, 'load', null );
}
public function setCharSet(newCharSet:String):void {
if ( newCharSet == 'UTF16LE' ) {
charSet = newCharSet;
} else {
charSet = 'UTF8';
}
}
public function setBomInc(newBomInc:Boolean):void {
incBom = newBomInc;
}
public function clearText():void {
clipText = '';
}
public function appendText(newText:String):void {
clipText += newText;
}
public function setText(newText:String):void {
clipText = newText;
}
public function setFileName(newFileName:String):void {
fileName = newFileName;
}
public function setAction(newAction:String):void {
action = newAction;
}
public function setHandCursor(enabled:Boolean):void {
// control whether the hand cursor is shown on rollover (true)
// or the default arrow cursor (false)
button.useHandCursor = enabled;
}
private function clickHandler(event:Event):void {
var fileRef:FileReference = new FileReference();
if ( action == "save" ) {
/* Save as a file */
if ( charSet == 'UTF16LE' ) {
fileRef.save( strToUTF16LE(clipText), fileName );
} else {
fileRef.save( strToUTF8(clipText), fileName );
}
} else if ( action == "pdf" ) {
/* Save as a PDF */
var pdf:PDF = configPdf();
fileRef.save( pdf.save( Method.LOCAL ), fileName );
} else {
/* Copy the text to the clipboard. Note charset and BOM have no effect here */
System.setClipboard( clipText );
}
ExternalInterface.call( 'ZeroClipboard.dispatch', domId, 'complete', clipText );
}
private function getProp( prop:String, opts:Array ):String
{
var i:int, iLen:int;
for ( i=0, iLen=opts.length ; i<iLen ; i++ )
{
if ( opts[i].indexOf( prop+":" ) != -1 )
{
return opts[i].replace( prop+":", "" );
}
}
return "";
}
private function configPdf():PDF
{
var
pdf:PDF,
i:int, iLen:int,
splitText:Array = clipText.split("--/TableToolsOpts--\n"),
opts:Array = splitText[0].split("\n"),
dataIn:Array = splitText[1].split("\n"),
aColRatio:Array = getProp( 'colWidth', opts ).split('\t'),
title:String = getProp( 'title', opts ),
message:String = getProp( 'message', opts ),
iPageWidth:int = 0,
dataOut:Array = [],
columns:Array = [],
headers:Array,
y:int = 0;
/* Create the PDF */
pdf = new PDF( Orientation.PORTRAIT, Unit.MM, Size.A4 );
pdf.setDisplayMode( Display.FULL_WIDTH );
pdf.addPage();
iPageWidth = pdf.getCurrentPage().w-20
/* Data setup. Split up the headers, and then construct the columns */
for ( i=0, iLen=dataIn.length ; i<iLen ; i++ )
{
dataOut.push( dataIn[i].split("\t") );
}
headers = dataOut.shift();
for ( i=0, iLen=headers.length ; i<iLen ; i++ )
{
columns.push( new GridColumn( headers[i], i.toString(), aColRatio[i]*iPageWidth ) );
}
pdf.textStyle( new RGBColor(0), 1 );
pdf.setFont( new CoreFont(FontFamily.HELVETICA), 11 );
var grid:Grid = new Grid(
dataOut, /* 1. data */
iPageWidth, /* 2. width */
100, /* 3. height */
new RGBColor (0x00CCFF), /* 4. headerColor */
new RGBColor (0xFFFFFF), /* 5. backgroundColor */
true, /* 6. alternateRowColor */
new RGBColor ( 0x0 ), /* 7. borderColor */
.1, /* 8. border alpha */
null, /* 9. joins */
columns /* 10. columns */
);
pdf.addGrid( grid, 0, y );
return pdf;
}
/*
* Function: strToUTF8
* Purpose: Convert a string to the output utf-8
* Returns: ByteArray
* Inputs: String
*/
private function strToUTF8( str:String ):ByteArray {
var utf8:ByteArray = new ByteArray();
/* BOM first */
if ( incBom ) {
utf8.writeByte( 0xEF );
utf8.writeByte( 0xBB );
utf8.writeByte( 0xBF );
}
utf8.writeUTFBytes( str );
return utf8;
}
/*
* Function: strToUTF16LE
* Purpose: Convert a string to the output utf-16
* Returns: ByteArray
* Inputs: String
* Notes: The fact that this function is needed is a little annoying. Basically, strings in
* AS3 are UTF-16 (with surrogate pairs and everything), but characters which take up less
* than 8 bytes appear to be stored as only 8 bytes. This function effective adds the
* padding required, and the BOM
*/
private function strToUTF16LE( str:String ):ByteArray {
var utf16:ByteArray = new ByteArray();
var iChar:uint;
var i:uint=0, iLen:uint = str.length;
/* BOM first */
if ( incBom ) {
utf16.writeByte( 0xFF );
utf16.writeByte( 0xFE );
}
while ( i < iLen ) {
iChar = str.charCodeAt(i);
if ( iChar < 0xFF ) {
/* one byte char */
utf16.writeByte( iChar );
utf16.writeByte( 0 );
} else {
/* two byte char */
utf16.writeByte( iChar & 0x00FF );
utf16.writeByte( iChar >> 8 );
}
i++;
}
return utf16;
}
}
}
|
Comment updated for the correct file name with the compile command
|
Fix: Comment updated for the correct file name with the compile command
|
ActionScript
|
mit
|
phillipmadsen/TableTools,mhlibchuk/TableTools,mhlibchuk/TableTools,Riddhika/TableTool,Riddhika/TableTool,viniciusferreira/TableTools,nandadotexe/TableTools,nandadotexe/TableTools,modulexcite/TableTools,viniciusferreira/TableTools,DataTables/TableTools,phillipmadsen/TableTools,modulexcite/TableTools,DataTables/TableTools
|
a3732353c9a30ae1a7603fe23b264ad7ddb184e5
|
src/aerys/minko/scene/node/Scene.as
|
src/aerys/minko/scene/node/Scene.as
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.Effect;
import aerys.minko.render.Viewport;
import aerys.minko.scene.controller.scene.RenderingController;
import aerys.minko.scene.node.camera.AbstractCamera;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.DataProviderUsage;
import flash.display.BitmapData;
import flash.utils.getTimer;
/**
* Scene objects are the root of any 3D scene.
*
* @author Jean-Marc Le Roux
*
*/
public final class Scene extends Group
{
use namespace minko_scene;
minko_scene var _camera : AbstractCamera;
private var _renderingCtrl : RenderingController;
private var _properties : DataProvider;
private var _bindings : DataBindings;
private var _numTriangles : uint;
private var _enterFrame : Signal;
private var _renderingBegin : Signal;
private var _renderingEnd : Signal;
private var _exitFrame : Signal;
public function get activeCamera() : AbstractCamera
{
return _camera;
}
public function get numPasses() : uint
{
return _renderingCtrl.numPasses;
}
public function get numTriangles() : uint
{
return _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();
}
override protected function initialize() : void
{
_bindings = new DataBindings(this);
this.properties = new DataProvider(DataProviderUsage.EXCLUSIVE);
super.initialize();
}
override protected function initializeSignals() : void
{
super.initializeSignals();
_enterFrame = new Signal('Scene.enterFrame');
_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 flash.display.BitmapData;
import flash.utils.getTimer;
/**
* Scene objects are the root of any 3D scene.
*
* @author Jean-Marc Le Roux
*
*/
public final class Scene extends Group
{
use namespace minko_scene;
minko_scene var _camera : AbstractCamera;
private var _renderingCtrl : RenderingController;
private var _properties : DataProvider;
private var _bindings : DataBindings;
private var _numTriangles : uint;
private var _enterFrame : Signal;
private var _renderingBegin : Signal;
private var _renderingEnd : Signal;
private var _exitFrame : Signal;
public function get activeCamera() : AbstractCamera
{
return _camera;
}
public function get numPasses() : uint
{
return _renderingCtrl.numPasses;
}
public function get numTriangles() : uint
{
return _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);
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 Scene constructor to pass the children argument to the parent constructor and init. children properly (issue #1105)
|
fix Scene constructor to pass the children argument to the parent constructor and init. children properly (issue #1105)
|
ActionScript
|
mit
|
aerys/minko-as3
|
12b5370169f8668e572597945c8cf19ce2ca9806
|
dolly-framework/src/test/actionscript/dolly/CloningOfCompositeCloneableClassTest.as
|
dolly-framework/src/test/actionscript/dolly/CloningOfCompositeCloneableClassTest.as
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.CloneableClass;
import dolly.data.CompositeCloneableClass;
import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertFalse;
import org.flexunit.asserts.assertNotNull;
import org.hamcrest.assertThat;
import org.hamcrest.collection.array;
import org.hamcrest.collection.arrayWithSize;
import org.hamcrest.collection.everyItem;
import org.hamcrest.core.isA;
import org.hamcrest.object.equalTo;
use namespace dolly_internal;
public class CloningOfCompositeCloneableClassTest {
private var compositeCloneableClass:CompositeCloneableClass;
private var compositeCloneableClassType:Type;
[Before]
public function before():void {
compositeCloneableClass = new CompositeCloneableClass();
const nestedCloneable:CloneableClass = new CloneableClass();
nestedCloneable.property1 = "property1 value";
nestedCloneable.writableField1 = "writableField1 value";
const nestedCompositeCloneable:CompositeCloneableClass = new CompositeCloneableClass();
nestedCompositeCloneable.compositeCloneable = compositeCloneableClass;
nestedCompositeCloneable.array = [1, 2, 3];
nestedCompositeCloneable.arrayList = new ArrayList([1, 2, 3]);
nestedCompositeCloneable.arrayCollection = new ArrayCollection([1, 2, 3]);
compositeCloneableClass.cloneable = nestedCloneable;
compositeCloneableClass.compositeCloneable = nestedCompositeCloneable;
compositeCloneableClass.array = [1, 2, 3, 4, 5];
compositeCloneableClass.arrayList = new ArrayList([1, 2, 3, 4, 5]);
compositeCloneableClass.arrayCollection = new ArrayCollection([1, 2, 3, 4, 5]);
compositeCloneableClassType = Type.forInstance(compositeCloneableClass);
}
[After]
public function after():void {
compositeCloneableClass.compositeCloneable =
compositeCloneableClass.compositeCloneable.compositeCloneable = null;
compositeCloneableClass.cloneable = null;
compositeCloneableClass = null;
compositeCloneableClassType = null;
}
[Test]
public function findingAllWritableFieldsForType():void {
const writableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(compositeCloneableClassType);
assertNotNull(writableFields);
assertEquals(5, writableFields.length);
}
[Test]
public function cloningOfArray():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
assertNotNull(clone.array);
assertThat(clone.array, arrayWithSize(5));
assertThat(clone.array, compositeCloneableClass.array);
assertFalse(clone.array == compositeCloneableClass.array);
assertThat(clone.array, everyItem(isA(Number)));
assertThat(clone.array, array(equalTo(1), equalTo(2), equalTo(3), equalTo(4), equalTo(5)));
}
[Test]
public function cloningOfArrayList():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const arrayList:ArrayList = clone.arrayList;
assertNotNull(arrayList);
assertFalse(clone.arrayList == compositeCloneableClass.arrayList);
assertEquals(arrayList.length, 5);
assertEquals(arrayList.getItemAt(0), 1);
assertEquals(arrayList.getItemAt(1), 2);
assertEquals(arrayList.getItemAt(2), 3);
assertEquals(arrayList.getItemAt(3), 4);
assertEquals(arrayList.getItemAt(4), 5);
}
[Test]
public function cloningOfArrayCollection():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const arrayCollection:ArrayCollection = clone.arrayCollection;
assertNotNull(arrayCollection);
assertFalse(clone.arrayCollection == compositeCloneableClass.arrayCollection);
assertEquals(arrayCollection.length, 5);
assertEquals(arrayCollection.getItemAt(0), 1);
assertEquals(arrayCollection.getItemAt(1), 2);
assertEquals(arrayCollection.getItemAt(2), 3);
assertEquals(arrayCollection.getItemAt(3), 4);
assertEquals(arrayCollection.getItemAt(4), 5);
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.CloneableClass;
import dolly.data.CompositeCloneableClass;
import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertFalse;
import org.flexunit.asserts.assertNotNull;
import org.hamcrest.assertThat;
import org.hamcrest.collection.array;
import org.hamcrest.collection.arrayWithSize;
import org.hamcrest.collection.everyItem;
import org.hamcrest.core.isA;
import org.hamcrest.core.not;
import org.hamcrest.object.equalTo;
use namespace dolly_internal;
public class CloningOfCompositeCloneableClassTest {
private var compositeCloneableClass:CompositeCloneableClass;
private var compositeCloneableClassType:Type;
[Before]
public function before():void {
compositeCloneableClass = new CompositeCloneableClass();
const nestedCloneable:CloneableClass = new CloneableClass();
nestedCloneable.property1 = "property1 value";
nestedCloneable.writableField1 = "writableField1 value";
const nestedCompositeCloneable:CompositeCloneableClass = new CompositeCloneableClass();
nestedCompositeCloneable.compositeCloneable = compositeCloneableClass;
nestedCompositeCloneable.array = [1, 2, 3];
nestedCompositeCloneable.arrayList = new ArrayList([1, 2, 3]);
nestedCompositeCloneable.arrayCollection = new ArrayCollection([1, 2, 3]);
compositeCloneableClass.cloneable = nestedCloneable;
compositeCloneableClass.compositeCloneable = nestedCompositeCloneable;
compositeCloneableClass.array = [1, 2, 3, 4, 5];
compositeCloneableClass.arrayList = new ArrayList([1, 2, 3, 4, 5]);
compositeCloneableClass.arrayCollection = new ArrayCollection([1, 2, 3, 4, 5]);
compositeCloneableClassType = Type.forInstance(compositeCloneableClass);
}
[After]
public function after():void {
compositeCloneableClass.compositeCloneable =
compositeCloneableClass.compositeCloneable.compositeCloneable = null;
compositeCloneableClass.cloneable = null;
compositeCloneableClass = null;
compositeCloneableClassType = null;
}
[Test]
public function findingAllWritableFieldsForType():void {
const writableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(compositeCloneableClassType);
assertNotNull(writableFields);
assertEquals(5, writableFields.length);
}
[Test]
public function cloningOfArray():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
assertNotNull(clone.array);
assertThat(clone.array, arrayWithSize(5));
assertThat(clone.array, compositeCloneableClass.array);
assertFalse(clone.array == compositeCloneableClass.array);
assertThat(clone.array, everyItem(isA(Number)));
assertThat(clone.array, array(equalTo(1), equalTo(2), equalTo(3), equalTo(4), equalTo(5)));
}
[Test]
public function cloningOfArrayList():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const arrayList:ArrayList = clone.arrayList;
assertNotNull(arrayList);
assertFalse(clone.arrayList == compositeCloneableClass.arrayList);
assertEquals(arrayList.length, 5);
assertEquals(arrayList.getItemAt(0), 1);
assertEquals(arrayList.getItemAt(1), 2);
assertEquals(arrayList.getItemAt(2), 3);
assertEquals(arrayList.getItemAt(3), 4);
assertEquals(arrayList.getItemAt(4), 5);
}
[Test]
public function cloningOfArrayCollection():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const arrayCollection:ArrayCollection = clone.arrayCollection;
assertNotNull(arrayCollection);
assertFalse(clone.arrayCollection == compositeCloneableClass.arrayCollection);
assertEquals(arrayCollection.length, 5);
assertEquals(arrayCollection.getItemAt(0), 1);
assertEquals(arrayCollection.getItemAt(1), 2);
assertEquals(arrayCollection.getItemAt(2), 3);
assertEquals(arrayCollection.getItemAt(3), 4);
assertEquals(arrayCollection.getItemAt(4), 5);
}
[Test]
public function cloningOfCloneableProperty():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const cloneable:CloneableClass = clone.cloneable;
assertNotNull(cloneable);
assertThat(cloneable, isA(CloneableClass));
assertEquals(cloneable.property1, "property1 value");
assertEquals(cloneable.writableField1, "writableField1 value");
assertThat(cloneable, not(compositeCloneableClass.cloneable));
}
}
}
|
Test for cloning of property with type CloneableClass in CompositeCloneableClass.
|
Test for cloning of property with type CloneableClass in CompositeCloneableClass.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
a7b2255a6b48e127f13ecdca307579c8147671d0
|
dolly-framework/src/test/actionscript/dolly/ClonerTest.as
|
dolly-framework/src/test/actionscript/dolly/ClonerTest.as
|
package dolly {
import dolly.core.dolly_internal;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertNotNull;
import org.flexunit.asserts.assertNull;
use namespace dolly_internal;
public class ClonerTest {
private var classMarkedAsCloneable:ClassLevelCloneable;
private var classWithSomeCloneableFields:PropertyLevelCloneable;
private var classMarkedAsCloneableType:Type;
private var classWithSomeCloneableFieldsType:Type;
[Before]
public function before():void {
classMarkedAsCloneable = new ClassLevelCloneable();
classMarkedAsCloneable.property1 = "value 1";
classMarkedAsCloneable.property2 = "value 2";
classMarkedAsCloneable.property3 = "value 3";
classMarkedAsCloneable.writableField = "value 4";
classWithSomeCloneableFields = new PropertyLevelCloneable();
classWithSomeCloneableFields.property1 = "value 1";
classWithSomeCloneableFields.property2 = "value 2";
classWithSomeCloneableFields.property3 = "value 3";
classWithSomeCloneableFields.writableField = "value 4";
classMarkedAsCloneableType = Type.forInstance(classMarkedAsCloneable);
classWithSomeCloneableFieldsType = Type.forInstance(classWithSomeCloneableFields);
}
[After]
public function after():void {
classMarkedAsCloneable = null;
classWithSomeCloneableFields = null;
classMarkedAsCloneableType = null;
classWithSomeCloneableFieldsType = null;
}
[Test]
public function testGetCloneableFieldsForType():void {
var cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(classMarkedAsCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
cloneableFields = Cloner.getCloneableFieldsForType(classWithSomeCloneableFieldsType);
assertNotNull(cloneableFields);
assertEquals(3, cloneableFields.length);
}
[Test]
public function testCloneWithClassLevelMetadata():void {
const clone:ClassLevelCloneable = Cloner.clone(classMarkedAsCloneable) as ClassLevelCloneable;
assertNotNull(clone);
assertNotNull(clone.property1);
assertEquals(clone.property1, classMarkedAsCloneable.property1);
assertNotNull(clone.property2);
assertEquals(clone.property2, classMarkedAsCloneable.property2);
assertNotNull(clone.property3);
assertEquals(clone.property3, classMarkedAsCloneable.property3);
assertNotNull(clone.writableField);
assertEquals(clone.writableField, classMarkedAsCloneable.writableField);
}
[Test]
public function testCloneWithPropertyLevelMetadata():void {
const clone:PropertyLevelCloneable = Cloner.clone(
classWithSomeCloneableFields
) as PropertyLevelCloneable;
assertNotNull(clone);
assertNull(clone.property1);
assertNotNull(clone.property2);
assertEquals(clone.property2, classWithSomeCloneableFields.property2);
assertNotNull(clone.property3);
assertEquals(clone.property3, classWithSomeCloneableFields.property3);
assertNotNull(clone.writableField);
assertEquals(clone.writableField, classWithSomeCloneableFields.writableField);
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertNotNull;
import org.flexunit.asserts.assertNull;
use namespace dolly_internal;
public class ClonerTest {
private var classLevelCloneable:ClassLevelCloneable;
private var classLevelCloneableType:Type;
private var propertyLevelCloneable:PropertyLevelCloneable;
private var propertyLevelCloneableType:Type;
[Before]
public function before():void {
classLevelCloneable = new ClassLevelCloneable();
classLevelCloneable.property1 = "value 1";
classLevelCloneable.property2 = "value 2";
classLevelCloneable.property3 = "value 3";
classLevelCloneable.writableField = "value 4";
propertyLevelCloneable = new PropertyLevelCloneable();
propertyLevelCloneable.property1 = "value 1";
propertyLevelCloneable.property2 = "value 2";
propertyLevelCloneable.property3 = "value 3";
propertyLevelCloneable.writableField = "value 4";
classLevelCloneableType = Type.forInstance(classLevelCloneable);
propertyLevelCloneableType = Type.forInstance(propertyLevelCloneable);
}
[After]
public function after():void {
classLevelCloneable = null;
propertyLevelCloneable = null;
classLevelCloneableType = null;
propertyLevelCloneableType = null;
}
[Test]
public function testGetCloneableFieldsForType():void {
var cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(classLevelCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
cloneableFields = Cloner.getCloneableFieldsForType(propertyLevelCloneableType);
assertNotNull(cloneableFields);
assertEquals(3, cloneableFields.length);
}
[Test]
public function testCloneWithClassLevelMetadata():void {
const clone:ClassLevelCloneable = Cloner.clone(classLevelCloneable) as ClassLevelCloneable;
assertNotNull(clone);
assertNotNull(clone.property1);
assertEquals(clone.property1, classLevelCloneable.property1);
assertNotNull(clone.property2);
assertEquals(clone.property2, classLevelCloneable.property2);
assertNotNull(clone.property3);
assertEquals(clone.property3, classLevelCloneable.property3);
assertNotNull(clone.writableField);
assertEquals(clone.writableField, classLevelCloneable.writableField);
}
[Test]
public function testCloneWithPropertyLevelMetadata():void {
const clone:PropertyLevelCloneable = Cloner.clone(
propertyLevelCloneable
) as PropertyLevelCloneable;
assertNotNull(clone);
assertNull(clone.property1);
assertNotNull(clone.property2);
assertEquals(clone.property2, propertyLevelCloneable.property2);
assertNotNull(clone.property3);
assertEquals(clone.property3, propertyLevelCloneable.property3);
assertNotNull(clone.writableField);
assertEquals(clone.writableField, propertyLevelCloneable.writableField);
}
}
}
|
Rename properties in test class.
|
Rename properties in test class.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
c2c1b92d8f30c7eaf8375d42983816e97def77d8
|
src/org/mangui/hls/model/Level.as
|
src/org/mangui/hls/model/Level.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 {
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
import org.mangui.hls.utils.PTS;
/** HLS streaming quality level. **/
public class Level {
/** audio only Level ? **/
public var audio : Boolean;
/** AAC codec signaled ? **/
public var codec_aac : Boolean;
/** MP3 codec signaled ? **/
public var codec_mp3 : Boolean;
/** H264 codec signaled ? **/
public var codec_h264 : Boolean;
/** Level Bitrate. **/
public var bitrate : uint;
/** Level Name. **/
public var name : String;
/** level index (sorted by bitrate) **/
public var index : int = 0;
/** level index (manifest order) **/
public var manifest_index : int = 0;
/** video width (from playlist) **/
public var width : int;
/** video height (from playlist) **/
public var height : int;
/** URL of this bitrate level (for M3U8). (it is a vector so that we can store redundant streams in same level) **/
public var urls : Vector.<String>;
// index of used url (non 0 if we switch to a redundant stream)
private var _redundantStreamId : int = 0;
/** Level fragments **/
public var fragments : Vector.<Fragment>;
/** min sequence number from M3U8. **/
public var start_seqnum : int;
/** max sequence number from M3U8. **/
public var end_seqnum : int;
/** target fragment duration from M3U8 **/
public var targetduration : Number;
/** average fragment duration **/
public var averageduration : Number;
/** Total duration **/
public var duration : Number;
/** Audio Identifier **/
public var audio_stream_id : String;
/** Create the quality level. **/
public function Level() : void {
this.fragments = new Vector.<Fragment>();
};
public function get url() : String {
return urls[_redundantStreamId];
}
public function get redundantStreamsNb() : int {
if(urls && urls.length) {
return urls.length-1;
} else {
return 0;
}
}
public function get redundantStreamId() : int {
return _redundantStreamId;
}
// when switching to a redundant stream, reset fragments. they will be retrieved from new playlist
public function set redundantStreamId(id) : void {
if(id < urls.length && id != _redundantStreamId) {
_redundantStreamId = id;
fragments = new Vector.<Fragment>();
}
}
/** Return the Fragment before a given time position. **/
public function getFragmentBeforePosition(position : Number) : Fragment {
if (fragments[0].data.valid && position < fragments[0].start_time)
return fragments[0];
var len : int = fragments.length;
for (var i : int = 0; i < len; i++) {
/* check whether fragment contains current position */
if (fragments[i].data.valid && fragments[i].start_time <= position && fragments[i].start_time + fragments[i].duration > position) {
return fragments[i];
}
}
return fragments[len - 1];
};
/** Return the sequence number from a given program date **/
public function getSeqNumFromProgramDate(program_date : Number) : int {
if (program_date < fragments[0].program_date)
return -1;
var len : int = fragments.length;
for (var i : int = 0; i < len; i++) {
/* check whether fragment contains current position */
if (fragments[i].data.valid && fragments[i].program_date <= program_date && fragments[i].program_date + 1000 * fragments[i].duration > program_date) {
return (start_seqnum + i);
}
}
return -1;
};
/** Return the sequence number nearest a PTS **/
public function getSeqNumNearestPTS(pts : Number, continuity : int) : Number {
if (fragments.length == 0)
return -1;
var firstIndex : Number = getFirstIndexfromContinuity(continuity);
if (firstIndex == -1 || isNaN(fragments[firstIndex].data.pts_start_computed))
return -1;
var lastIndex : Number = getLastIndexfromContinuity(continuity);
for (var i : int = firstIndex; i <= lastIndex; i++) {
var frag : Fragment = fragments[i];
/* check nearest fragment */
if ( frag.data.valid && (frag.duration >= 0) && (Math.abs(frag.data.pts_start_computed - pts) < Math.abs(frag.data.pts_start_computed + 1000 * frag.duration - pts))) {
return frag.seqnum;
}
}
// requested PTS above max PTS of this level
return Number.POSITIVE_INFINITY;
};
public function getLevelstartPTS() : Number {
if (fragments.length)
return fragments[0].data.pts_start_computed;
else
return NaN;
}
/** Return the fragment index from fragment sequence number **/
public function getFragmentfromSeqNum(seqnum : Number) : Fragment {
var index : int = getIndexfromSeqNum(seqnum);
if (index != -1) {
return fragments[index];
} else {
return null;
}
}
/** Return the fragment index from fragment sequence number **/
private function getIndexfromSeqNum(seqnum : int) : int {
if (seqnum >= start_seqnum && seqnum <= end_seqnum) {
return (fragments.length - 1 - (end_seqnum - seqnum));
} else {
return -1;
}
}
/** Return the first index matching with given continuity counter **/
private function getFirstIndexfromContinuity(continuity : int) : int {
// look for first fragment matching with given continuity index
var len : int = fragments.length;
for (var i : int = 0; i < len; i++) {
if (fragments[i].continuity == continuity)
return i;
}
return -1;
}
/** Return the first seqnum matching with given continuity counter **/
public function getFirstSeqNumfromContinuity(continuity : int) : Number {
var index : int = getFirstIndexfromContinuity(continuity);
if (index == -1) {
return Number.NEGATIVE_INFINITY;
}
return fragments[index].seqnum;
}
/** Return the last seqnum matching with given continuity counter **/
public function getLastSeqNumfromContinuity(continuity : int) : Number {
var index : int = getLastIndexfromContinuity(continuity);
if (index == -1) {
return Number.NEGATIVE_INFINITY;
}
return fragments[index].seqnum;
}
/** Return the last index matching with given continuity counter **/
private function getLastIndexfromContinuity(continuity : Number) : int {
var firstIndex : int = getFirstIndexfromContinuity(continuity);
if (firstIndex == -1)
return -1;
var lastIndex : int = firstIndex;
// look for first fragment matching with given continuity index
for (var i : int = firstIndex; i < fragments.length; i++) {
if (fragments[i].continuity == continuity)
lastIndex = i;
else
break;
}
return lastIndex;
}
/** set Fragments **/
public function updateFragments(_fragments : Vector.<Fragment>) : void {
var idx_with_metrics : int = -1;
var len : int = _fragments.length;
var continuity_offset : int;
var frag : Fragment;
// update PTS from previous fragments
for (var i : int = 0; i < len; i++) {
frag = getFragmentfromSeqNum(_fragments[i].seqnum);
if (frag != null) {
continuity_offset = frag.continuity - _fragments[i].continuity;
if(!isNaN(frag.data.pts_start)) {
_fragments[i].data = frag.data;
idx_with_metrics = i;
}
}
}
if(continuity_offset) {
CONFIG::LOGGING {
Log.debug("updateFragments: discontinuity sliding from live playlist,take into account discontinuity drift:" + continuity_offset);
}
for (i = 0; i < len; i++) {
_fragments[i].continuity+= continuity_offset;
}
}
updateFragmentsProgramDate(_fragments);
fragments = _fragments;
if (len > 0) {
start_seqnum = _fragments[0].seqnum;
end_seqnum = _fragments[len - 1].seqnum;
if (idx_with_metrics != -1) {
frag = fragments[idx_with_metrics];
// if at least one fragment contains PTS info, recompute PTS information for all fragments
CONFIG::LOGGING {
Log.debug("updateFragments: found PTS info from previous playlist,seqnum/PTS:" + frag.seqnum + "/" + frag.data.pts_start);
}
updateFragment(frag.seqnum, true, frag.data.pts_start, frag.data.pts_start + 1000 * frag.duration);
} else {
CONFIG::LOGGING {
Log.debug("updateFragments: unknown PTS info for this level");
}
duration = _fragments[len - 1].start_time + _fragments[len - 1].duration;
}
averageduration = duration / len;
} else {
duration = 0;
averageduration = 0;
}
}
private function updateFragmentsProgramDate(_fragments : Vector.<Fragment>) : void {
var len : int = _fragments.length;
var continuity : int;
var program_date : Number;
var frag : Fragment;
for (var i : int = 0; i < len; i++) {
frag = _fragments[i];
if (frag.continuity != continuity) {
continuity = frag.continuity;
program_date = 0;
}
if (frag.program_date) {
program_date = frag.program_date + 1000 * frag.duration;
} else if (program_date) {
frag.program_date = program_date;
}
}
}
private function _updatePTS(from_index : int, to_index : int) : void {
// CONFIG::LOGGING {
// Log.info("updateFragmentPTS from/to:" + from_index + "/" + to_index);
// }
var frag_from : Fragment = fragments[from_index];
var frag_to : Fragment = fragments[to_index];
if (frag_from.data.valid && frag_to.data.valid) {
if (!isNaN(frag_to.data.pts_start)) {
// we know PTS[to_index]
frag_to.data.pts_start_computed = frag_to.data.pts_start;
/* normalize computed PTS value based on known PTS value.
* this is to avoid computing wrong fragment duration in case of PTS looping */
var from_pts : Number = PTS.normalize(frag_to.data.pts_start, frag_from.data.pts_start_computed);
/* update fragment duration.
it helps to fix drifts between playlist reported duration and fragment real duration */
if (to_index > from_index) {
frag_from.duration = (frag_to.data.pts_start - from_pts) / 1000;
CONFIG::LOGGING {
if (frag_from.duration < 0) {
Log.error("negative duration computed for " + frag_from + ", there should be some duration drift between playlist and fragment!");
}
}
} else {
frag_to.duration = ( from_pts - frag_to.data.pts_start) / 1000;
CONFIG::LOGGING {
if (frag_to.duration < 0) {
Log.error("negative duration computed for " + frag_to + ", there should be some duration drift between playlist and fragment!");
}
}
}
} else {
// we dont know PTS[to_index]
if (to_index > from_index)
frag_to.data.pts_start_computed = frag_from.data.pts_start_computed + 1000 * frag_from.duration;
else
frag_to.data.pts_start_computed = frag_from.data.pts_start_computed - 1000 * frag_to.duration;
}
}
}
public function updateFragment(seqnum : Number, valid : Boolean, min_pts : Number = 0, max_pts : Number = 0) : void {
// CONFIG::LOGGING {
// Log.info("updatePTS : seqnum/min/max:" + seqnum + '/' + min_pts + '/' + max_pts);
// }
// get fragment from seqnum
var fragIdx : int = getIndexfromSeqNum(seqnum);
if (fragIdx != -1) {
var frag : Fragment = fragments[fragIdx];
// update fragment start PTS + duration
if (valid) {
frag.data.pts_start = min_pts;
frag.data.pts_start_computed = min_pts;
frag.duration = (max_pts - min_pts) / 1000;
} else {
frag.duration = 0;
}
frag.data.valid = valid;
// CONFIG::LOGGING {
// Log.info("SN["+fragments[fragIdx].seqnum+"]:pts/duration:" + fragments[fragIdx].start_pts_computed + "/" + fragments[fragIdx].duration);
// }
// adjust fragment PTS/duration from seqnum-1 to frag 0
for (var i : int = fragIdx; i > 0 && fragments[i - 1].continuity == frag.continuity; i--) {
_updatePTS(i, i - 1);
// CONFIG::LOGGING {
// Log.info("SN["+fragments[i-1].seqnum+"]:pts/duration:" + fragments[i-1].start_pts_computed + "/" + fragments[i-1].duration);
// }
}
// adjust fragment PTS/duration from seqnum to last frag
for (i = fragIdx; i < fragments.length - 1 && fragments[i + 1].continuity == frag.continuity; i++) {
_updatePTS(i, i + 1);
// CONFIG::LOGGING {
// Log.info("SN["+fragments[i+1].seqnum+"]:pts/duration:" + fragments[i+1].start_pts_computed + "/" + fragments[i+1].duration);
// }
}
// second, adjust fragment offset
var start_time_offset : Number = fragments[0].start_time;
var len : int = fragments.length;
for (i = 0; i < len; i++) {
fragments[i].start_time = start_time_offset;
start_time_offset += fragments[i].duration;
// CONFIG::LOGGING {
// Log.info("SN["+fragments[i].seqnum+"]:start_time/continuity/pts/duration:" + fragments[i].start_time + "/" + fragments[i].continuity + "/"+ fragments[i].start_pts_computed + "/" + fragments[i].duration);
// }
}
duration = start_time_offset;
} else {
CONFIG::LOGGING {
Log.error("updateFragment:seqnum " + seqnum + " not found!");
}
}
}
}
}
|
/* 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 {
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
import org.mangui.hls.utils.PTS;
/** HLS streaming quality level. **/
public class Level {
/** audio only Level ? **/
public var audio : Boolean;
/** AAC codec signaled ? **/
public var codec_aac : Boolean;
/** MP3 codec signaled ? **/
public var codec_mp3 : Boolean;
/** H264 codec signaled ? **/
public var codec_h264 : Boolean;
/** Level Bitrate. **/
public var bitrate : uint;
/** Level Name. **/
public var name : String;
/** level index (sorted by bitrate) **/
public var index : int = 0;
/** level index (manifest order) **/
public var manifest_index : int = 0;
/** video width (from playlist) **/
public var width : int;
/** video height (from playlist) **/
public var height : int;
/** URL of this bitrate level (for M3U8). (it is a vector so that we can store redundant streams in same level) **/
public var urls : Vector.<String>;
// index of used url (non 0 if we switch to a redundant stream)
private var _redundantStreamId : int = 0;
/** Level fragments **/
public var fragments : Vector.<Fragment>;
/** min sequence number from M3U8. **/
public var start_seqnum : int;
/** max sequence number from M3U8. **/
public var end_seqnum : int;
/** target fragment duration from M3U8 **/
public var targetduration : Number;
/** average fragment duration **/
public var averageduration : Number;
/** Total duration **/
public var duration : Number;
/** Audio Identifier **/
public var audio_stream_id : String;
/** Create the quality level. **/
public function Level() : void {
this.fragments = new Vector.<Fragment>();
};
public function get url() : String {
return urls[_redundantStreamId];
}
public function get redundantStreamsNb() : int {
if(urls && urls.length) {
return urls.length-1;
} else {
return 0;
}
}
public function get redundantStreamId() : int {
return _redundantStreamId;
}
// when switching to a redundant stream, reset fragments. they will be retrieved from new playlist
public function set redundantStreamId(id : int) : void {
if(id < urls.length && id != _redundantStreamId) {
_redundantStreamId = id;
fragments = new Vector.<Fragment>();
}
}
/** Return the Fragment before a given time position. **/
public function getFragmentBeforePosition(position : Number) : Fragment {
if (fragments[0].data.valid && position < fragments[0].start_time)
return fragments[0];
var len : int = fragments.length;
for (var i : int = 0; i < len; i++) {
/* check whether fragment contains current position */
if (fragments[i].data.valid && fragments[i].start_time <= position && fragments[i].start_time + fragments[i].duration > position) {
return fragments[i];
}
}
return fragments[len - 1];
};
/** Return the sequence number from a given program date **/
public function getSeqNumFromProgramDate(program_date : Number) : int {
if (program_date < fragments[0].program_date)
return -1;
var len : int = fragments.length;
for (var i : int = 0; i < len; i++) {
/* check whether fragment contains current position */
if (fragments[i].data.valid && fragments[i].program_date <= program_date && fragments[i].program_date + 1000 * fragments[i].duration > program_date) {
return (start_seqnum + i);
}
}
return -1;
};
/** Return the sequence number nearest a PTS **/
public function getSeqNumNearestPTS(pts : Number, continuity : int) : Number {
if (fragments.length == 0)
return -1;
var firstIndex : Number = getFirstIndexfromContinuity(continuity);
if (firstIndex == -1 || isNaN(fragments[firstIndex].data.pts_start_computed))
return -1;
var lastIndex : Number = getLastIndexfromContinuity(continuity);
for (var i : int = firstIndex; i <= lastIndex; i++) {
var frag : Fragment = fragments[i];
/* check nearest fragment */
if ( frag.data.valid && (frag.duration >= 0) && (Math.abs(frag.data.pts_start_computed - pts) < Math.abs(frag.data.pts_start_computed + 1000 * frag.duration - pts))) {
return frag.seqnum;
}
}
// requested PTS above max PTS of this level
return Number.POSITIVE_INFINITY;
};
public function getLevelstartPTS() : Number {
if (fragments.length)
return fragments[0].data.pts_start_computed;
else
return NaN;
}
/** Return the fragment index from fragment sequence number **/
public function getFragmentfromSeqNum(seqnum : Number) : Fragment {
var index : int = getIndexfromSeqNum(seqnum);
if (index != -1) {
return fragments[index];
} else {
return null;
}
}
/** Return the fragment index from fragment sequence number **/
private function getIndexfromSeqNum(seqnum : int) : int {
if (seqnum >= start_seqnum && seqnum <= end_seqnum) {
return (fragments.length - 1 - (end_seqnum - seqnum));
} else {
return -1;
}
}
/** Return the first index matching with given continuity counter **/
private function getFirstIndexfromContinuity(continuity : int) : int {
// look for first fragment matching with given continuity index
var len : int = fragments.length;
for (var i : int = 0; i < len; i++) {
if (fragments[i].continuity == continuity)
return i;
}
return -1;
}
/** Return the first seqnum matching with given continuity counter **/
public function getFirstSeqNumfromContinuity(continuity : int) : Number {
var index : int = getFirstIndexfromContinuity(continuity);
if (index == -1) {
return Number.NEGATIVE_INFINITY;
}
return fragments[index].seqnum;
}
/** Return the last seqnum matching with given continuity counter **/
public function getLastSeqNumfromContinuity(continuity : int) : Number {
var index : int = getLastIndexfromContinuity(continuity);
if (index == -1) {
return Number.NEGATIVE_INFINITY;
}
return fragments[index].seqnum;
}
/** Return the last index matching with given continuity counter **/
private function getLastIndexfromContinuity(continuity : Number) : int {
var firstIndex : int = getFirstIndexfromContinuity(continuity);
if (firstIndex == -1)
return -1;
var lastIndex : int = firstIndex;
// look for first fragment matching with given continuity index
for (var i : int = firstIndex; i < fragments.length; i++) {
if (fragments[i].continuity == continuity)
lastIndex = i;
else
break;
}
return lastIndex;
}
/** set Fragments **/
public function updateFragments(_fragments : Vector.<Fragment>) : void {
var idx_with_metrics : int = -1;
var len : int = _fragments.length;
var continuity_offset : int;
var frag : Fragment;
// update PTS from previous fragments
for (var i : int = 0; i < len; i++) {
frag = getFragmentfromSeqNum(_fragments[i].seqnum);
if (frag != null) {
continuity_offset = frag.continuity - _fragments[i].continuity;
if(!isNaN(frag.data.pts_start)) {
_fragments[i].data = frag.data;
idx_with_metrics = i;
}
}
}
if(continuity_offset) {
CONFIG::LOGGING {
Log.debug("updateFragments: discontinuity sliding from live playlist,take into account discontinuity drift:" + continuity_offset);
}
for (i = 0; i < len; i++) {
_fragments[i].continuity+= continuity_offset;
}
}
updateFragmentsProgramDate(_fragments);
fragments = _fragments;
if (len > 0) {
start_seqnum = _fragments[0].seqnum;
end_seqnum = _fragments[len - 1].seqnum;
if (idx_with_metrics != -1) {
frag = fragments[idx_with_metrics];
// if at least one fragment contains PTS info, recompute PTS information for all fragments
CONFIG::LOGGING {
Log.debug("updateFragments: found PTS info from previous playlist,seqnum/PTS:" + frag.seqnum + "/" + frag.data.pts_start);
}
updateFragment(frag.seqnum, true, frag.data.pts_start, frag.data.pts_start + 1000 * frag.duration);
} else {
CONFIG::LOGGING {
Log.debug("updateFragments: unknown PTS info for this level");
}
duration = _fragments[len - 1].start_time + _fragments[len - 1].duration;
}
averageduration = duration / len;
} else {
duration = 0;
averageduration = 0;
}
}
private function updateFragmentsProgramDate(_fragments : Vector.<Fragment>) : void {
var len : int = _fragments.length;
var continuity : int;
var program_date : Number;
var frag : Fragment;
for (var i : int = 0; i < len; i++) {
frag = _fragments[i];
if (frag.continuity != continuity) {
continuity = frag.continuity;
program_date = 0;
}
if (frag.program_date) {
program_date = frag.program_date + 1000 * frag.duration;
} else if (program_date) {
frag.program_date = program_date;
}
}
}
private function _updatePTS(from_index : int, to_index : int) : void {
// CONFIG::LOGGING {
// Log.info("updateFragmentPTS from/to:" + from_index + "/" + to_index);
// }
var frag_from : Fragment = fragments[from_index];
var frag_to : Fragment = fragments[to_index];
if (frag_from.data.valid && frag_to.data.valid) {
if (!isNaN(frag_to.data.pts_start)) {
// we know PTS[to_index]
frag_to.data.pts_start_computed = frag_to.data.pts_start;
/* normalize computed PTS value based on known PTS value.
* this is to avoid computing wrong fragment duration in case of PTS looping */
var from_pts : Number = PTS.normalize(frag_to.data.pts_start, frag_from.data.pts_start_computed);
/* update fragment duration.
it helps to fix drifts between playlist reported duration and fragment real duration */
if (to_index > from_index) {
frag_from.duration = (frag_to.data.pts_start - from_pts) / 1000;
CONFIG::LOGGING {
if (frag_from.duration < 0) {
Log.error("negative duration computed for " + frag_from + ", there should be some duration drift between playlist and fragment!");
}
}
} else {
frag_to.duration = ( from_pts - frag_to.data.pts_start) / 1000;
CONFIG::LOGGING {
if (frag_to.duration < 0) {
Log.error("negative duration computed for " + frag_to + ", there should be some duration drift between playlist and fragment!");
}
}
}
} else {
// we dont know PTS[to_index]
if (to_index > from_index)
frag_to.data.pts_start_computed = frag_from.data.pts_start_computed + 1000 * frag_from.duration;
else
frag_to.data.pts_start_computed = frag_from.data.pts_start_computed - 1000 * frag_to.duration;
}
}
}
public function updateFragment(seqnum : Number, valid : Boolean, min_pts : Number = 0, max_pts : Number = 0) : void {
// CONFIG::LOGGING {
// Log.info("updatePTS : seqnum/min/max:" + seqnum + '/' + min_pts + '/' + max_pts);
// }
// get fragment from seqnum
var fragIdx : int = getIndexfromSeqNum(seqnum);
if (fragIdx != -1) {
var frag : Fragment = fragments[fragIdx];
// update fragment start PTS + duration
if (valid) {
frag.data.pts_start = min_pts;
frag.data.pts_start_computed = min_pts;
frag.duration = (max_pts - min_pts) / 1000;
} else {
frag.duration = 0;
}
frag.data.valid = valid;
// CONFIG::LOGGING {
// Log.info("SN["+fragments[fragIdx].seqnum+"]:pts/duration:" + fragments[fragIdx].start_pts_computed + "/" + fragments[fragIdx].duration);
// }
// adjust fragment PTS/duration from seqnum-1 to frag 0
for (var i : int = fragIdx; i > 0 && fragments[i - 1].continuity == frag.continuity; i--) {
_updatePTS(i, i - 1);
// CONFIG::LOGGING {
// Log.info("SN["+fragments[i-1].seqnum+"]:pts/duration:" + fragments[i-1].start_pts_computed + "/" + fragments[i-1].duration);
// }
}
// adjust fragment PTS/duration from seqnum to last frag
for (i = fragIdx; i < fragments.length - 1 && fragments[i + 1].continuity == frag.continuity; i++) {
_updatePTS(i, i + 1);
// CONFIG::LOGGING {
// Log.info("SN["+fragments[i+1].seqnum+"]:pts/duration:" + fragments[i+1].start_pts_computed + "/" + fragments[i+1].duration);
// }
}
// second, adjust fragment offset
var start_time_offset : Number = fragments[0].start_time;
var len : int = fragments.length;
for (i = 0; i < len; i++) {
fragments[i].start_time = start_time_offset;
start_time_offset += fragments[i].duration;
// CONFIG::LOGGING {
// Log.info("SN["+fragments[i].seqnum+"]:start_time/continuity/pts/duration:" + fragments[i].start_time + "/" + fragments[i].continuity + "/"+ fragments[i].start_pts_computed + "/" + fragments[i].duration);
// }
}
duration = start_time_offset;
} else {
CONFIG::LOGGING {
Log.error("updateFragment:seqnum " + seqnum + " not found!");
}
}
}
}
}
|
Fix redundantStreamId param type
|
[Mangui.Level] Fix redundantStreamId param type
|
ActionScript
|
mpl-2.0
|
codex-corp/flashls,codex-corp/flashls
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.