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
|
---|---|---|---|---|---|---|---|---|---|
38cbf6a1fc42f95b9606bf8b5f016ef6bdaac86c
|
collect-client/src/main/flex/org/openforis/collect/ui/component/detail/RelevanceDisplayManager.as
|
collect-client/src/main/flex/org/openforis/collect/ui/component/detail/RelevanceDisplayManager.as
|
package org.openforis.collect.ui.component.detail
{
import mx.collections.IList;
import mx.core.UIComponent;
import org.openforis.collect.metamodel.proxy.AttributeDefinitionProxy;
import org.openforis.collect.metamodel.proxy.EntityDefinitionProxy;
import org.openforis.collect.metamodel.proxy.NodeDefinitionProxy;
import org.openforis.collect.metamodel.proxy.UIOptionsProxy;
import org.openforis.collect.model.proxy.CodeAttributeProxy;
import org.openforis.collect.model.proxy.EntityProxy;
import org.openforis.collect.model.proxy.NodeProxy;
import org.openforis.collect.util.UIUtil;
/**
*
* @author S. Ricci
* */
public class RelevanceDisplayManager {
public static const STYLE_NAME_NOT_RELEVANT:String = "notRelevant";
/**
* Display of the error (stylename "error" or "warning" will be set on this component)
*/
private var _display:UIComponent;
public function RelevanceDisplayManager(display:UIComponent) {
this._display = display;
}
public function displayNodeRelevance(parentEntity:EntityProxy, defn:NodeDefinitionProxy):void {
if(parentEntity != null && defn != null) {
if ( canBeHidden(parentEntity, defn) ) {
_display.visible = false;
_display.includeInLayout = false;
} else {
_display.visible = true;
_display.includeInLayout = true;
var relevant:Boolean = parentEntity.isRelevant(defn);
UIUtil.toggleStyleName(_display, STYLE_NAME_NOT_RELEVANT, ! relevant);
}
}
}
public function reset():void {
_display.visible = true;
_display.includeInLayout = true;
UIUtil.removeStyleNames(_display, [
STYLE_NAME_NOT_RELEVANT
]);
}
private function canBeHidden(parentEntity:EntityProxy, childDefn:NodeDefinitionProxy):Boolean {
if ( childDefn.hideWhenNotRelevant ) {
//if nearest parent entity is table, hide fields when all cousins are not relevant and empty
var nearestParentMultipleEntity:EntityDefinitionProxy = childDefn.nearestParentMultipleEntity;
var nodes:IList;
if ( nearestParentMultipleEntity.layout == UIUtil.LAYOUT_TABLE ) {
nodes = parentEntity.getDescendantCousins(childDefn);
} else {
nodes = parentEntity.getChildren(childDefn);
}
//do not hide multiple entities renderer if they are relevant but no entities are defined or it will be impossible to add new entities
if ( childDefn is EntityDefinitionProxy && nodes.length == 0 ) {
var result:Boolean = ! parentEntity.isRelevant(childDefn);
return result;
} else {
//hide table columns when all the cells are not relevant and empty
var allNodesEmptyAndNotRelevant:Boolean = isAllNodesEmptyAndNotRelevant(nodes);
return allNodesEmptyAndNotRelevant;
}
} else {
return false;
}
}
private function isAllNodesEmptyAndNotRelevant(nodes:IList):Boolean {
for each (var node:NodeProxy in nodes) {
if ( node.relevant || (node.userSpecified && ! node.empty)) {
return false;
}
}
return true;
}
}
}
|
package org.openforis.collect.ui.component.detail
{
import mx.collections.IList;
import mx.core.UIComponent;
import org.openforis.collect.metamodel.proxy.AttributeDefinitionProxy;
import org.openforis.collect.metamodel.proxy.BooleanAttributeDefinitionProxy
import org.openforis.collect.metamodel.proxy.EntityDefinitionProxy;
import org.openforis.collect.metamodel.proxy.NodeDefinitionProxy;
import org.openforis.collect.metamodel.proxy.UIOptionsProxy;
import org.openforis.collect.model.proxy.AttributeProxy;
import org.openforis.collect.model.proxy.CodeAttributeProxy;
import org.openforis.collect.model.proxy.EntityProxy;
import org.openforis.collect.model.proxy.NodeProxy;
import org.openforis.collect.util.UIUtil;
/**
*
* @author S. Ricci
* */
public class RelevanceDisplayManager {
public static const STYLE_NAME_NOT_RELEVANT:String = "notRelevant";
/**
* Display of the error (stylename "error" or "warning" will be set on this component)
*/
private var _display:UIComponent;
public function RelevanceDisplayManager(display:UIComponent) {
this._display = display;
}
public function displayNodeRelevance(parentEntity:EntityProxy, defn:NodeDefinitionProxy):void {
if(parentEntity != null && defn != null) {
if ( canBeHidden(parentEntity, defn) ) {
_display.visible = false;
_display.includeInLayout = false;
} else {
_display.visible = true;
_display.includeInLayout = true;
var relevant:Boolean = parentEntity.isRelevant(defn);
UIUtil.toggleStyleName(_display, STYLE_NAME_NOT_RELEVANT, ! relevant);
}
}
}
public function reset():void {
_display.visible = true;
_display.includeInLayout = true;
UIUtil.removeStyleNames(_display, [
STYLE_NAME_NOT_RELEVANT
]);
}
private function canBeHidden(parentEntity:EntityProxy, childDefn:NodeDefinitionProxy):Boolean {
if ( childDefn.hideWhenNotRelevant ) {
//if nearest parent entity is table, hide fields when all cousins are not relevant and empty
var nearestParentMultipleEntity:EntityDefinitionProxy = childDefn.nearestParentMultipleEntity;
var nodes:IList;
if ( nearestParentMultipleEntity.layout == UIUtil.LAYOUT_TABLE ) {
nodes = parentEntity.getDescendantCousins(childDefn);
} else {
nodes = parentEntity.getChildren(childDefn);
}
//do not hide multiple entities renderer if they are relevant but no entities are defined or it will be impossible to add new entities
if ( childDefn is EntityDefinitionProxy && nodes.length == 0 ) {
var result:Boolean = ! parentEntity.isRelevant(childDefn);
return result;
} else {
//hide table columns when all the cells are not relevant and empty
var allNodesEmptyAndNotRelevant:Boolean = isAllNodesEmptyAndNotRelevant(nodes);
return allNodesEmptyAndNotRelevant;
}
} else {
return false;
}
}
private function isAllNodesEmptyAndNotRelevant(nodes:IList):Boolean {
for each (var node:NodeProxy in nodes) {
if (node.relevant) {
return false;
} else if (node.userSpecified) {
if (node.definition is BooleanAttributeDefinitionProxy
&& BooleanAttributeDefinitionProxy(node.definition).affirmativeOnly) {
if (AttributeProxy(node).getField(0).value == true) {
return false;
}
} else if (! node.empty) {
return false;
}
}
}
return true;
}
}
}
|
Hide non-relevant affirmative only boolean attributes when not empty but selected value is "false"
|
Hide non-relevant affirmative only boolean attributes when not empty but
selected value is "false"
|
ActionScript
|
mit
|
openforis/collect,openforis/collect,openforis/collect,openforis/collect
|
e4548eddfc0afe78be2256d6bf49f29e79ab1ecc
|
src/com/esri/viewer/utils/PortalBasemapAppender.as
|
src/com/esri/viewer/utils/PortalBasemapAppender.as
|
///////////////////////////////////////////////////////////////////////////
// Copyright (c) 2010-2011 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.viewer.utils
{
import com.esri.ags.components.IdentityManager;
import com.esri.ags.events.PortalEvent;
import com.esri.ags.portal.Portal;
import com.esri.ags.portal.supportClasses.PortalGroup;
import com.esri.ags.portal.supportClasses.PortalItem;
import com.esri.ags.portal.supportClasses.PortalQueryParameters;
import com.esri.ags.portal.supportClasses.PortalQueryResult;
import com.esri.viewer.AppEvent;
import com.esri.viewer.ConfigData;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.utils.Dictionary;
import mx.resources.ResourceManager;
import mx.rpc.AsyncResponder;
import mx.rpc.Fault;
import mx.rpc.events.FaultEvent;
import mx.utils.ObjectUtil;
public class PortalBasemapAppender extends EventDispatcher
{
private const PORTAL_BASEMAP_APPENDER:String = "PortalBasemapAppender";
private var configData:ConfigData;
private var portalURL:String;
private var portalItemOrder:Array;
private var portalItemToLabel:Dictionary;
private var processedArcGISBasemaps:Array;
private var totalBasemaps:int;
private var totalPossibleArcGISBasemaps:int;
private var comparableDefaultBasemapObjects:Array;
private var defaultBasemapTitle:String;
private var cultureCode:String;
public function PortalBasemapAppender(portalURL:String, configData:ConfigData)
{
this.portalURL = portalURL;
this.configData = configData;
}
public function fetchAndAppendPortalBasemaps():void
{
const idMgrEnabled:Boolean = IdentityManager.instance.enabled;
var portal:Portal = new Portal();
// the Portal constructor enables the IdentityManager so restore it back to what it was
IdentityManager.instance.enabled = idMgrEnabled;
portal.addEventListener(PortalEvent.LOAD, portal_loadHandler);
portal.addEventListener(FaultEvent.FAULT, portal_faultHandler);
cultureCode = toCultureCode(ResourceManager.getInstance().localeChain[0]);
portal.load(portalURL, cultureCode);
}
protected function portal_loadHandler(event:PortalEvent):void
{
var portal:Portal = event.target as Portal;
portal.removeEventListener(PortalEvent.LOAD, portal_loadHandler);
portal.removeEventListener(FaultEvent.FAULT, portal_faultHandler);
comparableDefaultBasemapObjects = getComparableBasemapObjects(portal.info.defaultBasemap);
var queryParams:PortalQueryParameters = PortalQueryParameters.forQuery(portal.info.basemapGalleryGroupQuery);
portal.queryGroups(queryParams, new AsyncResponder(portal_queryGroupsResultHandler, portal_queryGroupsFaultHandler, portal));
}
protected function portal_queryGroupsResultHandler(queryResult:PortalQueryResult, portal:Portal):void
{
if (queryResult.results.length > 0)
{
var portalGroup:PortalGroup = queryResult.results[0];
var queryParams:PortalQueryParameters = PortalQueryParameters.forItemsInGroup(portalGroup.id).withLimit(50).withSortField("name");
portal.queryItems(queryParams, new AsyncResponder(portal_queryItemsResultHandler, portal_queryItemsFaultHandler));
}
else
{
dispatchComplete();
}
}
private function portal_queryItemsResultHandler(queryResult:PortalQueryResult, token:Object = null):void
{
const resultItems:Array = queryResult.results;
totalPossibleArcGISBasemaps = resultItems.length;
portalItemOrder = [];
portalItemToLabel = new Dictionary(true);
processedArcGISBasemaps = [];
totalBasemaps = configData.basemaps.length;
for each (var portalItem:PortalItem in resultItems)
{
portalItemOrder.push(portalItem);
portalItem.getJSONData(new AsyncResponder(portalItem_getJSONDataResultHandler,
portalItem_getJSONDataFaultHandler,
portalItem));
}
}
private function portalItem_getJSONDataResultHandler(itemData:Object, item:PortalItem):void
{
createBasemapLayerObject(itemData, item);
if (isDefaultBasemap(itemData.baseMap))
{
defaultBasemapTitle = itemData.baseMap.title;
}
updateTotalArcGISBasemaps();
}
private function createBasemapLayerObject(itemData:Object, item:PortalItem):void
{
if (!itemData)
{
return;
}
var basemapObject:Object = itemData.baseMap;
var basemapLayerObjects:Array = basemapObject.baseMapLayers;
if (!(basemapObject && basemapLayerObjects))
{
return;
}
var title:String = basemapObject.title;
var iconURL:String = item.thumbnailURL;
var existingBasemapLayerObject:Object = findBasemapLayerObjectById(title);
if (existingBasemapLayerObject)
{
existingBasemapLayerObject.icon = iconURL;
return;
}
portalItemToLabel[item] = title;
var basemapLayerObject:Object = basemapLayerObjects[0];
addBasemapLayerObject(baseMapLayerObjectToLayerXML(title,
basemapLayerObject,
iconURL));
var totalBaseMapLayers:int = basemapLayerObjects.length;
if (totalBaseMapLayers > 1)
{
basemapLayerObject = basemapLayerObjects[1];
addBasemapLayerObject(baseMapLayerObjectToLayerXML(title,
basemapLayerObject,
iconURL));
}
}
private function isDefaultBasemap(basemapObject:Object):Boolean
{
var comparableBasemapObjects:Array = getComparableBasemapObjects(basemapObject);
return (ObjectUtil.compare(comparableBasemapObjects, comparableDefaultBasemapObjects) == 0);
}
private function getComparableBasemapObjects(basemapObject:Object):Array
{
var basemapLayerObjects:Array = basemapObject.baseMapLayers;
var comparableBasemapObjects:Array = [];
var comparableBasemapLayerObject:Object;
for each (var basemapLayerObject:Object in basemapLayerObjects)
{
comparableBasemapLayerObject = {};
if (basemapLayerObject.url)
{
comparableBasemapLayerObject.url = basemapLayerObject.url;
}
if (basemapLayerObject.type)
{
comparableBasemapLayerObject.type = basemapLayerObject.type;
}
comparableBasemapObjects.push(comparableBasemapLayerObject);
}
return comparableBasemapObjects;
}
private function findBasemapLayerObjectById(id:String):Object
{
var layerObjectResult:Object;
var basemapLayerObjects:Array = configData.basemaps;
for each (var layerObject:Object in basemapLayerObjects)
{
if (layerObject.layer && (layerObject.layer.id == id))
{
layerObjectResult = layerObject;
break;
}
}
return layerObjectResult;
}
private function updateTotalArcGISBasemaps():void
{
totalPossibleArcGISBasemaps--;
if (totalPossibleArcGISBasemaps == 0)
{
addArcGISBasemapsToConfig();
dispatchComplete();
}
}
private function dispatchComplete():void
{
dispatchEvent(new Event(Event.COMPLETE));
}
private function addArcGISBasemapsToConfig():void
{
var hasBasemaps:Boolean = (configData.basemaps.length > 0);
if (!hasBasemaps)
{
if (defaultBasemapTitle)
{
setDefaultBasemapVisible();
}
else
{
setFirstBasemapVisible();
}
}
addBasemapsInOrder();
}
private function setDefaultBasemapVisible():void
{
for each (var layerObject:Object in processedArcGISBasemaps)
{
if (defaultBasemapTitle == layerObject.label)
{
layerObject.visible = true;
}
}
}
private function setFirstBasemapVisible():void
{
if (!portalItemOrder || portalItemOrder.length == 0)
{
return;
}
var firstBasemapLabel:String = portalItemToLabel[portalItemOrder[0]];
for each (var layerObject:Object in processedArcGISBasemaps)
{
if (layerObject.label == firstBasemapLabel)
{
layerObject.visible = true;
}
}
}
private function addBasemapsInOrder():void
{
for each (var portalItem:PortalItem in portalItemOrder)
{
for each (var layerObject:Object in processedArcGISBasemaps)
{
if (layerObject.label == portalItemToLabel[portalItem])
{
configData.basemaps.push(layerObject);
}
}
}
}
private function addBasemapLayerObject(layerXML:XML):void
{
if (layerXML)
{
processedArcGISBasemaps.push(LayerObjectUtil.getLayerObject(layerXML,
totalBasemaps++,
false,
configData.bingKey));
}
}
private function baseMapLayerObjectToLayerXML(title:String, basemapLayerObject:Object, iconURL:String = null):XML
{
var layerXML:XML;
const url:String = basemapLayerObject.url;
const type:String = basemapLayerObject.type;
if (url)
{
layerXML = createTiledLayerXML(title, iconURL, url, basemapLayerObject, false);
}
else if (isAllowedType(type))
{
layerXML = createNonEsriLayerXML(title, iconURL, basemapLayerObject, false, type);
}
return layerXML;
}
private function createTiledLayerXML(title:String, iconURL:String, url:String, basemapLayerObject:Object, visible:Boolean):XML
{
var layerXML:XML = <layer label={title}
type="tiled"
icon={iconURL}
url={url}
alpha={basemapLayerObject.opacity}
visible={visible}/>;
return layerXML;
}
private function isAllowedType(type:String):Boolean
{
return type == "OpenStreetMap" ||
(isBingBasemap(type) && hasBingKey());
}
private function createNonEsriLayerXML(title:String, iconURL:String, basemapLayerObject:Object, visible:Boolean, type:String):XML
{
var layerXML:XML = <layer label={title}
icon={iconURL}
type={toViewerNonEsriLayerType(basemapLayerObject.type)}
alpha={basemapLayerObject.opacity}
visible={visible}/>;
if (isBingBasemap(type))
{
layerXML.@style = mapBingStyleFromBasemapType(type);
layerXML.@culture = cultureCode;
}
return layerXML;
}
private function toViewerNonEsriLayerType(type:String):String
{
var viewerType:String;
if (type == "OpenStreetMap")
{
viewerType = "osm";
}
else if (isBingBasemap(type))
{
viewerType = "bing";
}
return viewerType;
}
private function isBingBasemap(type:String):Boolean
{
return type && type.indexOf('BingMaps') > -1;
}
private function hasBingKey():Boolean
{
var bingKey:String = configData.bingKey;
return (bingKey != null && bingKey.length > 0);
}
private function mapBingStyleFromBasemapType(type:String):String
{
if (type == 'BingMapsAerial')
{
return 'aerial';
}
else if (type == 'BingMapsHybrid')
{
return 'aerialWithLabels';
}
else
{
//default - BingMapsRoad
return 'road';
}
}
private function portalItem_getJSONDataFaultHandler(fault:Fault, token:Object = null):void
{
AppEvent.dispatch(AppEvent.APP_ERROR,
LocalizationUtil.getDefaultString("couldNotFetchBasemapData",
fault.faultString));
updateTotalArcGISBasemaps();
}
private function portal_queryGroupsFaultHandler(fault:Fault, token:Object = null):void
{
AppEvent.showError(LocalizationUtil.getDefaultString("couldNotQueryPortal"), PORTAL_BASEMAP_APPENDER);
dispatchComplete();
}
private function portal_queryItemsFaultHandler(fault:Fault, token:Object = null):void
{
AppEvent.showError(LocalizationUtil.getDefaultString("couldNotQueryPortalItems"), PORTAL_BASEMAP_APPENDER);
dispatchComplete();
}
private function portal_faultHandler(event:FaultEvent):void
{
var portal:Portal = event.target as Portal;
portal.removeEventListener(PortalEvent.LOAD, portal_loadHandler);
portal.removeEventListener(FaultEvent.FAULT, portal_faultHandler);
AppEvent.showError(LocalizationUtil.getDefaultString("couldNotConnectToPortal"), PORTAL_BASEMAP_APPENDER);
dispatchComplete();
}
private function toCultureCode(locale:String):String
{
return locale ? locale.replace('_', '-') : locale;
}
}
}
|
///////////////////////////////////////////////////////////////////////////
// Copyright (c) 2010-2011 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.viewer.utils
{
import com.esri.ags.components.IdentityManager;
import com.esri.ags.events.PortalEvent;
import com.esri.ags.portal.Portal;
import com.esri.ags.portal.supportClasses.PortalGroup;
import com.esri.ags.portal.supportClasses.PortalItem;
import com.esri.ags.portal.supportClasses.PortalQueryParameters;
import com.esri.ags.portal.supportClasses.PortalQueryResult;
import com.esri.viewer.AppEvent;
import com.esri.viewer.ConfigData;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.utils.Dictionary;
import mx.resources.ResourceManager;
import mx.rpc.AsyncResponder;
import mx.rpc.Fault;
import mx.rpc.events.FaultEvent;
import mx.utils.ObjectUtil;
public class PortalBasemapAppender extends EventDispatcher
{
private const PORTAL_BASEMAP_APPENDER:String = "PortalBasemapAppender";
private var configData:ConfigData;
private var portalURL:String;
private var portalItemOrder:Array;
private var portalItemToLabel:Dictionary;
private var processedArcGISBasemaps:Array;
private var totalBasemaps:int;
private var totalPossibleArcGISBasemaps:int;
private var comparableDefaultBasemapObjects:Array;
private var defaultBasemapTitle:String;
private var cultureCode:String;
public function PortalBasemapAppender(portalURL:String, configData:ConfigData)
{
this.portalURL = portalURL;
this.configData = configData;
}
public function fetchAndAppendPortalBasemaps():void
{
const idMgrEnabled:Boolean = IdentityManager.instance.enabled;
var portal:Portal = new Portal();
// the Portal constructor enables the IdentityManager so restore it back to what it was
IdentityManager.instance.enabled = idMgrEnabled;
portal.addEventListener(PortalEvent.LOAD, portal_loadHandler);
portal.addEventListener(FaultEvent.FAULT, portal_faultHandler);
cultureCode = toCultureCode(ResourceManager.getInstance().localeChain[0]);
portal.load(portalURL, cultureCode);
}
protected function portal_loadHandler(event:PortalEvent):void
{
var portal:Portal = event.target as Portal;
portal.removeEventListener(PortalEvent.LOAD, portal_loadHandler);
portal.removeEventListener(FaultEvent.FAULT, portal_faultHandler);
comparableDefaultBasemapObjects = getComparableBasemapObjects(portal.info.defaultBasemap);
var queryParams:PortalQueryParameters = PortalQueryParameters.forQuery(portal.info.basemapGalleryGroupQuery);
portal.queryGroups(queryParams, new AsyncResponder(portal_queryGroupsResultHandler, portal_queryGroupsFaultHandler, portal));
}
protected function portal_queryGroupsResultHandler(queryResult:PortalQueryResult, portal:Portal):void
{
if (queryResult.results.length > 0)
{
var portalGroup:PortalGroup = queryResult.results[0];
var queryParams:PortalQueryParameters = PortalQueryParameters.forItemsInGroup(portalGroup.id).withLimit(50).withSortField("name");
portal.queryItems(queryParams, new AsyncResponder(portal_queryItemsResultHandler, portal_queryItemsFaultHandler));
}
else
{
dispatchComplete();
}
}
private function portal_queryItemsResultHandler(queryResult:PortalQueryResult, token:Object = null):void
{
const resultItems:Array = queryResult.results;
totalPossibleArcGISBasemaps = resultItems.length;
portalItemOrder = [];
portalItemToLabel = new Dictionary(true);
processedArcGISBasemaps = [];
totalBasemaps = configData.basemaps.length;
for each (var portalItem:PortalItem in resultItems)
{
portalItemOrder.push(portalItem);
portalItem.getJSONData(new AsyncResponder(portalItem_getJSONDataResultHandler,
portalItem_getJSONDataFaultHandler,
portalItem));
}
}
private function portalItem_getJSONDataResultHandler(itemData:Object, item:PortalItem):void
{
createBasemapLayerObjectFromWebMapItemAndData(item, itemData);
if (isDefaultBasemap(itemData.baseMap))
{
defaultBasemapTitle = itemData.baseMap.title;
}
updateTotalArcGISBasemaps();
}
private function createBasemapLayerObjectFromWebMapItemAndData(item:PortalItem, itemData:Object):void
{
if (!itemData)
{
return;
}
var basemapObject:Object = itemData.baseMap;
var basemapLayerObjects:Array = basemapObject.baseMapLayers;
if (!(basemapObject && basemapLayerObjects))
{
return;
}
var title:String = basemapObject.title;
var iconURL:String = item.thumbnailURL;
var existingBasemapLayerObject:Object = findBasemapLayerObjectById(title);
if (existingBasemapLayerObject)
{
existingBasemapLayerObject.icon = iconURL;
return;
}
portalItemToLabel[item] = title;
var basemapLayerObject:Object = basemapLayerObjects[0];
addBasemapLayerObject(baseMapLayerObjectToLayerXML(title,
basemapLayerObject,
iconURL));
var totalBaseMapLayers:int = basemapLayerObjects.length;
if (totalBaseMapLayers > 1)
{
basemapLayerObject = basemapLayerObjects[1];
addBasemapLayerObject(baseMapLayerObjectToLayerXML(title,
basemapLayerObject,
iconURL));
}
}
private function isDefaultBasemap(basemapObject:Object):Boolean
{
var comparableBasemapObjects:Array = getComparableBasemapObjects(basemapObject);
return (ObjectUtil.compare(comparableBasemapObjects, comparableDefaultBasemapObjects) == 0);
}
private function getComparableBasemapObjects(basemapObject:Object):Array
{
var basemapLayerObjects:Array = basemapObject.baseMapLayers;
var comparableBasemapObjects:Array = [];
var comparableBasemapLayerObject:Object;
for each (var basemapLayerObject:Object in basemapLayerObjects)
{
comparableBasemapLayerObject = {};
if (basemapLayerObject.url)
{
comparableBasemapLayerObject.url = basemapLayerObject.url;
}
if (basemapLayerObject.type)
{
comparableBasemapLayerObject.type = basemapLayerObject.type;
}
comparableBasemapObjects.push(comparableBasemapLayerObject);
}
return comparableBasemapObjects;
}
private function findBasemapLayerObjectById(id:String):Object
{
var layerObjectResult:Object;
var basemapLayerObjects:Array = configData.basemaps;
for each (var layerObject:Object in basemapLayerObjects)
{
if (layerObject.layer && (layerObject.layer.id == id))
{
layerObjectResult = layerObject;
break;
}
}
return layerObjectResult;
}
private function updateTotalArcGISBasemaps():void
{
totalPossibleArcGISBasemaps--;
if (totalPossibleArcGISBasemaps == 0)
{
addArcGISBasemapsToConfig();
dispatchComplete();
}
}
private function dispatchComplete():void
{
dispatchEvent(new Event(Event.COMPLETE));
}
private function addArcGISBasemapsToConfig():void
{
var hasBasemaps:Boolean = (configData.basemaps.length > 0);
if (!hasBasemaps)
{
if (defaultBasemapTitle)
{
setDefaultBasemapVisible();
}
else
{
setFirstBasemapVisible();
}
}
addBasemapsInOrder();
}
private function setDefaultBasemapVisible():void
{
for each (var layerObject:Object in processedArcGISBasemaps)
{
if (defaultBasemapTitle == layerObject.label)
{
layerObject.visible = true;
}
}
}
private function setFirstBasemapVisible():void
{
if (!portalItemOrder || portalItemOrder.length == 0)
{
return;
}
var firstBasemapLabel:String = portalItemToLabel[portalItemOrder[0]];
for each (var layerObject:Object in processedArcGISBasemaps)
{
if (layerObject.label == firstBasemapLabel)
{
layerObject.visible = true;
}
}
}
private function addBasemapsInOrder():void
{
for each (var portalItem:PortalItem in portalItemOrder)
{
for each (var layerObject:Object in processedArcGISBasemaps)
{
if (layerObject.label == portalItemToLabel[portalItem])
{
configData.basemaps.push(layerObject);
}
}
}
}
private function addBasemapLayerObject(layerXML:XML):void
{
if (layerXML)
{
processedArcGISBasemaps.push(LayerObjectUtil.getLayerObject(layerXML,
totalBasemaps++,
false,
configData.bingKey));
}
}
private function baseMapLayerObjectToLayerXML(title:String, basemapLayerObject:Object, iconURL:String = null):XML
{
var layerXML:XML;
const url:String = basemapLayerObject.url;
const type:String = basemapLayerObject.type;
if (url)
{
layerXML = createTiledLayerXML(title, iconURL, url, basemapLayerObject, false);
}
else if (isNonEsriType(type))
{
layerXML = createNonEsriLayerXML(title, iconURL, basemapLayerObject, false, type);
}
return layerXML;
}
private function createTiledLayerXML(title:String, iconURL:String, url:String, basemapLayerObject:Object, visible:Boolean):XML
{
var layerXML:XML = <layer label={title}
type="tiled"
icon={iconURL}
url={url}
alpha={basemapLayerObject.opacity}
visible={visible}/>;
return layerXML;
}
private function isNonEsriType(type:String):Boolean
{
return type == "OpenStreetMap" ||
(isBingBasemap(type) && hasBingKey());
}
private function createNonEsriLayerXML(title:String, iconURL:String, basemapLayerObject:Object, visible:Boolean, type:String):XML
{
var layerXML:XML = <layer label={title}
icon={iconURL}
type={toViewerNonEsriLayerType(basemapLayerObject.type)}
alpha={basemapLayerObject.opacity}
visible={visible}/>;
if (isBingBasemap(type))
{
layerXML.@style = mapBingStyleFromBasemapType(type);
layerXML.@culture = cultureCode;
}
return layerXML;
}
private function toViewerNonEsriLayerType(type:String):String
{
var viewerType:String;
if (type == "OpenStreetMap")
{
viewerType = "osm";
}
else if (isBingBasemap(type))
{
viewerType = "bing";
}
return viewerType;
}
private function isBingBasemap(type:String):Boolean
{
return type && type.indexOf('BingMaps') > -1;
}
private function hasBingKey():Boolean
{
var bingKey:String = configData.bingKey;
return (bingKey != null && bingKey.length > 0);
}
private function mapBingStyleFromBasemapType(type:String):String
{
if (type == 'BingMapsAerial')
{
return 'aerial';
}
else if (type == 'BingMapsHybrid')
{
return 'aerialWithLabels';
}
else
{
//default - BingMapsRoad
return 'road';
}
}
private function portalItem_getJSONDataFaultHandler(fault:Fault, token:Object = null):void
{
AppEvent.dispatch(AppEvent.APP_ERROR,
LocalizationUtil.getDefaultString("couldNotFetchBasemapData",
fault.faultString));
updateTotalArcGISBasemaps();
}
private function portal_queryGroupsFaultHandler(fault:Fault, token:Object = null):void
{
AppEvent.showError(LocalizationUtil.getDefaultString("couldNotQueryPortal"), PORTAL_BASEMAP_APPENDER);
dispatchComplete();
}
private function portal_queryItemsFaultHandler(fault:Fault, token:Object = null):void
{
AppEvent.showError(LocalizationUtil.getDefaultString("couldNotQueryPortalItems"), PORTAL_BASEMAP_APPENDER);
dispatchComplete();
}
private function portal_faultHandler(event:FaultEvent):void
{
var portal:Portal = event.target as Portal;
portal.removeEventListener(PortalEvent.LOAD, portal_loadHandler);
portal.removeEventListener(FaultEvent.FAULT, portal_faultHandler);
AppEvent.showError(LocalizationUtil.getDefaultString("couldNotConnectToPortal"), PORTAL_BASEMAP_APPENDER);
dispatchComplete();
}
private function toCultureCode(locale:String):String
{
return locale ? locale.replace('_', '-') : locale;
}
}
}
|
Clean up.
|
Clean up.
|
ActionScript
|
apache-2.0
|
CanterburyRegionalCouncil/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex,Esri/arcgis-viewer-flex,Esri/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex
|
0582deee9113e24fef45d1be5db97860bad67c01
|
src/org/mangui/osmf/plugins/traits/HLSPlayTrait.as
|
src/org/mangui/osmf/plugins/traits/HLSPlayTrait.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.osmf.plugins.traits {
import org.mangui.hls.HLS;
import org.mangui.hls.constant.HLSPlayStates;
import org.mangui.hls.event.HLSEvent;
import org.osmf.traits.PlayState;
import org.osmf.traits.PlayTrait;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
public class HLSPlayTrait extends PlayTrait
{
private var _hls : HLS;
private var streamStarted : Boolean = false;
public function HLSPlayTrait(hls : HLS)
{
CONFIG::LOGGING {
Log.debug("HLSPlayTrait()");
}
super();
_hls = hls;
_hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateChangedHandler);
_hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _playbackComplete);
}
override public function dispose() : void
{
CONFIG::LOGGING {
Log.debug("HLSPlayTrait:dispose");
}
_hls.removeEventListener(HLSEvent.PLAYBACK_STATE, _stateChangedHandler);
_hls.removeEventListener(HLSEvent.PLAYBACK_COMPLETE, _playbackComplete);
super.dispose();
}
override protected function playStateChangeStart(newPlayState:String):void
{
CONFIG::LOGGING
{
Log.info("HLSPlayTrait:playStateChangeStart:" + newPlayState);
}
switch (newPlayState)
{
case PlayState.PLAYING:
if (!streamStarted)
{
_hls.stream.play();
streamStarted = true;
}
else
{
_hls.stream.resume();
}
break;
case PlayState.PAUSED:
_hls.stream.pause();
break;
case PlayState.STOPPED:
streamStarted = false;
_hls.stream.close();
break;
}
}
/** state changed handler **/
private function _stateChangedHandler(event:HLSEvent):void
{
switch (event.state)
{
case HLSPlayStates.PLAYING:
CONFIG::LOGGING
{
Log.debug("HLSPlayTrait:_stateChangedHandler:setBuffering(true)");
}
if (!streamStarted)
{
streamStarted = true;
play();
}
default:
}
}
/** playback complete handler **/
private function _playbackComplete(event : HLSEvent) : void {
stop();
}
}
}
|
/* 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.osmf.plugins.traits {
import org.mangui.hls.HLS;
import org.mangui.hls.constant.HLSPlayStates;
import org.mangui.hls.event.HLSEvent;
import org.osmf.traits.PlayState;
import org.osmf.traits.PlayTrait;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
public class HLSPlayTrait extends PlayTrait
{
private var _hls : HLS;
private var streamStarted : Boolean = false;
public function HLSPlayTrait(hls : HLS)
{
CONFIG::LOGGING {
Log.debug("HLSPlayTrait()");
}
super();
_hls = hls;
_hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateChangedHandler);
_hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _playbackComplete);
}
override public function dispose() : void
{
CONFIG::LOGGING {
Log.debug("HLSPlayTrait:dispose");
}
_hls.removeEventListener(HLSEvent.PLAYBACK_STATE, _stateChangedHandler);
_hls.removeEventListener(HLSEvent.PLAYBACK_COMPLETE, _playbackComplete);
super.dispose();
}
override protected function playStateChangeStart(newPlayState:String):void
{
CONFIG::LOGGING
{
Log.info("HLSPlayTrait:playStateChangeStart:" + newPlayState);
}
switch (newPlayState)
{
case PlayState.PLAYING:
if (!streamStarted)
{
_hls.stream.play();
streamStarted = true;
}
else
{
_hls.stream.resume();
}
break;
case PlayState.PAUSED:
_hls.stream.pause();
break;
case PlayState.STOPPED:
streamStarted = false;
_hls.stream.close();
break;
}
}
/** state changed handler **/
private function _stateChangedHandler(event:HLSEvent):void {
switch (event.state) {
case HLSPlayStates.PLAYING:
CONFIG::LOGGING {
Log.debug("HLSPlayTrait:_stateChangedHandler:setBuffering(true)");
}
if (!streamStarted) {
streamStarted = true;
play();
}
default:
}
}
/** playback complete handler **/
private function _playbackComplete(event : HLSEvent) : void {
stop();
}
}
}
|
fix indents and spaces
|
fix indents and spaces
|
ActionScript
|
mpl-2.0
|
codex-corp/flashls,clappr/flashls,loungelogic/flashls,mangui/flashls,neilrackett/flashls,tedconf/flashls,tedconf/flashls,jlacivita/flashls,fixedmachine/flashls,hola/flashls,hola/flashls,mangui/flashls,NicolasSiver/flashls,NicolasSiver/flashls,vidible/vdb-flashls,loungelogic/flashls,neilrackett/flashls,codex-corp/flashls,clappr/flashls,fixedmachine/flashls,thdtjsdn/flashls,thdtjsdn/flashls,vidible/vdb-flashls,jlacivita/flashls
|
9066bc86d2a95c957f2016b62a28b4d52cb7156f
|
src/aerys/minko/scene/node/Camera.as
|
src/aerys/minko/scene/node/Camera.as
|
package aerys.minko.scene.node
{
import aerys.minko.render.Viewport;
import aerys.minko.scene.controller.camera.CameraController;
import aerys.minko.type.Signal;
import aerys.minko.type.data.IDataProvider;
import aerys.minko.type.math.Frustum;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
/**
* Camera objects describe the position and the look-at point of a 3D camera.
*
* @author Jean-Marc Le Roux
*
*/
public final class Camera extends AbstractSceneNode implements IDataProvider
{
public static const DEFAULT_FOV : Number = Math.PI * .25;
public static const DEFAULT_ZNEAR : Number = .1;
public static const DEFAULT_ZFAR : Number = 1000.;
private static const DATA_DESCRIPTOR : Object = {
"camera position" : "position",
"camera look at" : "lookAt",
"camera up" : "up",
"camera world position" : "worldPosition",
"camera world look at" : "worldLookAt",
"camera world up" : "worldUp",
"camera fov" : "fieldOfView",
"camera z near" : "zNear",
"camera z far" : "zFar",
"world to view" : "worldToView",
"projection" : "projection",
"world to screen" : "worldToScreen"
};
private var _viewport : Viewport = null;
private var _position : Vector4 = new Vector4(0, 0, 0);
private var _lookAt : Vector4 = new Vector4(0, 0, 1);
private var _up : Vector4 = new Vector4(0, 1, 0);
private var _worldToView : Matrix4x4 = new Matrix4x4();
private var _worldPosition : Vector4 = new Vector4();
private var _worldLookAt : Vector4 = new Vector4();
private var _worldUp : Vector4 = new Vector4();
private var _fov : Number = 0;
private var _zNear : Number = 0;
private var _zFar : Number = 0;
private var _frustum : Frustum = new Frustum();
private var _projection : Matrix4x4 = new Matrix4x4();
private var _worldToScreen : Matrix4x4 = new Matrix4x4();
private var _locked : Boolean = false;
private var _changed : Signal = new Signal();
public function get viewport() : Viewport
{
return _viewport;
}
/**
* The position of the camera in local space.
* @return
*
*/
public function get position() : Vector4
{
return _position;
}
/**
* The look-at point of the camera in local space.
* @return
*
*/
public function get lookAt() : Vector4
{
return _lookAt;
}
/**
* The up axis of the camera in local space. Default value
* is the +Y axis.
* @return
*
*/
public function get up() : Vector4
{
return _up;
}
/**
* The position of the camera in world space. This value is
* updated everytime:
* <ul>
* <li>The parent 3D transformation changes.</li>
* <li>The "position" property changes.</li>
* </ul>
* @return
*
*/
public function get worldPosition() : Vector4
{
return _worldPosition;
}
/**
* The look-at point of the camera in world space. This value is
* updated everytime:
* <ul>
* <li>The parent 3D transformation changes.</li>
* <li>The "lookAt" property changes.</li>
* </ul>
* @return
*
*/
public function get worldLookAt() : Vector4
{
return _worldLookAt;
}
/**
* The up axis of the camera in world space. This value is
* updated everytime:
* <ul>
* <li>The parent 3D transformation changes.</li>
* <li>The "up" property changes.</li>
* </ul>
* @return
*
*/
public function get worldUp() : Vector4
{
return _worldUp;
}
/**
* The matrix that transforms world space coordinates
* into view (or camera) space coordinates.
* @return
*
*/
public function get worldToView() : Matrix4x4
{
return _worldToView;
}
/**
* The matrix that transforms view space coordinates
* into clip space (or normalized screen space) coordinates.
* @return
*
*/
public function get projection() : Matrix4x4
{
return _projection;
}
/**
* The matrix that transforms world space coordinates
* into clip space (or normalized space) coordinates.
* @return
*
*/
public function get worldToScreen() : Matrix4x4
{
return _worldToScreen;
}
/**
* The field of view of the camera. Setting this property
* will update the projection matrix and trigger the "changed"
* signal.
* @return
*
*/
public function get fieldOfView() : Number
{
return _fov;
}
public function set fieldOfView(value : Number) : void
{
_fov = value;
if (!_locked)
_changed.execute(this, "fieldOfView");
}
/**
* The z-near clipping plane of the camera. Setting this
* property will update the projection matrix and trigger the "changed"
* signal.
* @return
*
*/
public function get zNear() : Number
{
return _zNear;
}
public function set zNear(value : Number) : void
{
_zNear = value;
if (!_locked)
_changed.execute(this, "zNear");
}
/**
* The z-far clipping plane of the camera. Setting this property
* will update the projection matrix and trigger the "changed"
* signal.
* @return
*
*/
public function get zFar() : Number
{
return _zFar;
}
public function set zFar(value : Number) : void
{
_zFar = value;
if (!_locked)
_changed.execute(this, "zFar");
}
public function get frustum() : Frustum
{
return _frustum;
}
public function get locked() : Boolean
{
return _locked;
}
public function get changed() : Signal
{
return _changed;
}
public function get dataDescriptor() : Object
{
return DATA_DESCRIPTOR;
}
public function Camera(viewport : Viewport,
fieldOfView : Number = DEFAULT_FOV,
zNear : Number = DEFAULT_ZNEAR,
zFar : Number = DEFAULT_ZFAR)
{
super();
_viewport = viewport;
_fov = fieldOfView;
_zNear = zNear;
_zFar = zFar;
addController(new CameraController(viewport));
}
public function lock() : void
{
_locked = true;
}
public function unlock() : void
{
var locked : Boolean = _locked;
_locked = false;
if (locked)
_changed.execute(this, null);
}
}
}
|
package aerys.minko.scene.node
{
import aerys.minko.render.Viewport;
import aerys.minko.scene.controller.camera.CameraController;
import aerys.minko.type.Signal;
import aerys.minko.type.data.IDataProvider;
import aerys.minko.type.math.Frustum;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
/**
* Camera objects describe the position and the look-at point of a 3D camera.
*
* @author Jean-Marc Le Roux
*
*/
public class Camera extends AbstractSceneNode implements IDataProvider
{
public static const DEFAULT_FOV : Number = Math.PI * .25;
public static const DEFAULT_ZNEAR : Number = .1;
public static const DEFAULT_ZFAR : Number = 1000.;
private static const DATA_DESCRIPTOR : Object = {
"camera position" : "position",
"camera look at" : "lookAt",
"camera up" : "up",
"camera world position" : "worldPosition",
"camera world look at" : "worldLookAt",
"camera world up" : "worldUp",
"camera fov" : "fieldOfView",
"camera z near" : "zNear",
"camera z far" : "zFar",
"world to view" : "worldToView",
"projection" : "projection",
"world to screen" : "worldToScreen"
};
private var _viewport : Viewport = null;
private var _position : Vector4 = new Vector4(0, 0, 0);
private var _lookAt : Vector4 = new Vector4(0, 0, 1);
private var _up : Vector4 = new Vector4(0, 1, 0);
private var _worldToView : Matrix4x4 = new Matrix4x4();
private var _worldPosition : Vector4 = new Vector4();
private var _worldLookAt : Vector4 = new Vector4();
private var _worldUp : Vector4 = new Vector4();
private var _fov : Number = 0;
private var _zNear : Number = 0;
private var _zFar : Number = 0;
private var _frustum : Frustum = new Frustum();
private var _projection : Matrix4x4 = new Matrix4x4();
private var _worldToScreen : Matrix4x4 = new Matrix4x4();
private var _locked : Boolean = false;
private var _changed : Signal = new Signal();
public function get viewport() : Viewport
{
return _viewport;
}
/**
* The position of the camera in local space.
* @return
*
*/
public function get position() : Vector4
{
return _position;
}
/**
* The look-at point of the camera in local space.
* @return
*
*/
public function get lookAt() : Vector4
{
return _lookAt;
}
/**
* The up axis of the camera in local space. Default value
* is the +Y axis.
* @return
*
*/
public function get up() : Vector4
{
return _up;
}
/**
* The position of the camera in world space. This value is
* updated everytime:
* <ul>
* <li>The parent 3D transformation changes.</li>
* <li>The "position" property changes.</li>
* </ul>
* @return
*
*/
public function get worldPosition() : Vector4
{
return _worldPosition;
}
/**
* The look-at point of the camera in world space. This value is
* updated everytime:
* <ul>
* <li>The parent 3D transformation changes.</li>
* <li>The "lookAt" property changes.</li>
* </ul>
* @return
*
*/
public function get worldLookAt() : Vector4
{
return _worldLookAt;
}
/**
* The up axis of the camera in world space. This value is
* updated everytime:
* <ul>
* <li>The parent 3D transformation changes.</li>
* <li>The "up" property changes.</li>
* </ul>
* @return
*
*/
public function get worldUp() : Vector4
{
return _worldUp;
}
/**
* The matrix that transforms world space coordinates
* into view (or camera) space coordinates.
* @return
*
*/
public function get worldToView() : Matrix4x4
{
return _worldToView;
}
/**
* The matrix that transforms view space coordinates
* into clip space (or normalized screen space) coordinates.
* @return
*
*/
public function get projection() : Matrix4x4
{
return _projection;
}
/**
* The matrix that transforms world space coordinates
* into clip space (or normalized space) coordinates.
* @return
*
*/
public function get worldToScreen() : Matrix4x4
{
return _worldToScreen;
}
/**
* The field of view of the camera. Setting this property
* will update the projection matrix and trigger the "changed"
* signal.
* @return
*
*/
public function get fieldOfView() : Number
{
return _fov;
}
public function set fieldOfView(value : Number) : void
{
_fov = value;
if (!_locked)
_changed.execute(this, "fieldOfView");
}
/**
* The z-near clipping plane of the camera. Setting this
* property will update the projection matrix and trigger the "changed"
* signal.
* @return
*
*/
public function get zNear() : Number
{
return _zNear;
}
public function set zNear(value : Number) : void
{
_zNear = value;
if (!_locked)
_changed.execute(this, "zNear");
}
/**
* The z-far clipping plane of the camera. Setting this property
* will update the projection matrix and trigger the "changed"
* signal.
* @return
*
*/
public function get zFar() : Number
{
return _zFar;
}
public function set zFar(value : Number) : void
{
_zFar = value;
if (!_locked)
_changed.execute(this, "zFar");
}
public function get frustum() : Frustum
{
return _frustum;
}
public function get locked() : Boolean
{
return _locked;
}
public function get changed() : Signal
{
return _changed;
}
public function get dataDescriptor() : Object
{
return DATA_DESCRIPTOR;
}
public function Camera(viewport : Viewport,
fieldOfView : Number = DEFAULT_FOV,
zNear : Number = DEFAULT_ZNEAR,
zFar : Number = DEFAULT_ZFAR)
{
super();
_viewport = viewport;
_fov = fieldOfView;
_zNear = zNear;
_zFar = zFar;
addController(new CameraController(viewport));
}
public function lock() : void
{
_locked = true;
}
public function unlock() : void
{
var locked : Boolean = _locked;
_locked = false;
if (locked)
_changed.execute(this, null);
}
}
}
|
Remove final from Camera.
|
Remove final from Camera.
|
ActionScript
|
mit
|
aerys/minko-as3
|
19b3ec3533ba4bed538afd50ec0d10ac83f6e146
|
src/main/org/shypl/common/util/SimplePath.as
|
src/main/org/shypl/common/util/SimplePath.as
|
package org.shypl.common.util {
import org.shypl.common.lang.IllegalStateException;
public class SimplePath implements Path {
private var _value:String;
public function SimplePath(value:String = null) {
if (value === "") {
value = null;
}
else if (value !== null) {
while (StringUtils.endsWith(value, "/")) {
value = value.substr(0, -1);
}
}
_value = value;
}
public function get empty():Boolean {
return _value === null;
}
public function get parent():Path {
if (_value === null) {
throw new IllegalStateException();
}
var i:int = _value.lastIndexOf("/");
if (i === -1) {
throw new IllegalStateException();
}
return factoryPath(_value.substring(0, i));
}
public function get value():String {
return _value;
}
public function resolve(path:String):Path {
var i:int;
var p:Path = this;
while ((i = path.indexOf("../")) >= 0) {
p = p.parent;
path = path.substr(3);
}
return factoryPath(p.empty ? path : (p.value + "/" + path));
}
public function resolveSibling(path:String):Path {
return parent.resolve(path);
}
public function toString():String {
return _value;
}
protected function factoryPath(value:String):Path {
return new SimplePath(value);
}
}
}
|
package org.shypl.common.util {
import org.shypl.common.lang.IllegalStateException;
public class SimplePath implements Path {
private var _value:String;
public function SimplePath(value:String = null) {
if (value === "") {
value = null;
}
else if (value !== null) {
while (StringUtils.endsWith(value, "/")) {
value = value.substr(0, -1);
}
}
_value = value;
}
public function get empty():Boolean {
return _value === null;
}
public function get parent():Path {
if (_value === null) {
throw new IllegalStateException();
}
var i:int = _value.lastIndexOf("/");
if (i === -1) {
throw new IllegalStateException();
}
return factoryPath(_value.substring(0, i));
}
public function get value():String {
return _value;
}
public function resolve(path:String):Path {
var i:int;
var p:Path = this;
while ((i = path.indexOf("..")) == 0) {
p = p.parent;
if (path.indexOf("../") == 0) {
path = path.substr(3);
}
else {
path = path.substr(2);
}
}
return factoryPath(p.empty ? path : (p.value + "/" + path));
}
public function resolveSibling(path:String):Path {
return parent.resolve(path);
}
public function toString():String {
return _value;
}
protected function factoryPath(value:String):Path {
return new SimplePath(value);
}
}
}
|
Refactor Path
|
Refactor Path
|
ActionScript
|
apache-2.0
|
shypl/common-flash
|
bef3536ea2222c4b37c3f8d3c39ca73291e40fd1
|
src/battlecode/client/viewer/render/DrawState.as
|
src/battlecode/client/viewer/render/DrawState.as
|
package battlecode.client.viewer.render {
import battlecode.common.MapLocation;
import battlecode.common.ResearchType;
import battlecode.common.RobotType;
import battlecode.common.Team;
import battlecode.serial.RoundDelta;
import battlecode.serial.RoundStats;
import battlecode.world.GameMap;
import battlecode.world.signals.*;
public class DrawState extends DefaultSignalHandler {
// state
private var mines:Array; // Team[][]
private var neutralEncampments:Object;
private var encampments:Object;
private var groundRobots:Object;
private var hqA:DrawRobot;
private var hqB:DrawRobot;
// stats
private var aPoints:Number;
private var bPoints:Number;
private var aFlux:Number;
private var bFlux:Number;
private var aGatheredPoints:Number;
private var bGatheredPoints:Number;
private var roundNum:uint;
private var progressA:Array;
private var progressB:Array;
private var unitCounts:Object;
// immutables
private var map:GameMap;
private var origin:MapLocation;
public function DrawState(map:GameMap) {
neutralEncampments = new Object();
encampments = new Object();
groundRobots = new Object();
mines = new Array();
for (var i:int = 0; i < map.getWidth(); i++) {
mines[i] = new Array();
for (var j:int = 0; j < map.getHeight(); j++) {
mines[i][j] = null;
}
}
aPoints = 0;
bPoints = 0;
aFlux = 0;
bFlux = 0;
aGatheredPoints = 0;
bGatheredPoints = 0;
roundNum = 1;
progressA = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
progressB = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
unitCounts = new Object();
unitCounts[Team.A] = new Object();
unitCounts[Team.B] = new Object();
for each (var type:String in RobotType.values()) {
unitCounts[Team.A][type] = 0;
unitCounts[Team.B][type] = 0;
}
this.map = map;
this.origin = map.getOrigin();
}
///////////////////////////////////////////////////////
///////////////// PROPERTY GETTERS ////////////////////
///////////////////////////////////////////////////////
public function getMines():Array {
return mines;
}
public function getNeutralEncampments():Object {
return neutralEncampments;
}
public function getEncampments():Object {
return encampments
}
public function getGroundRobots():Object {
return groundRobots;
}
public function getHQ(team:String):DrawRobot {
return team == Team.A ? hqA : hqB;
}
public function getPoints(team:String):uint {
return (team == Team.A) ? aPoints : bPoints;
}
public function getFlux(team:String):uint {
return (team == Team.A) ? aFlux : bFlux;
}
public function getResearchProgress(team:String):Array {
return team == Team.A ? progressA : progressB;
}
public function getUnitCount(type:String, team:String):int {
return unitCounts[team][type];
}
///////////////////////////////////////////////////////
/////////////////// CORE FUNCTIONS ////////////////////
///////////////////////////////////////////////////////
private function copyStateFrom(state:DrawState):void {
var a:*;
mines = new Array();
for (var i:int = 0; i < map.getWidth(); i++) {
mines[i] = new Array();
for (var j:int = 0; j < map.getHeight(); j++) {
mines[i][j] = state.mines[i][j];
}
}
neutralEncampments = new Object();
for (a in state.neutralEncampments) {
neutralEncampments[a] = state.neutralEncampments[a].clone();
}
encampments = new Object();
for (a in state.encampments) {
encampments[a] = state.encampments[a].clone();
}
groundRobots = new Object();
for (a in state.groundRobots) {
groundRobots[a] = state.groundRobots[a].clone();
}
hqA = state.hqA ? state.hqA.clone() as DrawRobot : null;
hqB = state.hqB ? state.hqB.clone() as DrawRobot : null;
progressA = state.progressA.concat();
progressB = state.progressB.concat();
unitCounts = new Object();
unitCounts[Team.A] = new Object();
unitCounts[Team.B] = new Object();
for (a in state.unitCounts[Team.A]) {
unitCounts[Team.A][a] = state.unitCounts[Team.A][a];
unitCounts[Team.B][a] = state.unitCounts[Team.B][a];
}
roundNum = state.roundNum;
}
public function clone():DrawState {
var state:DrawState = new DrawState(map);
state.copyStateFrom(this);
return state;
}
public function applyDelta(delta:RoundDelta):void {
updateRound();
for each (var signal:Signal in delta.getSignals()) {
applySignal(signal);
}
processEndOfRound();
}
public function applySignal(signal:Signal):void {
if (signal != null) signal.accept(this);
}
public function applyStats(stats:RoundStats):void {
aPoints = stats.getPoints(Team.A);
bPoints = stats.getPoints(Team.B);
aGatheredPoints = stats.getGatheredPoints(Team.A);
bGatheredPoints = stats.getGatheredPoints(Team.B);
}
public function updateRound():void {
var a:*, i:uint, j:uint;
var o:DrawRobot;
for (a in groundRobots) {
o = groundRobots[a] as DrawRobot;
o.updateRound();
if (!o.isAlive()) {
if (o.parent) {
o.parent.removeChild(o);
}
delete groundRobots[a];
}
}
for (a in encampments) {
o = encampments[a] as DrawRobot;
o.updateRound();
if (!o.isAlive()) {
if (o.parent) {
o.parent.removeChild(o);
}
delete encampments[a];
}
}
if (hqA) {
hqA.updateRound();
if (!hqA.isAlive()) {
if (hqA.parent) {
hqA.parent.removeChild(hqA);
}
hqA = null;
}
}
if (hqB) {
hqB.updateRound();
if (!hqB.isAlive()) {
if (hqB.parent) {
hqB.parent.removeChild(hqB);
}
hqB = null;
}
}
}
private function processEndOfRound():void {
roundNum++;
}
///////////////////////////////////////////////////////
////////////// PRIVATE HELPER FUNCTIONS ///////////////
///////////////////////////////////////////////////////
private function getRobot(id:uint):DrawRobot {
if (groundRobots[id]) return groundRobots[id] as DrawRobot;
if (encampments[id]) return encampments[id] as DrawRobot;
return null;
}
private function removeRobot(id:uint):void {
if (groundRobots[id]) delete groundRobots[id];
if (encampments[id]) delete encampments[id];
}
private function translateCoordinates(loc:MapLocation):MapLocation {
return new MapLocation(loc.getX() - origin.getX(), loc.getY() - origin.getY());
}
///////////////////////////////////////////////////////
/////////////////// SIGNAL HANDLERS ///////////////////
///////////////////////////////////////////////////////
override public function visitAttackSignal(s:AttackSignal):* {
getRobot(s.getRobotID()).attack(s.getTargetLoc());
}
override public function visitBroadcastSignal(s:BroadcastSignal):* {
getRobot(s.getRobotID()).broadcast();
}
override public function visitCaptureSignal(s:CaptureSignal):* {
var robot:DrawRobot = getRobot(s.getParentID());
robot.capture();
}
override public function visitDeathSignal(s:DeathSignal):* {
var robot:DrawRobot = getRobot(s.getRobotID());
robot.destroyUnit();
if (robot.getType() == RobotType.HQ) {
var hq:DrawRobot = robot.getTeam() == Team.A ? hqA : hqB;
hq.destroyUnit();
}
if (RobotType.isEncampment(robot.getType())) {
var encampment:DrawRobot = new DrawRobot(0, RobotType.ENCAMPMENT, Team.NEUTRAL);
encampment.setLocation(robot.getLocation());
neutralEncampments[robot.getLocation()] = encampment;
}
unitCounts[robot.getTeam()][robot.getType()]--;
}
override public function visitEnergonChangeSignal(s:EnergonChangeSignal):* {
var robotIDs:Array = s.getRobotIDs();
var energon:Array = s.getEnergon();
for (var i:uint; i < robotIDs.length; i++) {
var robot:DrawRobot = getRobot(robotIDs[i]);
robot.setEnergon(energon[i]);
if (robot.getType() == RobotType.HQ) {
var hq:DrawRobot = robot.getTeam() == Team.A ? hqA : hqB;
hq.setEnergon(energon[i]);
}
}
}
override public function visitFluxChangeSignal(s:FluxChangeSignal):* {
aFlux = s.getFlux(Team.A);
bFlux = s.getFlux(Team.B);
}
override public function visitIndicatorStringSignal(s:IndicatorStringSignal):* {
getRobot(s.getRobotID()).setIndicatorString(s.getIndicatorString(), s.getIndex());
}
override public function visitMineSignal(s:MineSignal):* {
var loc:MapLocation = translateCoordinates(s.getLocation());
if (map.isOnMap(loc)) {
if (s.isBirth()) {
if (!mines[loc.getX()][loc.getY()]) {
mines[loc.getX()][loc.getY()] = s.getTeam();
}
} else {
mines[loc.getX()][loc.getY()] = null;
}
}
}
override public function visitMineLayerSignal(s:MineLayerSignal):* {
var robot:DrawRobot = getRobot(s.getRobotID());
if (s.isLaying()) {
robot.layMine();
} else {
var researchProgress:Array = robot.getTeam() == Team.A ? progressA : progressB;
var hasUpgrade:Boolean = researchProgress[ResearchType.getField(ResearchType.DEFUSION)] == 1.0;
robot.diffuseMine(hasUpgrade);
}
}
override public function visitMovementSignal(s:MovementSignal):* {
getRobot(s.getRobotID()).moveToLocation(s.getTargetLoc());
}
override public function visitNodeBirthSignal(s:NodeBirthSignal):* {
var encampment:DrawRobot = new DrawRobot(0, RobotType.ENCAMPMENT, Team.NEUTRAL);
encampment.setLocation(s.getLocation());
neutralEncampments[s.getLocation()] = encampment;
}
override public function visitResearchChangeSignal(s:ResearchChangeSignal):* {
progressA = s.getProgress(Team.A);
progressB = s.getProgress(Team.B);
}
override public function visitSpawnSignal(s:SpawnSignal):* {
var robot:DrawRobot = new DrawRobot(s.getRobotID(), s.getRobotType(), s.getTeam());
robot.setLocation(s.getLocation());
if (s.getRobotType() == RobotType.HQ) {
if (s.getTeam() == Team.A) hqA = robot.clone() as DrawRobot;
if (s.getTeam() == Team.B) hqB = robot.clone() as DrawRobot;
}
if (RobotType.isEncampment(s.getRobotType())) {
var o:DrawRobot = neutralEncampments[s.getLocation()];
if (o) {
if (o.parent) {
o.parent.removeChild(o);
}
delete neutralEncampments[s.getLocation()];
}
encampments[s.getRobotID()] = robot;
} else {
groundRobots[s.getRobotID()] = robot;
}
if (RobotType.isEncampment(s.getRobotType())) {
trace(s.getRobotType())
}
unitCounts[s.getTeam()][s.getRobotType()]++;
}
}
}
|
package battlecode.client.viewer.render {
import battlecode.common.MapLocation;
import battlecode.common.ResearchType;
import battlecode.common.RobotType;
import battlecode.common.Team;
import battlecode.serial.RoundDelta;
import battlecode.serial.RoundStats;
import battlecode.world.GameMap;
import battlecode.world.signals.*;
public class DrawState extends DefaultSignalHandler {
// state
private var mines:Array; // Team[][]
private var neutralEncampments:Object;
private var encampments:Object;
private var groundRobots:Object;
private var hqA:DrawRobot;
private var hqB:DrawRobot;
// stats
private var aPoints:Number;
private var bPoints:Number;
private var aFlux:Number;
private var bFlux:Number;
private var aGatheredPoints:Number;
private var bGatheredPoints:Number;
private var roundNum:uint;
private var progressA:Array;
private var progressB:Array;
private var unitCounts:Object;
// immutables
private var map:GameMap;
private var origin:MapLocation;
public function DrawState(map:GameMap) {
neutralEncampments = new Object();
encampments = new Object();
groundRobots = new Object();
mines = new Array();
for (var i:int = 0; i < map.getWidth(); i++) {
mines[i] = new Array();
for (var j:int = 0; j < map.getHeight(); j++) {
mines[i][j] = null;
}
}
aPoints = 0;
bPoints = 0;
aFlux = 0;
bFlux = 0;
aGatheredPoints = 0;
bGatheredPoints = 0;
roundNum = 1;
progressA = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
progressB = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
unitCounts = new Object();
unitCounts[Team.A] = new Object();
unitCounts[Team.B] = new Object();
for each (var type:String in RobotType.values()) {
unitCounts[Team.A][type] = 0;
unitCounts[Team.B][type] = 0;
}
this.map = map;
this.origin = map.getOrigin();
}
///////////////////////////////////////////////////////
///////////////// PROPERTY GETTERS ////////////////////
///////////////////////////////////////////////////////
public function getMines():Array {
return mines;
}
public function getNeutralEncampments():Object {
return neutralEncampments;
}
public function getEncampments():Object {
return encampments
}
public function getGroundRobots():Object {
return groundRobots;
}
public function getHQ(team:String):DrawRobot {
return team == Team.A ? hqA : hqB;
}
public function getPoints(team:String):uint {
return (team == Team.A) ? aPoints : bPoints;
}
public function getFlux(team:String):uint {
return (team == Team.A) ? aFlux : bFlux;
}
public function getResearchProgress(team:String):Array {
return team == Team.A ? progressA : progressB;
}
public function getUnitCount(type:String, team:String):int {
return unitCounts[team][type];
}
///////////////////////////////////////////////////////
/////////////////// CORE FUNCTIONS ////////////////////
///////////////////////////////////////////////////////
private function copyStateFrom(state:DrawState):void {
var a:*;
mines = new Array();
for (var i:int = 0; i < map.getWidth(); i++) {
mines[i] = new Array();
for (var j:int = 0; j < map.getHeight(); j++) {
mines[i][j] = state.mines[i][j];
}
}
neutralEncampments = new Object();
for (a in state.neutralEncampments) {
neutralEncampments[a] = state.neutralEncampments[a].clone();
}
encampments = new Object();
for (a in state.encampments) {
encampments[a] = state.encampments[a].clone();
}
groundRobots = new Object();
for (a in state.groundRobots) {
groundRobots[a] = state.groundRobots[a].clone();
}
hqA = state.hqA ? state.hqA.clone() as DrawRobot : null;
hqB = state.hqB ? state.hqB.clone() as DrawRobot : null;
progressA = state.progressA.concat();
progressB = state.progressB.concat();
unitCounts = new Object();
unitCounts[Team.A] = new Object();
unitCounts[Team.B] = new Object();
for (a in state.unitCounts[Team.A]) {
unitCounts[Team.A][a] = state.unitCounts[Team.A][a];
unitCounts[Team.B][a] = state.unitCounts[Team.B][a];
}
roundNum = state.roundNum;
}
public function clone():DrawState {
var state:DrawState = new DrawState(map);
state.copyStateFrom(this);
return state;
}
public function applyDelta(delta:RoundDelta):void {
updateRound();
for each (var signal:Signal in delta.getSignals()) {
applySignal(signal);
}
processEndOfRound();
}
public function applySignal(signal:Signal):void {
if (signal != null) signal.accept(this);
}
public function applyStats(stats:RoundStats):void {
aPoints = stats.getPoints(Team.A);
bPoints = stats.getPoints(Team.B);
aGatheredPoints = stats.getGatheredPoints(Team.A);
bGatheredPoints = stats.getGatheredPoints(Team.B);
}
public function updateRound():void {
var a:*, i:uint, j:uint;
var o:DrawRobot;
for (a in groundRobots) {
o = groundRobots[a] as DrawRobot;
o.updateRound();
if (!o.isAlive()) {
if (o.parent) {
o.parent.removeChild(o);
}
delete groundRobots[a];
}
}
for (a in encampments) {
o = encampments[a] as DrawRobot;
o.updateRound();
if (!o.isAlive()) {
if (o.parent) {
o.parent.removeChild(o);
}
delete encampments[a];
}
}
if (hqA) {
hqA.updateRound();
if (!hqA.isAlive()) {
if (hqA.parent) {
hqA.parent.removeChild(hqA);
}
hqA = null;
}
}
if (hqB) {
hqB.updateRound();
if (!hqB.isAlive()) {
if (hqB.parent) {
hqB.parent.removeChild(hqB);
}
hqB = null;
}
}
}
private function processEndOfRound():void {
roundNum++;
}
///////////////////////////////////////////////////////
////////////// PRIVATE HELPER FUNCTIONS ///////////////
///////////////////////////////////////////////////////
private function getRobot(id:uint):DrawRobot {
if (groundRobots[id]) return groundRobots[id] as DrawRobot;
if (encampments[id]) return encampments[id] as DrawRobot;
return null;
}
private function removeRobot(id:uint):void {
if (groundRobots[id]) delete groundRobots[id];
if (encampments[id]) delete encampments[id];
}
private function translateCoordinates(loc:MapLocation):MapLocation {
return new MapLocation(loc.getX() - origin.getX(), loc.getY() - origin.getY());
}
///////////////////////////////////////////////////////
/////////////////// SIGNAL HANDLERS ///////////////////
///////////////////////////////////////////////////////
override public function visitAttackSignal(s:AttackSignal):* {
getRobot(s.getRobotID()).attack(s.getTargetLoc());
}
override public function visitBroadcastSignal(s:BroadcastSignal):* {
getRobot(s.getRobotID()).broadcast();
}
override public function visitCaptureSignal(s:CaptureSignal):* {
var robot:DrawRobot = getRobot(s.getParentID());
robot.capture();
}
override public function visitDeathSignal(s:DeathSignal):* {
var robot:DrawRobot = getRobot(s.getRobotID());
robot.destroyUnit();
if (robot.getType() == RobotType.HQ) {
var hq:DrawRobot = robot.getTeam() == Team.A ? hqA : hqB;
hq.destroyUnit();
}
if (RobotType.isEncampment(robot.getType())) {
var encampment:DrawRobot = new DrawRobot(0, RobotType.ENCAMPMENT, Team.NEUTRAL);
encampment.setLocation(robot.getLocation());
neutralEncampments[robot.getLocation()] = encampment;
}
unitCounts[robot.getTeam()][robot.getType()]--;
}
override public function visitEnergonChangeSignal(s:EnergonChangeSignal):* {
var robotIDs:Array = s.getRobotIDs();
var energon:Array = s.getEnergon();
for (var i:uint; i < robotIDs.length; i++) {
var robot:DrawRobot = getRobot(robotIDs[i]);
robot.setEnergon(energon[i]);
if (robot.getType() == RobotType.HQ) {
var hq:DrawRobot = robot.getTeam() == Team.A ? hqA : hqB;
hq.setEnergon(energon[i]);
}
}
}
override public function visitFluxChangeSignal(s:FluxChangeSignal):* {
aFlux = s.getFlux(Team.A);
bFlux = s.getFlux(Team.B);
}
override public function visitIndicatorStringSignal(s:IndicatorStringSignal):* {
getRobot(s.getRobotID()).setIndicatorString(s.getIndicatorString(), s.getIndex());
}
override public function visitMineSignal(s:MineSignal):* {
var loc:MapLocation = translateCoordinates(s.getLocation());
if (map.isOnMap(loc)) {
if (s.isBirth()) {
if (!mines[loc.getX()][loc.getY()]) {
mines[loc.getX()][loc.getY()] = s.getTeam();
}
} else {
mines[loc.getX()][loc.getY()] = null;
}
}
}
override public function visitMineLayerSignal(s:MineLayerSignal):* {
var robot:DrawRobot = getRobot(s.getRobotID());
if (s.isLaying()) {
robot.layMine();
} else {
var researchProgress:Array = robot.getTeam() == Team.A ? progressA : progressB;
var hasUpgrade:Boolean = researchProgress[ResearchType.getField(ResearchType.DEFUSION)] == 1.0;
robot.diffuseMine(hasUpgrade);
}
}
override public function visitMovementSignal(s:MovementSignal):* {
getRobot(s.getRobotID()).moveToLocation(s.getTargetLoc());
}
override public function visitNodeBirthSignal(s:NodeBirthSignal):* {
var encampment:DrawRobot = new DrawRobot(0, RobotType.ENCAMPMENT, Team.NEUTRAL);
encampment.setLocation(s.getLocation());
neutralEncampments[s.getLocation()] = encampment;
}
override public function visitResearchChangeSignal(s:ResearchChangeSignal):* {
progressA = s.getProgress(Team.A);
progressB = s.getProgress(Team.B);
}
override public function visitSpawnSignal(s:SpawnSignal):* {
var robot:DrawRobot = new DrawRobot(s.getRobotID(), s.getRobotType(), s.getTeam());
robot.setLocation(s.getLocation());
if (s.getRobotType() == RobotType.HQ) {
if (s.getTeam() == Team.A) hqA = robot.clone() as DrawRobot;
if (s.getTeam() == Team.B) hqB = robot.clone() as DrawRobot;
}
if (RobotType.isEncampment(s.getRobotType())) {
var o:DrawRobot = neutralEncampments[s.getLocation()];
if (o) {
if (o.parent) {
o.parent.removeChild(o);
}
delete neutralEncampments[s.getLocation()];
}
encampments[s.getRobotID()] = robot;
} else {
groundRobots[s.getRobotID()] = robot;
}
unitCounts[s.getTeam()][s.getRobotType()]++;
}
}
}
|
remove trace statement
|
remove trace statement
|
ActionScript
|
mit
|
trun/battlecode-webclient
|
c3d5ccd3008ff63f3e9b130d764a16b1a3c49da4
|
source/com/kemsky/support/ValueIterator.as
|
source/com/kemsky/support/ValueIterator.as
|
/*
* Copyright: (c) 2015. Turtsevich Alexander
*
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.html
*/
package com.kemsky.support
{
import com.kemsky.Iterator;
import com.kemsky.Stream;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
use namespace flash_proxy;
/**
* @private
*/
public class ValueIterator extends Proxy implements Iterator
{
protected var stream:Stream;
protected var _next:int;
protected var _current:int = -1;
public function ValueIterator(array:Stream, index:uint = 0)
{
stream = array;
_next = index >= stream.length ? -1 : index;
}
/**
* @private
*/
private function get nextIndex():int
{
return _next;
}
/**
* @inheritDoc
*/
public function get index():int
{
return _current;
}
/**
* @inheritDoc
*/
public function get item():*
{
return stream.getItem(_current);
}
/**
* @inheritDoc
*/
public function reset():void
{
_next = stream.length ? 0 : -1;
_current = -1;
}
/**
* @inheritDoc
*/
public function end():void
{
_next = _current = -1;
}
/**
* @inheritDoc
*/
public function remove():void
{
if (_current == -1)
{
throw new StreamError("Current item is not available");
}
if (_next > 0)
{
_next--;
}
stream.removeItem(_current);
_current = -1;
}
/**
* @inheritDoc
*/
public function get hasNext():Boolean
{
return _next > -1;
}
/**
* @inheritDoc
*/
public function next():*
{
if (_next == -1)
{
throw new StreamError("Next item is not available");
}
_current = _next;
_next = _next >= stream.length - 1 ? -1 : _next + 1;
return stream.getItem(_current);
}
/**
* @inheritDoc
*/
public function set item(value:*):void
{
if (_current == -1 || _current == stream.length)
{
throw new StreamError("Current item is not available");
}
stream.setItem(_current, value);
}
/**
* @private
*/
override flash_proxy function nextNameIndex(index:int):int
{
return hasNext ? nextIndex + 1 : 0;
}
/**
* @private
*/
override flash_proxy function nextValue(index:int):*
{
return next();
}
}
}
|
/*
* Copyright: (c) 2015. Turtsevich Alexander
*
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.html
*/
package com.kemsky.support
{
import com.kemsky.Iterator;
import com.kemsky.Stream;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
use namespace flash_proxy;
/**
* @private
*/
public class ValueIterator extends Proxy implements Iterator
{
protected var stream:Stream;
protected var _next:int;
protected var _current:int = -1;
/**
* Constructor.
* @param stream underlying stream.
*/
public function ValueIterator(stream:Stream)
{
this.stream = stream;
_next = this.stream.length == 0 ? -1 : 0;
}
/**
* @private
*/
private function get nextIndex():int
{
return _next;
}
/**
* @inheritDoc
*/
public function get index():int
{
return _current;
}
/**
* @inheritDoc
*/
public function get item():*
{
return stream.getItem(_current);
}
/**
* @inheritDoc
*/
public function reset():void
{
_next = stream.length ? 0 : -1;
_current = -1;
}
/**
* @inheritDoc
*/
public function end():void
{
_next = _current = -1;
}
/**
* @inheritDoc
*/
public function remove():void
{
if (_current == -1)
{
throw new StreamError("Current item is not available");
}
if (_next > 0)
{
_next--;
}
stream.removeItem(_current);
_current = -1;
}
/**
* @inheritDoc
*/
public function get hasNext():Boolean
{
return _next > -1;
}
/**
* @inheritDoc
*/
public function next():*
{
if (_next == -1)
{
throw new StreamError("Next item is not available");
}
_current = _next;
_next = _next >= stream.length - 1 ? -1 : _next + 1;
return stream.getItem(_current);
}
/**
* @inheritDoc
*/
public function set item(value:*):void
{
if (_current == -1 || _current == stream.length)
{
throw new StreamError("Current item is not available");
}
stream.setItem(_current, value);
}
/**
* @private
*/
override flash_proxy function nextNameIndex(index:int):int
{
return hasNext ? nextIndex + 1 : 0;
}
/**
* @private
*/
override flash_proxy function nextValue(index:int):*
{
return next();
}
}
}
|
clean up
|
clean up
|
ActionScript
|
mit
|
kemsky/stream
|
237e0f42f93f3fefd5dbe2dd9491871a42a2a2c4
|
lib/src/com/amanitadesign/steam/SteamConstants.as
|
lib/src/com/amanitadesign/steam/SteamConstants.as
|
/*
* SteamConstants.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
{
public class SteamConstants
{
/* response values */
public static const RESPONSE_OK:int = 0;
public static const RESPONSE_FAILED:int = 1;
/* response types */
public static const RESPONSE_OnUserStatsReceived:int = 0;
public static const RESPONSE_OnUserStatsStored:int = 1;
public static const RESPONSE_OnAchievementStored:int = 2;
public static const RESPONSE_OnGameOverlayActivated:int = 3;
public static const RESPONSE_OnFileShared:int = 4;
public static const RESPONSE_OnUGCDownload:int = 5;
public static const RESPONSE_OnPublishWorkshopFile:int = 6;
public static const RESPONSE_OnDeletePublishedFile:int = 7;
public static const RESPONSE_OnGetPublishedFileDetails:int = 8;
public static const RESPONSE_OnEnumerateUserPublishedFiles:int = 9;
public static const RESPONSE_OnEnumeratePublishedWorkshopFiles:int = 10;
public static const RESPONSE_OnEnumerateUserSubscribedFiles:int = 11;
public static const RESPONSE_OnEnumerateUserSharedWorkshopFiles:int = 12;
public static const RESPONSE_OnEnumeratePublishedFilesByUserAction:int = 13;
public static const RESPONSE_OnCommitPublishedFileUpdate:int = 14;
public static const RESPONSE_OnSubscribePublishedFile:int = 15;
public static const RESPONSE_OnUnsubscribePublishedFile:int = 16;
public static const RESPONSE_OnGetPublishedItemVoteDetails:int = 17;
public static const RESPONSE_OnUpdateUserPublishedItemVote:int = 18;
public static const RESPONSE_OnSetUserPublishedFileAction:int = 19;
public static const RESPONSE_OnDLCInstalled:int = 20;
}
}
|
/*
* SteamConstants.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
{
public class SteamConstants
{
/* response types */
public static const RESPONSE_OnUserStatsReceived:int = 0;
public static const RESPONSE_OnUserStatsStored:int = 1;
public static const RESPONSE_OnAchievementStored:int = 2;
public static const RESPONSE_OnGameOverlayActivated:int = 3;
public static const RESPONSE_OnFileShared:int = 4;
public static const RESPONSE_OnUGCDownload:int = 5;
public static const RESPONSE_OnPublishWorkshopFile:int = 6;
public static const RESPONSE_OnDeletePublishedFile:int = 7;
public static const RESPONSE_OnGetPublishedFileDetails:int = 8;
public static const RESPONSE_OnEnumerateUserPublishedFiles:int = 9;
public static const RESPONSE_OnEnumeratePublishedWorkshopFiles:int = 10;
public static const RESPONSE_OnEnumerateUserSubscribedFiles:int = 11;
public static const RESPONSE_OnEnumerateUserSharedWorkshopFiles:int = 12;
public static const RESPONSE_OnEnumeratePublishedFilesByUserAction:int = 13;
public static const RESPONSE_OnCommitPublishedFileUpdate:int = 14;
public static const RESPONSE_OnSubscribePublishedFile:int = 15;
public static const RESPONSE_OnUnsubscribePublishedFile:int = 16;
public static const RESPONSE_OnGetPublishedItemVoteDetails:int = 17;
public static const RESPONSE_OnUpdateUserPublishedItemVote:int = 18;
public static const RESPONSE_OnSetUserPublishedFileAction:int = 19;
public static const RESPONSE_OnDLCInstalled:int = 20;
}
}
|
Remove obsolete values
|
Remove obsolete values
|
ActionScript
|
bsd-2-clause
|
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
|
844f2e29678139e8486a4e92fd78883463d051d1
|
WEB-INF/lps/lfc/debugger/platform/swf9/LzDebug.as
|
WEB-INF/lps/lfc/debugger/platform/swf9/LzDebug.as
|
/* -*- mode: JavaScript; c-basic-offset: 2; -*- */
/*
* Platform-specific DebugService
*
* @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*/
// The last three debugger eval values
var _;
var __;
var ___;
class LzAS3DebugService extends LzDebugService {
#passthrough (toplevel:true) {
import flash.net.*;
import flash.events.*;
import flash.external.*;
import flash.display.*;
import flash.utils.*;
import flash.system.*;
import mx.core.Application;
}#
/**
* @access private
*/
function LzAS3DebugService (base:LzBootstrapDebugService) {
super(null);
}
/**
** Platform-specific implementation of debug I/O
**/
/**
* Instantiates an instance of the user Debugger window
* Called last thing by the compiler when the app is completely loaded.
* @access private
*/
function makeDebugWindow () {
// Make the real console. This is only called if the user code
// did not actually instantiate a <debug /> tag
var params:Object = LFCApplication.stage.loaderInfo.parameters;
var remote =( params[ "lzconsoledebug" ] );
trace('makeDebugWindow lzconsoledebug=', 'remote=', remote);
if (remote == 'true') {
// Open the remote debugger socket
this.attachDebugConsole(new LzFlashRemoteDebugConsole());
} else {
// This will attach itself, once it is fully initialized.
new lz.LzDebugWindow();
}
}
// Map of object=>id
var swf9_object_table:Dictionary = new Dictionary();
// Map of id=>object
var swf9_id_table:Array = [];
override function IDForObject (obj:*, force:Boolean=false):Number {
var id:Number;
// TODO [hqm 2008-09-11] in swf9 we can use the flash.utils.Dictionary object
// to do hash table lookups using === object equality, so we don't need to
// iterate over the id_to_object_table to see if an object has been interned.
var ot = this.swf9_object_table;
if (ot[obj] != null) {
return ot[obj];
}
if (!force) {
// ID anything that has identity
if (! this.isObjectLike(obj)) {
return null;
}
}
id = this.objseq++;
this.swf9_object_table[obj] = id;
this.swf9_id_table[id] = obj;
return id;
};
override function ObjectForID (id) {
return this.swf9_id_table[id];
};
/**
* @access private
* @devnote The only reason this is here is because the SWF eval
* compiler does not (yet) wrap `with (Debug.environment)` around the
* compiled expression, so we have to put the "previous value's" in
* _level0
*/
override function displayResult (result=(void 0)) {
if (typeof(result) != 'undefined') {
// Advance saved results if you have a new one
if (result !== global._) {
if (typeof(global.__) != 'undefined') {
global.___ = global.__;
}
if (typeof(global._) != 'undefined') {
global.__ = global._;
}
global._ = result;
}
}
this.freshLine();
// Output any result from the evalloader
if (typeof(result) != 'undefined') {
this.format("%#w", result);
}
this.freshPrompt();
};
/**
* @access private
*/
override function functionName (fn, mustBeUnique:Boolean=false) {
if ((fn is Class) && fn['tagname']) {
// Handle tag classes
if ((! mustBeUnique) || (fn === lz[fn.tagname])) {
return '<' + fn.tagname + '>';
}
}
return super.functionName(fn, mustBeUnique);
}
/**
* @access private
*/
/**
* Adds unenumerable object properties for DHMTL runtime
*
* @access private
*/
override function objectOwnProperties (obj:*, names:Array=null, indices:Array=null, limit:Number=Infinity, nonEnumerable:Boolean=false) {
// TODO [2008-09-11 hqm] not sure what to do here, maybe we can use the introspection API
// flash.utils.describeType() to at least enumerate public properties...
return super.objectOwnProperties(obj, names, indices, limit,nonEnumerable);
}
}
var Debug = new LzAS3DebugService(null);
var __LzDebug = Debug;
|
/* -*- mode: JavaScript; c-basic-offset: 2; -*- */
/*
* Platform-specific DebugService
*
* @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*/
// The last three debugger eval values
var _;
var __;
var ___;
class LzAS3DebugService extends LzDebugService {
#passthrough (toplevel:true) {
import flash.net.*;
import flash.events.*;
import flash.external.*;
import flash.display.*;
import flash.utils.*;
import flash.system.*;
import mx.core.Application;
}#
/**
* @access private
*/
function LzAS3DebugService (base:LzBootstrapDebugService) {
super(null);
}
/**
** Platform-specific implementation of debug I/O
**/
/**
* Instantiates an instance of the user Debugger window
* Called last thing by the compiler when the app is completely loaded.
* @access private
*/
function makeDebugWindow () {
// Make the real console. This is only called if the user code
// did not actually instantiate a <debug /> tag
var params:Object = LFCApplication.stage.loaderInfo.parameters;
var remote =( params[ "lzconsoledebug" ] );
trace('makeDebugWindow lzconsoledebug=', 'remote=', remote);
if (remote == 'true') {
// Open the remote debugger socket
this.attachDebugConsole(new LzFlashRemoteDebugConsole());
} else {
// This will attach itself, once it is fully initialized.
new lz.LzDebugWindow();
}
}
// Map of object=>id
var swf9_object_table:Dictionary = new Dictionary();
// Map of id=>object
var swf9_id_table:Array = [];
override function IDForObject (obj:*, force:Boolean=false):Number {
var id:Number;
// TODO [hqm 2008-09-11] in swf9 we can use the flash.utils.Dictionary object
// to do hash table lookups using === object equality, so we don't need to
// iterate over the id_to_object_table to see if an object has been interned.
var ot = this.swf9_object_table;
if (ot[obj] != null) {
return ot[obj];
}
if (!force) {
// ID anything that has identity
if (! this.isObjectLike(obj)) {
return null;
}
}
id = this.objseq++;
this.swf9_object_table[obj] = id;
this.swf9_id_table[id] = obj;
return id;
};
override function ObjectForID (id) {
return this.swf9_id_table[id];
};
/**
* @access private
* @devnote The only reason this is here is because the SWF eval
* compiler does not (yet) wrap `with (Debug.environment)` around the
* compiled expression, so we have to put the "previous value's" in
* _level0
*/
override function displayResult (result=(void 0)) {
if (typeof(result) != 'undefined') {
// Advance saved results if you have a new one
if (result !== global._) {
if (typeof(global.__) != 'undefined') {
global.___ = global.__;
}
if (typeof(global._) != 'undefined') {
global.__ = global._;
}
global._ = result;
}
}
this.freshLine();
// Output any result from the evalloader
if (typeof(result) != 'undefined') {
this.format("%#w", result);
}
this.freshPrompt();
};
/**
* @access private
*/
override function functionName (fn, mustBeUnique:Boolean=false) {
if ((fn is Class) && fn['tagname']) {
// Handle tag classes
if ((! mustBeUnique) || (fn === lz[fn.tagname])) {
return '<' + fn.tagname + '>';
}
}
return super.functionName(fn, mustBeUnique);
}
/**
* @access private
*/
/**
* Adds unenumerable object properties for DHMTL runtime
*
* @access private
*/
#passthrough {
override function objectOwnProperties (obj:*, names:Array=null, indices:Array=null, limit:Number=Infinity, nonEnumerable:Boolean=false) {
// TODO [2008-09-11 hqm] not sure what to do here, maybe we can use the introspection API
// flash.utils.describeType() to at least enumerate public properties...
var description:XML = describeType(obj);
trace('objectOwnProperties', description);
for each(var a:XML in description.variable) {
if (names != null) {
names.push(a.@name);
}
}
return super.objectOwnProperties(obj, names, indices, limit,nonEnumerable);
}
}#
}
var Debug = new LzAS3DebugService(null);
var __LzDebug = Debug;
|
Change 20080918-hqm-z by [email protected] on 2008-09-18 16:07:26 EDT in /Users/hqm/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk
|
Change 20080918-hqm-z by [email protected] on 2008-09-18 16:07:26 EDT
in /Users/hqm/openlaszlo/trunk
for http://svn.openlaszlo.org/openlaszlo/trunk
Summary: use swf9 introspection in debugger inspector
New Features:
Bugs Fixed:
Technical Reviewer: ptr (pending)
QA Reviewer: (pending)
Doc Reviewer: (pending)
Documentation:
Release Notes:
Details:
Tests:
git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@11083 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
|
ActionScript
|
epl-1.0
|
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
|
e7cbdfab19d615b146da95f6fbabc3520795fb4f
|
test/flash_test.as
|
test/flash_test.as
|
package {
import stdio.Sprite
[SWF(width=0, height=0)]
public class flash_test extends Sprite {
public function main(): void {
test_body()
}
}
}
|
package {
import stdio.Sprite
[SWF(width=100, height=100)]
public class flash_test extends Sprite {
public function flash_test(): void {
graphics.beginFill(0xff0000)
graphics.drawRect(10, 10, 80, 80)
graphics.endFill()
}
public function main(): void {
graphics.beginFill(0x0000ff)
graphics.drawRect(30, 30, 40, 40)
graphics.endFill()
test_body()
}
}
}
|
Add colors to Flash test to ease debugging.
|
Add colors to Flash test to ease debugging.
|
ActionScript
|
mit
|
dbrock/stdio.as,dbrock/stdio.as,dbrock/stdio.as
|
18cb429eb33af643b37afceaba5879f3e158370e
|
exporter/src/main/as/flump/export/Publisher.as
|
exporter/src/main/as/flump/export/Publisher.as
|
//
// Flump - Copyright 2013 Flump Authors
package flump.export {
import aspire.util.Log;
import flash.filesystem.File;
import flump.xfl.XflLibrary;
public class Publisher
{
public function Publisher (exportDir :File, project :ProjectConf, projectName :String) {
_exportDir = exportDir;
_projectName = projectName;
for each (var export :ExportConf in project.exports) _confs.push(export);
}
public function modified (libs :Vector.<XflLibrary>, idx :int = -1) :Boolean {
// Instantiate all formats and check for modified. For a ProjectConf that contains combined
// exports, all individual libs will check as modified if any single lib is modified
return instantiate(libs, idx).some(function (export :PublishFormat, ..._) :Boolean {
return export.modified;
});
}
public function publishSingle (lib :XflLibrary) :int {
var libs :Vector.<XflLibrary> = new <XflLibrary>[lib];
var formats :Vector.<PublishFormat> = instantiate(libs, 0, false);
for each (var format :PublishFormat in formats) format.publish();
return formats.length;
}
public function publishCombined (libs :Vector.<XflLibrary>) :int {
// no index passed to instantiate() acts as a <do not include non-combined> flag
var formats :Vector.<PublishFormat> = instantiate(libs);
for each (var format :PublishFormat in formats) format.publish();
return formats.length;
}
protected function instantiate (libs :Vector.<XflLibrary>,
idx :int = -1, includeCombined :Boolean = true) :Vector.<PublishFormat> {
const formats :Vector.<PublishFormat> = new <PublishFormat>[];
for each (var conf :ExportConf in _confs) {
if (conf.combine && includeCombined) {
formats.push(conf.createPublishFormat(_exportDir, libs, _projectName));
} else if (!conf.combine && idx >= 0) {
formats.push(conf.createPublishFormat(_exportDir, new <XflLibrary>[libs[idx]],
_projectName))
}
}
return formats;
}
private var _exportDir :File;
private var _projectName :String;
private const _confs :Vector.<ExportConf> = new <ExportConf>[];
private static const log :Log = Log.getLog(Publisher);
}
}
|
//
// Flump - Copyright 2013 Flump Authors
package flump.export {
import flash.filesystem.File;
import flump.xfl.XflLibrary;
public class Publisher
{
public function Publisher (exportDir :File, project :ProjectConf, projectName :String) {
_exportDir = exportDir;
_projectName = projectName;
for each (var conf :ExportConf in project.exports) _confs.push(conf);
}
public function modified (libs :Vector.<XflLibrary>, idx :int = -1) :Boolean {
// Instantiate all formats and check for modified. For a ProjectConf that contains combined
// exports, all individual libs will check as modified if any single lib is modified
return instantiate(libs, idx).some(function (conf :PublishFormat, ..._) :Boolean {
return conf.modified;
});
}
public function publishSingle (lib :XflLibrary) :int {
var libs :Vector.<XflLibrary> = new <XflLibrary>[lib];
var formats :Vector.<PublishFormat> = instantiate(libs, 0, false);
for each (var format :PublishFormat in formats) format.publish();
return formats.length;
}
public function publishCombined (libs :Vector.<XflLibrary>) :int {
// no index passed to instantiate() acts as a <do not include non-combined> flag
var formats :Vector.<PublishFormat> = instantiate(libs);
for each (var format :PublishFormat in formats) format.publish();
return formats.length;
}
protected function instantiate (libs :Vector.<XflLibrary>,
idx :int = -1, includeCombined :Boolean = true) :Vector.<PublishFormat> {
const formats :Vector.<PublishFormat> = new <PublishFormat>[];
for each (var conf :ExportConf in _confs) {
if (conf.combine && includeCombined) {
formats.push(conf.createPublishFormat(_exportDir, libs, _projectName));
} else if (!conf.combine && idx >= 0) {
formats.push(conf.createPublishFormat(_exportDir, new <XflLibrary>[libs[idx]],
_projectName))
}
}
return formats;
}
private var _exportDir :File;
private var _projectName :String;
private const _confs :Vector.<ExportConf> = new <ExportConf>[];
}
}
|
Remove unused log; fix IntelliJ warnings
|
Remove unused log; fix IntelliJ warnings
("export" is a reserved keyword)
|
ActionScript
|
mit
|
tconkling/flump,tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump,mathieuanthoine/flump
|
efaf8fb21dac89b04211c4fd64f11055461ebe47
|
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.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 +'")');
}
}
}
|
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/100;
}
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 +'")');
}
}
}
|
fix volume level value (close #4)
|
RTMP.as: fix volume level value (close #4)
|
ActionScript
|
apache-2.0
|
flavioribeiro/clappr-rtmp-plugin,hxl-dy/clappr-rtmp-plugin,flavioribeiro/clappr-rtmp-plugin,video-dev/clappr-rtmp-plugin,eventials/clappr-rtmp-plugin,hxl-dy/clappr-rtmp-plugin,flavioribeiro/clappr-rtmp-plugin,eventials/clappr-rtmp-plugin,clappr/clappr-rtmp-plugin,hxl-dy/clappr-rtmp-plugin,clappr/clappr-rtmp-plugin,eventials/clappr-rtmp-plugin,clappr/clappr-rtmp-plugin,video-dev/clappr-rtmp-plugin,video-dev/clappr-rtmp-plugin
|
37be868b6ce5856d557209a28fab5db6df20f0d0
|
src/com/ryanberdeen/echonest/api/v4/track/TrackApi.as
|
src/com/ryanberdeen/echonest/api/v4/track/TrackApi.as
|
/*
* Copyright 2011 Ryan Berdeen. All rights reserved.
* Distributed under the terms of the MIT License.
* See accompanying file LICENSE.txt
*/
package com.ryanberdeen.echonest.api.v4.track {
import com.adobe.serialization.json.JSON;
import com.ryanberdeen.echonest.api.v4.ApiSupport;
import com.ryanberdeen.echonest.api.v4.EchoNestError;
import flash.events.DataEvent;
import flash.events.Event;
import flash.net.FileReference;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.utils.ByteArray;
/**
* Methods to interact with the Echo Nest track API.
*
* <p>All of the API methods in this class accept basically the same
* parameters. The <code>parameters</code> parameter contains the parameters
* to pass to the Echo Nest method. For most methods, this will be
* <strong><code>id</code></strong> or <strong><code>md5</code></strong>.
* The <code>api_key</code> parameter will always be
* set.</p>
*
* <p>The <code>loaderOptions</code> parameter contains the event listeners
* for the loading process. Most importantly, the
* <strong><code>onResponse</code></strong> method will be called with the
* results of the API method. See the <code>ApiSupport.createLoader()</code>
* method for a description of the loader options.</p>
*
* <p>For a description of the response formats, see the various
* <code>process...Response()</code> methods.</p>
*
* <p>Be sure to set the <code>apiKey</code> property before calling any API
* methods.</p>
*/
public class TrackApi extends ApiSupport {
/**
* Adds the standard Echo Nest Flash API event listeners to a file
* reference.
*
* @param options The event listener options. See
* <code>createLoader()</code> for the list of available options.
* @param dispatcher The file reference to add the event listeners to.
*/
public function addFileReferenceEventListeners(options:Object, fileReference:FileReference, responseProcessor:Function, ...responseProcessorArgs):void {
// TODO document
if (options.onOpen) {
fileReference.addEventListener(Event.OPEN, options.onOpen);
}
if (options.onComplete) {
fileReference.addEventListener(Event.COMPLETE, options.onComplete);
}
if (options.onResponse) {
fileReference.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, function(e:DataEvent):void {
try {
var responseObject:* = parseRawResponse(e.data);
responseProcessorArgs.push(responseObject);
var response:Object = responseProcessor.apply(responseProcessor, responseProcessorArgs);
options.onResponse(response);
}
catch (e:EchoNestError) {
if (options.onEchoNestError) {
options.onEchoNestError(e);
}
}
});
}
addEventListeners(options, fileReference);
}
public function loadAnalysis(track:Object, loaderOptions:Object):URLLoader {
var loader:URLLoader = new URLLoader();
if (loaderOptions.onComplete) {
loader.addEventListener(Event.COMPLETE, loaderOptions.onComplete);
}
if (loaderOptions.onResponse) {
loader.addEventListener(Event.COMPLETE, function(e:Event):void {
var analysis:Object = JSON.decode(loader.data);
loaderOptions.onResponse(analysis);
});
}
addEventListeners(loaderOptions, loader);
var request:URLRequest = new URLRequest();
request.url = track.audio_summary.analysis_url;
loader.load(request);
return loader;
}
/**
* Processes the response from the <code>upload</code> API method.
*
* @param response The response to process.
*
* @return The result of processing the response.
*
* @see #upload()
* @see #uploadFileData()
*/
public function processUploadResponse(response:*):Object {
return response.track;
}
/**
* Invokes the Echo Nest <code>upload</code> API method with a file
* reference.
*
* <p>The <code>parameters</code> object must include a <code>track</code>
* property, which must be a <code>FileReference</code> that may be
* <code>upload()</code>ed.</p>
*
* @param parameters The parameters to include in the API request.
* @param loaderOptions The event listener options for the loader.
*
* @see com.ryanberdeen.echonest.api.v3.ApiSupport#createRequest()
* @see #processUploadResponse()
* @see http://developer.echonest.com/docs/v4/track.html#upload
*/
public function uploadFileReference(parameters:Object, loaderOptions:Object):URLRequest {
var fileReference:FileReference = parameters.track;
delete parameters.track;
addFileReferenceEventListeners(loaderOptions, fileReference, processUploadResponse);
var request:URLRequest = createRequest('track/upload', parameters);
fileReference.upload(request, 'track');
return request;
}
/**
* Invokes the Echo Nest <code>upload</code> API method.
*
* <p>This method is for uploads using the <code>url</code> parameter.
* To upload a file, use <code>uploadFileReference()</code>.
*
* @param parameters The parameters to include in the API request.
* @param loaderOptions The event listener options for the loader.
*
* @return The <code>URLLoader</code> being used to perform the API call.
*
* @see com.ryanberdeen.echonest.api.v4.ApiSupport#createRequest()
* @see com.ryanberdeen.echonest.api.v4.ApiSupport#createLoader()
* @see #processUploadResponse()
* @see http://developer.echonest.com/docs/v4/track.html#upload
*/
public function upload(parameters:Object, loaderOptions:Object):URLLoader {
var request:URLRequest = createRequest('track/upload', parameters);
request.method = URLRequestMethod.POST;
var loader:URLLoader = createLoader(loaderOptions, processUploadResponse);
loader.load(request);
return loader;
}
}
}
|
/*
* Copyright 2011 Ryan Berdeen. All rights reserved.
* Distributed under the terms of the MIT License.
* See accompanying file LICENSE.txt
*/
package com.ryanberdeen.echonest.api.v4.track {
import com.adobe.serialization.json.JSON;
import com.ryanberdeen.echonest.api.v4.ApiSupport;
import com.ryanberdeen.echonest.api.v4.EchoNestError;
import flash.events.DataEvent;
import flash.events.Event;
import flash.net.FileReference;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.utils.ByteArray;
/**
* Methods to interact with the Echo Nest track API.
*
* <p>All of the API methods in this class accept basically the same
* parameters. The <code>parameters</code> parameter contains the parameters
* to pass to the Echo Nest method. For most methods, this will be
* <strong><code>id</code></strong> or <strong><code>md5</code></strong>.
* The <code>api_key</code> parameter will always be
* set.</p>
*
* <p>The <code>loaderOptions</code> parameter contains the event listeners
* for the loading process. Most importantly, the
* <strong><code>onResponse</code></strong> method will be called with the
* results of the API method. See the <code>ApiSupport.createLoader()</code>
* method for a description of the loader options.</p>
*
* <p>For a description of the response formats, see the various
* <code>process...Response()</code> methods.</p>
*
* <p>Be sure to set the <code>apiKey</code> property before calling any API
* methods.</p>
*/
public class TrackApi extends ApiSupport {
/**
* Adds the standard Echo Nest Flash API event listeners to a file
* reference.
*
* @param options The event listener options. See
* <code>createLoader()</code> for the list of available options.
* @param dispatcher The file reference to add the event listeners to.
*/
public function addFileReferenceEventListeners(options:Object, fileReference:FileReference, responseProcessor:Function, ...responseProcessorArgs):void {
// TODO document
if (options.onOpen) {
fileReference.addEventListener(Event.OPEN, options.onOpen);
}
if (options.onComplete) {
fileReference.addEventListener(Event.COMPLETE, options.onComplete);
}
if (options.onResponse) {
fileReference.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, function(e:DataEvent):void {
try {
var responseObject:* = parseRawResponse(e.data);
responseProcessorArgs.push(responseObject);
var response:Object = responseProcessor.apply(responseProcessor, responseProcessorArgs);
options.onResponse(response);
}
catch (e:EchoNestError) {
if (options.onEchoNestError) {
options.onEchoNestError(e);
}
}
});
}
addEventListeners(options, fileReference);
}
public function loadAnalysis(track:Object, loaderOptions:Object):URLLoader {
var loader:URLLoader = new URLLoader();
if (loaderOptions.onComplete) {
loader.addEventListener(Event.COMPLETE, loaderOptions.onComplete);
}
if (loaderOptions.onResponse) {
loader.addEventListener(Event.COMPLETE, function(e:Event):void {
var analysis:Object = JSON.decode(loader.data);
loaderOptions.onResponse(analysis);
});
}
addEventListeners(loaderOptions, loader);
var request:URLRequest = new URLRequest();
request.url = track.audio_summary.analysis_url;
loader.load(request);
return loader;
}
/**
* Processes the response from the <code>upload</code> API method.
*
* @param response The response to process.
*
* @return The result of processing the response.
*
* @see #upload()
* @see #uploadFileData()
*/
public function processUploadResponse(response:*):Object {
return response.track;
}
/**
* Invokes the Echo Nest <code>upload</code> API method with a file
* reference.
*
* <p>The <code>parameters</code> object must include a <code>track</code>
* property, which must be a <code>FileReference</code> that may be
* <code>upload()</code>ed.</p>
*
* @param parameters The parameters to include in the API request.
* @param loaderOptions The event listener options for the loader.
*
* @see com.ryanberdeen.echonest.api.v3.ApiSupport#createRequest()
* @see #processUploadResponse()
* @see http://developer.echonest.com/docs/v4/track.html#upload
*/
public function uploadFileReference(parameters:Object, loaderOptions:Object):URLRequest {
var fileReference:FileReference = parameters.track;
delete parameters.track;
addFileReferenceEventListeners(loaderOptions, fileReference, processUploadResponse);
var request:URLRequest = createRequest('track/upload', parameters);
fileReference.upload(request, 'track');
return request;
}
/**
* Invokes the Echo Nest <code>upload</code> API method.
*
* <p>This method is for uploads using the <code>url</code> parameter.
* To upload a file, use <code>uploadFileReference()</code>.</p>
*
* @param parameters The parameters to include in the API request.
* @param loaderOptions The event listener options for the loader.
*
* @return The <code>URLLoader</code> being used to perform the API call.
*
* @see com.ryanberdeen.echonest.api.v4.ApiSupport#createRequest()
* @see com.ryanberdeen.echonest.api.v4.ApiSupport#createLoader()
* @see #processUploadResponse()
* @see http://developer.echonest.com/docs/v4/track.html#upload
*/
public function upload(parameters:Object, loaderOptions:Object):URLLoader {
var request:URLRequest = createRequest('track/upload', parameters);
request.method = URLRequestMethod.POST;
var loader:URLLoader = createLoader(loaderOptions, processUploadResponse);
loader.load(request);
return loader;
}
}
}
|
fix asdoc html
|
fix asdoc html
|
ActionScript
|
mit
|
also/echo-nest-flash-api
|
fafb3368c3bd1bbbcea0a022b4484de4e6d27056
|
MultitouchAndGestures/src/MultitouchAndGestures.as
|
MultitouchAndGestures/src/MultitouchAndGestures.as
|
package
{
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.TouchEvent;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
import org.osmf.layout.HorizontalAlign;
[ SWF(backgrouncColor="0xFFFFFF",
frameRate="25",
width="320",
height="480") ]
public class MultitouchAndGestures extends Sprite
{
private var coordinates:TextField;
private var multitouch:TextField;
private var offsetX:Number;
private var offsetY:Number;
public function MultitouchAndGestures()
{
super();
// 支持 autoOrient
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
multitouch = new TextField();
multitouch.autoSize = TextFieldAutoSize.LEFT;
switch(Multitouch.supportsTouchEvents)
{
case true:
{
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
multitouch.text = "Touch Supported, max points: " + Multitouch.maxTouchPoints;
stage.addEventListener(TouchEvent.TOUCH_BEGIN, onTouch);
stage.addEventListener(TouchEvent.TOUCH_MOVE, onTouch);
stage.addEventListener(TouchEvent.TOUCH_END, onTouch);
}
break;
case false:
{
multitouch.text = "Not Supported";
}
break;
default:
break;
}
stage.addChild(multitouch);
}
private function onTouch(e:TouchEvent):void
{
var id:Number = e.touchPointID;
var x:Number = e.stageX;
var y:Number = e.stageY;
switch(e.type) {
case TouchEvent.TOUCH_BEGIN:
removeShape(id);
drawLines(id, x, y);
drawShape(id, x, y);
break;
case TouchEvent.TOUCH_MOVE:
moveLines(id, x, y);
drawShape(id, x, y);
break;
case TouchEvent.TOUCH_END:
removeLines(id);
break;
}
}
private function drawLines(id:Number, x:Number, y:Number):void {
offsetX = x;
offsetY = y;
var vertical:Sprite = new Sprite();
vertical.name = id+"v";
vertical.graphics.lineStyle(2, 0x000000);
vertical.graphics.moveTo(x, 0);
vertical.graphics.lineTo(x, stage.stageHeight);
stage.addChild(vertical);
var horizontal:Sprite = new Sprite();
horizontal.name = id + "h";
horizontal.graphics.lineStyle(2, 0x000000);
horizontal.graphics.moveTo(0, y);
horizontal.graphics.lineTo(stage.stageWidth, y);
stage.addChild(horizontal);
setCoordinates(x, y);
}
private function moveLines(id:Number, x:Number, y:Number):void {
var vertical:Sprite = Sprite(stage.getChildByName(id + "v"));
var horizontal:Sprite = Sprite(stage.getChildByName(id + "h"));
vertical.x = x - offsetX;
horizontal.y = y - offsetY;
setCoordinates(x, y);
}
private function removeLines(id:Number):void {
stage.removeChild(Sprite(stage.getChildByName(id + "v")));
stage.removeChild(Sprite(stage.getChildByName(id + "h")));
stage.removeChild(coordinates);
coordinates = null;
}
private function setCoordinates(x:Number, y:Number):void {
if (!coordinates) {
coordinates = new TextField();
stage.addChild(coordinates);
}
coordinates.text = "("+x+", "+y+")";
coordinates.x = x-200;
if (coordinates.x < 0) {
coordinates.x = x + 100;
}
coordinates.y = y-70;
if (coordinates.y < 0) {
coordinates.y = y + 100;
}
}
private function drawShape(id:Number, x:Number, y:Number):void {
var shape:Sprite;
var shapeId:String = "shape01";
// var shapeId:String = id.toString();
if (!stage.getChildByName(shapeId)) {
shape = new Sprite();
shape.name = shapeId;
stage.addChild(shape);
} else {
shape = stage.getChildByName(shapeId) as Sprite;
}
var width:Number = x - offsetX;
var height:Number = y - offsetY;
shape.graphics.lineStyle(2, 0x000000, 1.0);
shape.graphics.beginFill(0x000000, 0.0);
shape.graphics.drawRect(offsetX, offsetY, width, height);
shape.graphics.endFill();
}
private function removeShape(id:Number):void {
var shapeId:String = "shape01";
// var shapeId:String = id.toString();
var shape:Sprite = null;
shape = stage.getChildByName(shapeId) as Sprite;
if (shape != null) {
stage.removeChild(shape);
}
}
}
}
|
package
{
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.GesturePhase;
import flash.events.TimerEvent;
import flash.events.TouchEvent;
import flash.events.TransformGestureEvent;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
import flash.utils.Timer;
import org.flexunit.internals.matchers.Each;
[ SWF(backgrouncColor="0xFFFFFF",
frameRate="25",
width="320",
height="480") ]
public class MultitouchAndGestures extends Sprite
{
private var coordinates:TextField;
private var multitouch:TextField;
private var currentTarget:String;
private var idleTimer:Timer;
private var offsetX:Number;
private var offsetY:Number;
public function MultitouchAndGestures()
{
super();
// 支持 autoOrient
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
multitouch = new TextField();
multitouch.autoSize = TextFieldAutoSize.LEFT;
idleTimer = new Timer(1000);
idleTimer.addEventListener(TimerEvent.TIMER, onTimer);
switch(Multitouch.supportsTouchEvents)
{
case true:
{
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
multitouch.text = "Touch Supported, max points: " + Multitouch.maxTouchPoints;
stage.addEventListener(TouchEvent.TOUCH_BEGIN, onTouch);
stage.addEventListener(TouchEvent.TOUCH_MOVE, onTouch);
stage.addEventListener(TouchEvent.TOUCH_END, onTouch);
}
break;
case false:
{
multitouch.text = "Not Supported";
}
break;
default:
break;
}
stage.addChild(multitouch);
}
private function onTouch(e:TouchEvent):void
{
var id:Number = e.touchPointID;
var x:Number = e.stageX;
var y:Number = e.stageY;
switch(e.type) {
case TouchEvent.TOUCH_BEGIN:
if (e.target is Stage) {
removeShape(id);
drawLines(id, x, y);
drawShape(id, x, y);
} else {
currentTarget = e.target.name;
initializeGestures();
}
break;
case TouchEvent.TOUCH_MOVE:
moveLines(id, x, y);
drawShape(id, x, y);
break;
case TouchEvent.TOUCH_END:
removeLines(id);
break;
}
}
private function drawLines(id:Number, x:Number, y:Number):void {
offsetX = x;
offsetY = y;
var vertical:Sprite = new Sprite();
vertical.name = id+"v";
vertical.graphics.lineStyle(2, 0x000000);
vertical.graphics.moveTo(x, 0);
vertical.graphics.lineTo(x, stage.stageHeight);
stage.addChild(vertical);
var horizontal:Sprite = new Sprite();
horizontal.name = id + "h";
horizontal.graphics.lineStyle(2, 0x000000);
horizontal.graphics.moveTo(0, y);
horizontal.graphics.lineTo(stage.stageWidth, y);
stage.addChild(horizontal);
setCoordinates(x, y);
}
private function moveLines(id:Number, x:Number, y:Number):void {
var vertical:Sprite = Sprite(stage.getChildByName(id + "v"));
var horizontal:Sprite = Sprite(stage.getChildByName(id + "h"));
vertical.x = x - offsetX;
horizontal.y = y - offsetY;
setCoordinates(x, y);
}
private function removeLines(id:Number):void {
stage.removeChild(Sprite(stage.getChildByName(id + "v")));
stage.removeChild(Sprite(stage.getChildByName(id + "h")));
stage.removeChild(coordinates);
coordinates = null;
}
private function setCoordinates(x:Number, y:Number):void {
if (!coordinates) {
coordinates = new TextField();
stage.addChild(coordinates);
}
coordinates.text = "("+x+", "+y+")";
coordinates.x = x-200;
if (coordinates.x < 0) {
coordinates.x = x + 100;
}
coordinates.y = y-70;
if (coordinates.y < 0) {
coordinates.y = y + 100;
}
}
private function drawShape(id:Number, x:Number, y:Number):void {
var shape:Sprite;
var shapeId:String = "shape01";
// var shapeId:String = id.toString();
if (!stage.getChildByName(shapeId)) {
shape = new Sprite();
shape.name = shapeId;
for each(var g:String in Multitouch.supportedGestures) {
switch(g)
{
case TransformGestureEvent.GESTURE_PAN:
shape.addEventListener(g, onPan);
break;
default:
break;
}
}
stage.addChild(shape);
} else {
shape = stage.getChildByName(shapeId) as Sprite;
}
var width:Number = x - offsetX;
var height:Number = y - offsetY;
shape.graphics.lineStyle(2, 0x000000, 1.0);
shape.graphics.beginFill(0x000000, 0.0);
shape.graphics.drawRect(offsetX, offsetY, width, height);
shape.graphics.endFill();
}
private function removeShape(id:Number):void {
var shapeId:String = "shape01";
// var shapeId:String = id.toString();
var shape:Sprite = null;
shape = stage.getChildByName(shapeId) as Sprite;
if (shape != null) {
stage.removeChild(shape);
}
}
//--------------------------
private function onTimer(e:TimerEvent):void {
idleTimer.stop();
initializeTouch();
}
private function initializeTimer():void {
idleTimer.delay = 1000;
if (!idleTimer.running) {
idleTimer.start();
}
}
private function initializeGestures():void {
if (Multitouch.supportsGestureEvents) {
Multitouch.inputMode = MultitouchInputMode.GESTURE;
initializeTimer();
}
}
private function initializeTouch():void {
if (Multitouch.supportsTouchEvents) {
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
}
}
private function onPan(e:TransformGestureEvent):void {
var shape:Sprite = stage.getChildByName(currentTarget) as Sprite;
switch(e.phase) {
case GesturePhase.UPDATE:
shape.x = shape.x + e.offsetX;
shape.y = shape.y + e.offsetY;
initializeTimer();
break;
}
}
}
}
|
add Gestures # modified: MultitouchAndGestures/src/MultitouchAndGestures.as
|
add Gestures
# modified: MultitouchAndGestures/src/MultitouchAndGestures.as
|
ActionScript
|
mit
|
victoryckl/flex-demos,victoryckl/flex-demos,victoryckl/flex-demos
|
bddc891f49ec0b7adeccb3a4cbc8d19025e6820b
|
build-aux/instrument.as
|
build-aux/instrument.as
|
## -*- shell-script -*-
## instrument.as: This file is part of build-aux.
## Copyright (C) Gostai S.A.S., 2006-2008.
##
## This software is provided "as is" without warranty of any kind,
## either expressed or implied, including but not limited to the
## implied warranties of fitness for a particular purpose.
##
## See the LICENSE file for more information.
## For comments, bug reports and feedback: http://www.urbiforge.com
##
m4_defun([_URBI_INSTRUMENT_PREPARE],
[normalize_boolean ()
{
local var=$[1]
local val
eval val=\$$var
case $val in
yes|true|1) eval $var=true;;
*) eval $var=false;;
esac
eval stderr "$var=\$$var"
}
# COMMAND-PREFIX instrument LOG-FILE
# ----------------------------------
# Return what's to be prepended to an executable so that it is instrumented
# to be checked: Valgrind or Darwin's Malloc features.
#
# Use LOG-FILE as output file.
#
# Shared with uconsole-check, please keep sync.
instrument ()
{
local log=$[1]
case $INSTRUMENT:$(uname -s) in
true:Darwin)
# Instrument to use Darwin's malloc features. The man page
# says "MallocBadFreeAbort" exists, but setting MallocHelp
# reports about "MallocErrorAbort". The former does not
# work, the latter does.
echo "env" \
"MallocGuardEdges=1" \
"MallocPreScribble=1" \
"MallocScribble=1" \
"MallocErrorAbort=1" \
"MallocCheckHeapAbort=1" \
"MallocLogFile=$log"
;;
true:*)
# Instrument using Valgrind.
: ${VALGRIND=valgrind}
if ($VALGRIND --version) >/dev/null 2>&1; then
local suppressions
if test -f $srcdir/valgrind-suppressions; then
suppressions="--suppressions=$srcdir/valgrind-suppressions"
fi
echo "$VALGRIND" \
"--error-exitcode=242" \
"--log-file-exactly=$log" \
"$suppressions" \
"--"
else
stderr "cannot find valgrind as $VALGRIND"
fi
;;
*)
# Don't instrument.
;;
esac
}
# FIXME: This should be issued farther in the code, not with the functions.
normalize_boolean INSTRUMENT
])
m4_defun([URBI_INSTRUMENT_PREPARE],
[m4_divert_text([M4SH-INIT], [_URBI_INSTRUMENT_PREPARE])])
|
## -*- shell-script -*-
## instrument.as: This file is part of build-aux.
## Copyright (C) Gostai S.A.S., 2006-2008.
##
## This software is provided "as is" without warranty of any kind,
## either expressed or implied, including but not limited to the
## implied warranties of fitness for a particular purpose.
##
## See the LICENSE file for more information.
## For comments, bug reports and feedback: http://www.urbiforge.com
##
m4_defun([_URBI_INSTRUMENT_PREPARE],
[normalize_boolean ()
{
local var=$[1]
local val
eval val=\$$var
case $val in
yes|true|1) eval $var=true;;
*) eval $var=false;;
esac
eval stderr "$var=\$$var"
}
# COMMAND-PREFIX instrument LOG-FILE
# ----------------------------------
# Return what's to be prepended to an executable so that it is instrumented
# to be checked: Valgrind or Darwin's Malloc features.
#
# Use LOG-FILE as output file.
#
# Shared with uconsole-check, please keep sync.
instrument ()
{
local log=$[1]
case $INSTRUMENT:$(uname -s) in
true:Darwin)
# Instrument to use Darwin's malloc features. The man page
# says "MallocBadFreeAbort" exists, but setting MallocHelp
# reports about "MallocErrorAbort". The former does not
# work, the latter does.
echo "env" \
"MallocGuardEdges=1" \
"MallocPreScribble=1" \
"MallocScribble=1" \
"MallocErrorAbort=1" \
"MallocCheckHeapAbort=1" \
"MallocLogFile=$log"
;;
true:*)
# Instrument using Valgrind.
: ${VALGRIND=valgrind}
if ($VALGRIND --version) >/dev/null 2>&1; then
local suppressions
if test -f $srcdir/valgrind-suppressions; then
suppressions="--suppressions=$srcdir/valgrind-suppressions"
fi
case $($VALGRIND --help) in
*--log-file-exactly*) valgrind_log_option_name=--log-file-exactly ;;
*) valgrind_log_option_name=--log-file ;;
esac
echo "$VALGRIND" \
"--error-exitcode=242" \
"$valgrind_log_option_name=$log" \
"$suppressions" \
"--"
else
stderr "cannot find valgrind as $VALGRIND"
fi
;;
*)
# Don't instrument.
;;
esac
}
# FIXME: This should be issued farther in the code, not with the functions.
normalize_boolean INSTRUMENT
])
m4_defun([URBI_INSTRUMENT_PREPARE],
[m4_divert_text([M4SH-INIT], [_URBI_INSTRUMENT_PREPARE])])
|
Handle recent valgrinds without --log-file-exactly option.
|
Handle recent valgrinds without --log-file-exactly option.
* build-aux/instrument.as(instrument): Check output of valgrind
--help to find the name of the loging option.
Signed-off-by: Matthieu Nottale <[email protected]>
|
ActionScript
|
bsd-3-clause
|
aldebaran/libport,aldebaran/libport,aldebaran/libport,aldebaran/libport,aldebaran/libport
|
456b93e08ff4dfad844eb890719c450a1fa3f287
|
src/as/com/threerings/ezgame/client/EZGamePanel.as
|
src/as/com/threerings/ezgame/client/EZGamePanel.as
|
//
// $Id$
//
// Vilya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/vilya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.ezgame.client {
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.Loader;
import flash.events.Event;
import flash.utils.Dictionary;
import mx.containers.Canvas;
import mx.core.Container;
import mx.core.IChildList;
import com.threerings.flash.MediaContainer;
import com.threerings.crowd.client.PlaceView;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.crowd.util.CrowdContext;
import com.threerings.ezgame.data.EZGameConfig;
import com.threerings.ezgame.data.EZGameObject;
public class EZGamePanel extends Canvas
implements PlaceView
{
/** The game object backend. */
public var backend :GameControlBackend;
public function EZGamePanel (ctx :CrowdContext, ctrl :EZGameController)
{
_ctx = ctx;
_ctrl = ctrl;
}
// from PlaceView
public function willEnterPlace (plobj :PlaceObject) :void
{
var cfg :EZGameConfig = (_ctrl.getPlaceConfig() as EZGameConfig);
_ezObj = (plobj as EZGameObject);
backend = createBackend();
_gameView = new GameContainer(cfg.getGameDefinition().getMediaPath(cfg.getGameId()));
_gameView.percentWidth = 100;
_gameView.percentHeight = 100;
backend.setSharedEvents(
Loader(_gameView.getMediaContainer().getMedia()).contentLoaderInfo.sharedEvents);
backend.setContainer(_gameView);
addChild(_gameView);
}
// from PlaceView
public function didLeavePlace (plobj :PlaceObject) :void
{
_gameView.getMediaContainer().shutdown(true);
removeChild(_gameView);
backend.shutdown();
}
/**
* Creates the backend object that will handle requests from user code.
*/
protected function createBackend () :GameControlBackend
{
return new GameControlBackend(_ctx, _ezObj, _ctrl);
}
protected var _ctx :CrowdContext;
protected var _ctrl :EZGameController;
protected var _gameView :GameContainer;
protected var _ezObj :EZGameObject;
}
}
|
//
// $Id$
//
// Vilya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/vilya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.ezgame.client {
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.Loader;
import flash.events.Event;
import flash.utils.Dictionary;
import mx.containers.Canvas;
import mx.core.Container;
import mx.core.IChildList;
import com.threerings.flash.MediaContainer;
import com.threerings.crowd.client.PlaceView;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.crowd.util.CrowdContext;
import com.threerings.ezgame.data.EZGameConfig;
import com.threerings.ezgame.data.EZGameObject;
public class EZGamePanel extends Canvas
implements PlaceView
{
/** The game object backend. */
public var backend :GameControlBackend;
public function EZGamePanel (ctx :CrowdContext, ctrl :EZGameController)
{
_ctx = ctx;
_ctrl = ctrl;
}
// from PlaceView
public function willEnterPlace (plobj :PlaceObject) :void
{
var cfg :EZGameConfig = (_ctrl.getPlaceConfig() as EZGameConfig);
_ezObj = (plobj as EZGameObject);
backend = createBackend();
_gameView = new GameContainer(cfg.getGameDefinition().getMediaPath(cfg.getGameId()));
configureGameView(_gameView);
backend.setSharedEvents(
Loader(_gameView.getMediaContainer().getMedia()).contentLoaderInfo.sharedEvents);
backend.setContainer(_gameView);
addChild(_gameView);
}
// from PlaceView
public function didLeavePlace (plobj :PlaceObject) :void
{
_gameView.getMediaContainer().shutdown(true);
removeChild(_gameView);
backend.shutdown();
}
/**
* Creates the backend object that will handle requests from user code.
*/
protected function createBackend () :GameControlBackend
{
return new GameControlBackend(_ctx, _ezObj, _ctrl);
}
protected function configureGameView (view :GameContainer) :void
{
view.percentWidth = 100;
view.percentHeight = 100;
}
protected var _ctx :CrowdContext;
protected var _ctrl :EZGameController;
protected var _gameView :GameContainer;
protected var _ezObj :EZGameObject;
}
}
|
Allow our derived class to override our width/height configuration.
|
Allow our derived class to override our width/height configuration.
git-svn-id: a3e1eb16dde062992de22c830ed8045c8013209a@460 c613c5cb-e716-0410-b11b-feb51c14d237
|
ActionScript
|
lgpl-2.1
|
threerings/vilya,threerings/vilya
|
76155102fd6151b96029033e1013e6adecf16410
|
WEB-INF/lps/lfc/kernel/swf9/LzInputTextSprite.as
|
WEB-INF/lps/lfc/kernel/swf9/LzInputTextSprite.as
|
/**
* LzInputTextSprite.as
*
* @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic AS2
*/
/**
* @shortdesc Used for input text.
*
*/
class LzInputTextSprite extends LzTextSprite {
#passthrough (toplevel:true) {
import flash.display.*;
import flash.events.*;
import flash.text.*;
}#
#passthrough {
function LzInputTextSprite (newowner = null, args = null) {
super(newowner);
}
var __handlelostFocusdel;
var enabled = true;
var focusable = true;
var hasFocus = false;
var scroll = 0;
override public function __initTextProperties (args:Object) {
super.__initTextProperties(args);
// We do not support html in input fields.
if (this.enabled) {
textfield.type = TextFieldType.INPUT;
} else {
textfield.type = TextFieldType.DYNAMIC;
}
/*
TODO [hqm 2008-01]
these handlers need to be implemented via Flash native event listenters:
focusIn , focusOut
change -- dispatched after text input is modified
textInput -- dispatched before the content is modified
Do we need to use this for intercepting when we have
a pattern restriction on input?
*/
textfield.addEventListener(Event.CHANGE , __onChanged);
//textfield.addEventListener(TextEvent.TEXT_INPUT, __onTextInput);
textfield.addEventListener(FocusEvent.FOCUS_IN , __gotFocus);
textfield.addEventListener(FocusEvent.FOCUS_OUT, __lostFocus);
this.hasFocus = false;
}
/**
* @access private
*/
public function gotFocus ( ){
//Debug.write('LzInputTextSprite.__handleOnFocus');
if ( this.hasFocus ) { return; }
this.select();
this.hasFocus = true;
}
function select ( ){
textfield.setSelection(0, textfield.text.length);
}
// XXXX selectionBeginIndex property
function deselect ( ){
textfield.setSelection(0,0);
}
/**
* @access private
*/
function gotBlur ( ){
//Debug.write('LzInputTextSprite.__handleOnBlur');
this.hasFocus = false;
this.deselect();
}
/**
* TODO [hqm 2008-01] I have no idea whether this comment
* still applies:
* Register for update on every frame when the text field gets the focus.
* Set the behavior of the enter key depending on whether the field is
* multiline or not.
*
* @access private
*/
function __gotFocus ( event:Event ){
// scroll text fields horizontally back to start
if (owner) owner.inputtextevent('onfocus');
}
/**
* Register to be called when the text field is modified. Convert this
* into a LFC ontext event.
* @access private
*/
function __onChanged (event:Event ){
if (owner) owner.inputtextevent('onchange', this.text);
}
/**
* @access private
* TODO [hqm 2008-01] Does we still need this workaround???
*/
function __lostFocus (event:Event){
trace('lost focus', event.target);
//if (this['__handlelostFocusdel'] == null) this.__handlelostFocusdel = new LzDelegate(this, "__handlelostFocus");
//lz.Idle.callOnIdle(this.__handlelostFocusdel);
}
/**
* TODO [hqm 2008-01] Does this comment still apply? Do we still need this workaround???
*
* must be called after an idle event to prevent the selection from being
* cleared prematurely, e.g. before a button click. If the selection is
* cleared, the button doesn't send mouse events.
* @access private
*/
function __handlelostFocus (evt ){
if (owner == lz.Focus.getFocus()) {
lz.Focus.clearFocus();
if (owner) owner.inputtextevent('onblur');
}
}
/**
* Retrieves the contents of the text field for use by a datapath. See
* <code>LzDatapath.updateData</code> for more on this.
* @access protected
*/
function updateData (){
return textfield.text;
}
/**
* Sets whether user can modify input text field
* @param Boolean enabled: true if the text field can be edited
*/
function setEnabled (enabled){
this.enabled = enabled;
if (enabled) {
textfield.type = 'input';
} else {
textfield.type = 'dynamic';
}
}
/**
* Set the html flag on this text view
*/
function setHTML (htmlp) {
// TODO [hqm 2008-10] what do we do here?
}
override public function getTextfieldHeight ( ){
return this.textfield.height;
}
/**
* If a mouse event occurs in an input text field, find the focused view
* TODO: implement
*/
static function findSelection(){
return null;
}
}# // #passthrough
} // End of LzInputTextSprite
|
/**
* LzInputTextSprite.as
*
* @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic AS2
*/
/**
* @shortdesc Used for input text.
*
*/
class LzInputTextSprite extends LzTextSprite {
#passthrough (toplevel:true) {
import flash.display.*;
import flash.events.*;
import flash.text.*;
}#
#passthrough {
function LzInputTextSprite (newowner = null, args = null) {
super(newowner);
}
var __handlelostFocusdel;
var enabled = true;
var focusable = true;
var hasFocus = false;
var scroll = 0;
override public function __initTextProperties (args:Object) {
super.__initTextProperties(args);
// We do not support html in input fields.
if (this.enabled) {
textfield.type = TextFieldType.INPUT;
} else {
textfield.type = TextFieldType.DYNAMIC;
}
/*
TODO [hqm 2008-01]
these handlers need to be implemented via Flash native event listenters:
focusIn , focusOut
change -- dispatched after text input is modified
textInput -- dispatched before the content is modified
Do we need to use this for intercepting when we have
a pattern restriction on input?
*/
textfield.addEventListener(Event.CHANGE , __onChanged);
//textfield.addEventListener(TextEvent.TEXT_INPUT, __onTextInput);
textfield.addEventListener(FocusEvent.FOCUS_IN , __gotFocus);
textfield.addEventListener(FocusEvent.FOCUS_OUT, __lostFocus);
this.hasFocus = false;
}
/**
* @access private
*/
public function gotFocus ( ){
//Debug.write('LzInputTextSprite.__handleOnFocus');
if ( this.hasFocus ) { return; }
this.select();
this.hasFocus = true;
}
function select ( ){
textfield.setSelection(0, textfield.text.length);
}
// XXXX selectionBeginIndex property
function deselect ( ){
textfield.setSelection(0,0);
}
/**
* @access private
*/
function gotBlur ( ){
//Debug.write('LzInputTextSprite.__handleOnBlur');
this.hasFocus = false;
this.deselect();
}
/**
* TODO [hqm 2008-01] I have no idea whether this comment
* still applies:
* Register for update on every frame when the text field gets the focus.
* Set the behavior of the enter key depending on whether the field is
* multiline or not.
*
* @access private
*/
function __gotFocus ( event:Event ){
// scroll text fields horizontally back to start
if (owner) owner.inputtextevent('onfocus');
}
/**
* Register to be called when the text field is modified. Convert this
* into a LFC ontext event.
* @access private
*/
function __onChanged (event:Event ){
if (owner) owner.inputtextevent('onchange', this.text);
}
/**
* @access private
* TODO [hqm 2008-01] Does we still need this workaround???
*/
function __lostFocus (event:Event){
trace('lost focus', event.target);
//if (this['__handlelostFocusdel'] == null) this.__handlelostFocusdel = new LzDelegate(this, "__handlelostFocus");
//lz.Idle.callOnIdle(this.__handlelostFocusdel);
}
/**
* TODO [hqm 2008-01] Does this comment still apply? Do we still need this workaround???
*
* must be called after an idle event to prevent the selection from being
* cleared prematurely, e.g. before a button click. If the selection is
* cleared, the button doesn't send mouse events.
* @access private
*/
function __handlelostFocus (evt ){
if (owner == lz.Focus.getFocus()) {
lz.Focus.clearFocus();
if (owner) owner.inputtextevent('onblur');
}
}
/**
* Get the current text for this inputtext-sprite.
* @protected
*/
override public function getText():String {
return textfield.text;
}
/**
* Retrieves the contents of the text field for use by a datapath. See
* <code>LzDatapath.updateData</code> for more on this.
* @access protected
*/
function updateData (){
return textfield.text;
}
/**
* Sets whether user can modify input text field
* @param Boolean enabled: true if the text field can be edited
*/
function setEnabled (enabled){
this.enabled = enabled;
if (enabled) {
textfield.type = 'input';
} else {
textfield.type = 'dynamic';
}
}
/**
* Set the html flag on this text view
*/
function setHTML (htmlp) {
// TODO [hqm 2008-10] what do we do here?
}
override public function getTextfieldHeight ( ){
return this.textfield.height;
}
/**
* If a mouse event occurs in an input text field, find the focused view
* TODO: implement
*/
static function findSelection(){
return null;
}
}# // #passthrough
} // End of LzInputTextSprite
|
Change 20080601-bargull-EDo by bargull@dell--p4--2-53 on 2008-06-01 02:15:32 in /home/Admin/src/svn/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk
|
Change 20080601-bargull-EDo by bargull@dell--p4--2-53 on 2008-06-01 02:15:32
in /home/Admin/src/svn/openlaszlo/trunk
for http://svn.openlaszlo.org/openlaszlo/trunk
Summary: return current text for inputtext-sprite
New Features:
Bugs Fixed: LPP-6079
Technical Reviewer: hminsky
QA Reviewer: (pending)
Doc Reviewer: (pending)
Documentation:
Release Notes:
Details:
Just return the flash textfield's text. That way it's consistent across all runtimes.
Tests:
git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@9415 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
|
ActionScript
|
epl-1.0
|
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
|
b2db2e48b2d2946d8a560c37cfa241a13cc5c72f
|
src/com/axis/http/auth.as
|
src/com/axis/http/auth.as
|
package com.axis.http {
import com.adobe.crypto.MD5;
import com.axis.Logger;
import com.axis.rtspclient.GUID;
import flash.net.Socket;
import mx.utils.Base64Encoder;
public class auth {
public static function basic(user:String, pass:String):String {
var b64:Base64Encoder = new Base64Encoder();
b64.insertNewLines = false;
b64.encode(user + ':' + pass);
return 'Basic ' + b64.toString();
}
public static function digest(
user:String,
pass:String,
httpmethod:String,
realm:String,
uri:String,
qop:String,
nonce:String,
nc:uint
):String {
/* NOTE: Unsupported: md5-sess and auth-int */
if (qop && 'auth' !== qop) {
Logger.log('unsupported quality of protection: ' + qop);
return "";
}
var ha1:String = MD5.hash(user + ':' + realm + ':' + pass);
var ha2:String = MD5.hash(httpmethod + ':' + uri);
var cnonce:String = MD5.hash(GUID.create());
var hashme:String = qop ?
(ha1 + ':' + nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2) :
(ha1 + ':' + nonce + ':' + ha2)
var resp:String = MD5.hash(hashme);
return 'Digest ' +
'username="' + user + '", ' +
'realm="' + realm + '", ' +
'nonce="' + nonce + '", ' +
'uri="' + uri + '", ' +
'nc="' + nc + '", ' +
(qop ? ('qop="' + qop + '", ') : '') +
(qop ? ('cnonce="' + cnonce + '", ') : '') +
'response="' + resp + '"'
;
}
public static function nextMethod(current:String, authOpts:Object):String {
switch (current) {
case 'none':
/* No authorization attempt yet, try with the best method supported by server */
if (authOpts.digestRealm)
return 'digest';
else if (authOpts.basicRealm)
return 'basic';
break;
case 'digest':
/* Weird to get unauthorized here unless credentials are invalid.
On the off-chance of server-bug, try basic aswell */
if (authOpts.basicRealm)
return 'basic';
case 'basic':
/* If we failed with basic, we're done. Credentials are invalid. */
}
/* Getting the same method as passed as current should be considered an error */
return current;
}
public static function authorizationHeader(
method:String,
authState:String,
authOpts:Object,
urlParsed:Object,
digestNC:uint):String {
var content:String = '';
switch (authState) {
case "basic":
content = basic(urlParsed.user, urlParsed.pass);
break;
case "digest":
content = digest(
urlParsed.user,
urlParsed.pass,
method,
authOpts.digestRealm,
urlParsed.urlpath,
authOpts.qop,
authOpts.nonce,
digestNC
);
break;
default:
case "none":
return "";
}
return "Authorization: " + content + "\r\n"
}
}
}
|
package com.axis.http {
import com.adobe.crypto.MD5;
import com.axis.Logger;
import com.axis.rtspclient.GUID;
import flash.net.Socket;
import mx.utils.Base64Encoder;
public class auth {
public static function basic(user:String, pass:String):String {
var b64:Base64Encoder = new Base64Encoder();
b64.insertNewLines = false;
b64.encode(user + ':' + pass);
return 'Basic ' + b64.toString();
}
public static function digest(
user:String,
pass:String,
httpmethod:String,
realm:String,
uri:String,
qop:String,
nonce:String,
nc:uint
):String {
/* NOTE: Unsupported: md5-sess and auth-int */
if (qop && 'auth' !== qop) {
Logger.log('unsupported quality of protection: ' + qop);
return "";
}
var ha1:String = MD5.hash(user + ':' + realm + ':' + pass);
var ha2:String = MD5.hash(httpmethod + ':' + uri);
var cnonce:String = MD5.hash(GUID.create());
var hashme:String = qop ?
(ha1 + ':' + nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2) :
(ha1 + ':' + nonce + ':' + ha2)
var resp:String = MD5.hash(hashme);
return 'Digest ' +
'username="' + user + '", ' +
'realm="' + realm + '", ' +
'nonce="' + nonce + '", ' +
'uri="' + uri + '", ' +
'nc="' + nc + '", ' +
(qop ? ('qop="' + qop + '", ') : '') +
(qop ? ('cnonce="' + cnonce + '", ') : '') +
'response="' + resp + '"'
;
}
public static function nextMethod(current:String, authOpts:Object):String {
switch (current) {
case 'none':
/* No authorization attempt yet, try with the best method supported by server */
if (authOpts.digestRealm)
return 'digest';
else if (authOpts.hasOwnProperty('basicRealm'))
return 'basic';
break;
case 'digest':
/* Weird to get unauthorized here unless credentials are invalid.
On the off-chance of server-bug, try basic aswell */
if (authOpts.basicRealm)
return 'basic';
case 'basic':
/* If we failed with basic, we're done. Credentials are invalid. */
}
/* Getting the same method as passed as current should be considered an error */
return current;
}
public static function authorizationHeader(
method:String,
authState:String,
authOpts:Object,
urlParsed:Object,
digestNC:uint):String {
var content:String = '';
switch (authState) {
case "basic":
content = basic(urlParsed.user, urlParsed.pass);
break;
case "digest":
content = digest(
urlParsed.user,
urlParsed.pass,
method,
authOpts.digestRealm,
urlParsed.urlpath,
authOpts.qop,
authOpts.nonce,
digestNC
);
break;
default:
case "none":
return "";
}
return "Authorization: " + content + "\r\n"
}
}
}
|
Check that property exist, not value (might be empty string)
|
Check that property exist, not value (might be empty string)
|
ActionScript
|
bsd-3-clause
|
gaetancollaud/locomote-video-player,AxisCommunications/locomote-video-player
|
ac70152b618adadf69a92aa99fc3176b5e3c6ecf
|
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 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;
[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);
}
[After]
public function after():void {
classLevelCloneable = null;
classLevelCloneableType = null;
classLevelCopyableCloneable = null;
classLevelCopyableCloneableType = null;
propertyLevelCloneable = null;
propertyLevelCloneableType = null;
}
[Test]
public function testGetCloneableFieldsForType():void {
var cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(classLevelCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
cloneableFields = 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);
}
}
}
|
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 testGetCloneableFieldsForType():void {
var cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(classLevelCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
cloneableFields = Cloner.getCloneableFieldsForType(classLevelCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
cloneableFields = Cloner.getCloneableFieldsForType(propertyLevelCloneableType);
assertNotNull(cloneableFields);
assertEquals(3, cloneableFields.length);
cloneableFields = Cloner.getCloneableFieldsForType(propertyLevelCopyableCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
}
[Test]
public function testCloneWithClassLevelMetadata():void {
const clone1:ClassLevelCloneable = Cloner.clone(classLevelCloneable);
assertNotNull(clone1);
assertNotNull(clone1.property1);
assertEquals(clone1.property1, classLevelCloneable.property1);
assertNotNull(clone1.property2);
assertEquals(clone1.property2, classLevelCloneable.property2);
assertNotNull(clone1.property3);
assertEquals(clone1.property3, classLevelCloneable.property3);
assertNotNull(clone1.writableField);
assertEquals(clone1.writableField, classLevelCloneable.writableField);
const clone2:ClassLevelCopyableCloneable = Cloner.clone(classLevelCopyableCloneable);
assertNotNull(clone2);
assertNotNull(clone2.property1);
assertEquals(clone2.property1, classLevelCloneable.property1);
assertNotNull(clone2.property2);
assertEquals(clone2.property2, classLevelCloneable.property2);
assertNotNull(clone2.property3);
assertEquals(clone2.property3, classLevelCloneable.property3);
assertNotNull(clone2.writableField);
assertEquals(clone2.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);
}
}
}
|
Test classes ClassLevelCopyableCloneable and PropertyLevelCopyableCloneable in ClonerTest.
|
Test classes ClassLevelCopyableCloneable and PropertyLevelCopyableCloneable in ClonerTest.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
42c38ea8fb3ee3571a6afd9e43a9099d0c84ed66
|
src/aerys/minko/render/geometry/primitive/CubeGeometry.as
|
src/aerys/minko/render/geometry/primitive/CubeGeometry.as
|
package aerys.minko.render.geometry.primitive
{
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.geometry.stream.IVertexStream;
import aerys.minko.render.geometry.stream.IndexStream;
import aerys.minko.render.geometry.stream.StreamUsage;
import aerys.minko.render.geometry.stream.VertexStream;
import aerys.minko.render.geometry.stream.format.VertexFormat;
/**
* The CubeGeometry class represents the 3D geometry of a cube.
*
* @author Jean-Marc Le Roux
*/
public class CubeGeometry extends Geometry
{
private static var _instance : CubeGeometry = null;
public static function get cubeGeometry() : CubeGeometry
{
return _instance || (_instance = new CubeGeometry(StreamUsage.DYNAMIC));
}
/**
* Creates a new CubeMesh object.
*/
public function CubeGeometry(vertexStreamUsage : uint = 3,
indexStreamUsage : uint = 3)
{
var data : Vector.<Number> = new <Number>[
// top
0.5, 0.5, 0.5, 1., 0., -0.5, 0.5, -0.5, 0., 1., 0.5, 0.5, -0.5, 1., 1.,
0.5, 0.5, 0.5, 1., 0., -0.5, 0.5, 0.5, 0., 0., -0.5, 0.5, -0.5, 0., 1.,
// bottom
-0.5, -0.5, -0.5, 0., 0., 0.5, -0.5, 0.5, 1., 1., 0.5, -0.5, -0.5, 1., 0.,
-0.5, -0.5, 0.5, 0., 1., 0.5, -0.5, 0.5, 1., 1., -0.5, -0.5, -0.5, 0., 0.,
// back
0.5, -0.5, 0.5, 0., 1., -0.5, 0.5, 0.5, 1., 0., 0.5, 0.5, 0.5, 0., 0.,
-0.5, 0.5, 0.5, 1., 0., 0.5, -0.5, 0.5, 0., 1., -0.5, -0.5, 0.5, 1., 1.,
// front
-0.5, 0.5, -0.5, 0., 0., -0.5, -0.5, -0.5, 0., 1., 0.5, 0.5, -0.5, 1., 0.,
-0.5, -0.5, -0.5, 0., 1., 0.5, -0.5, -0.5, 1., 1., 0.5, 0.5, -0.5, 1., 0.,
// left
-0.5, -0.5, -0.5, 1., 1., -0.5, 0.5, 0.5, 0., 0., -0.5, -0.5, 0.5, 0., 1.,
-0.5, 0.5, 0.5, 0., 0., -0.5, -0.5, -0.5, 1., 1., -0.5, 0.5, -0.5, 1., 0.,
// right
0.5, -0.5, 0.5, 1., 1., 0.5, 0.5, 0.5, 1., 0., 0.5, 0.5, -0.5, 0., 0.,
0.5, 0.5, -0.5, 0., 0., 0.5, -0.5, -0.5, 0., 1., 0.5, -0.5, 0.5, 1., 1.
];
var vertexStream : VertexStream = VertexStream.fromVector(
vertexStreamUsage, VertexFormat.XYZ_UV, data
);
super(
new <IVertexStream>[vertexStream],
new IndexStream(indexStreamUsage, IndexStream.dummyData(vertexStream.numVertices, 0))
);
}
}
}
|
package aerys.minko.render.geometry.primitive
{
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.geometry.stream.IVertexStream;
import aerys.minko.render.geometry.stream.IndexStream;
import aerys.minko.render.geometry.stream.StreamUsage;
import aerys.minko.render.geometry.stream.VertexStream;
import aerys.minko.render.geometry.stream.format.VertexFormat;
import aerys.minko.type.math.BoundingBox;
import aerys.minko.type.math.Vector4;
/**
* The CubeGeometry class represents the 3D geometry of a cube.
*
* @author Jean-Marc Le Roux
*/
public class CubeGeometry extends Geometry
{
private static var _instance : CubeGeometry = null;
public static function get cubeGeometry() : CubeGeometry
{
return _instance || (_instance = new CubeGeometry(StreamUsage.DYNAMIC));
}
/**
* Creates a new CubeMesh object.
*/
public function CubeGeometry(vertexStreamUsage : uint = 3,
indexStreamUsage : uint = 3)
{
var data : Vector.<Number> = new <Number>[
// top
0.5, 0.5, 0.5, 1., 0., -0.5, 0.5, -0.5, 0., 1., 0.5, 0.5, -0.5, 1., 1.,
0.5, 0.5, 0.5, 1., 0., -0.5, 0.5, 0.5, 0., 0., -0.5, 0.5, -0.5, 0., 1.,
// bottom
-0.5, -0.5, -0.5, 0., 0., 0.5, -0.5, 0.5, 1., 1., 0.5, -0.5, -0.5, 1., 0.,
-0.5, -0.5, 0.5, 0., 1., 0.5, -0.5, 0.5, 1., 1., -0.5, -0.5, -0.5, 0., 0.,
// back
0.5, -0.5, 0.5, 0., 1., -0.5, 0.5, 0.5, 1., 0., 0.5, 0.5, 0.5, 0., 0.,
-0.5, 0.5, 0.5, 1., 0., 0.5, -0.5, 0.5, 0., 1., -0.5, -0.5, 0.5, 1., 1.,
// front
-0.5, 0.5, -0.5, 0., 0., -0.5, -0.5, -0.5, 0., 1., 0.5, 0.5, -0.5, 1., 0.,
-0.5, -0.5, -0.5, 0., 1., 0.5, -0.5, -0.5, 1., 1., 0.5, 0.5, -0.5, 1., 0.,
// left
-0.5, -0.5, -0.5, 1., 1., -0.5, 0.5, 0.5, 0., 0., -0.5, -0.5, 0.5, 0., 1.,
-0.5, 0.5, 0.5, 0., 0., -0.5, -0.5, -0.5, 1., 1., -0.5, 0.5, -0.5, 1., 0.,
// right
0.5, -0.5, 0.5, 1., 1., 0.5, 0.5, 0.5, 1., 0., 0.5, 0.5, -0.5, 0., 0.,
0.5, 0.5, -0.5, 0., 0., 0.5, -0.5, -0.5, 0., 1., 0.5, -0.5, 0.5, 1., 1.
];
var vertexStream : VertexStream = VertexStream.fromVector(
vertexStreamUsage, VertexFormat.XYZ_UV, data
);
super(
new <IVertexStream>[vertexStream],
new IndexStream(indexStreamUsage, IndexStream.dummyData(vertexStream.numVertices, 0))
);
}
static public function fromBoundingBox(boundingBox : BoundingBox,
vertexStreamUsage : uint = 3,
indexStreamUsage : uint = 3) : Geometry
{
var max : Vector4 = boundingBox.max;
var min : Vector4 = boundingBox.min;
var data : Vector.<Number> = new <Number>[
// top
max.x, max.y, max.z, 1., 0., min.x, max.y, min.z, 0., 1., max.x, max.y, min.z, 1., 1.,
max.x, max.y, max.z, 1., 0., min.x, max.y, max.z, 0., 0., min.x, max.y, min.z, 0., 1.,
// bottom
min.x, min.y, min.z, 0., 0., max.x, min.y, max.z, 1., 1., max.x, min.y, min.z, 1., 0.,
min.x, min.y, max.z, 0., 1., max.x, min.y, max.z, 1., 1., min.x, min.y, min.z, 0., 0.,
// back
max.x, min.y, max.z, 0., 1., min.x, max.y, max.z, 1., 0., max.x, max.y, max.z, 0., 0.,
min.x, max.y, max.z, 1., 0., max.x, min.y, max.z, 0., 1., min.x, min.y, max.z, 1., 1.,
// front
min.x, max.y, min.z, 0., 0., min.x, min.y, min.z, 0., 1., max.x, max.y, min.z, 1., 0.,
min.x, min.y, min.z, 0., 1., max.x, min.y, min.z, 1., 1., max.x, max.y, min.z, 1., 0.,
// left
min.x, min.y, min.z, 1., 1., min.x, max.y, max.z, 0., 0., min.x, min.y, max.z, 0., 1.,
min.x, max.y, max.z, 0., 0., min.x, min.y, min.z, 1., 1., min.x, max.y, min.z, 1., 0.,
// right
max.x, min.y, max.z, 1., 1., max.x, max.y, max.z, 1., 0., max.x, max.y, min.z, 0., 0.,
max.x, max.y, min.z, 0., 0., max.x, min.y, min.z, 0., 1., max.x, min.y, max.z, 1., 1.
];
var vertexStream : VertexStream = VertexStream.fromVector(
vertexStreamUsage, VertexFormat.XYZ_UV, data
);
return new Geometry(
new <IVertexStream>[vertexStream],
new IndexStream(indexStreamUsage, IndexStream.dummyData(vertexStream.numVertices, 0))
);
}
}
}
|
add CubeGeometry.fromBoundingBox()
|
add CubeGeometry.fromBoundingBox()
|
ActionScript
|
mit
|
aerys/minko-as3
|
ba0c86d5bcdd950776a210b628718c57c69c58a1
|
src/aerys/minko/render/shader/ShaderDataBindings.as
|
src/aerys/minko/render/shader/ShaderDataBindings.as
|
package aerys.minko.render.shader
{
import aerys.minko.render.shader.compiler.graph.nodes.leaf.BindableConstant;
import aerys.minko.render.shader.compiler.graph.nodes.leaf.BindableSampler;
import aerys.minko.type.binding.DataBindings;
/**
* The wrapper used to expose scene/mesh data bindings in ActionScript shaders.
*
* @author Jean-Marc Le Roux
*
*/
public final class ShaderDataBindings
{
private var _dataBindings : DataBindings = null;
private var _signature : Signature = null;
private var _signatureFlags : uint = 0;
public function ShaderDataBindings(bindings : DataBindings,
signature : Signature,
signatureFlags : uint)
{
_dataBindings = bindings;
_signature = signature;
_signatureFlags = signatureFlags;
}
public function getParameter(name : String, size : uint) : SFloat
{
return new SFloat(new BindableConstant(name, size));
}
public function getTextureParameter(bindingName : String,
filter : uint = 1,
mipmap : uint = 0,
wrapping : uint = 1,
dimension : uint = 0) : SFloat
{
return new SFloat(
new BindableSampler(bindingName, filter, mipmap, wrapping, dimension)
);
}
public function propertyExists(propertyName : String) : Boolean
{
var value : Boolean = _dataBindings.propertyExists(propertyName);
_signature.update(
propertyName,
value,
Signature.OPERATION_EXISTS | _signatureFlags
);
return value;
}
public function getConstant(propertyName : String,
defaultValue : Object = null) : *
{
if (!_dataBindings.propertyExists(propertyName))
{
if (defaultValue === null)
{
throw new Error(
"The property '" + propertyName
+ "' does not exist and no default value was provided."
);
}
_signature.update(
propertyName,
false,
Signature.OPERATION_EXISTS | _signatureFlags
);
return defaultValue;
}
var value : Object = _dataBindings.getProperty(propertyName);
_signature.update(
propertyName,
value,
Signature.OPERATION_GET | _signatureFlags
);
return value;
}
}
}
|
package aerys.minko.render.shader
{
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.render.shader.compiler.Serializer;
import aerys.minko.render.shader.compiler.graph.nodes.leaf.BindableConstant;
import aerys.minko.render.shader.compiler.graph.nodes.leaf.BindableSampler;
import aerys.minko.render.shader.compiler.graph.nodes.leaf.Constant;
import aerys.minko.render.shader.compiler.graph.nodes.leaf.Sampler;
import aerys.minko.type.binding.DataBindings;
/**
* The wrapper used to expose scene/mesh data bindings in ActionScript shaders.
*
* @author Jean-Marc Le Roux
*
*/
public final class ShaderDataBindings
{
private var _dataBindings : DataBindings = null;
private var _signature : Signature = null;
private var _signatureFlags : uint = 0;
public function ShaderDataBindings(bindings : DataBindings,
signature : Signature,
signatureFlags : uint)
{
_dataBindings = bindings;
_signature = signature;
_signatureFlags = signatureFlags;
}
public function getParameter(name : String,
size : uint,
defaultValue : Object = null) : SFloat
{
if (defaultValue != null && !propertyExists(name))
{
var constantValue : Vector.<Number> = new Vector.<Number>();
Serializer.serializeKnownLength(defaultValue, constantValue, 0, size);
return new SFloat(new Constant(constantValue));
}
return new SFloat(new BindableConstant(name, size));
}
public function getTextureParameter(bindingName : String,
filter : uint = 1,
mipmap : uint = 0,
wrapping : uint = 1,
dimension : uint = 0,
defaultValue : TextureResource = null) : SFloat
{
if (defaultValue != null && !propertyExists(bindingName))
return new SFloat(new Sampler(defaultValue, filter, mipmap, wrapping, dimension));
return new SFloat(
new BindableSampler(bindingName, filter, mipmap, wrapping, dimension)
);
}
public function propertyExists(propertyName : String) : Boolean
{
var value : Boolean = _dataBindings.propertyExists(propertyName);
_signature.update(
propertyName,
value,
Signature.OPERATION_EXISTS | _signatureFlags
);
return value;
}
public function getConstant(propertyName : String,
defaultValue : Object = null) : *
{
if (!_dataBindings.propertyExists(propertyName))
{
if (defaultValue === null)
{
throw new Error(
"The property '" + propertyName
+ "' does not exist and no default value was provided."
);
}
_signature.update(
propertyName,
false,
Signature.OPERATION_EXISTS | _signatureFlags
);
return defaultValue;
}
var value : Object = _dataBindings.getProperty(propertyName);
_signature.update(
propertyName,
value,
Signature.OPERATION_GET | _signatureFlags
);
return value;
}
}
}
|
Add default values to shader parameters (#380)
|
Add default values to shader parameters (#380)
|
ActionScript
|
mit
|
aerys/minko-as3
|
ac55c8b5274f736bc2b5bf0104dd13c42757c3fd
|
frameworks/projects/framework/src/mx/styles/CSSDimension.as
|
frameworks/projects/framework/src/mx/styles/CSSDimension.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package mx.styles
{
import mx.utils.ObjectUtil;
/**
* Represents a dimension with an optional unit, to be used in css media queries.
* <p>Valid units are:
* no unit
* px : pixel
* in : inch
* cm : centimeter
* pt : point
* dp : device independent pixel ( 1 pix at about 160 DPI )
*
* @langversion 3.0
* @playerversion AIR 3.0
* @productversion Flex 4.13
*/
public class CSSDimension
{
/* device independent units */
static public const NO_UNIT: String = "";
static public const UNIT_INCH: String = "in";
static public const UNIT_CM: String = "cm";
static public const UNIT_PT: String = "pt";
static public const UNIT_DP: String = "dp";
/* pixel units */
static private const UNIT_PX: String = "px";
/* scale factor for device independent units */
static private const INCH_PER_INCH: Number = 1.0;
static private const CM_PER_INCH: Number = 2.54;
static private const PT_PER_INCH: Number = 72;
static private const DP_PER_INCH: Number = 160;
private var _value: Number;
private var _unit: String;
private var _pixelValue: int;
/** Constructor
*
* @param value
* @param refDPI
* @param unit
*
*/
public function CSSDimension(value: Number, refDPI: Number, unit: String = NO_UNIT)
{
_value = value;
_unit = unit;
_pixelValue = computePixelValue(refDPI);
}
/** Dimension unit, as a string, or empty string if no unit
*
*/
public function get unit(): String
{
return _unit;
}
/** Dimension value as a number, without the unit
*/
public function get value(): Number
{
return _value;
}
/**
* Dimension converted to actual pixels, considering the current device DPI
*/
public function get pixelValue(): Number
{
return _pixelValue;
}
/**
* Compares to another CSSDimension instance.
* Actual pixel values are used for comparison, so dimensions can have different units.
*
* @param other another CSSDimension instance
*
* @return 0 if both dimensions are of equal value. rounding errors may occur due to conversion
* -1 if <code>this</code> is lower than <code>other</code>.
* 1 if <code>this</code> is greater than <code>other</code>.
*
* @langversion 3.0
* @playerversion AIR 3.0
* @productversion Flex 4.13
*/
public function compareTo(other: CSSDimension): int
{
return ObjectUtil.numericCompare(_pixelValue, other.pixelValue);
}
/**
* Printable string of the dimension
* @return version as a string
*/
public function toString(): String
{
return _value.toString() + _unit;
}
/** @private converts a value with unit an actual pixel value, according to refDPI screen resolution
* the formula is the following for physical units
* pixelValue = value * refDPI / unit_per_inch ;
* eg. 5in at 132 DPI => 5 * 132 /1 =
* eg. 19cm at 132 DPI => 19 * 132 /2.54 =
* */
private function computePixelValue(refDPI: Number): int
{
switch (_unit) {
// test device-independent units
case UNIT_INCH:
return _value * refDPI;
case UNIT_DP:
return _value * refDPI / DP_PER_INCH;
case UNIT_CM:
return _value * refDPI / CM_PER_INCH;
case UNIT_PT:
return _value * refDPI / PT_PER_INCH;
}
// else it's pixel unit
return _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 mx.styles
{
import mx.utils.ObjectUtil;
/**
* Represents a dimension with an optional unit, to be used in css media queries.
* <p>Valid units are:
* no unit
* px : pixel
* in : inch
* cm : centimeter
* pt : point
* dp : device independent pixel ( 1 pix at about 160 DPI )
* </p>
*
* @langversion 3.0
* @playerversion AIR 3.0
* @productversion Flex 4.13
*/
public class CSSDimension
{
/* device independent units */
static public const NO_UNIT: String = "";
static public const UNIT_INCH: String = "in";
static public const UNIT_CM: String = "cm";
static public const UNIT_PT: String = "pt";
static public const UNIT_DP: String = "dp";
/* pixel units */
static private const UNIT_PX: String = "px";
/* scale factor for device independent units */
static private const INCH_PER_INCH: Number = 1.0;
static private const CM_PER_INCH: Number = 2.54;
static private const PT_PER_INCH: Number = 72;
static private const DP_PER_INCH: Number = 160;
private var _value: Number;
private var _unit: String;
private var _pixelValue: int;
/** Constructor
*
* @param value
* @param refDPI
* @param unit
*
*/
public function CSSDimension(value: Number, refDPI: Number, unit: String = NO_UNIT)
{
_value = value;
_unit = unit;
_pixelValue = computePixelValue(refDPI);
}
/** Dimension unit, as a string, or empty string if no unit
*
*/
public function get unit(): String
{
return _unit;
}
/** Dimension value as a number, without the unit
*/
public function get value(): Number
{
return _value;
}
/**
* Dimension converted to actual pixels, considering the current device DPI
*/
public function get pixelValue(): Number
{
return _pixelValue;
}
/**
* Compares to another CSSDimension instance.
* Actual pixel values are used for comparison, so dimensions can have different units.
*
* @param other another CSSDimension instance
*
* @return 0 if both dimensions are of equal value. rounding errors may occur due to conversion
* -1 if <code>this</code> is lower than <code>other</code>.
* 1 if <code>this</code> is greater than <code>other</code>.
*
* @langversion 3.0
* @playerversion AIR 3.0
* @productversion Flex 4.13
*/
public function compareTo(other: CSSDimension): int
{
return ObjectUtil.numericCompare(_pixelValue, other.pixelValue);
}
/**
* Printable string of the dimension
* @return version as a string
*/
public function toString(): String
{
return _value.toString() + _unit;
}
/** @private converts a value with unit an actual pixel value, according to refDPI screen resolution
* the formula is the following for physical units
* pixelValue = value * refDPI / unit_per_inch ;
* eg. 5in at 132 DPI => 5 * 132 /1 =
* eg. 19cm at 132 DPI => 19 * 132 /2.54 =
* */
private function computePixelValue(refDPI: Number): int
{
switch (_unit) {
// test device-independent units
case UNIT_INCH:
return _value * refDPI;
case UNIT_DP:
return _value * refDPI / DP_PER_INCH;
case UNIT_CM:
return _value * refDPI / CM_PER_INCH;
case UNIT_PT:
return _value * refDPI / PT_PER_INCH;
}
// else it's pixel unit
return _value;
}
}
}
|
fix asdoc html
|
fix asdoc html
|
ActionScript
|
apache-2.0
|
shyamalschandra/flex-sdk,apache/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk
|
0bb53f4a222996f77e58a13868390ba1774438e0
|
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
|
f314c4f756b1c2f1172f8714245fca14ca8a2682
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/ImageAndTextButtonView.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/ImageAndTextButtonView.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.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.BeadViewBase;
import org.apache.flex.core.CSSTextField;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IBeadView;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IStrandWithModel;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.html.beads.models.ImageAndTextModel;
/**
* The ImageButtonView class provides an image-only view
* for the standard Button. Unlike the CSSButtonView, this
* class does not support background and border; only images
* for the up, over, and active states.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class ImageAndTextButtonView extends BeadViewBase implements IBeadView, IBead
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function ImageAndTextButtonView()
{
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";
}
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
override public function set strand(value:IStrand):void
{
super.strand = value;
textModel = IStrandWithModel(value).model as ImageAndTextModel;
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;
setupBackground(upSprite, upTextField, 0xCCCCCC);
setupBackground(overSprite, overTextField, 0xFFCCCC, "hover");
setupBackground(downSprite, downTextField, 0x808080, "active");
upTextField.styleParent = value;
downTextField.styleParent = value;
overTextField.styleParent = value;
}
private var upSprite:Sprite;
private var downSprite:Sprite;
private var overSprite:Sprite;
private var shape:Shape;
private var textModel:ImageAndTextModel;
/**
* The URL of an icon to use in the button
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get image():String
{
return textModel.image;
}
/**
* @private
*/
private function setupBackground(sprite:Sprite, textField:CSSTextField, color:uint, state:String = null):void
{
var backgroundImage:Object = image;
if (backgroundImage)
{
var loader:Loader = new Loader();
sprite.addChildAt(loader, 0);
sprite.addChild(textField);
var url:String = backgroundImage as String;
loader.load(new URLRequest(url));
loader.contentLoaderInfo.addEventListener(flash.events.Event.COMPLETE, function (e:flash.events.Event):void {
updateHitArea();
textField.x = loader.width;
sprite.graphics.clear();
sprite.graphics.beginFill(color);
sprite.graphics.drawRect(0, 0, sprite.width, sprite.height);
sprite.graphics.endFill();
});
}
}
private function textChangeHandler(event:Event):void
{
text = textModel.text;
}
private function htmlChangeHandler(event:Event):void
{
html = textModel.html;
}
/**
* The CSSTextField in the up state
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var upTextField:CSSTextField;
/**
* The CSSTextField in the down state
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var downTextField:CSSTextField;
/**
* The CSSTextField in the over state
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var overTextField:CSSTextField;
/**
* @copy org.apache.flex.html.core.ITextModel#text
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get text():String
{
return upTextField.text;
}
/**
* @private
*/
public function set text(value:String):void
{
upTextField.text = value;
downTextField.text = value;
overTextField.text = value;
shape.graphics.clear();
shape.graphics.beginFill(0xCCCCCC);
shape.graphics.drawRect(0, 0, upSprite.width, upSprite.height);
shape.graphics.endFill();
}
/**
* @copy org.apache.flex.html.core.ITextModel#text
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get html():String
{
return upTextField.htmlText;
}
/**
* @private
*/
public function set html(value:String):void
{
upTextField.htmlText = value;
downTextField.htmlText = value;
overTextField.htmlText = value;
}
/**
* @private
*/
private function updateHitArea():void
{
shape.graphics.clear();
shape.graphics.beginFill(0xCCCCCC);
shape.graphics.drawRect(0, 0, upSprite.width, upSprite.height);
shape.graphics.endFill();
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.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.BeadViewBase;
import org.apache.flex.core.CSSTextField;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IBeadView;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IStrandWithModel;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.html.beads.models.ImageAndTextModel;
import org.apache.flex.utils.SolidBorderUtil;
/**
* The ImageButtonView class provides an image-only view
* for the standard Button. Unlike the CSSButtonView, this
* class does not support background and border; only images
* for the up, over, and active states.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class ImageAndTextButtonView extends BeadViewBase implements IBeadView, IBead
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function ImageAndTextButtonView()
{
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";
}
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
override public function set strand(value:IStrand):void
{
super.strand = value;
textModel = IStrandWithModel(value).model as ImageAndTextModel;
textModel.addEventListener("textChange", textChangeHandler);
textModel.addEventListener("htmlChange", htmlChangeHandler);
textModel.addEventListener("imageChange", imageChangeHandler);
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;
setupBackground(upSprite, upTextField, 0xCCCCCC);
setupBackground(overSprite, overTextField, 0xFFCCCC, "hover");
setupBackground(downSprite, downTextField, 0x808080, "active");
upTextField.styleParent = value;
downTextField.styleParent = value;
overTextField.styleParent = value;
}
private var upSprite:Sprite;
private var downSprite:Sprite;
private var overSprite:Sprite;
private var shape:Shape;
private var textModel:ImageAndTextModel;
/**
* The URL of an icon to use in the button
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get image():String
{
return textModel.image;
}
/**
* @private
*/
private function setupBackground(sprite:Sprite, textField:CSSTextField, color:uint, state:String = null):void
{
var backgroundImage:Object = image;
if (backgroundImage)
{
var loader:Loader = new Loader();
sprite.addChildAt(loader, 0);
sprite.addChild(textField);
var url:String = backgroundImage as String;
loader.load(new URLRequest(url));
loader.contentLoaderInfo.addEventListener(flash.events.Event.COMPLETE, function (e:flash.events.Event):void {
var padding:int = 2;
var borderWidth:int = 1;
updateHitArea();
loader.x = padding;
textField.x = loader.width + padding;
textField.y = padding;
loader.y = (textField.height + padding + padding - loader.height) / 2;
sprite.graphics.clear();
sprite.graphics.beginFill(color);
sprite.graphics.drawRect(0, 0, sprite.width, sprite.height);
sprite.graphics.endFill();
SolidBorderUtil.drawBorder(sprite.graphics,
0, 0, textField.x + textField.width + padding, textField.height + padding + padding,
0x000000, color, borderWidth);
});
}
}
private function textChangeHandler(event:Event):void
{
text = textModel.text;
}
private function htmlChangeHandler(event:Event):void
{
html = textModel.html;
}
private function imageChangeHandler(event:Event):void
{
setupBackground(upSprite, upTextField, 0xCCCCCC);
setupBackground(overSprite, overTextField, 0xFFCCCC, "hover");
setupBackground(downSprite, downTextField, 0x808080, "active");
}
/**
* The CSSTextField in the up state
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var upTextField:CSSTextField;
/**
* The CSSTextField in the down state
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var downTextField:CSSTextField;
/**
* The CSSTextField in the over state
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var overTextField:CSSTextField;
/**
* @copy org.apache.flex.html.core.ITextModel#text
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get text():String
{
return upTextField.text;
}
/**
* @private
*/
public function set text(value:String):void
{
upTextField.text = value;
downTextField.text = value;
overTextField.text = value;
shape.graphics.clear();
shape.graphics.beginFill(0xCCCCCC);
shape.graphics.drawRect(0, 0, upSprite.width, upSprite.height);
shape.graphics.endFill();
}
/**
* @copy org.apache.flex.html.core.ITextModel#text
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get html():String
{
return upTextField.htmlText;
}
/**
* @private
*/
public function set html(value:String):void
{
upTextField.htmlText = value;
downTextField.htmlText = value;
overTextField.htmlText = value;
}
/**
* @private
*/
private function updateHitArea():void
{
shape.graphics.clear();
shape.graphics.beginFill(0xCCCCCC);
shape.graphics.drawRect(0, 0, upSprite.width, upSprite.height);
shape.graphics.endFill();
}
}
}
|
fix ImageAndTextButton on AS
|
fix ImageAndTextButton on AS
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
59536d47ad1ce93e7f4be04f9319a6084cb4b6ba
|
src/as/com/threerings/flash/video/FlvVideoPlayer.as
|
src/as/com/threerings/flash/video/FlvVideoPlayer.as
|
//
// $Id$
package com.threerings.flash.video {
import flash.display.DisplayObject;
import flash.events.AsyncErrorEvent;
import flash.events.IOErrorEvent;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.NetStatusEvent;
import flash.events.SecurityErrorEvent;
import flash.events.TimerEvent;
import flash.geom.Point;
import flash.media.SoundTransform;
import flash.media.Video;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.utils.Timer;
import com.threerings.util.Log;
import com.threerings.util.ValueEvent;
public class FlvVideoPlayer extends EventDispatcher
implements VideoPlayer
{
public function FlvVideoPlayer (autoPlay :Boolean = true)
{
_autoPlay = autoPlay;
_sizeChecker = new Timer(100);
_sizeChecker.addEventListener(TimerEvent.TIMER, handleSizeCheck);
_positionChecker = new Timer(250);
_positionChecker.addEventListener(TimerEvent.TIMER, handlePositionCheck);
}
/**
* Start playing a video!
*/
public function load (url :String) :void
{
_netCon = new NetConnection();
_netCon.addEventListener(NetStatusEvent.NET_STATUS, handleNetStatus);
// error handlers
_netCon.addEventListener(AsyncErrorEvent.ASYNC_ERROR, handleAsyncError);
_netCon.addEventListener(IOErrorEvent.IO_ERROR, handleIOError);
_netCon.addEventListener(SecurityErrorEvent.SECURITY_ERROR, handleSecurityError);
_netCon.connect(null);
_netStream = new NetStream(_netCon);
// pass in refs to some of our protected methods
_netStream.client = {
onMetaData: handleMetaData
};
_netStream.soundTransform = new SoundTransform(_volume);
_netStream.addEventListener(NetStatusEvent.NET_STATUS, handleStreamNetStatus);
_vid.attachNetStream(_netStream);
_sizeChecker.start();
_netStream.play(url);
if (_autoPlay) {
updateState(VideoPlayerCodes.STATE_PLAYING);
} else {
_netStream.pause();
updateState(VideoPlayerCodes.STATE_READY);
}
}
// from VideoPlayer
public function getDisplay () :DisplayObject
{
return _vid;
}
// from VideoPlayer
public function getState () :int
{
return _state;
}
// from VideoPlayer
public function getSize () :Point
{
return _size.clone();
}
// from VideoPlayer
public function play () :void
{
if (_netStream != null) {
_netStream.resume();
updateState(VideoPlayerCodes.STATE_PLAYING);
}
// TODO: throw an error if _netStream == null??
}
// from VideoPlayer
public function pause () :void
{
if (_netStream != null) {
_netStream.pause();
updateState(VideoPlayerCodes.STATE_PAUSED);
}
}
// from VideoPlayer
public function getDuration () :Number
{
return _duration;
}
// from VideoPlayer
public function getPosition () :Number
{
if (_netStream != null) {
return _netStream.time;
}
return NaN;
}
// from VideoPlayer
public function seek (position :Number) :void
{
if (_netStream != null) {
_netStream.seek(position);
}
}
// from VideoPlayer
public function getVolume () :Number
{
return _volume;
}
// from VideoPlayer
public function setVolume (volume :Number) :void
{
_volume = Math.max(0, Math.min(1, volume));
if (_netStream != null) {
_netStream.soundTransform = new SoundTransform(_volume);
}
}
// from VideoPlayer
public function unload () :void
{
_sizeChecker.reset();
_vid.attachNetStream(null);
if (_netStream != null) {
_netStream.close();
_netStream.removeEventListener(NetStatusEvent.NET_STATUS, handleStreamNetStatus);
_netStream = null;
}
if (_netCon != null) {
_netCon.close();
_netCon.removeEventListener(NetStatusEvent.NET_STATUS, handleNetStatus);
_netCon.removeEventListener(AsyncErrorEvent.ASYNC_ERROR, handleAsyncError);
_netCon.removeEventListener(IOErrorEvent.IO_ERROR, handleIOError);
_netCon.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, handleSecurityError);
_netCon = null;
}
}
/**
* Check to see if we now know the dimensions of the video.
*/
protected function handleSizeCheck (event :TimerEvent) :void
{
if (_vid.videoWidth == 0 || _vid.videoHeight == 0) {
return; // not known yet!
}
// stop the checker timer
_sizeChecker.stop();
_size = new Point(_vid.videoWidth, _vid.videoHeight);
// set up the width/height
_vid.width = _size.x;
_vid.height = _size.y;
log.debug("====> size known: " + _size);
dispatchEvent(new ValueEvent(VideoPlayerCodes.SIZE, _size.clone()));
}
protected function handlePositionCheck (event :TimerEvent) :void
{
dispatchEvent(new ValueEvent(VideoPlayerCodes.POSITION, getPosition()));
}
protected function handleNetStatus (event :NetStatusEvent) :void
{
var info :Object = event.info;
if ("error" == info.level) {
log.warning("NetStatus error: " + info.code);
dispatchEvent(new ValueEvent(VideoPlayerCodes.ERROR, info.code));
return;
}
// else info.level == "status"
switch (info.code) {
case "NetConnection.Connect.Success":
case "NetConnection.Connect.Closed":
// these status events we ignore
break;
default:
log.info("NetStatus status: " + info.code);
break;
}
}
protected function handleStreamNetStatus (event :NetStatusEvent) :void
{
log.debug("NetStatus", "level", event.info.level, "code", event.info.code);
switch (event.info.code) {
case "NetStream.Play.Stop":
// rewind to the beginning
_netStream.seek(0);
_netStream.pause();
updateState(VideoPlayerCodes.STATE_PAUSED);
break;
case "NetStream.Seek.Notify":
handlePositionCheck(null);
break;
}
}
protected function handleAsyncError (event :AsyncErrorEvent) :void
{
redispatchError(event);
}
protected function handleIOError (event :IOErrorEvent) :void
{
redispatchError(event);
}
protected function handleSecurityError (event :SecurityErrorEvent) :void
{
redispatchError(event);
}
/**
* Redispatch some error we received to our listeners.
*/
protected function redispatchError (event :ErrorEvent) :void
{
log.warning("got video error: " + event);
dispatchEvent(new ValueEvent(VideoPlayerCodes.ERROR, event.text));
}
/**
* Called when metadata (if any) is found in the video stream.
*/
protected function handleMetaData (info :Object) :void
{
log.info("Got video metadata:");
for (var n :String in info) {
log.info(" " + n + ": " + info[n]);
}
// TODO: total duration is info.duration
if ("duration" in info) {
_duration = Number(info.duration);
if (!isNaN(_duration)) {
dispatchEvent(new ValueEvent(VideoPlayerCodes.DURATION, _duration));
}
}
}
protected function updateState (newState :int) :void
{
const oldState :int = _state;
_state = newState;
dispatchEvent(new ValueEvent(VideoPlayerCodes.STATE, newState));
if (_state == VideoPlayerCodes.STATE_PLAYING) {
_positionChecker.start();
} else {
_positionChecker.reset();
if (oldState == VideoPlayerCodes.STATE_PLAYING) {
handlePositionCheck(null);
}
}
}
protected const log :Log = Log.getLog(this);
protected var _autoPlay :Boolean;
protected var _vid :Video = new Video();
protected var _netCon :NetConnection;
protected var _netStream :NetStream;
protected var _state :int = VideoPlayerCodes.STATE_UNREADY;
/** Our size, null until known. */
protected var _size :Point;
protected var _duration :Number = NaN;
protected var _volume :Number = 1;
/** Checks the video every 100ms to see if the dimensions are now know.
* Yes, this is how to do it. We could trigger on ENTER_FRAME, but then
* we may not know the dimensions unless we're added on the display list,
* and we want this to work in the general case. */
protected var _sizeChecker :Timer;
protected var _positionChecker :Timer;
}
}
|
//
// $Id$
package com.threerings.flash.video {
import flash.display.DisplayObject;
import flash.events.AsyncErrorEvent;
import flash.events.IOErrorEvent;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.NetStatusEvent;
import flash.events.SecurityErrorEvent;
import flash.events.TimerEvent;
import flash.geom.Point;
import flash.media.SoundTransform;
import flash.media.Video;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.utils.Timer;
import com.threerings.util.Log;
import com.threerings.util.ValueEvent;
public class FlvVideoPlayer extends EventDispatcher
implements VideoPlayer
{
public function FlvVideoPlayer (autoPlay :Boolean = true)
{
_autoPlay = autoPlay;
_sizeChecker = new Timer(100);
_sizeChecker.addEventListener(TimerEvent.TIMER, handleSizeCheck);
_positionChecker = new Timer(250);
_positionChecker.addEventListener(TimerEvent.TIMER, handlePositionCheck);
}
/**
* Start playing a video!
*/
public function load (url :String) :void
{
_netCon = new NetConnection();
_netCon.addEventListener(NetStatusEvent.NET_STATUS, handleNetStatus);
// error handlers
_netCon.addEventListener(AsyncErrorEvent.ASYNC_ERROR, handleAsyncError);
_netCon.addEventListener(IOErrorEvent.IO_ERROR, handleIOError);
_netCon.addEventListener(SecurityErrorEvent.SECURITY_ERROR, handleSecurityError);
_netCon.connect(null);
_netStream = new NetStream(_netCon);
// pass in refs to some of our protected methods
_netStream.client = {
onMetaData: handleMetaData
};
_netStream.soundTransform = new SoundTransform(_volume);
_netStream.addEventListener(NetStatusEvent.NET_STATUS, handleStreamNetStatus);
_vid.attachNetStream(_netStream);
_sizeChecker.start();
_netStream.play(url);
if (_autoPlay) {
updateState(VideoPlayerCodes.STATE_PLAYING);
} else {
_netStream.pause();
updateState(VideoPlayerCodes.STATE_READY);
}
}
// from VideoPlayer
public function getDisplay () :DisplayObject
{
return _vid;
}
// from VideoPlayer
public function getState () :int
{
return _state;
}
// from VideoPlayer
public function getSize () :Point
{
return _size.clone();
}
// from VideoPlayer
public function play () :void
{
if (_netStream != null) {
_netStream.resume();
updateState(VideoPlayerCodes.STATE_PLAYING);
}
// TODO: throw an error if _netStream == null??
}
// from VideoPlayer
public function pause () :void
{
if (_netStream != null) {
_netStream.pause();
updateState(VideoPlayerCodes.STATE_PAUSED);
}
}
// from VideoPlayer
public function getDuration () :Number
{
return _duration;
}
// from VideoPlayer
public function getPosition () :Number
{
if (_netStream != null) {
return _netStream.time;
}
return NaN;
}
// from VideoPlayer
public function seek (position :Number) :void
{
if (_netStream != null) {
_netStream.seek(position);
}
}
// from VideoPlayer
public function getVolume () :Number
{
return _volume;
}
// from VideoPlayer
public function setVolume (volume :Number) :void
{
_volume = Math.max(0, Math.min(1, volume));
if (_netStream != null) {
_netStream.soundTransform = new SoundTransform(_volume);
}
}
// from VideoPlayer
public function unload () :void
{
_sizeChecker.reset();
_positionChecker.reset();
_vid.attachNetStream(null);
if (_netStream != null) {
_netStream.close();
_netStream.removeEventListener(NetStatusEvent.NET_STATUS, handleStreamNetStatus);
_netStream = null;
}
if (_netCon != null) {
_netCon.close();
_netCon.removeEventListener(NetStatusEvent.NET_STATUS, handleNetStatus);
_netCon.removeEventListener(AsyncErrorEvent.ASYNC_ERROR, handleAsyncError);
_netCon.removeEventListener(IOErrorEvent.IO_ERROR, handleIOError);
_netCon.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, handleSecurityError);
_netCon = null;
}
}
/**
* Check to see if we now know the dimensions of the video.
*/
protected function handleSizeCheck (event :TimerEvent) :void
{
if (_vid.videoWidth == 0 || _vid.videoHeight == 0) {
return; // not known yet!
}
// stop the checker timer
_sizeChecker.stop();
_size = new Point(_vid.videoWidth, _vid.videoHeight);
// set up the width/height
_vid.width = _size.x;
_vid.height = _size.y;
log.debug("====> size known: " + _size);
dispatchEvent(new ValueEvent(VideoPlayerCodes.SIZE, _size.clone()));
}
protected function handlePositionCheck (event :TimerEvent) :void
{
dispatchEvent(new ValueEvent(VideoPlayerCodes.POSITION, getPosition()));
}
protected function handleNetStatus (event :NetStatusEvent) :void
{
var info :Object = event.info;
if ("error" == info.level) {
log.warning("NetStatus error: " + info.code);
dispatchEvent(new ValueEvent(VideoPlayerCodes.ERROR, info.code));
return;
}
// else info.level == "status"
switch (info.code) {
case "NetConnection.Connect.Success":
case "NetConnection.Connect.Closed":
// these status events we ignore
break;
default:
log.info("NetStatus status: " + info.code);
break;
}
}
protected function handleStreamNetStatus (event :NetStatusEvent) :void
{
log.debug("NetStatus", "level", event.info.level, "code", event.info.code);
switch (event.info.code) {
case "NetStream.Play.Stop":
// rewind to the beginning
_netStream.seek(0);
_netStream.pause();
updateState(VideoPlayerCodes.STATE_PAUSED);
break;
case "NetStream.Seek.Notify":
handlePositionCheck(null);
break;
}
}
protected function handleAsyncError (event :AsyncErrorEvent) :void
{
redispatchError(event);
}
protected function handleIOError (event :IOErrorEvent) :void
{
redispatchError(event);
}
protected function handleSecurityError (event :SecurityErrorEvent) :void
{
redispatchError(event);
}
/**
* Redispatch some error we received to our listeners.
*/
protected function redispatchError (event :ErrorEvent) :void
{
log.warning("got video error: " + event);
dispatchEvent(new ValueEvent(VideoPlayerCodes.ERROR, event.text));
}
/**
* Called when metadata (if any) is found in the video stream.
*/
protected function handleMetaData (info :Object) :void
{
log.info("Got video metadata:");
for (var n :String in info) {
log.info(" " + n + ": " + info[n]);
}
// TODO: total duration is info.duration
if ("duration" in info) {
_duration = Number(info.duration);
if (!isNaN(_duration)) {
dispatchEvent(new ValueEvent(VideoPlayerCodes.DURATION, _duration));
}
}
}
protected function updateState (newState :int) :void
{
const oldState :int = _state;
_state = newState;
dispatchEvent(new ValueEvent(VideoPlayerCodes.STATE, newState));
if (_state == VideoPlayerCodes.STATE_PLAYING) {
_positionChecker.start();
} else {
_positionChecker.reset();
if (oldState == VideoPlayerCodes.STATE_PLAYING) {
handlePositionCheck(null);
}
}
}
protected const log :Log = Log.getLog(this);
protected var _autoPlay :Boolean;
protected var _vid :Video = new Video();
protected var _netCon :NetConnection;
protected var _netStream :NetStream;
protected var _state :int = VideoPlayerCodes.STATE_UNREADY;
/** Our size, null until known. */
protected var _size :Point;
protected var _duration :Number = NaN;
protected var _volume :Number = 1;
/** Checks the video every 100ms to see if the dimensions are now know.
* Yes, this is how to do it. We could trigger on ENTER_FRAME, but then
* we may not know the dimensions unless we're added on the display list,
* and we want this to work in the general case. */
protected var _sizeChecker :Timer;
protected var _positionChecker :Timer;
}
}
|
stop the positionTimer when we unload.
|
Bugfix: stop the positionTimer when we unload.
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@698 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
51947dc8a2d710513289f6f86c6715a85c8577ba
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/layouts/NonVirtualBasicLayout.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/layouts/NonVirtualBasicLayout.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 NonVirtualBasicLayout class is a simple layout
* bead. It takes the set of children and lays them out
* as specified by CSS properties like left, right, top
* and bottom.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class NonVirtualBasicLayout implements IBeadLayout
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function NonVirtualBasicLayout()
{
}
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("widthChanged", 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 w:Number = contentView.width;
var h:Number = contentView.height;
var n:int = contentView.numElements;
for (var i:int = 0; i < n; i++)
{
var child:ILayoutChild = contentView.getElementAt(i) as ILayoutChild;
var left:Number = ValuesManager.valuesImpl.getValue(child, "left");
var right:Number = ValuesManager.valuesImpl.getValue(child, "right");
var top:Number = ValuesManager.valuesImpl.getValue(child, "top");
var bottom:Number = ValuesManager.valuesImpl.getValue(child, "bottom");
if (!isNaN(left))
{
child.x = left;
}
if (!isNaN(top))
{
child.y = top;
}
var ilc:ILayoutChild;
if (child is ILayoutChild)
{
ilc = child as ILayoutChild;
if (!isNaN(ilc.percentHeight))
ilc.setHeight(contentView.height * ilc.percentHeight / 100);
}
if (child is ILayoutChild)
{
ilc = child as ILayoutChild;
if (!isNaN(ilc.percentWidth))
ilc.setWidth(contentView.width * ilc.percentWidth / 100);
}
if (!isNaN(right))
{
if (!isNaN(left))
child.width = w - right - left;
else
child.x = w - right - child.width;
}
if (!isNaN(bottom))
{
if (!isNaN(top))
child.height = h - bottom - top;
else
child.y = h - bottom - child.height;
}
}
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.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 NonVirtualBasicLayout class is a simple layout
* bead. It takes the set of children and lays them out
* as specified by CSS properties like left, right, top
* and bottom.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class NonVirtualBasicLayout implements IBeadLayout
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function NonVirtualBasicLayout()
{
}
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("widthChanged", changeHandler);
IEventDispatcher(value).addEventListener("childrenAdded", changeHandler);
IEventDispatcher(value).addEventListener("layoutNeeded", 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 w:Number = contentView.width;
var h:Number = contentView.height;
var n:int = contentView.numElements;
for (var i:int = 0; i < n; i++)
{
var child:ILayoutChild = contentView.getElementAt(i) as ILayoutChild;
var left:Number = ValuesManager.valuesImpl.getValue(child, "left");
var right:Number = ValuesManager.valuesImpl.getValue(child, "right");
var top:Number = ValuesManager.valuesImpl.getValue(child, "top");
var bottom:Number = ValuesManager.valuesImpl.getValue(child, "bottom");
var ww:Number = w;
var hh:Number = h;
if (!isNaN(left))
{
child.x = left;
ww -= left;
}
if (!isNaN(top))
{
child.y = top;
hh -= top;
}
var ilc:ILayoutChild;
if (child is ILayoutChild)
{
ilc = child as ILayoutChild;
if (!isNaN(ilc.percentWidth))
ilc.setWidth((ww - (isNaN(right) ? 0 : right)) * ilc.percentWidth / 100);
}
if (!isNaN(right))
{
if (!isNaN(left))
child.width = ww - right;
else
child.x = w - right - child.width;
}
if (child is ILayoutChild)
{
ilc = child as ILayoutChild;
if (!isNaN(ilc.percentHeight))
ilc.setHeight((hh - (isNaN(bottom) ? 0 : bottom)) * ilc.percentHeight / 100);
}
if (!isNaN(bottom))
{
if (!isNaN(top))
child.height = hh - bottom;
else
child.y = h - bottom - child.height;
}
}
}
}
}
|
fix sizing logic
|
fix sizing logic
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
26586ac1b1c161add61d13dfc0ec9e76999d6ce5
|
collect-flex/collect-flex-client/src/main/flex/org/openforis/collect/presenter/MasterPresenter.as
|
collect-flex/collect-flex-client/src/main/flex/org/openforis/collect/presenter/MasterPresenter.as
|
package org.openforis.collect.presenter {
/**
*
* @author Mino Togna
* */
import mx.rpc.AsyncResponder;
import mx.rpc.events.ResultEvent;
import org.openforis.collect.Application;
import org.openforis.collect.client.ClientFactory;
import org.openforis.collect.client.DataClient;
import org.openforis.collect.event.UIEvent;
import org.openforis.collect.metamodel.proxy.EntityDefinitionProxy;
import org.openforis.collect.model.CollectRecord$Step;
import org.openforis.collect.model.proxy.RecordProxy;
import org.openforis.collect.ui.view.MasterView;
import org.openforis.collect.util.AlertUtil;
public class MasterPresenter extends AbstractPresenter {
private var _view:MasterView;
private var _dataClient:DataClient;
public function MasterPresenter(view:MasterView) {
super();
this._view = view;
this._dataClient = ClientFactory.dataClient;
_view.currentState = MasterView.LOADING_STATE;
/*
wait for surveys and sessionState loading, then dispatch APPLICATION_INITIALIZED event
if more than one survey is found, then whow surveySelection view
*/
/*
flow: loading -> surveySelection (optional) -> rootEntitySelection (optional) -> list -> edit
*/
}
override internal function initEventListeners():void {
//eventDispatcher.addEventListener(ApplicationEvent.APPLICATION_INITIALIZED, applicationInitializedHandler);
eventDispatcher.addEventListener(UIEvent.ROOT_ENTITY_SELECTED, rootEntitySelectedHandler);
eventDispatcher.addEventListener(UIEvent.BACK_TO_LIST, backToListHandler);
eventDispatcher.addEventListener(UIEvent.RECORD_SELECTED, recordSelectedHandler);
eventDispatcher.addEventListener(UIEvent.RECORD_CREATED, recordCreatedHandler);
}
/**
* RecordSummary selected from list page
* */
internal function recordSelectedHandler(uiEvent:UIEvent):void {
var record:RecordProxy = uiEvent.obj as RecordProxy;
_dataClient.loadRecord(new AsyncResponder(loadRecordResultHandler, faultHandler, record), record.id, record.step);
}
/**
* New Record created
* */
internal function recordCreatedHandler(uiEvent:UIEvent):void {
var record:RecordProxy = uiEvent.obj as RecordProxy;
setActiveRecord(record);
}
/**
* Record selected in list page loaded from server
* */
protected function loadRecordResultHandler(event:ResultEvent, token:Object = null):void {
var record:RecordProxy = RecordProxy(event.result);
setActiveRecord(record);
}
protected function setActiveRecord(record:RecordProxy):void {
Application.activeRecord = record;
_view.currentState = MasterView.DETAIL_STATE;
var uiEvent:UIEvent = new UIEvent(UIEvent.ACTIVE_RECORD_CHANGED);
eventDispatcher.dispatchEvent(uiEvent);
}
/**
* Root entity selected
* */
internal function rootEntitySelectedHandler(event:UIEvent):void {
var rootEntityDef:EntityDefinitionProxy = event.obj as EntityDefinitionProxy;
Application.activeRootEntity = rootEntityDef;
_view.currentState = MasterView.LIST_STATE;
var uiEvent:UIEvent = new UIEvent(UIEvent.LOAD_RECORD_SUMMARIES);
eventDispatcher.dispatchEvent(uiEvent);
}
internal function newRecordCreatedHandler(event:UIEvent):void {
_view.currentState = MasterView.DETAIL_STATE;
}
internal function backToListHandler(event:UIEvent):void {
//reload record summaries
_view.currentState = MasterView.LIST_STATE;
var uiEvent:UIEvent = new UIEvent(UIEvent.RELOAD_RECORD_SUMMARIES);
eventDispatcher.dispatchEvent(uiEvent);
}
}
}
|
package org.openforis.collect.presenter {
/**
*
* @author Mino Togna
* */
import mx.rpc.AsyncResponder;
import mx.rpc.events.ResultEvent;
import org.openforis.collect.Application;
import org.openforis.collect.client.ClientFactory;
import org.openforis.collect.client.DataClient;
import org.openforis.collect.event.UIEvent;
import org.openforis.collect.metamodel.proxy.EntityDefinitionProxy;
import org.openforis.collect.model.CollectRecord$Step;
import org.openforis.collect.model.proxy.RecordProxy;
import org.openforis.collect.ui.view.MasterView;
import org.openforis.collect.util.AlertUtil;
public class MasterPresenter extends AbstractPresenter {
private var _view:MasterView;
private var _dataClient:DataClient;
public function MasterPresenter(view:MasterView) {
super();
this._view = view;
this._dataClient = ClientFactory.dataClient;
_view.currentState = MasterView.LOADING_STATE;
/*
wait for surveys and sessionState loading, then dispatch APPLICATION_INITIALIZED event
if more than one survey is found, then whow surveySelection view
*/
/*
flow: loading -> surveySelection (optional) -> rootEntitySelection (optional) -> list -> edit
*/
}
override internal function initEventListeners():void {
//eventDispatcher.addEventListener(ApplicationEvent.APPLICATION_INITIALIZED, applicationInitializedHandler);
eventDispatcher.addEventListener(UIEvent.ROOT_ENTITY_SELECTED, rootEntitySelectedHandler);
eventDispatcher.addEventListener(UIEvent.BACK_TO_LIST, backToListHandler);
eventDispatcher.addEventListener(UIEvent.RECORD_SELECTED, recordSelectedHandler);
eventDispatcher.addEventListener(UIEvent.RECORD_CREATED, recordCreatedHandler);
}
/**
* RecordSummary selected from list page
* */
internal function recordSelectedHandler(uiEvent:UIEvent):void {
var record:RecordProxy = uiEvent.obj as RecordProxy;
_dataClient.loadRecord(new AsyncResponder(loadRecordResultHandler, faultHandler, record), record.id, record.step);
}
/**
* New Record created
* */
internal function recordCreatedHandler(uiEvent:UIEvent):void {
var record:RecordProxy = uiEvent.obj as RecordProxy;
setActiveRecord(record);
}
/**
* Record selected in list page loaded from server
* */
protected function loadRecordResultHandler(event:ResultEvent, token:Object = null):void {
var record:RecordProxy = RecordProxy(event.result);
record.markNodesAsVisited();
setActiveRecord(record);
}
protected function setActiveRecord(record:RecordProxy):void {
Application.activeRecord = record;
_view.currentState = MasterView.DETAIL_STATE;
var uiEvent:UIEvent = new UIEvent(UIEvent.ACTIVE_RECORD_CHANGED);
eventDispatcher.dispatchEvent(uiEvent);
}
/**
* Root entity selected
* */
internal function rootEntitySelectedHandler(event:UIEvent):void {
var rootEntityDef:EntityDefinitionProxy = event.obj as EntityDefinitionProxy;
Application.activeRootEntity = rootEntityDef;
_view.currentState = MasterView.LIST_STATE;
var uiEvent:UIEvent = new UIEvent(UIEvent.LOAD_RECORD_SUMMARIES);
eventDispatcher.dispatchEvent(uiEvent);
}
internal function newRecordCreatedHandler(event:UIEvent):void {
_view.currentState = MasterView.DETAIL_STATE;
}
internal function backToListHandler(event:UIEvent):void {
//reload record summaries
_view.currentState = MasterView.LIST_STATE;
var uiEvent:UIEvent = new UIEvent(UIEvent.RELOAD_RECORD_SUMMARIES);
eventDispatcher.dispatchEvent(uiEvent);
}
}
}
|
Mark all nodes as visited when opening a saved record so that validation errors will be shown
|
Mark all nodes as visited when opening a saved record so that validation
errors will be shown
|
ActionScript
|
mit
|
openforis/collect,openforis/collect,openforis/collect,openforis/collect
|
f1fc39278a4e983ee6f7a0ca1f395bdfe9e60273
|
src/aerys/minko/render/material/basic/BasicShader.as
|
src/aerys/minko/render/material/basic/BasicShader.as
|
package aerys.minko.render.material.basic
{
import aerys.minko.render.DrawCall;
import aerys.minko.render.RenderTarget;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.ShaderInstance;
import aerys.minko.render.shader.ShaderSettings;
import aerys.minko.render.shader.part.DiffuseShaderPart;
import aerys.minko.render.shader.part.animation.VertexAnimationShaderPart;
import aerys.minko.type.enum.Blending;
import aerys.minko.type.enum.BlendingSource;
import aerys.minko.type.enum.DepthTest;
import aerys.minko.type.enum.StencilAction;
import aerys.minko.type.enum.TriangleCulling;
/**
* The BasicShader is a simple shader program handling hardware vertex
* animations (skinning and morphing), a diffuse color or a texture and
* a directional light.
*
* <table class="bindingsSummary">
* <tr>
* <th>Property Name</th>
* <th>Source</th>
* <th>Type</th>
* <th>Description</th>
* <th>Requires</th>
* </tr>
* <tr>
* <td>lightEnabled</td>
* <td>Scene</td>
* <td>Boolean</td>
* <td>Whether the light is enabled or not on the scene.</td>
* <td>lightDirection, lightAmbient, lightAmbientColor, lightDiffuse, lightDiffuseColor</td>
* </tr>
* <tr>
* <td>lightDirection</td>
* <td>Scene</td>
* <td>Vector4</td>
* <td>The direction of the light.</td>
* <td></td>
* </tr>
* <tr>
* <td>lightAmbient</td>
* <td>Scene</td>
* <td>Number</td>
* <td>The ambient factor of the light.</td>
* <td></td>
* </tr>
* <tr>
* <td>lightAmbientColor</td>
* <td>Scene</td>
* <td>uint or Vector4</td>
* <td>The ambient color of the light.</td>
* <td></td>
* </tr>
* <tr>
* <td>lightDiffuse</td>
* <td>Scene</td>
* <td>Number</td>
* <td>The diffuse factor of the light</td>
* <td></td>
* </tr>
* <tr>
* <td>lightDiffuseColor</td>
* <td>Scene</td>
* <td>uint or Vector4</td>
* <td>The diffuse color of the light.</td>
* <td></td>
* </tr>
* <tr>
* <td>lightEnabled</td>
* <td>Mesh</td>
* <td>Boolean</td>
* <td>Whether the light is enabled or not on the mesh.</td>
* <td></td>
* </tr>
* <tr>
* <td>diffuseMap</td>
* <td>Mesh</td>
* <td>TextureResource</td>
* <td>The texture to use for rendering.</td>
* <td></td>
* </tr>
* <tr>
* <td>diffuseColor</td>
* <td>Mesh</td>
* <td>uint or Vector4</td>
* <td>The color to use for rendering. If the "diffuseMap" binding is set, this
* value is not used.</td>
* <td></td>
* </tr>
* </table>
*
* @author Jean-Marc Le Roux
*
*/
public class BasicShader extends Shader
{
private var _vertexAnimationPart : VertexAnimationShaderPart;
private var _diffuseShaderPart : DiffuseShaderPart;
protected function get diffuse() : DiffuseShaderPart
{
return _diffuseShaderPart;
}
protected function get vertexAnimation() : VertexAnimationShaderPart
{
return _vertexAnimationPart;
}
/**
* @param priority Default value is 0.
* @param target Default value is null.
*/
public function BasicShader(target : RenderTarget = null,
priority : Number = 0.)
{
super(target, priority);
// init shader parts
_vertexAnimationPart = new VertexAnimationShaderPart(this);
_diffuseShaderPart = new DiffuseShaderPart(this);
}
override protected function initializeSettings(settings : ShaderSettings) : void
{
super.initializeSettings(settings);
// depth test
settings.depthWriteEnabled = meshBindings.getProperty(
BasicProperties.DEPTH_WRITE_ENABLED, true
);
settings.depthTest = meshBindings.getProperty(
BasicProperties.DEPTH_TEST, DepthTest.LESS
);
settings.triangleCulling = meshBindings.getProperty(
BasicProperties.TRIANGLE_CULLING, TriangleCulling.BACK
);
// stencil operations
settings.stencilTriangleFace = meshBindings.getProperty(
BasicProperties.STENCIL_TRIANGLE_FACE, TriangleCulling.BOTH
);
settings.stencilCompareMode = meshBindings.getProperty(
BasicProperties.STENCIL_COMPARE_MODE, DepthTest.EQUAL
);
settings.stencilActionOnBothPass = meshBindings.getProperty(
BasicProperties.STENCIL_ACTION_BOTH_PASS, StencilAction.KEEP
);
settings.stencilActionOnDepthFail = meshBindings.getProperty(
BasicProperties.STENCIL_ACTION_DEPTH_FAIL, StencilAction.KEEP
);
settings.stencilActionOnDepthPassStencilFail = meshBindings.getProperty(
BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL, StencilAction.KEEP
);
settings.stencilReferenceValue = meshBindings.getProperty(
BasicProperties.STENCIL_REFERENCE_VALUE, 0
);
settings.stencilReadMask = meshBindings.getProperty(
BasicProperties.STENCIL_READ_MASK, 255
);
settings.stencilWriteMask = meshBindings.getProperty(
BasicProperties.STENCIL_WRITE_MASK, 255
);
// blending and priority
var blending : uint = meshBindings.getProperty(
BasicProperties.BLENDING, Blending.OPAQUE
);
if ((blending & 0xff) == BlendingSource.SOURCE_ALPHA)
{
settings.priority -= 0.5;
settings.depthSortDrawCalls = true;
}
settings.blending = blending;
settings.enabled = true;
settings.scissorRectangle = null;
}
/**
* @return The position of the vertex in clip space (normalized
* screen space).
*
*/
override protected function getVertexPosition() : SFloat
{
var triangleCulling : uint = meshBindings.getProperty(
BasicProperties.TRIANGLE_CULLING, TriangleCulling.BACK
);
return localToScreen(
_vertexAnimationPart.getAnimatedVertexPosition()
);
}
/**
* @return The pixel color using a diffuse color/map and an optional
* directional light.
*/
override protected function getPixelColor() : SFloat
{
var diffuse : SFloat = _diffuseShaderPart.getDiffuseColor();
return diffuse;
}
}
}
|
package aerys.minko.render.material.basic
{
import aerys.minko.render.RenderTarget;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.ShaderSettings;
import aerys.minko.render.shader.part.DiffuseShaderPart;
import aerys.minko.render.shader.part.animation.VertexAnimationShaderPart;
import aerys.minko.type.enum.Blending;
import aerys.minko.type.enum.BlendingSource;
import aerys.minko.type.enum.DepthTest;
import aerys.minko.type.enum.StencilAction;
import aerys.minko.type.enum.TriangleCulling;
/**
* The BasicShader is a simple shader program handling hardware vertex
* animations (skinning and morphing), a diffuse color or a texture and
* a directional light.
*
* <table class="bindingsSummary">
* <tr>
* <th>Property Name</th>
* <th>Source</th>
* <th>Type</th>
* <th>Description</th>
* <th>Requires</th>
* </tr>
* <tr>
* <td>lightEnabled</td>
* <td>Scene</td>
* <td>Boolean</td>
* <td>Whether the light is enabled or not on the scene.</td>
* <td>lightDirection, lightAmbient, lightAmbientColor, lightDiffuse, lightDiffuseColor</td>
* </tr>
* <tr>
* <td>lightDirection</td>
* <td>Scene</td>
* <td>Vector4</td>
* <td>The direction of the light.</td>
* <td></td>
* </tr>
* <tr>
* <td>lightAmbient</td>
* <td>Scene</td>
* <td>Number</td>
* <td>The ambient factor of the light.</td>
* <td></td>
* </tr>
* <tr>
* <td>lightAmbientColor</td>
* <td>Scene</td>
* <td>uint or Vector4</td>
* <td>The ambient color of the light.</td>
* <td></td>
* </tr>
* <tr>
* <td>lightDiffuse</td>
* <td>Scene</td>
* <td>Number</td>
* <td>The diffuse factor of the light</td>
* <td></td>
* </tr>
* <tr>
* <td>lightDiffuseColor</td>
* <td>Scene</td>
* <td>uint or Vector4</td>
* <td>The diffuse color of the light.</td>
* <td></td>
* </tr>
* <tr>
* <td>lightEnabled</td>
* <td>Mesh</td>
* <td>Boolean</td>
* <td>Whether the light is enabled or not on the mesh.</td>
* <td></td>
* </tr>
* <tr>
* <td>diffuseMap</td>
* <td>Mesh</td>
* <td>TextureResource</td>
* <td>The texture to use for rendering.</td>
* <td></td>
* </tr>
* <tr>
* <td>diffuseColor</td>
* <td>Mesh</td>
* <td>uint or Vector4</td>
* <td>The color to use for rendering. If the "diffuseMap" binding is set, this
* value is not used.</td>
* <td></td>
* </tr>
* </table>
*
* @author Jean-Marc Le Roux
*
*/
public class BasicShader extends Shader
{
private var _vertexAnimationPart : VertexAnimationShaderPart;
private var _diffuseShaderPart : DiffuseShaderPart;
protected function get diffuse() : DiffuseShaderPart
{
return _diffuseShaderPart;
}
protected function get vertexAnimation() : VertexAnimationShaderPart
{
return _vertexAnimationPart;
}
/**
* @param priority Default value is 0.
* @param target Default value is null.
*/
public function BasicShader(target : RenderTarget = null,
priority : Number = 0.)
{
super(target, priority);
// init shader parts
_vertexAnimationPart = new VertexAnimationShaderPart(this);
_diffuseShaderPart = new DiffuseShaderPart(this);
}
override protected function initializeSettings(settings : ShaderSettings) : void
{
super.initializeSettings(settings);
// depth test
settings.depthWriteEnabled = meshBindings.getProperty(
BasicProperties.DEPTH_WRITE_ENABLED, true
);
settings.depthTest = meshBindings.getProperty(
BasicProperties.DEPTH_TEST, DepthTest.LESS
);
settings.triangleCulling = meshBindings.getProperty(
BasicProperties.TRIANGLE_CULLING, TriangleCulling.BACK
);
// stencil operations
settings.stencilTriangleFace = meshBindings.getProperty(
BasicProperties.STENCIL_TRIANGLE_FACE, TriangleCulling.BOTH
);
settings.stencilCompareMode = meshBindings.getProperty(
BasicProperties.STENCIL_COMPARE_MODE, DepthTest.EQUAL
);
settings.stencilActionOnBothPass = meshBindings.getProperty(
BasicProperties.STENCIL_ACTION_BOTH_PASS, StencilAction.KEEP
);
settings.stencilActionOnDepthFail = meshBindings.getProperty(
BasicProperties.STENCIL_ACTION_DEPTH_FAIL, StencilAction.KEEP
);
settings.stencilActionOnDepthPassStencilFail = meshBindings.getProperty(
BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL, StencilAction.KEEP
);
settings.stencilReferenceValue = meshBindings.getProperty(
BasicProperties.STENCIL_REFERENCE_VALUE, 0
);
settings.stencilReadMask = meshBindings.getProperty(
BasicProperties.STENCIL_READ_MASK, 255
);
settings.stencilWriteMask = meshBindings.getProperty(
BasicProperties.STENCIL_WRITE_MASK, 255
);
// blending and priority
var blending : uint = meshBindings.getProperty(
BasicProperties.BLENDING, Blending.OPAQUE
);
if ((blending & 0xff) == BlendingSource.SOURCE_ALPHA)
{
settings.priority -= 0.5;
settings.depthSortDrawCalls = true;
}
settings.blending = blending;
settings.enabled = true;
settings.scissorRectangle = null;
}
/**
* @return The position of the vertex in clip space (normalized
* screen space).
*
*/
override protected function getVertexPosition() : SFloat
{
return localToScreen(
_vertexAnimationPart.getAnimatedVertexPosition()
);
}
/**
* @return The pixel color using a diffuse color/map and an optional
* directional light.
*/
override protected function getPixelColor() : SFloat
{
return _diffuseShaderPart.getDiffuseColor();
}
}
}
|
remove useless imports
|
remove useless imports
|
ActionScript
|
mit
|
aerys/minko-as3
|
cd48a4a5fc330dee3c02ad0046229b49c6c353c9
|
test/src/FRESteamWorksTest.as
|
test/src/FRESteamWorksTest.as
|
/*
* FRESteamWorks.h
* This file is part of FRESteamWorks.
*
* Created by David ´Oldes´ Oliva on 3/29/12.
* Contributors: Ventero <http://github.com/Ventero>
* Copyright (c) 2012 Amanita Design. All rights reserved.
* Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved.
*/
package
{
import com.amanitadesign.steam.FRESteamWorks;
import com.amanitadesign.steam.SteamConstants;
import com.amanitadesign.steam.SteamEvent;
import com.amanitadesign.steam.WorkshopConstants;
import flash.desktop.NativeApplication;
import flash.display.SimpleButton;
import flash.display.Sprite;
import flash.display.StageDisplayState;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.utils.ByteArray;
public class FRESteamWorksTest extends Sprite
{
public var Steamworks:FRESteamWorks = new FRESteamWorks();
public var tf:TextField;
private var _buttonPos:int = 5;
private var _appId:uint;
public function FRESteamWorksTest()
{
tf = new TextField();
tf.x = 160;
tf.width = stage.stageWidth - tf.x;
tf.height = stage.stageHeight;
addChild(tf);
addButton("Check stats/achievements", checkAchievements);
addButton("Toggle achievement", toggleAchievement);
addButton("Toggle cloud enabled", toggleCloudEnabled);
addButton("Toggle file", toggleFile);
addButton("Publish file", publishFile);
addButton("Toggle fullscreen", toggleFullscreen);
addButton("Show Friends overlay", activateOverlay);
Steamworks.addEventListener(SteamEvent.STEAM_RESPONSE, onSteamResponse);
NativeApplication.nativeApplication.addEventListener(Event.EXITING, onExit);
try {
//Steamworks.useCrashHandler(480, "1.0", "Feb 20 2013", "21:42:20");
if(!Steamworks.init()){
log("STEAMWORKS API is NOT available");
return;
}
log("STEAMWORKS API is available\n");
log("User ID: " + Steamworks.getUserID());
_appId = Steamworks.getAppID();
log("App ID: " + _appId);
log("Persona name: " + Steamworks.getPersonaName());
log("isCloudEnabledForApp() == "+Steamworks.isCloudEnabledForApp() );
log("getFileCount() == "+Steamworks.getFileCount() );
log("fileExists('test.txt') == "+Steamworks.fileExists('test.txt') );
Steamworks.resetAllStats(true);
} catch(e:Error) {
log("*** ERROR ***");
log(e.message);
log(e.getStackTrace());
}
}
private function log(value:String):void{
tf.appendText(value+"\n");
tf.scrollV = tf.maxScrollV;
}
public function writeFileToCloud(fileName:String, data:String):Boolean {
var dataOut:ByteArray = new ByteArray();
dataOut.writeUTFBytes(data);
return Steamworks.fileWrite(fileName, dataOut);
}
public function readFileFromCloud(fileName:String):String {
var dataIn:ByteArray = new ByteArray();
var result:String;
dataIn.position = 0;
dataIn.length = Steamworks.getFileSize(fileName);
if(dataIn.length>0 && Steamworks.fileRead(fileName,dataIn)){
result = dataIn.readUTFBytes(dataIn.length);
}
return result;
}
private function checkAchievements(e:Event = null):void {
if(!Steamworks.isReady) return;
// current stats and achievement ids are from steam example app
log("isAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.isAchievement("ACH_WIN_ONE_GAME"));
log("isAchievement('ACH_TRAVEL_FAR_SINGLE') == "+Steamworks.isAchievement("ACH_TRAVEL_FAR_SINGLE"));
log("setStatFloat('FeetTraveled') == "+Steamworks.setStatFloat('FeetTraveled', 21.3));
log("setStatInt('NumGames', 2) == "+Steamworks.setStatInt('NumGames', 2));
Steamworks.storeStats();
log("getStatInt('NumGames') == "+Steamworks.getStatInt('NumGames'));
log("getStatFloat('FeetTraveled') == "+Steamworks.getStatFloat('FeetTraveled'));
}
private function toggleAchievement(e:Event = null):void{
if(!Steamworks.isReady) return;
var result:Boolean = Steamworks.isAchievement("ACH_WIN_ONE_GAME");
log("isAchievement('ACH_WIN_ONE_GAME') == " + result);
if(!result) {
log("setAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.setAchievement("ACH_WIN_ONE_GAME"));
} else {
log("clearAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.clearAchievement("ACH_WIN_ONE_GAME"));
}
}
private function toggleCloudEnabled(e:Event = null):void {
if(!Steamworks.isReady) return;
var enabled:Boolean = Steamworks.isCloudEnabledForApp();
log("isCloudEnabledForApp() == " + enabled);
log("setCloudEnabledForApp(" + !enabled + ") == " + Steamworks.setCloudEnabledForApp(!enabled));
log("isCloudEnabledForApp() == " + Steamworks.isCloudEnabledForApp());
}
private function toggleFile(e:Event = null):void {
if(!Steamworks.isReady) return;
var result:Boolean = Steamworks.fileExists('test.txt');
log("fileExists('test.txt') == " + result);
if(result){
log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') );
log("fileDelete('test.txt') == "+Steamworks.fileDelete('test.txt'));
} else {
log("writeFileToCloud('test.txt','click') == "+writeFileToCloud('test.txt','click'));
}
}
private function publishFile(e:Event = null):void {
if(!Steamworks.isReady) return;
var res:Boolean = Steamworks.publishWorkshopFile("test.txt", "", _appId,
"Test.txt", "Test.txt", WorkshopConstants.VISIBILITY_Private,
["TestTag"], WorkshopConstants.FILETYPE_Community);
log("publishWorkshopFile('test.txt' ...) == " + res);
}
private function toggleFullscreen(e:Event = null):void {
if(stage.displayState == StageDisplayState.NORMAL)
stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;
else
stage.displayState = StageDisplayState.NORMAL;
}
private function activateOverlay(e:Event = null):void {
if(!Steamworks.isReady) return;
log("activateGameOverlay('Friends') == " + Steamworks.activateGameOverlay("Friends"));
}
private function onSteamResponse(e:SteamEvent):void{
switch(e.req_type){
case SteamConstants.RESPONSE_OnUserStatsStored:
log("RESPONSE_OnUserStatsStored: "+e.response);
break;
case SteamConstants.RESPONSE_OnUserStatsReceived:
log("RESPONSE_OnUserStatsReceived: "+e.response);
break;
case SteamConstants.RESPONSE_OnAchievementStored:
log("RESPONSE_OnAchievementStored: "+e.response);
break;
case SteamConstants.RESPONSE_OnPublishWorkshopFile:
log("RESPONSE_OnPublishWorkshopFile: " + e.response);
log("File published as " + Steamworks.publishWorkshopFileResult());
default:
log("STEAMresponse type:"+e.req_type+" response:"+e.response);
}
}
private function onExit(e:Event):void{
log("Exiting application, cleaning up");
Steamworks.dispose();
}
private function addButton(label:String, callback:Function):void {
var button:Sprite = new Sprite();
button.graphics.beginFill(0xaaaaaa);
button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5);
button.graphics.endFill();
button.buttonMode = true;
button.useHandCursor = true;
button.addEventListener(MouseEvent.CLICK, callback);
button.x = 5;
button.y = _buttonPos;
_buttonPos += button.height + 5;
var text:TextField = new TextField();
text.text = label;
text.width = 140;
text.height = 25;
text.x = 5;
text.y = 5;
text.mouseEnabled = false;
button.addChild(text);
addChild(button);
}
}
}
|
/*
* FRESteamWorks.h
* This file is part of FRESteamWorks.
*
* Created by David ´Oldes´ Oliva on 3/29/12.
* Contributors: Ventero <http://github.com/Ventero>
* Copyright (c) 2012 Amanita Design. All rights reserved.
* Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved.
*/
package
{
import com.amanitadesign.steam.FRESteamWorks;
import com.amanitadesign.steam.SteamConstants;
import com.amanitadesign.steam.SteamEvent;
import com.amanitadesign.steam.WorkshopConstants;
import flash.desktop.NativeApplication;
import flash.display.SimpleButton;
import flash.display.Sprite;
import flash.display.StageDisplayState;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.utils.ByteArray;
public class FRESteamWorksTest extends Sprite
{
public var Steamworks:FRESteamWorks = new FRESteamWorks();
public var tf:TextField;
private var _buttonPos:int = 5;
private var _appId:uint;
public function FRESteamWorksTest()
{
tf = new TextField();
tf.x = 160;
tf.width = stage.stageWidth - tf.x;
tf.height = stage.stageHeight;
addChild(tf);
addButton("Check stats/achievements", checkAchievements);
addButton("Toggle achievement", toggleAchievement);
addButton("Toggle cloud enabled", toggleCloudEnabled);
addButton("Toggle file", toggleFile);
addButton("Publish file", publishFile);
addButton("Toggle fullscreen", toggleFullscreen);
addButton("Show Friends overlay", activateOverlay);
addButton("List subscribed files", enumerateSubscribedFiles);
Steamworks.addEventListener(SteamEvent.STEAM_RESPONSE, onSteamResponse);
NativeApplication.nativeApplication.addEventListener(Event.EXITING, onExit);
try {
//Steamworks.useCrashHandler(480, "1.0", "Feb 20 2013", "21:42:20");
if(!Steamworks.init()){
log("STEAMWORKS API is NOT available");
return;
}
log("STEAMWORKS API is available\n");
log("User ID: " + Steamworks.getUserID());
_appId = Steamworks.getAppID();
log("App ID: " + _appId);
log("Persona name: " + Steamworks.getPersonaName());
log("isCloudEnabledForApp() == "+Steamworks.isCloudEnabledForApp() );
log("getFileCount() == "+Steamworks.getFileCount() );
log("fileExists('test.txt') == "+Steamworks.fileExists('test.txt') );
Steamworks.resetAllStats(true);
} catch(e:Error) {
log("*** ERROR ***");
log(e.message);
log(e.getStackTrace());
}
}
private function log(value:String):void{
tf.appendText(value+"\n");
tf.scrollV = tf.maxScrollV;
}
public function writeFileToCloud(fileName:String, data:String):Boolean {
var dataOut:ByteArray = new ByteArray();
dataOut.writeUTFBytes(data);
return Steamworks.fileWrite(fileName, dataOut);
}
public function readFileFromCloud(fileName:String):String {
var dataIn:ByteArray = new ByteArray();
var result:String;
dataIn.position = 0;
dataIn.length = Steamworks.getFileSize(fileName);
if(dataIn.length>0 && Steamworks.fileRead(fileName,dataIn)){
result = dataIn.readUTFBytes(dataIn.length);
}
return result;
}
private function checkAchievements(e:Event = null):void {
if(!Steamworks.isReady) return;
// current stats and achievement ids are from steam example app
log("isAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.isAchievement("ACH_WIN_ONE_GAME"));
log("isAchievement('ACH_TRAVEL_FAR_SINGLE') == "+Steamworks.isAchievement("ACH_TRAVEL_FAR_SINGLE"));
log("setStatFloat('FeetTraveled') == "+Steamworks.setStatFloat('FeetTraveled', 21.3));
log("setStatInt('NumGames', 2) == "+Steamworks.setStatInt('NumGames', 2));
Steamworks.storeStats();
log("getStatInt('NumGames') == "+Steamworks.getStatInt('NumGames'));
log("getStatFloat('FeetTraveled') == "+Steamworks.getStatFloat('FeetTraveled'));
}
private function toggleAchievement(e:Event = null):void{
if(!Steamworks.isReady) return;
var result:Boolean = Steamworks.isAchievement("ACH_WIN_ONE_GAME");
log("isAchievement('ACH_WIN_ONE_GAME') == " + result);
if(!result) {
log("setAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.setAchievement("ACH_WIN_ONE_GAME"));
} else {
log("clearAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.clearAchievement("ACH_WIN_ONE_GAME"));
}
}
private function toggleCloudEnabled(e:Event = null):void {
if(!Steamworks.isReady) return;
var enabled:Boolean = Steamworks.isCloudEnabledForApp();
log("isCloudEnabledForApp() == " + enabled);
log("setCloudEnabledForApp(" + !enabled + ") == " + Steamworks.setCloudEnabledForApp(!enabled));
log("isCloudEnabledForApp() == " + Steamworks.isCloudEnabledForApp());
}
private function toggleFile(e:Event = null):void {
if(!Steamworks.isReady) return;
var result:Boolean = Steamworks.fileExists('test.txt');
log("fileExists('test.txt') == " + result);
if(result){
log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') );
log("fileDelete('test.txt') == "+Steamworks.fileDelete('test.txt'));
} else {
log("writeFileToCloud('test.txt','click') == "+writeFileToCloud('test.txt','click'));
}
}
private function publishFile(e:Event = null):void {
if(!Steamworks.isReady) return;
var res:Boolean = Steamworks.publishWorkshopFile("test.txt", "", _appId,
"Test.txt", "Test.txt", WorkshopConstants.VISIBILITY_Private,
["TestTag"], WorkshopConstants.FILETYPE_Community);
log("publishWorkshopFile('test.txt' ...) == " + res);
}
private function toggleFullscreen(e:Event = null):void {
if(stage.displayState == StageDisplayState.NORMAL)
stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;
else
stage.displayState = StageDisplayState.NORMAL;
}
private function activateOverlay(e:Event = null):void {
if(!Steamworks.isReady) return;
log("activateGameOverlay('Friends') == " + Steamworks.activateGameOverlay("Friends"));
}
private function enumerateSubscribedFiles(e:Event = null):void {
if(!Steamworks.isReady) return;
log("enumerateUserSubscribedFiles(0) == " + Steamworks.enumerateUserSubscribedFiles(0));
}
private function onSteamResponse(e:SteamEvent):void{
switch(e.req_type){
case SteamConstants.RESPONSE_OnUserStatsStored:
log("RESPONSE_OnUserStatsStored: "+e.response);
break;
case SteamConstants.RESPONSE_OnUserStatsReceived:
log("RESPONSE_OnUserStatsReceived: "+e.response);
break;
case SteamConstants.RESPONSE_OnAchievementStored:
log("RESPONSE_OnAchievementStored: "+e.response);
break;
case SteamConstants.RESPONSE_OnPublishWorkshopFile:
log("RESPONSE_OnPublishWorkshopFile: " + e.response);
var file:String = Steamworks.publishWorkshopFileResult();
log("File published as " + file);
log("subscribePublishedFile(...) == " + Steamworks.subscribePublishedFile(file));
break;
case SteamConstants.RESPONSE_OnEnumerateUserSubscribedFiles:
log("RESPONSE_OnEnumerateUserSubscribedFiles: " + e.response);
var result:SubscribedFilesResult = Steamworks.enumerateUserSubscribedFilesResult();
log("User subscribed files: " + result.resultsReturned + "/" + result.totalResults);
for(var i:int = 0; i < result.resultsReturned; i++)
log(i + ": " + result.publishedFileId[i] + " (" + result.timeSubscribed[i] + ")");
break;
default:
log("STEAMresponse type:"+e.req_type+" response:"+e.response);
}
}
private function onExit(e:Event):void{
log("Exiting application, cleaning up");
Steamworks.dispose();
}
private function addButton(label:String, callback:Function):void {
var button:Sprite = new Sprite();
button.graphics.beginFill(0xaaaaaa);
button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5);
button.graphics.endFill();
button.buttonMode = true;
button.useHandCursor = true;
button.addEventListener(MouseEvent.CLICK, callback);
button.x = 5;
button.y = _buttonPos;
_buttonPos += button.height + 5;
var text:TextField = new TextField();
text.text = label;
text.width = 140;
text.height = 25;
text.x = 5;
text.y = 5;
text.mouseEnabled = false;
button.addChild(text);
addChild(button);
}
}
}
|
Add subscribed file test
|
Add subscribed file test
|
ActionScript
|
bsd-2-clause
|
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
|
bd3e1d9febd1e230d1544a7579085d75bcc49649
|
HLSPlugin/src/org/denivip/osmf/elements/M3U8Loader.as
|
HLSPlugin/src/org/denivip/osmf/elements/M3U8Loader.as
|
package org.denivip.osmf.elements
{
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.utils.getTimer;
import org.denivip.osmf.elements.m3u8Classes.M3U8PlaylistParser;
import org.denivip.osmf.net.httpstreaming.hls.HTTPStreamingHLSNetLoader;
import org.osmf.elements.VideoElement;
import org.osmf.elements.proxyClasses.LoadFromDocumentLoadTrait;
import org.osmf.events.MediaError;
import org.osmf.events.MediaErrorEvent;
import org.osmf.events.ParseEvent;
import org.osmf.logging.Log;
import org.osmf.logging.Logger;
import org.osmf.media.MediaElement;
import org.osmf.media.MediaResourceBase;
import org.osmf.media.URLResource;
import org.osmf.traits.LoadState;
import org.osmf.traits.LoadTrait;
import org.osmf.traits.LoaderBase;
/**
* Loader for .m3u8 playlist file.
* Works like a F4MLoader
*/
public class M3U8Loader extends LoaderBase
{
private var _loadTrait:LoadTrait;
private var _parser:M3U8PlaylistParser = null;
private var _loadTime:int = 0;
private var _playlistLoader:URLLoader = null;
public function M3U8Loader(){
super();
}
public static function canHandle(resource:MediaResourceBase):Boolean
{
if (resource !== null && resource is URLResource) {
var urlResource:URLResource = URLResource(resource);
if (urlResource.url.search(/(https?|file)\:\/\/.*?\.m3u8(\?.*)?/i) !== -1) {
return true;
}
var contentType:Object = urlResource.getMetadataValue("content-type");
if (contentType && contentType is String) {
// If the filename doesn't include a .m3u8 extension, but
// explicit content-type metadata is found on the
// URLResource, we can handle it. Must be either of:
// - "application/x-mpegURL"
// - "vnd.apple.mpegURL"
if ((contentType as String).search(/(application\/x-mpegURL|vnd.apple.mpegURL)/i) !== -1) {
return true;
}
}
}
return false;
}
override public function canHandleResource(resource:MediaResourceBase):Boolean{
return canHandle(resource);
}
private function onError(e:ErrorEvent):void
{
removeListeners();
updateLoadTrait(_loadTrait, LoadState.LOAD_ERROR);
_loadTrait.dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR, false, false, new MediaError(0, 'This video is not available.')));
}
private function onComplete(e:Event):void
{
removeListeners();
try{
CONFIG::LOGGING
{
_loadTime = getTimer() - _loadTime;
var url:String = _loadTrait.resource['url'];
logger.info("Playlist {0} loaded", url);
logger.info("size = {0}Kb", (_playlistLoader.bytesLoaded/1024).toFixed(3));
logger.info("load time = {0} sec", (_loadTime/1000));
}
var resData:String = String((e.target as URLLoader).data);
_parser = new M3U8PlaylistParser();
_parser.addEventListener(ParseEvent.PARSE_COMPLETE, parseComplete);
_parser.addEventListener(ParseEvent.PARSE_ERROR, parseError);
_parser.parse(resData, URLResource(_loadTrait.resource));
}catch(err:Error){
updateLoadTrait(_loadTrait, LoadState.LOAD_ERROR);
dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR, false, false, new MediaError(err.errorID, err.message)));
}
}
private function onHTTPStatus(event:flash.events.HTTPStatusEvent):void
{
if( event.status >= 400 )
{
// some 400-level fail, let's forward this out to jscript land
removeListeners();
updateLoadTrait(_loadTrait, LoadState.LOAD_ERROR);
_loadTrait.dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR, false, false, new MediaError(event.status, "")));
}
}
private function removeListeners():void
{
_playlistLoader.removeEventListener(Event.COMPLETE, onComplete);
_playlistLoader.removeEventListener(IOErrorEvent.IO_ERROR, onError);
_playlistLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
_playlistLoader.removeEventListener(flash.events.HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);
}
override protected function executeLoad(loadTrait:LoadTrait):void
{
if( _playlistLoader != null )
{
// There's some previous request that is lingering in abject misery--kill it dead. This is
// important because otherwise you can have strange race conditions happen when multiple
// executeLoad calls are fired in rapid succession.
// Remove all listeners, close it (which under the hood cancels everything), set to null.
this.removeListeners();
_playlistLoader.close();
_playlistLoader = null;
}
if( _parser != null )
{
// If there's an outstanding parser, also kill that dead.
removeParserListeners();
_parser = null;
}
_loadTrait = loadTrait;
updateLoadTrait(loadTrait, LoadState.LOADING);
_playlistLoader = new URLLoader(new URLRequest(URLResource(loadTrait.resource).url));
_playlistLoader.addEventListener(Event.COMPLETE, onComplete);
_playlistLoader.addEventListener(IOErrorEvent.IO_ERROR, onError);
_playlistLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
_playlistLoader.addEventListener(flash.events.HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);
CONFIG::LOGGING
{
_loadTime = getTimer();
}
}
override protected function executeUnload(loadTrait:LoadTrait):void
{
updateLoadTrait(loadTrait, LoadState.UNINITIALIZED);
}
private function removeParserListeners():void
{
_parser.removeEventListener(ParseEvent.PARSE_COMPLETE, parseComplete);
_parser.removeEventListener(ParseEvent.PARSE_ERROR, parseError);
}
private function parseComplete(event:ParseEvent):void
{
removeParserListeners();
finishPlaylistLoading(MediaResourceBase(event.data));
}
private function parseError(event:ParseEvent):void{
removeParserListeners();
}
private function finishPlaylistLoading(resource:MediaResourceBase):void{
try{
var loadedElem:MediaElement = new VideoElement(null, new HTTPStreamingHLSNetLoader());
loadedElem.resource = resource;
VideoElement(loadedElem).smoothing = true;
LoadFromDocumentLoadTrait(_loadTrait).mediaElement = loadedElem;
updateLoadTrait(_loadTrait, LoadState.READY);
}catch(e:Error){
updateLoadTrait(_loadTrait, LoadState.LOAD_ERROR);
_loadTrait.dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR, false, false, new MediaError(e.errorID, e.message)));
}
}
CONFIG::LOGGING
{
protected var logger:Logger = Log.getLogger("org.denivip.osmf.elements.M3U8Loader") as Logger;
}
}
}
|
package org.denivip.osmf.elements
{
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.utils.getTimer;
import org.denivip.osmf.elements.m3u8Classes.M3U8PlaylistParser;
import org.denivip.osmf.net.httpstreaming.hls.HTTPStreamingHLSNetLoader;
import org.osmf.elements.VideoElement;
import org.osmf.elements.proxyClasses.LoadFromDocumentLoadTrait;
import org.osmf.events.MediaError;
import org.osmf.events.MediaErrorEvent;
import org.osmf.events.ParseEvent;
import org.osmf.logging.Log;
import org.osmf.logging.Logger;
import org.osmf.media.MediaElement;
import org.osmf.media.MediaResourceBase;
import org.osmf.media.URLResource;
import org.osmf.traits.LoadState;
import org.osmf.traits.LoadTrait;
import org.osmf.traits.LoaderBase;
/**
* Loader for .m3u8 playlist file.
* Works like a F4MLoader
*/
public class M3U8Loader extends LoaderBase
{
private var _loadTrait:LoadTrait;
private var _parser:M3U8PlaylistParser = null;
private var _loadTime:int = 0;
private var _playlistLoader:URLLoader = null;
private var _errorHit:Boolean = false; // So we only handle HTTP errors once; handling stuff twice dorks things.
public function M3U8Loader(){
super();
}
public static function canHandle(resource:MediaResourceBase):Boolean
{
if (resource !== null && resource is URLResource) {
var urlResource:URLResource = URLResource(resource);
if (urlResource.url.search(/(https?|file)\:\/\/.*?\.m3u8(\?.*)?/i) !== -1) {
return true;
}
var contentType:Object = urlResource.getMetadataValue("content-type");
if (contentType && contentType is String) {
// If the filename doesn't include a .m3u8 extension, but
// explicit content-type metadata is found on the
// URLResource, we can handle it. Must be either of:
// - "application/x-mpegURL"
// - "vnd.apple.mpegURL"
if ((contentType as String).search(/(application\/x-mpegURL|vnd.apple.mpegURL)/i) !== -1) {
return true;
}
}
}
return false;
}
override public function canHandleResource(resource:MediaResourceBase):Boolean{
return canHandle(resource);
}
private function onError(e:ErrorEvent):void
{
if( !_errorHit) {
_errorHit = true;
updateLoadTrait(_loadTrait, LoadState.LOAD_ERROR);
_loadTrait.dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR, false, false, new MediaError(0, 'This video is not available.')));
}
}
private function onComplete(e:Event):void
{
removeListeners();
try
{
CONFIG::LOGGING
{
_loadTime = getTimer() - _loadTime;
var url:String = _loadTrait.resource['url'];
logger.info("Playlist {0} loaded", url);
logger.info("size = {0}Kb", (_playlistLoader.bytesLoaded/1024).toFixed(3));
logger.info("load time = {0} sec", (_loadTime/1000));
}
var resData:String = String((e.target as URLLoader).data);
_parser = new M3U8PlaylistParser();
_parser.addEventListener(ParseEvent.PARSE_COMPLETE, parseComplete);
_parser.addEventListener(ParseEvent.PARSE_ERROR, parseError);
_parser.parse(resData, URLResource(_loadTrait.resource));
}catch(err:Error){
updateLoadTrait(_loadTrait, LoadState.LOAD_ERROR);
dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR, false, false, new MediaError(err.errorID, err.message)));
}
}
private function onHTTPStatus(event:flash.events.HTTPStatusEvent):void
{
if( event.status >= 400 && !_errorHit )
{
// some 400-level fail, let's forward this out to jscript land
_errorHit = true;
updateLoadTrait(_loadTrait, LoadState.LOAD_ERROR);
_loadTrait.dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR, false, false, new MediaError(event.status, "")));
}
}
private function removeListeners():void
{
_playlistLoader.removeEventListener(Event.COMPLETE, onComplete);
_playlistLoader.removeEventListener(IOErrorEvent.IO_ERROR, onError);
_playlistLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
_playlistLoader.removeEventListener(flash.events.HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);
}
override protected function executeLoad(loadTrait:LoadTrait):void
{
if( _playlistLoader != null )
{
// There's some previous request that is lingering in abject misery--kill it dead. This is
// important because otherwise you can have strange race conditions happen when multiple
// executeLoad calls are fired in rapid succession.
// Remove all listeners, close it (which under the hood cancels everything), set to null.
this.removeListeners();
_playlistLoader.close();
_playlistLoader = null;
}
// Reset our error hit logic since we're trying again.
_errorHit = false;
if( _parser != null )
{
// If there's an outstanding parser, also kill that dead.
removeParserListeners();
_parser = null;
}
_loadTrait = loadTrait;
updateLoadTrait(loadTrait, LoadState.LOADING);
_playlistLoader = new URLLoader();
_playlistLoader.addEventListener(Event.COMPLETE, onComplete);
_playlistLoader.addEventListener(IOErrorEvent.IO_ERROR, onError);
_playlistLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
_playlistLoader.addEventListener(flash.events.HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);
_playlistLoader.load(new URLRequest(URLResource(loadTrait.resource).url));
CONFIG::LOGGING
{
_loadTime = getTimer();
}
}
override protected function executeUnload(loadTrait:LoadTrait):void
{
updateLoadTrait(loadTrait, LoadState.UNINITIALIZED);
}
private function removeParserListeners():void
{
_parser.removeEventListener(ParseEvent.PARSE_COMPLETE, parseComplete);
_parser.removeEventListener(ParseEvent.PARSE_ERROR, parseError);
}
private function parseComplete(event:ParseEvent):void
{
removeParserListeners();
finishPlaylistLoading(MediaResourceBase(event.data));
}
private function parseError(event:ParseEvent):void{
removeParserListeners();
}
private function finishPlaylistLoading(resource:MediaResourceBase):void{
try{
var loadedElem:MediaElement = new VideoElement(null, new HTTPStreamingHLSNetLoader());
loadedElem.resource = resource;
VideoElement(loadedElem).smoothing = true;
LoadFromDocumentLoadTrait(_loadTrait).mediaElement = loadedElem;
updateLoadTrait(_loadTrait, LoadState.READY);
}catch(e:Error){
updateLoadTrait(_loadTrait, LoadState.LOAD_ERROR);
_loadTrait.dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR, false, false, new MediaError(e.errorID, e.message)));
}
}
CONFIG::LOGGING
{
protected var logger:Logger = Log.getLogger("org.denivip.osmf.elements.M3U8Loader") as Logger;
}
}
}
|
Fix two race conditions: event handlers were being added _after_ the loader was supplied a URL, and the error event handlers should not be removing the error handlers. If an event handler is removed and there's an outstanding event, that results in an unhandled exception
|
Fix two race conditions: event handlers were being added _after_ the loader was supplied a URL, and the error event handlers should not be removing the error handlers. If an event handler is removed and there's an outstanding event, that results in an unhandled exception
|
ActionScript
|
isc
|
mruse/osmf-hls-plugin,mruse/osmf-hls-plugin,denivip/osmf-hls-plugin,denivip/osmf-hls-plugin
|
9b63e75d4716e87f9c42d8091f9ba07c937f4821
|
dolly-framework/src/main/actionscript/dolly/Cloner.as
|
dolly-framework/src/main/actionscript/dolly/Cloner.as
|
package dolly {
import dolly.core.dolly_internal;
import dolly.core.errors.CloningError;
import dolly.core.metadata.MetadataName;
import dolly.utils.ClassUtil;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import org.as3commons.reflect.Accessor;
import org.as3commons.reflect.AccessorAccess;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
use namespace dolly_internal;
public class Cloner {
private static var _isClassPreparedForCloningMap:Dictionary = new Dictionary();
private static function isTypeCloneable(type:Type):Boolean {
return type.hasMetadata(MetadataName.CLONEABLE);
}
private static function isTypePreparedForCloning(type:Type):Boolean {
return _isClassPreparedForCloningMap[type.clazz];
}
private static function failIfTypeIsNotCloneable(type:Type):void {
if (!isTypeCloneable(type)) {
throw new CloningError(
CloningError.CLASS_IS_NOT_CLONEABLE_MESSAGE,
CloningError.CLASS_IS_NOT_CLONEABLE_CODE
);
}
}
private static function prepareTypeForCloning(type:Type):void {
if (isTypePreparedForCloning(type)) {
return;
}
ClassUtil.registerAliasFor(type.clazz);
_isClassPreparedForCloningMap[type.clazz] = true;
}
dolly_internal static function findAllWritableFieldsForType(type:Type):Vector.<Field> {
failIfTypeIsNotCloneable(type);
if (!isTypePreparedForCloning(type)) {
prepareTypeForCloning(type);
}
const result:Vector.<Field> = new Vector.<Field>();
for each(var field:Field in type.properties) {
if (!(field is Accessor) || (field as Accessor).access == AccessorAccess.READ_WRITE) {
result.push(field);
}
}
return result;
}
dolly_internal static function doClone(source:*, type:Type = null):* {
if (!type) {
type = Type.forInstance(source);
}
prepareTypeForCloning(type);
const fieldsToClone:Vector.<Field> = findAllWritableFieldsForType(type);
for each(var field:Field in fieldsToClone) {
var fieldType:Type = field.type;
if (isTypeCloneable(fieldType)) {
prepareTypeForCloning(fieldType);
}
}
const byteArray:ByteArray = new ByteArray();
byteArray.writeObject(source);
byteArray.position = 0;
const clonedInstance:* = byteArray.readObject();
return clonedInstance;
}
public static function clone(source:*):* {
const type:Type = Type.forInstance(source);
failIfTypeIsNotCloneable(type);
return doClone(source, type);
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import dolly.core.errors.CloningError;
import dolly.core.metadata.MetadataName;
import dolly.utils.ClassUtil;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import org.as3commons.reflect.Accessor;
import org.as3commons.reflect.AccessorAccess;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
use namespace dolly_internal;
public class Cloner {
private static var _isClassPreparedForCloningMap:Dictionary = new Dictionary();
private static function isTypeCloneable(type:Type):Boolean {
return type.hasMetadata(MetadataName.CLONEABLE);
}
private static function isTypePreparedForCloning(type:Type):Boolean {
return _isClassPreparedForCloningMap[type.clazz];
}
private static function failIfTypeIsNotCloneable(type:Type):void {
if (!isTypeCloneable(type)) {
throw new CloningError(
CloningError.CLASS_IS_NOT_CLONEABLE_MESSAGE,
CloningError.CLASS_IS_NOT_CLONEABLE_CODE
);
}
}
private static function prepareTypeForCloning(type:Type):void {
if (isTypePreparedForCloning(type)) {
return;
}
ClassUtil.registerAliasFor(type.clazz);
_isClassPreparedForCloningMap[type.clazz] = true;
const fieldsToClone:Vector.<Field> = findAllWritableFieldsForType(type);
for each(var field:Field in fieldsToClone) {
var fieldType:Type = field.type;
if (isTypeCloneable(fieldType)) {
prepareTypeForCloning(fieldType);
}
}
}
dolly_internal static function findAllWritableFieldsForType(type:Type):Vector.<Field> {
failIfTypeIsNotCloneable(type);
if (!isTypePreparedForCloning(type)) {
prepareTypeForCloning(type);
}
const result:Vector.<Field> = new Vector.<Field>();
for each(var field:Field in type.properties) {
if (!(field is Accessor) || (field as Accessor).access == AccessorAccess.READ_WRITE) {
result.push(field);
}
}
return result;
}
dolly_internal static function doClone(source:*, type:Type = null):* {
if (!type) {
type = Type.forInstance(source);
}
prepareTypeForCloning(type);
const byteArray:ByteArray = new ByteArray();
byteArray.writeObject(source);
byteArray.position = 0;
const clonedInstance:* = byteArray.readObject();
return clonedInstance;
}
public static function clone(source:*):* {
const type:Type = Type.forInstance(source);
failIfTypeIsNotCloneable(type);
return doClone(source, type);
}
}
}
|
Move code preparing cloneable fields of type for cloning to method Cloner.prepareTypeForCloning().
|
Move code preparing cloneable fields of type for cloning to method Cloner.prepareTypeForCloning().
|
ActionScript
|
mit
|
Yarovoy/dolly
|
1e392cb30e75f544f0a0e141c7184139187f3816
|
src/aerys/minko/render/shader/sprite/SpriteShader.as
|
src/aerys/minko/render/shader/sprite/SpriteShader.as
|
package aerys.minko.render.shader.sprite
{
import aerys.minko.render.material.basic.BasicProperties;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.ShaderSettings;
import aerys.minko.render.shader.part.DiffuseShaderPart;
import aerys.minko.type.enum.Blending;
import aerys.minko.type.enum.BlendingSource;
import aerys.minko.type.enum.DepthTest;
public class SpriteShader extends Shader
{
private var _diffuse : DiffuseShaderPart;
private var _uv : SFloat;
public function SpriteShader()
{
super();
_diffuse = new DiffuseShaderPart(this);
}
override protected function initializeSettings(settings : ShaderSettings) : void
{
var blending : uint = meshBindings.getProperty(
BasicProperties.BLENDING, Blending.OPAQUE
);
settings.depthWriteEnabled = meshBindings.getProperty(
BasicProperties.DEPTH_WRITE_ENABLED, true
);
settings.depthTest = meshBindings.getProperty(
BasicProperties.DEPTH_TEST, DepthTest.LESS
);
if ((blending & 0xff) == BlendingSource.SOURCE_ALPHA)
{
settings.priority -= 0.5;
settings.depthSortDrawCalls = true;
}
settings.blending = blending;
settings.enabled = true;
settings.scissorRectangle = null;
}
override protected function getVertexPosition() : SFloat
{
var vertexXY : SFloat = vertexXY.xy;
_uv = multiply(add(vertexXY, 0.5), float2(1, -1));
var depth : SFloat = meshBindings.getParameter('depth', 1);
var xy : SFloat = float2(
meshBindings.getParameter('x', 1),
meshBindings.getParameter('y', 1)
);
var size : SFloat = float2(
meshBindings.getParameter('width', 1),
meshBindings.getParameter('height', 1)
);
var vpSize : SFloat = float2(
sceneBindings.getParameter('viewportWidth', 1),
sceneBindings.getParameter('viewportHeight', 1)
);
xy = divide(add(xy, divide(size, 2)), vpSize);
xy = multiply(subtract(xy, 0.5), float2(2, -2));
vertexXY.scaleBy(divide(size, divide(vpSize, 2)));
vertexXY.incrementBy(xy);
return float4(vertexXY, depth, 1);
}
override protected function getPixelColor() : SFloat
{
return _diffuse.getDiffuseColor(true, _uv);
}
}
}
|
package aerys.minko.render.shader.sprite
{
import aerys.minko.render.material.basic.BasicProperties;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.ShaderSettings;
import aerys.minko.render.shader.part.DiffuseShaderPart;
import aerys.minko.type.enum.Blending;
import aerys.minko.type.enum.BlendingSource;
import aerys.minko.type.enum.DepthTest;
public class SpriteShader extends Shader
{
private var _diffuse : DiffuseShaderPart;
private var _uv : SFloat;
public function SpriteShader()
{
super();
_diffuse = new DiffuseShaderPart(this);
}
override protected function initializeSettings(settings : ShaderSettings) : void
{
var blending : uint = meshBindings.getProperty(
BasicProperties.BLENDING, Blending.OPAQUE
);
settings.depthWriteEnabled = meshBindings.getProperty(
BasicProperties.DEPTH_WRITE_ENABLED, true
);
settings.depthTest = meshBindings.getProperty(
BasicProperties.DEPTH_TEST, DepthTest.LESS
);
if ((blending & 0xff) == BlendingSource.SOURCE_ALPHA)
{
settings.priority -= 0.5;
settings.depthSortDrawCalls = true;
}
settings.blending = blending;
settings.enabled = true;
settings.scissorRectangle = null;
}
override protected function getVertexPosition() : SFloat
{
var vertexXY : SFloat = vertexXY.xy;
_uv = multiply(add(vertexXY, 0.5), float2(1, -1));
var depth : SFloat = meshBindings.getParameter('depth', 1);
var xy : SFloat = float2(
meshBindings.getParameter('x', 1),
meshBindings.getParameter('y', 1)
);
var size : SFloat = float2(
meshBindings.getParameter('width', 1),
meshBindings.getParameter('height', 1)
);
var vpSize : SFloat = float2(
sceneBindings.getParameter('viewportWidth', 1),
sceneBindings.getParameter('viewportHeight', 1)
);
xy = divide(add(xy, divide(size, 2)), vpSize);
xy = multiply(subtract(xy, 0.5), float2(2, -2));
vertexXY.scaleBy(divide(size, divide(vpSize, 2)));
vertexXY.incrementBy(xy);
return float4(vertexXY, depth, 1);
}
override protected function getPixelColor() : SFloat
{
return _diffuse.getDiffuseColor(true, interpolate(_uv));
}
}
}
|
Fix sprite shader
|
Fix sprite shader
|
ActionScript
|
mit
|
aerys/minko-as3
|
5044133f169dbb0785891f4e00da0da336144bdc
|
generator/sources/as3/com/kaltura/utils/ObjectUtil.as
|
generator/sources/as3/com/kaltura/utils/ObjectUtil.as
|
package com.kaltura.utils
{
import flash.utils.describeType;
/**
* ObjectUtil class holds different utilities for use with objects
*/
public class ObjectUtil
{
/**
* retreives a list of all keys on the given object
* @param obj the object to operate on
* @return an array with all keys as strings
*/
public static function getObjectAllKeys( obj : Object ) : Array
{
var arr : Array = new Array();
arr = getObjectStaticKeys( obj );
arr = arr.concat( getObjectDynamicKeys( obj ) );
return arr;
}
/**
* retreives a list of all the keys defined at authoring time.
* @param obj the object to operate on
* @return an array with all keys as strings
*/
public static function getObjectStaticKeys( obj : Object ) : Array
{
var arr : Array = new Array();
var classInfo:XML = describeType(obj);
// don't take keys defined in ObjectProxy (i.e., uid)
var accessors:XMLList = classInfo..accessor.(@declaredBy != "mx.utils::ObjectProxy");
for each (var v:XML in accessors) {
arr.push( [email protected]() );
}
return arr;
}
/**
* retreives a list of all the keys defined at runtime (for dynamic objects).
* @param obj the object to operate on
* @return an array with all keys as strings
*/
public static function getObjectDynamicKeys( obj : Object ) : Array
{
var arr : Array = new Array();
for( var str:String in obj )
arr.push( str );
return arr;
}
/**
* retreives a list of all the values on the given object.
* @param obj the object to operate on
* @return an array with all values
*/
public static function getObjectAllValues( obj : Object ) : Array
{
var arr : Array = new Array();
arr = getObjectStaticValues( obj );
arr = arr.concat( getObjectDynamicValues( obj ) );
return arr;
}
/**
* retreives a list of all the values of keys defined at authoring time.
* @param obj the object to operate on
* @return an array with all values
*/
public static function getObjectStaticValues( obj : Object ) : Array
{
var arr : Array = new Array();
var classInfo:XML = describeType(obj);
for each (var v:XML in classInfo..variable)
arr.push( obj[v.@name] );
return arr;
}
/**
* retreives a list of all the values of keys defined at runtime (for dynamic objects).
* @param obj the object to operate on
* @return an array with all values
*/
public static function getObjectDynamicValues( obj : Object ) : Array
{
var arr : Array = new Array();
for( var str:String in obj )
arr.push( obj[str] );
return arr;
}
/**
* compare variables and properties of 2 given objects
* this function deliberately ignors the property uid.
* @param object1
* @param object2
* @return
*
*/
public static function compareObjects(object1:Object,object2:Object):Boolean
{
var ob1:Object = describeObject(object1);
var ob2:Object = describeObject(object2);
//run on obj1, check if the value exist in ob2 and check its value
for (var o:Object in ob1)
{
if (ob2.hasOwnProperty(o))
{
if(ob1[o] != ob2[o] && o!="uid")
return false;
} else
{
return false;
}
}
//run on obj2, check if the value exist in ob1 and check its value
for (var p:Object in ob2)
{
if (ob1.hasOwnProperty(p))
{
if(ob2[p] != ob1[p] && p!="uid")
return false;
} else
{
return false;
}
}
return true;
}
/**
* Return an object that holds all variables and properties and their values
* @param obj
* @return
*
*/
public static function describeObject(obj:Object):Object
{
var ob:Object = new Object();
var classInfo:XML = describeType(obj);
//map all variables
for each (var v:XML in classInfo..variable)
{
ob[v.@name] = obj[v.@name];
}
//map all properties
for each (var a:XML in classInfo..accessor)
{
ob[a.@name] = obj[a.@name];
}
return ob;
}
}
}
|
package com.kaltura.utils
{
import flash.utils.describeType;
/**
* ObjectUtil class holds different utilities for use with objects
*/
public class ObjectUtil
{
/**
* retreives a list of all keys on the given object
* @param obj the object to operate on
* @return an array with all keys as strings
*/
public static function getObjectAllKeys( obj : Object ) : Array
{
var arr : Array = new Array();
arr = getObjectStaticKeys( obj );
arr = arr.concat( getObjectDynamicKeys( obj ) );
return arr;
}
/**
* retreives a list of all the keys defined at authoring time.
* @param obj the object to operate on
* @return an array with all keys as strings
*/
public static function getObjectStaticKeys( obj : Object ) : Array
{
var arr : Array = new Array();
var classInfo:XML = describeType(obj);
// don't take keys defined in ObjectProxy (i.e., uid)
var accessors:XMLList = classInfo..accessor.(@declaredBy != "mx.utils::ObjectProxy");
for each (var v:XML in accessors) {
arr.push( [email protected]() );
}
return arr;
}
/**
* retreives a list of all the keys defined at runtime (for dynamic objects).
* @param obj the object to operate on
* @return an array with all keys as strings
*/
public static function getObjectDynamicKeys( obj : Object ) : Array
{
var arr : Array = new Array();
for( var str:String in obj )
arr.push( str );
return arr;
}
/**
* retreives a list of all the values on the given object.
* @param obj the object to operate on
* @return an array with all values
*/
public static function getObjectAllValues( obj : Object ) : Array
{
var arr : Array = new Array();
arr = getObjectStaticValues( obj );
arr = arr.concat( getObjectDynamicValues( obj ) );
return arr;
}
/**
* retreives a list of all the values of keys defined at authoring time.
* @param obj the object to operate on
* @return an array with all values
*/
public static function getObjectStaticValues( obj : Object ) : Array
{
var arr : Array = new Array();
var classInfo:XML = describeType(obj);
for each (var v:XML in classInfo..variable)
arr.push( obj[v.@name] );
return arr;
}
/**
* retreives a list of all the values of keys defined at runtime (for dynamic objects).
* @param obj the object to operate on
* @return an array with all values
*/
public static function getObjectDynamicValues( obj : Object ) : Array
{
var arr : Array = new Array();
for( var str:String in obj )
arr.push( obj[str] );
return arr;
}
/**
* compare variables and properties of 2 given objects
* this function deliberately ignors the property uid.
* @param object1
* @param object2
* @return
*
*/
public static function compareObjects(object1:Object,object2:Object):Boolean
{
var ob1:Object = describeObject(object1);
var ob2:Object = describeObject(object2);
//run on obj1, check if the value exist in ob2 and check its value
for (var o:Object in ob1)
{
if (ob2.hasOwnProperty(o))
{
if(ob1[o] != ob2[o] && o!="uid")
return false;
} else
{
return false;
}
}
//run on obj2, check if the value exist in ob1 and check its value
for (var p:Object in ob2)
{
if (ob1.hasOwnProperty(p))
{
if(ob2[p] != ob1[p] && p!="uid")
return false;
} else
{
return false;
}
}
return true;
}
/**
* Return an object that holds all variables and properties and their values
* @param obj
* @return
*
*/
public static function describeObject(obj:Object):Object
{
var ob:Object = new Object();
var classInfo:XML = describeType(obj);
//map all variables
for each (var v:XML in classInfo..variable)
{
ob[v.@name] = obj[v.@name];
}
//map all properties
for each (var a:XML in classInfo..accessor)
{
ob[a.@name] = obj[a.@name];
}
return ob;
}
/**
* Copy attributes from source object to target object
* @param source
* @param target
*
*/
public static function copyObject(source:Object, target:Object):void {
var atts:Array = getObjectAllKeys(source);
for (var i:int = 0; i< atts.length; i++) {
target[atts[i]] = source[atts[i]];
}
}
}
}
|
add copyObject function
|
add copyObject function
git-svn-id: 8a2ccb88241e16c78017770bc38d91d6d5396a5a@65593 6b8eccd3-e8c5-4e7d-8186-e12b5326b719
|
ActionScript
|
agpl-3.0
|
DBezemer/server,gale320/server,doubleshot/server,ivesbai/server,DBezemer/server,DBezemer/server,matsuu/server,DBezemer/server,doubleshot/server,ratliff/server,doubleshot/server,ivesbai/server,DBezemer/server,doubleshot/server,jorgevbo/server,gale320/server,ivesbai/server,doubleshot/server,matsuu/server,jorgevbo/server,DBezemer/server,gale320/server,ratliff/server,kaltura/server,matsuu/server,jorgevbo/server,matsuu/server,kaltura/server,gale320/server,kaltura/server,ivesbai/server,jorgevbo/server,ivesbai/server,matsuu/server,jorgevbo/server,DBezemer/server,ratliff/server,ratliff/server,jorgevbo/server,doubleshot/server,kaltura/server,ivesbai/server,ratliff/server,gale320/server,matsuu/server,jorgevbo/server,gale320/server,doubleshot/server,matsuu/server,ratliff/server,kaltura/server,ivesbai/server,matsuu/server,ratliff/server,kaltura/server,ivesbai/server,ratliff/server,doubleshot/server,DBezemer/server,jorgevbo/server,gale320/server,gale320/server
|
4b06b615c84d7e7347fd207f358ef0d65224fd99
|
src/org/jivesoftware/xiff/core/XMPPBOSHConnection.as
|
src/org/jivesoftware/xiff/core/XMPPBOSHConnection.as
|
package org.jivesoftware.xiff.core
{
import flash.events.ErrorEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.xml.XMLDocument;
import flash.xml.XMLNode;
import mx.messaging.messages.HTTPRequestMessage;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import org.jivesoftware.xiff.auth.Anonymous;
import org.jivesoftware.xiff.auth.External;
import org.jivesoftware.xiff.auth.Plain;
import org.jivesoftware.xiff.auth.SASLAuth;
import org.jivesoftware.xiff.data.IQ;
import org.jivesoftware.xiff.data.bind.BindExtension;
import org.jivesoftware.xiff.data.session.SessionExtension;
import org.jivesoftware.xiff.events.ConnectionSuccessEvent;
import org.jivesoftware.xiff.events.IncomingDataEvent;
import org.jivesoftware.xiff.events.LoginEvent;
import org.jivesoftware.xiff.util.Callback;
public class XMPPBOSHConnection extends XMPPConnection
{
private static var saslMechanisms:Object = {
"PLAIN":Plain,
"ANONYMOUS":Anonymous,
"EXTERNAL":External
};
private var maxConcurrentRequests:uint = 2;
private var boshVersion:Number = 1.6;
private var headers:Object = {
"post": [],
"get": ['Cache-Control', 'no-store', 'Cache-Control', 'no-cache', 'Pragma', 'no-cache']
};
private var requestCount:int = 0;
private var failedRequests:Array = [];
private var requestQueue:Array = [];
private var responseQueue:Array = [];
private const responseTimer:Timer = new Timer(0.0, 1);
private var isDisconnecting:Boolean = false;
private var boshPollingInterval:Number = 10000;
private var sid:String;
private var rid:Number;
private var wait:int;
private var inactivity:int;
private var pollTimer:Timer = new Timer(1, 1);
private var pollTimeoutTimer:Timer = new Timer(1, 1);
private var auth:SASLAuth;
private var authHandler:Function;
private var https:Boolean = false;
private var _port:Number = -1;
private var callbacks:Object = {};
public static var logger:Object = null;
private var lastPollTime:Date = null;
public override function connect(streamType:String=null):Boolean
{
if(logger)
logger.log("CONNECT()", "INFO");
BindExtension.enable();
active = false;
loggedIn = false;
var attrs:Object = {
xmlns: "http://jabber.org/protocol/httpbind",
hold: maxConcurrentRequests,
rid: nextRID,
secure: https,
wait: 10,
ver: boshVersion
}
var result:XMLNode = new XMLNode(1, "body");
result.attributes = attrs;
sendRequests(result);
return true;
}
public static function registerSASLMechanism(name:String, authClass:Class):void
{
saslMechanisms[name] = authClass;
}
public static function disableSASLMechanism(name:String):void
{
saslMechanisms[name] = null;
}
public function set secure(flag:Boolean):void
{
https = flag;
}
public override function set port(portnum:Number):void
{
_port = portnum;
}
public override function get port():Number
{
if(_port == -1)
return https ? 8483 : 8080;
return _port;
}
public function get httpServer():String
{
return (https ? "https" : "http") + "://" + server + ":" + port + "/http-bind/";
}
public override function disconnect():void
{
super.disconnect();
pollTimer.stop();
pollTimer = null;
pollTimeoutTimer.stop();
pollTimeoutTimer = null;
}
public function processConnectionResponse(responseBody:XMLNode):void
{
var attributes:Object = responseBody.attributes;
sid = attributes.sid;
boshPollingInterval = attributes.polling * 1000;
wait = attributes.wait;
inactivity = attributes.inactivity * 1000;
if(inactivity - 2000 >= boshPollingInterval || (boshPollingInterval <= 1000 && boshPollingInterval > 0))
{
boshPollingInterval += 1000;
}
inactivity -= 1000;
var serverRequests:int = attributes.requests;
if (serverRequests)
maxConcurrentRequests = Math.min(serverRequests, maxConcurrentRequests);
active = true;
configureConnection(responseBody);
responseTimer.addEventListener(TimerEvent.TIMER_COMPLETE, processResponse);
trace(boshPollingInterval);
pollTimer.delay = boshPollingInterval;
pollTimer.addEventListener(TimerEvent.TIMER_COMPLETE, pollServer);
pollTimer.start();
pollTimeoutTimer.delay = inactivity;
pollTimeoutTimer.addEventListener(TimerEvent.TIMER_COMPLETE, function(evt:TimerEvent):void {
trace("Poll timed out, resuming");
pollServer(evt, true);
});
}
private function processResponse(event:TimerEvent=null):void
{
// Read the data and send it to the appropriate parser
var currentNode:XMLNode = responseQueue.shift();
var nodeName:String = currentNode.nodeName.toLowerCase();
switch( nodeName )
{
case "stream:features":
//we already handled this in httpResponse()
break;
case "stream:error":
handleStreamError( currentNode );
break;
case "iq":
handleIQ( currentNode );
break;
case "message":
handleMessage( currentNode );
break;
case "presence":
handlePresence( currentNode );
break;
case "success":
handleAuthentication( currentNode );
break;
case "failure":
handleAuthentication( currentNode );
break;
default:
dispatchError( "undefined-condition", "Unknown Error", "modify", 500 );
break;
}
resetResponseProcessor();
}
private function resetResponseProcessor():void
{
if(responseQueue.length > 0)
{
responseTimer.reset();
responseTimer.start();
}
}
private function httpResponse(req:XMLNode, isPollResponse:Boolean, evt:ResultEvent):void
{
requestCount--;
var rawXML:String = evt.result as String;
if(logger)
logger.log(rawXML, "INCOMING");
var xmlData:XMLDocument = new XMLDocument();
xmlData.ignoreWhite = this.ignoreWhite;
xmlData.parseXML( rawXML );
var bodyNode:XMLNode = xmlData.firstChild;
var event:IncomingDataEvent = new IncomingDataEvent();
event.data = xmlData;
dispatchEvent( event );
if(bodyNode.attributes["type"] == "terminal")
{
dispatchError( "BOSH Error", bodyNode.attributes["condition"], "", -1 );
active = false;
}
for each(var childNode:XMLNode in bodyNode.childNodes)
{
if(childNode.nodeName == "stream:features")
{
_expireTagSearch = false;
processConnectionResponse( bodyNode );
}
else
responseQueue.push(childNode);
}
resetResponseProcessor();
//if we have no outstanding requests, then we're free to send a poll at the next opportunity
if(requestCount == 0 && !sendQueuedRequests())
resetPollTimer();
}
private function httpError(req:XMLNode, isPollResponse:Boolean, evt:FaultEvent):void
{
disconnect();
dispatchError("Unknown HTTP Error", evt.fault.rootCause.text, "", -1);
}
protected override function sendXML(body:*):void
{
sendQueuedRequests(body);
}
private function sendQueuedRequests(body:*=null):Boolean
{
if(body)
requestQueue.push(body);
else if(requestQueue.length == 0)
return false;
return sendRequests();
}
//returns true if any requests were sent
private function sendRequests(data:XMLNode = null, isPoll:Boolean = false):Boolean
{
if(requestCount >= maxConcurrentRequests)
return false;
requestCount++;
if(!data)
{
if(isPoll)
{
data = createRequest();
}
else
{
var temp:Array = [];
for(var i:uint = 0; i < 10 && requestQueue.length > 0; i++)
{
temp.push(requestQueue.shift());
}
data = createRequest(temp);
}
}
//build the http request
var request:HTTPService = new HTTPService();
request.method = "post";
request.headers = headers[request.method];
request.url = httpServer;
request.resultFormat = HTTPService.RESULT_FORMAT_TEXT;
request.contentType = "text/xml";
var responseCallback:Callback = new Callback(this, httpResponse, data, isPoll);
var errorCallback:Callback = new Callback(this, httpError, data, isPoll);
request.addEventListener(ResultEvent.RESULT, responseCallback.call, false);
request.addEventListener(FaultEvent.FAULT, errorCallback.call, false);
if(logger)
logger.log(data, "OUTGOING");
request.send(data);
if(isPoll) {
lastPollTime = new Date();
pollTimeoutTimer.reset();
pollTimeoutTimer.start();
trace("Polling at: " + lastPollTime.getMinutes() + ":" + lastPollTime.getSeconds());
}
pollTimer.stop();
return true;
}
private function resetPollTimer():void
{
if(!pollTimer)
return;
pollTimeoutTimer.stop();
pollTimer.reset();
var timeSinceLastPoll:Number = 0;
if(lastPollTime)
timeSinceLastPoll = new Date().time - lastPollTime.time;
if(timeSinceLastPoll >= boshPollingInterval)
timeSinceLastPoll = 0;
pollTimer.delay = boshPollingInterval - timeSinceLastPoll;
pollTimer.start();
}
private function pollServer(evt:TimerEvent, force:Boolean=false):void
{
if(force)
trace("Forcing poll!");
//We shouldn't poll if the connection is dead, if we had requests to send instead, or if there's already one in progress
if(!isActive() || ((sendQueuedRequests() || requestCount > 0) && !force))
return;
//this should be safe since sendRequests checks to be sure it's not over the concurrent requests limit, and we just ensured that the queue is empty by calling sendQueuedRequests()
sendRequests(null, true);
}
private function get nextRID():Number {
if(!rid)
rid = Math.floor(Math.random() * 1000000);
return ++rid;
}
private function createRequest(bodyContent:Array=null):XMLNode {
var attrs:Object = {
xmlns: "http://jabber.org/protocol/httpbind",
rid: nextRID,
sid: sid
}
var req:XMLNode = new XMLNode(1, "body");
if(bodyContent)
for each(var content:XMLNode in bodyContent)
req.appendChild(content);
req.attributes = attrs;
return req;
}
private function handleAuthentication(responseBody:XMLNode):void
{
// if(!response || response.length == 0) {
// return;
// }
var status:Object = auth.handleResponse(0, responseBody);
if (status.authComplete) {
if (status.authSuccess) {
bindConnection();
}
else {
dispatchError("Authentication Error", "", "", 401);
disconnect();
}
}
}
private function configureConnection(responseBody:XMLNode):void
{
var features:XMLNode = responseBody.firstChild;
var authentication:Object = {};
for each(var feature:XMLNode in features.childNodes)
{
if (feature.nodeName == "mechanisms")
authentication.auth = configureAuthMechanisms(feature);
else if (feature.nodeName == "bind")
authentication.bind = true;
else if (feature.nodeName == "session")
authentication.session = true;
}
auth = authentication.auth;
dispatchEvent(new ConnectionSuccessEvent());
authHandler = handleAuthentication;
sendXML(auth.request);
}
private function configureAuthMechanisms(mechanisms:XMLNode):SASLAuth
{
var authMechanism:SASLAuth;
var authClass:Class;
for each(var mechanism:XMLNode in mechanisms.childNodes)
{
authClass = saslMechanisms[mechanism.firstChild.nodeValue];
if(authClass)
break;
}
if (!authClass) {
dispatchError("SASL missing", "The server is not configured to support any available SASL mechanisms", "SASL", -1);
return null;
}
return new authClass(this);
}
public function handleBindResponse(packet:IQ):void
{
var bind:BindExtension = packet.getExtension("bind") as BindExtension;
var jid:UnescapedJID = bind.jid.unescaped;
myResource = jid.resource;
myUsername = jid.node;
domain = jid.domain;
establishSession();
}
private function bindConnection():void
{
var bindIQ:IQ = new IQ(null, "set");
var bindExt:BindExtension = new BindExtension();
if(resource)
bindExt.resource = resource;
bindIQ.addExtension(bindExt);
//this is laaaaaame, it should be a function
bindIQ.callbackName = "handleBindResponse";
bindIQ.callbackScope = this;
send(bindIQ);
}
public function handleSessionResponse(packet:IQ):void
{
dispatchEvent(new LoginEvent());
}
private function establishSession():void
{
var sessionIQ:IQ = new IQ(null, "set");
sessionIQ.addExtension(new SessionExtension());
sessionIQ.callbackName = "handleSessionResponse";
sessionIQ.callbackScope = this;
send(sessionIQ);
}
//do nothing, we use polling instead
public override function sendKeepAlive():void {}
}
}
|
package org.jivesoftware.xiff.core
{
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.xml.XMLDocument;
import flash.xml.XMLNode;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import org.jivesoftware.xiff.auth.Anonymous;
import org.jivesoftware.xiff.auth.External;
import org.jivesoftware.xiff.auth.Plain;
import org.jivesoftware.xiff.auth.SASLAuth;
import org.jivesoftware.xiff.data.IQ;
import org.jivesoftware.xiff.data.bind.BindExtension;
import org.jivesoftware.xiff.data.session.SessionExtension;
import org.jivesoftware.xiff.events.ConnectionSuccessEvent;
import org.jivesoftware.xiff.events.IncomingDataEvent;
import org.jivesoftware.xiff.events.LoginEvent;
import org.jivesoftware.xiff.util.Callback;
public class XMPPBOSHConnection extends XMPPConnection
{
private static var saslMechanisms:Object = {
"PLAIN":Plain,
"ANONYMOUS":Anonymous,
"EXTERNAL":External
};
private var maxConcurrentRequests:uint = 2;
private var boshVersion:Number = 1.6;
private var headers:Object = {
"post": [],
"get": ['Cache-Control', 'no-store', 'Cache-Control', 'no-cache', 'Pragma', 'no-cache']
};
private var requestCount:int = 0;
private var failedRequests:Array = [];
private var requestQueue:Array = [];
private var responseQueue:Array = [];
private const responseTimer:Timer = new Timer(0.0, 1);
private var isDisconnecting:Boolean = false;
private var boshPollingInterval:Number = 10000;
private var sid:String;
private var rid:Number;
private var wait:int;
private var inactivity:int;
private var pollTimer:Timer = new Timer(1, 1);
private var pollTimeoutTimer:Timer = new Timer(1, 1);
private var auth:SASLAuth;
private var authHandler:Function;
private var https:Boolean = false;
private var _port:Number = -1;
private var callbacks:Object = {};
public static var logger:Object = null;
private var lastPollTime:Date = null;
public override function connect(streamType:String=null):Boolean
{
if(logger)
logger.log("CONNECT()", "INFO");
BindExtension.enable();
active = false;
loggedIn = false;
var attrs:Object = {
xmlns: "http://jabber.org/protocol/httpbind",
hold: maxConcurrentRequests,
rid: nextRID,
secure: https,
wait: 10,
ver: boshVersion
}
var result:XMLNode = new XMLNode(1, "body");
result.attributes = attrs;
sendRequests(result);
return true;
}
public static function registerSASLMechanism(name:String, authClass:Class):void
{
saslMechanisms[name] = authClass;
}
public static function disableSASLMechanism(name:String):void
{
saslMechanisms[name] = null;
}
public function set secure(flag:Boolean):void
{
https = flag;
}
public function get secure():Boolean
{
return https;
}
public override function set port(portnum:Number):void
{
_port = portnum;
}
public override function get port():Number
{
if(_port == -1)
return https ? 8483 : 8080;
return _port;
}
public function get httpServer():String
{
return (https ? "https" : "http") + "://" + server + ":" + port + "/http-bind/";
}
public override function disconnect():void
{
super.disconnect();
pollTimer.stop();
pollTimer = null;
pollTimeoutTimer.stop();
pollTimeoutTimer = null;
}
public function processConnectionResponse(responseBody:XMLNode):void
{
var attributes:Object = responseBody.attributes;
sid = attributes.sid;
boshPollingInterval = attributes.polling * 1000;
wait = attributes.wait;
inactivity = attributes.inactivity * 1000;
if(inactivity - 2000 >= boshPollingInterval || (boshPollingInterval <= 1000 && boshPollingInterval > 0))
{
boshPollingInterval += 1000;
}
inactivity -= 1000;
var serverRequests:int = attributes.requests;
if (serverRequests)
maxConcurrentRequests = Math.min(serverRequests, maxConcurrentRequests);
active = true;
configureConnection(responseBody);
responseTimer.addEventListener(TimerEvent.TIMER_COMPLETE, processResponse);
trace(boshPollingInterval);
pollTimer.delay = boshPollingInterval;
pollTimer.addEventListener(TimerEvent.TIMER_COMPLETE, pollServer);
pollTimer.start();
pollTimeoutTimer.delay = inactivity;
pollTimeoutTimer.addEventListener(TimerEvent.TIMER_COMPLETE, function(evt:TimerEvent):void {
trace("Poll timed out, resuming");
pollServer(evt, true);
});
}
private function processResponse(event:TimerEvent=null):void
{
// Read the data and send it to the appropriate parser
var currentNode:XMLNode = responseQueue.shift();
var nodeName:String = currentNode.nodeName.toLowerCase();
switch( nodeName )
{
case "stream:features":
//we already handled this in httpResponse()
break;
case "stream:error":
handleStreamError( currentNode );
break;
case "iq":
handleIQ( currentNode );
break;
case "message":
handleMessage( currentNode );
break;
case "presence":
handlePresence( currentNode );
break;
case "success":
handleAuthentication( currentNode );
break;
case "failure":
handleAuthentication( currentNode );
break;
default:
dispatchError( "undefined-condition", "Unknown Error", "modify", 500 );
break;
}
resetResponseProcessor();
}
private function resetResponseProcessor():void
{
if(responseQueue.length > 0)
{
responseTimer.reset();
responseTimer.start();
}
}
private function httpResponse(req:XMLNode, isPollResponse:Boolean, evt:ResultEvent):void
{
requestCount--;
var rawXML:String = evt.result as String;
if(logger)
logger.log(rawXML, "INCOMING");
var xmlData:XMLDocument = new XMLDocument();
xmlData.ignoreWhite = this.ignoreWhite;
xmlData.parseXML( rawXML );
var bodyNode:XMLNode = xmlData.firstChild;
var event:IncomingDataEvent = new IncomingDataEvent();
event.data = xmlData;
dispatchEvent( event );
if(bodyNode.attributes["type"] == "terminal")
{
dispatchError( "BOSH Error", bodyNode.attributes["condition"], "", -1 );
active = false;
}
for each(var childNode:XMLNode in bodyNode.childNodes)
{
if(childNode.nodeName == "stream:features")
{
_expireTagSearch = false;
processConnectionResponse( bodyNode );
}
else
responseQueue.push(childNode);
}
resetResponseProcessor();
//if we have no outstanding requests, then we're free to send a poll at the next opportunity
if(requestCount == 0 && !sendQueuedRequests())
resetPollTimer();
}
private function httpError(req:XMLNode, isPollResponse:Boolean, evt:FaultEvent):void
{
disconnect();
dispatchError("Unknown HTTP Error", evt.fault.rootCause.text, "", -1);
}
protected override function sendXML(body:*):void
{
sendQueuedRequests(body);
}
private function sendQueuedRequests(body:*=null):Boolean
{
if(body)
requestQueue.push(body);
else if(requestQueue.length == 0)
return false;
return sendRequests();
}
//returns true if any requests were sent
private function sendRequests(data:XMLNode = null, isPoll:Boolean = false):Boolean
{
if(requestCount >= maxConcurrentRequests)
return false;
requestCount++;
if(!data)
{
if(isPoll)
{
data = createRequest();
}
else
{
var temp:Array = [];
for(var i:uint = 0; i < 10 && requestQueue.length > 0; i++)
{
temp.push(requestQueue.shift());
}
data = createRequest(temp);
}
}
//build the http request
var request:HTTPService = new HTTPService();
request.method = "post";
request.headers = headers[request.method];
request.url = httpServer;
request.resultFormat = HTTPService.RESULT_FORMAT_TEXT;
request.contentType = "text/xml";
var responseCallback:Callback = new Callback(this, httpResponse, data, isPoll);
var errorCallback:Callback = new Callback(this, httpError, data, isPoll);
request.addEventListener(ResultEvent.RESULT, responseCallback.call, false);
request.addEventListener(FaultEvent.FAULT, errorCallback.call, false);
if(logger)
logger.log(data, "OUTGOING");
request.send(data);
if(isPoll) {
lastPollTime = new Date();
pollTimeoutTimer.reset();
pollTimeoutTimer.start();
trace("Polling at: " + lastPollTime.getMinutes() + ":" + lastPollTime.getSeconds());
}
pollTimer.stop();
return true;
}
private function resetPollTimer():void
{
if(!pollTimer)
return;
pollTimeoutTimer.stop();
pollTimer.reset();
var timeSinceLastPoll:Number = 0;
if(lastPollTime)
timeSinceLastPoll = new Date().time - lastPollTime.time;
if(timeSinceLastPoll >= boshPollingInterval)
timeSinceLastPoll = 0;
pollTimer.delay = boshPollingInterval - timeSinceLastPoll;
pollTimer.start();
}
private function pollServer(evt:TimerEvent, force:Boolean=false):void
{
if(force)
trace("Forcing poll!");
//We shouldn't poll if the connection is dead, if we had requests to send instead, or if there's already one in progress
if(!isActive() || ((sendQueuedRequests() || requestCount > 0) && !force))
return;
//this should be safe since sendRequests checks to be sure it's not over the concurrent requests limit, and we just ensured that the queue is empty by calling sendQueuedRequests()
sendRequests(null, true);
}
private function get nextRID():Number {
if(!rid)
rid = Math.floor(Math.random() * 1000000);
return ++rid;
}
private function createRequest(bodyContent:Array=null):XMLNode {
var attrs:Object = {
xmlns: "http://jabber.org/protocol/httpbind",
rid: nextRID,
sid: sid
}
var req:XMLNode = new XMLNode(1, "body");
if(bodyContent)
for each(var content:XMLNode in bodyContent)
req.appendChild(content);
req.attributes = attrs;
return req;
}
private function handleAuthentication(responseBody:XMLNode):void
{
// if(!response || response.length == 0) {
// return;
// }
var status:Object = auth.handleResponse(0, responseBody);
if (status.authComplete) {
if (status.authSuccess) {
bindConnection();
}
else {
dispatchError("Authentication Error", "", "", 401);
disconnect();
}
}
}
private function configureConnection(responseBody:XMLNode):void
{
var features:XMLNode = responseBody.firstChild;
var authentication:Object = {};
for each(var feature:XMLNode in features.childNodes)
{
if (feature.nodeName == "mechanisms")
authentication.auth = configureAuthMechanisms(feature);
else if (feature.nodeName == "bind")
authentication.bind = true;
else if (feature.nodeName == "session")
authentication.session = true;
}
auth = authentication.auth;
dispatchEvent(new ConnectionSuccessEvent());
authHandler = handleAuthentication;
sendXML(auth.request);
}
private function configureAuthMechanisms(mechanisms:XMLNode):SASLAuth
{
var authMechanism:SASLAuth;
var authClass:Class;
for each(var mechanism:XMLNode in mechanisms.childNodes)
{
authClass = saslMechanisms[mechanism.firstChild.nodeValue];
if(authClass)
break;
}
if (!authClass) {
dispatchError("SASL missing", "The server is not configured to support any available SASL mechanisms", "SASL", -1);
return null;
}
return new authClass(this);
}
public function handleBindResponse(packet:IQ):void
{
var bind:BindExtension = packet.getExtension("bind") as BindExtension;
var jid:UnescapedJID = bind.jid.unescaped;
myResource = jid.resource;
myUsername = jid.node;
domain = jid.domain;
establishSession();
}
private function bindConnection():void
{
var bindIQ:IQ = new IQ(null, "set");
var bindExt:BindExtension = new BindExtension();
if(resource)
bindExt.resource = resource;
bindIQ.addExtension(bindExt);
//this is laaaaaame, it should be a function
bindIQ.callbackName = "handleBindResponse";
bindIQ.callbackScope = this;
send(bindIQ);
}
public function handleSessionResponse(packet:IQ):void
{
dispatchEvent(new LoginEvent());
}
private function establishSession():void
{
var sessionIQ:IQ = new IQ(null, "set");
sessionIQ.addExtension(new SessionExtension());
sessionIQ.callbackName = "handleSessionResponse";
sessionIQ.callbackScope = this;
send(sessionIQ);
}
//do nothing, we use polling instead
public override function sendKeepAlive():void {}
}
}
|
Add an accessor for whether or not we are using https. r=Armando
|
Add an accessor for whether or not we are using https. r=Armando
git-svn-id: c197267f952b24206666de142881703007ca05d5@10681 b35dd754-fafc-0310-a699-88a17e54d16e
|
ActionScript
|
apache-2.0
|
nazoking/xiff
|
58382dc5e32e8f67f57636400a5f34bce9a51d05
|
src/org/flintparticles/twoD/actions/GravityWell.as
|
src/org/flintparticles/twoD/actions/GravityWell.as
|
/*
* FLINT PARTICLE SYSTEM
* .....................
*
* Author: Richard Lord
* Copyright (c) Richard Lord 2008-2010
* http://flintparticles.org
*
*
* Licence Agreement
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.flintparticles.twoD.actions
{
import org.flintparticles.common.actions.ActionBase;
import org.flintparticles.common.emitters.Emitter;
import org.flintparticles.common.particles.Particle;
import org.flintparticles.twoD.particles.Particle2D;
/**
* The GravityWell action applies a force on the particle to draw it towards
* a single point. The force applied is inversely proportional to the square
* of the distance from the particle to the point, in accordance with Newton's
* law of gravity.
*
* <p>This simulates the effect of gravity over large distances (as between
* planets, for example). To simulate the effect of gravity at the surface
* of the eacrth, use an Acceleration action with the direction of force
* downwards.</p>
*
* @see Acceleration
*/
public class GravityWell extends ActionBase
{
private var _x:Number;
private var _y:Number;
private var _power:Number;
private var _epsilonSq:Number;
private var _gravityConst:Number = 10000; // just scales the power to a more reasonable number
private var lp:Particle2D;
private var lx:Number;
private var ly:Number;
private var ldSq:Number;
private var ld:Number;
private var lfactor:Number;
/**
* The constructor creates a GravityWell action for use by an emitter.
* To add a GravityWell to all particles created by an emitter, use the
* emitter's addAction method.
*
* @see org.flintparticles.common.emitters.Emitter#addAction()
*
* @param power The strength of the gravity force - larger numbers produce a
* stronger force.
* @param x The x coordinate of the point towards which the force draws
* the particles.
* @param y The y coordinate of the point towards which the force draws
* the particles.
* @param epsilon The minimum distance for which gravity is calculated.
* Particles closer than this distance experience a gravity force as if
* they were this distance away. This stops the gravity effect blowing
* up as distances get small. For realistic gravity effects you will want
* a small epsilon ( ~1 ), but for stable visual effects a larger
* epsilon (~100) is often better.
*/
public function GravityWell( power:Number = 0, x:Number = 0, y:Number = 0, epsilon:Number = 100 )
{
this.power = power;
this.x = x;
this.y = y;
this.epsilon = epsilon;
}
/**
* The strength of the gravity force - larger numbers produce a
* stronger force.
*/
public function get power():Number
{
return _power / _gravityConst;
}
public function set power( value:Number ):void
{
_power = value * _gravityConst;
}
/**
* The x coordinate of the point towards which the force draws
* the particles.
*/
public function get x():Number
{
return _x;
}
public function set x( value:Number ):void
{
_x = value;
}
/**
* The y coordinate of the point towards which the force draws
* the particles.
*/
public function get y():Number
{
return _y;
}
public function set y( value:Number ):void
{
_y = value;
}
/**
* The minimum distance for which the gravity force is calculated.
* Particles closer than this distance experience the gravity as if
* they were this distance away. This stops the gravity effect blowing
* up as distances get small. For realistic gravity effects you will want
* a small epsilon ( ~1 ), but for stable visual effects a larger
* epsilon (~100) is often better.
*/
public function get epsilon():Number
{
return Math.sqrt( _epsilonSq );
}
public function set epsilon( value:Number ):void
{
_epsilonSq = value * value;
}
/**
* Calculates the gravity force on the particle and applies it for
* the period of time indicated.
*
* <p>This method is called by the emitter and need not be called by the
* user.</p>
*
* @param emitter The Emitter that created the particle.
* @param particle The particle to be updated.
* @param time The duration of the frame - used for time based updates.
*
* @see org.flintparticles.common.actions.Action#update()
*/
override public function update( emitter:Emitter, particle:Particle, time:Number ):void
{
if( particle.mass == 0 )
{
return;
}
lp = Particle2D( particle );
lx = _x - lp.x;
ly = _y - lp.y;
ldSq = lx * lx + ly * ly;
if( ldSq == 0 )
{
return;
}
ld = Math.sqrt( ldSq );
if( ldSq < _epsilonSq ) ldSq = _epsilonSq;
lfactor = ( _power * time ) / ( ldSq * ld );
lp.velX += lx * lfactor;
lp.velY += ly * lfactor;
}
}
}
|
/*
* FLINT PARTICLE SYSTEM
* .....................
*
* Author: Richard Lord
* Copyright (c) Richard Lord 2008-2010
* http://flintparticles.org
*
*
* Licence Agreement
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.flintparticles.twoD.actions
{
import org.flintparticles.common.actions.ActionBase;
import org.flintparticles.common.emitters.Emitter;
import org.flintparticles.common.particles.Particle;
import org.flintparticles.twoD.particles.Particle2D;
/**
* The GravityWell action applies a force on the particle to draw it towards
* a single point. The force applied is inversely proportional to the square
* of the distance from the particle to the point, in accordance with Newton's
* law of gravity.
*
* <p>This simulates the effect of gravity over large distances (as between
* planets, for example). To simulate the effect of gravity at the surface
* of the eacrth, use an Acceleration action with the direction of force
* downwards.</p>
*
* @see Acceleration
*/
public class GravityWell extends ActionBase
{
private var _x:Number;
private var _y:Number;
private var _power:Number;
private var _epsilonSq:Number;
private var _gravityConst:Number = 10000; // just scales the power to a more reasonable number
/**
* The constructor creates a GravityWell action for use by an emitter.
* To add a GravityWell to all particles created by an emitter, use the
* emitter's addAction method.
*
* @see org.flintparticles.common.emitters.Emitter#addAction()
*
* @param power The strength of the gravity force - larger numbers produce a
* stronger force.
* @param x The x coordinate of the point towards which the force draws
* the particles.
* @param y The y coordinate of the point towards which the force draws
* the particles.
* @param epsilon The minimum distance for which gravity is calculated.
* Particles closer than this distance experience a gravity force as if
* they were this distance away. This stops the gravity effect blowing
* up as distances get small. For realistic gravity effects you will want
* a small epsilon ( ~1 ), but for stable visual effects a larger
* epsilon (~100) is often better.
*/
public function GravityWell( power:Number = 0, x:Number = 0, y:Number = 0, epsilon:Number = 100 )
{
this.power = power;
this.x = x;
this.y = y;
this.epsilon = epsilon;
}
/**
* The strength of the gravity force - larger numbers produce a
* stronger force.
*/
public function get power():Number
{
return _power / _gravityConst;
}
public function set power( value:Number ):void
{
_power = value * _gravityConst;
}
/**
* The x coordinate of the point towards which the force draws
* the particles.
*/
public function get x():Number
{
return _x;
}
public function set x( value:Number ):void
{
_x = value;
}
/**
* The y coordinate of the point towards which the force draws
* the particles.
*/
public function get y():Number
{
return _y;
}
public function set y( value:Number ):void
{
_y = value;
}
/**
* The minimum distance for which the gravity force is calculated.
* Particles closer than this distance experience the gravity as if
* they were this distance away. This stops the gravity effect blowing
* up as distances get small. For realistic gravity effects you will want
* a small epsilon ( ~1 ), but for stable visual effects a larger
* epsilon (~100) is often better.
*/
public function get epsilon():Number
{
return Math.sqrt( _epsilonSq );
}
public function set epsilon( value:Number ):void
{
_epsilonSq = value * value;
}
/**
* Calculates the gravity force on the particle and applies it for
* the period of time indicated.
*
* <p>This method is called by the emitter and need not be called by the
* user.</p>
*
* @param emitter The Emitter that created the particle.
* @param particle The particle to be updated.
* @param time The duration of the frame - used for time based updates.
*
* @see org.flintparticles.common.actions.Action#update()
*/
override public function update( emitter:Emitter, particle:Particle, time:Number ):void
{
if( particle.mass == 0 )
{
return;
}
var p:Particle2D = Particle2D( particle );
var x:Number = _x - p.x;
var y:Number = _y - p.y;
var dSq:Number = x * x + y * y;
if( dSq == 0 )
{
return;
}
var d:Number = Math.sqrt( dSq );
if( dSq < _epsilonSq ) dSq = _epsilonSq;
var factor:Number = ( _power * time ) / ( dSq * d );
p.velX += x * factor;
p.velY += y * factor;
}
}
}
|
Tidy up GravityWell class
|
Tidy up GravityWell class
|
ActionScript
|
mit
|
richardlord/Flint
|
8b48ab9107efca1c566f06b6af2a7cc2845fcbd8
|
src/as/com/threerings/presents/client/Communicator.as
|
src/as/com/threerings/presents/client/Communicator.as
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.presents.client {
import flash.errors.IOError;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
import flash.utils.Endian;
import com.threerings.util.Log;
import com.threerings.io.FrameAvailableEvent;
import com.threerings.io.FrameReader;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.presents.data.AuthCodes;
import com.threerings.presents.net.AuthRequest;
import com.threerings.presents.net.AuthResponse;
import com.threerings.presents.net.AuthResponseData;
import com.threerings.presents.net.DownstreamMessage;
import com.threerings.presents.net.LogoffRequest;
import com.threerings.presents.net.UpstreamMessage;
public class Communicator
{
public function Communicator (client :Client)
{
_client = client;
}
public function logon () :void
{
// create our input/output business
_outBuffer = new ByteArray();
_outBuffer.endian = Endian.BIG_ENDIAN;
_outStream = new ObjectOutputStream(_outBuffer);
_inStream = new ObjectInputStream();
_portIdx = 0;
logonToPort();
}
/**
* This method is strangely named, and it does two things which is
* bad style. Either log on to the next port, or save that the port
* we just logged on to was a good one.
*/
protected function logonToPort (logonWasSuccessful :Boolean = false) :Boolean
{
var ports :Array = _client.getPorts();
if (!logonWasSuccessful) {
if (_portIdx >= ports.length) {
return false;
}
if (_portIdx != 0) {
_client.reportLogonTribulations(
new LogonError(AuthCodes.TRYING_NEXT_PORT, true));
removeListeners();
}
// create the socket and set up listeners
_socket = new Socket();
_socket.endian = Endian.BIG_ENDIAN;
_socket.addEventListener(Event.CONNECT, socketOpened);
_socket.addEventListener(IOErrorEvent.IO_ERROR, socketError);
_socket.addEventListener(Event.CLOSE, socketClosed);
_frameReader = new FrameReader(_socket);
_frameReader.addEventListener(FrameAvailableEvent.FRAME_AVAILABLE,
inputFrameReceived);
}
var host :String = _client.getHostname();
var pportKey :String = host + ".preferred_port";
var pport :int = ports[0];
var ppidx :int = Math.max(0, ports.indexOf(pport));
var port :int = (ports[(_portIdx + ppidx) % ports.length] as int);
if (logonWasSuccessful) {
_portIdx = -1; // indicate that we're no longer trying new ports
} else {
Log.getLog(this).info(
"Connecting [host=" + host + ", port=" + port + "].");
_socket.connect(host, port);
}
return true;
}
protected function removeListeners () :void
{
_socket.removeEventListener(Event.CONNECT, socketOpened);
_socket.removeEventListener(IOErrorEvent.IO_ERROR, socketError);
_socket.removeEventListener(Event.CLOSE, socketClosed);
_frameReader.removeEventListener(FrameAvailableEvent.FRAME_AVAILABLE,
inputFrameReceived);
}
public function logoff () :void
{
if (_socket == null) {
return;
}
sendMessage(new LogoffRequest());
shutdown(null);
}
public function postMessage (msg :UpstreamMessage) :void
{
sendMessage(msg); // send it now: we have no out queue
}
protected function shutdown (logonError :Error) :void
{
if (_socket != null) {
try {
_socket.close();
} catch (err :Error) {
Log.getLog(this).warning("Error closing failed socket [error=" + err + "].");
}
removeListeners();
_socket = null;
_outStream = null;
_inStream = null;
_frameReader = null;
_outBuffer = null;
}
_client.notifyObservers(ClientEvent.CLIENT_DID_LOGOFF, null);
_client.cleanup(logonError);
}
protected function sendMessage (msg :UpstreamMessage) :void
{
if (_outStream == null) {
Log.getLog(this).warning("No socket, dropping msg [msg=" + msg + "].");
return;
}
// write the message (ends up in _outBuffer)
_outStream.writeObject(msg);
// Log.debug("outBuffer: " + StringUtil.unhexlate(_outBuffer));
// Frame it by writing the length, then the bytes.
// We add 4 to the length, because the length is of the entire frame
// including the 4 bytes used to encode the length!
_socket.writeInt(_outBuffer.length + 4);
_socket.writeBytes(_outBuffer);
_socket.flush();
// clean up the output buffer
_outBuffer.length = 0;
_outBuffer.position = 0;
// make a note of our most recent write time
updateWriteStamp();
}
/**
* Returns the time at which we last sent a packet to the server.
*/
internal function getLastWrite () :uint
{
return _lastWrite;
}
/**
* Makes a note of the time at which we last communicated with the server.
*/
internal function updateWriteStamp () :void
{
_lastWrite = flash.utils.getTimer();
}
/**
* Called when a frame of data from the server is ready to be
* decoded into a DownstreamMessage.
*/
protected function inputFrameReceived (event :FrameAvailableEvent) :void
{
// convert the frame data into a message from the server
var frameData :ByteArray = event.getFrameData();
//Log.debug("length of in frame: " + frameData.length);
//Log.debug("inBuffer: " + StringUtil.unhexlate(frameData));
_inStream.setSource(frameData);
var msg :DownstreamMessage;
try {
msg = (_inStream.readObject() as DownstreamMessage);
} catch (e :Error) {
var log :Log = Log.getLog(this);
log.warning("Error processing downstream message: " + e);
log.logStackTrace(e);
return;
}
if (frameData.bytesAvailable > 0) {
Log.getLog(this).warning(
"Beans! We didn't fully read a frame, surely there's " +
"a bug in some streaming code. " +
"[bytesLeftOver=" + frameData.bytesAvailable + "].");
}
if (_omgr != null) {
// if we're logged on, then just do the normal thing
_omgr.processMessage(msg);
return;
}
// Otherwise, this would be the AuthResponse to our logon attempt.
var rsp :AuthResponse = (msg as AuthResponse);
var data :AuthResponseData = rsp.getData();
if (data.code !== AuthResponseData.SUCCESS) {
shutdown(new Error(data.code));
return;
}
// logon success
_omgr = new ClientDObjectMgr(this, _client);
_client.setAuthResponseData(data);
}
/**
* Called when the connection to the server was successfully opened.
*/
protected function socketOpened (event :Event) :void
{
logonToPort(true);
// well that's great! let's logon
var req :AuthRequest = new AuthRequest(
_client.getCredentials(), _client.getVersion(), _client.getBootGroups());
sendMessage(req);
}
/**
* Called when there is an io error with the socket.
*/
protected function socketError (event :IOErrorEvent) :void
{
// if we're trying ports, try the next one.
if (_portIdx != -1) {
_portIdx++;
if (logonToPort()) {
return;
}
}
// total failure
Log.getLog(this).warning("socket error: " + event + ", target=" + event.target);
Log.dumpStack();
shutdown(new Error("socket closed unexpectedly."));
}
/**
* Called when the connection to the server was closed.
*/
protected function socketClosed (event :Event) :void
{
Log.getLog(this).warning("socket was closed: " + event);
_client.notifyObservers(ClientEvent.CLIENT_CONNECTION_FAILED);
logoff();
}
protected var _client :Client;
protected var _omgr :ClientDObjectMgr;
protected var _outBuffer :ByteArray;
protected var _outStream :ObjectOutputStream;
protected var _inStream :ObjectInputStream;
protected var _frameReader :FrameReader;
protected var _socket :Socket;
protected var _lastWrite :uint;
/** The current port we'll try to connect to. */
protected var _portIdx :int = -1;
}
}
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.presents.client {
import flash.errors.IOError;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
import flash.utils.Endian;
import com.threerings.util.Log;
import com.threerings.io.FrameAvailableEvent;
import com.threerings.io.FrameReader;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.presents.data.AuthCodes;
import com.threerings.presents.net.AuthRequest;
import com.threerings.presents.net.AuthResponse;
import com.threerings.presents.net.AuthResponseData;
import com.threerings.presents.net.DownstreamMessage;
import com.threerings.presents.net.LogoffRequest;
import com.threerings.presents.net.UpstreamMessage;
public class Communicator
{
public function Communicator (client :Client)
{
_client = client;
}
public function logon () :void
{
// create our input/output business
_outBuffer = new ByteArray();
_outBuffer.endian = Endian.BIG_ENDIAN;
_outStream = new ObjectOutputStream(_outBuffer);
_inStream = new ObjectInputStream();
_portIdx = 0;
logonToPort();
}
/**
* This method is strangely named, and it does two things which is
* bad style. Either log on to the next port, or save that the port
* we just logged on to was a good one.
*/
protected function logonToPort (logonWasSuccessful :Boolean = false) :Boolean
{
var ports :Array = _client.getPorts();
if (!logonWasSuccessful) {
if (_portIdx >= ports.length) {
return false;
}
if (_portIdx != 0) {
_client.reportLogonTribulations(
new LogonError(AuthCodes.TRYING_NEXT_PORT, true));
removeListeners();
}
// create the socket and set up listeners
_socket = new Socket();
_socket.endian = Endian.BIG_ENDIAN;
_socket.addEventListener(Event.CONNECT, socketOpened);
_socket.addEventListener(IOErrorEvent.IO_ERROR, socketError);
_socket.addEventListener(Event.CLOSE, socketClosed);
_frameReader = new FrameReader(_socket);
_frameReader.addEventListener(FrameAvailableEvent.FRAME_AVAILABLE,
inputFrameReceived);
}
var host :String = _client.getHostname();
var pportKey :String = host + ".preferred_port";
var pport :int = ports[0];
var ppidx :int = Math.max(0, ports.indexOf(pport));
var port :int = (ports[(_portIdx + ppidx) % ports.length] as int);
if (logonWasSuccessful) {
_portIdx = -1; // indicate that we're no longer trying new ports
} else {
Log.getLog(this).info(
"Connecting [host=" + host + ", port=" + port + "].");
_socket.connect(host, port);
}
return true;
}
protected function removeListeners () :void
{
_socket.removeEventListener(Event.CONNECT, socketOpened);
_socket.removeEventListener(IOErrorEvent.IO_ERROR, socketError);
_socket.removeEventListener(Event.CLOSE, socketClosed);
_frameReader.removeEventListener(FrameAvailableEvent.FRAME_AVAILABLE,
inputFrameReceived);
}
public function logoff () :void
{
if (_socket == null) {
return;
}
sendMessage(new LogoffRequest());
shutdown(null);
}
public function postMessage (msg :UpstreamMessage) :void
{
sendMessage(msg); // send it now: we have no out queue
}
protected function shutdown (logonError :Error) :void
{
if (_socket != null) {
try {
_socket.close();
} catch (err :Error) {
Log.getLog(this).warning("Error closing failed socket [error=" + err + "].");
}
removeListeners();
_socket = null;
_outStream = null;
_inStream = null;
_frameReader = null;
_outBuffer = null;
}
_client.notifyObservers(ClientEvent.CLIENT_DID_LOGOFF, null);
_client.cleanup(logonError);
}
protected function sendMessage (msg :UpstreamMessage) :void
{
if (_outStream == null) {
Log.getLog(this).warning("No socket, dropping msg [msg=" + msg + "].");
return;
}
// write the message (ends up in _outBuffer)
_outStream.writeObject(msg);
// Log.debug("outBuffer: " + StringUtil.unhexlate(_outBuffer));
// Frame it by writing the length, then the bytes.
// We add 4 to the length, because the length is of the entire frame
// including the 4 bytes used to encode the length!
_socket.writeInt(_outBuffer.length + 4);
_socket.writeBytes(_outBuffer);
_socket.flush();
// clean up the output buffer
_outBuffer.length = 0;
_outBuffer.position = 0;
// make a note of our most recent write time
updateWriteStamp();
}
/**
* Returns the time at which we last sent a packet to the server.
*/
internal function getLastWrite () :uint
{
return _lastWrite;
}
/**
* Makes a note of the time at which we last communicated with the server.
*/
internal function updateWriteStamp () :void
{
_lastWrite = flash.utils.getTimer();
}
/**
* Called when a frame of data from the server is ready to be
* decoded into a DownstreamMessage.
*/
protected function inputFrameReceived (event :FrameAvailableEvent) :void
{
// convert the frame data into a message from the server
var frameData :ByteArray = event.getFrameData();
//Log.debug("length of in frame: " + frameData.length);
//Log.debug("inBuffer: " + StringUtil.unhexlate(frameData));
_inStream.setSource(frameData);
var msg :DownstreamMessage;
try {
msg = (_inStream.readObject() as DownstreamMessage);
} catch (e :Error) {
var log :Log = Log.getLog(this);
log.warning("Error processing downstream message: " + e);
log.logStackTrace(e);
return;
}
if (frameData.bytesAvailable > 0) {
Log.getLog(this).warning(
"Beans! We didn't fully read a frame, surely there's " +
"a bug in some streaming code. " +
"[bytesLeftOver=" + frameData.bytesAvailable + ", msg=" + msg + "].");
}
if (_omgr != null) {
// if we're logged on, then just do the normal thing
_omgr.processMessage(msg);
return;
}
// Otherwise, this would be the AuthResponse to our logon attempt.
var rsp :AuthResponse = (msg as AuthResponse);
var data :AuthResponseData = rsp.getData();
if (data.code !== AuthResponseData.SUCCESS) {
shutdown(new Error(data.code));
return;
}
// logon success
_omgr = new ClientDObjectMgr(this, _client);
_client.setAuthResponseData(data);
}
/**
* Called when the connection to the server was successfully opened.
*/
protected function socketOpened (event :Event) :void
{
logonToPort(true);
// well that's great! let's logon
var req :AuthRequest = new AuthRequest(
_client.getCredentials(), _client.getVersion(), _client.getBootGroups());
sendMessage(req);
}
/**
* Called when there is an io error with the socket.
*/
protected function socketError (event :IOErrorEvent) :void
{
// if we're trying ports, try the next one.
if (_portIdx != -1) {
_portIdx++;
if (logonToPort()) {
return;
}
}
// total failure
Log.getLog(this).warning("socket error: " + event + ", target=" + event.target);
Log.dumpStack();
shutdown(new Error("socket closed unexpectedly."));
}
/**
* Called when the connection to the server was closed.
*/
protected function socketClosed (event :Event) :void
{
Log.getLog(this).warning("socket was closed: " + event);
_client.notifyObservers(ClientEvent.CLIENT_CONNECTION_FAILED);
logoff();
}
protected var _client :Client;
protected var _omgr :ClientDObjectMgr;
protected var _outBuffer :ByteArray;
protected var _outStream :ObjectOutputStream;
protected var _inStream :ObjectInputStream;
protected var _frameReader :FrameReader;
protected var _socket :Socket;
protected var _lastWrite :uint;
/** The current port we'll try to connect to. */
protected var _portIdx :int = -1;
}
}
|
Include the offending message when reporting a short frame
|
Include the offending message when reporting a short frame
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5328 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
dd0962a3756b506a297989ad60fdbca200ac10bb
|
src/aerys/minko/render/material/sprite/SpriteShader.as
|
src/aerys/minko/render/material/sprite/SpriteShader.as
|
package aerys.minko.render.material.sprite
{
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.ShaderSettings;
import aerys.minko.render.shader.part.DiffuseShaderPart;
import aerys.minko.type.enum.Blending;
import aerys.minko.type.enum.DepthTest;
import aerys.minko.type.enum.SamplerFiltering;
import aerys.minko.type.enum.SamplerMipMapping;
import aerys.minko.type.enum.SamplerWrapping;
public class SpriteShader extends Shader
{
private var _uv : SFloat = null;
public function SpriteShader()
{
super();
}
override protected function initializeSettings(settings : ShaderSettings) : void
{
settings.blending = Blending.ALPHA;
settings.depthTest = DepthTest.LESS;
}
override protected function getVertexPosition() : SFloat
{
var vertexXY : SFloat = vertexXY.xy;
_uv = multiply(add(vertexXY, 0.5), float2(1, -1));
var depth : SFloat = meshBindings.getParameter('depth', 1);
var xy : SFloat = float2(
meshBindings.getParameter('x', 1),
meshBindings.getParameter('y', 1)
);
var size : SFloat = float2(
meshBindings.getParameter('width', 1),
meshBindings.getParameter('height', 1)
);
var vpSize : SFloat = float2(
sceneBindings.getParameter('viewportWidth', 1),
sceneBindings.getParameter('viewportHeight', 1)
);
xy = divide(add(xy, divide(size, 2)), vpSize);
xy = multiply(subtract(xy, 0.5), float2(2, -2));
vertexXY.scaleBy(divide(size, divide(vpSize, 2)));
vertexXY.incrementBy(xy);
return float4(vertexXY, depth, 1);
}
override protected function getPixelColor() : SFloat
{
var diffuseMap : SFloat = meshBindings.getTextureParameter(
'diffuseMap',
meshBindings.getConstant("diffuseFiltering", SamplerFiltering.LINEAR),
meshBindings.getConstant("diffuseMipMapping", SamplerMipMapping.LINEAR),
meshBindings.getConstant("diffuseWrapping", SamplerWrapping.REPEAT)
);
return sampleTexture(diffuseMap, interpolate(_uv));
}
}
}
|
package aerys.minko.render.material.sprite
{
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.ShaderSettings;
import aerys.minko.render.shader.part.DiffuseShaderPart;
import aerys.minko.type.enum.Blending;
import aerys.minko.type.enum.DepthTest;
import aerys.minko.type.enum.SamplerFiltering;
import aerys.minko.type.enum.SamplerMipMapping;
import aerys.minko.type.enum.SamplerWrapping;
public class SpriteShader extends Shader
{
private var _diffuse : DiffuseShaderPart;
private var _uv : SFloat;
public function SpriteShader()
{
super();
_diffuse = new DiffuseShaderPart(this);
}
override protected function initializeSettings(settings : ShaderSettings) : void
{
// settings.blending = Blending.ALPHA;
settings.depthTest = DepthTest.LESS;
}
override protected function getVertexPosition() : SFloat
{
var vertexXY : SFloat = vertexXY.xy;
_uv = multiply(add(vertexXY, 0.5), float2(1, -1));
var depth : SFloat = meshBindings.getParameter('depth', 1);
var xy : SFloat = float2(
meshBindings.getParameter('x', 1),
meshBindings.getParameter('y', 1)
);
var size : SFloat = float2(
meshBindings.getParameter('width', 1),
meshBindings.getParameter('height', 1)
);
var vpSize : SFloat = float2(
sceneBindings.getParameter('viewportWidth', 1),
sceneBindings.getParameter('viewportHeight', 1)
);
xy = divide(add(xy, divide(size, 2)), vpSize);
xy = multiply(subtract(xy, 0.5), float2(2, -2));
vertexXY.scaleBy(divide(size, divide(vpSize, 2)));
vertexXY.incrementBy(xy);
return float4(vertexXY, depth, 1);
}
override protected function getPixelColor() : SFloat
{
return _diffuse.getDiffuseColor(true, _uv);
}
}
}
|
update SpriteShader to use DiffuseShaderPart.getDiffuseColor() with the new 'uv' optional argument
|
update SpriteShader to use DiffuseShaderPart.getDiffuseColor() with the new 'uv' optional argument
|
ActionScript
|
mit
|
aerys/minko-as3
|
2406327d42e54d1e1f410f1b74e841062d912b5c
|
src/com/pivotshare/hls/loader/FragmentDemuxedStream.as
|
src/com/pivotshare/hls/loader/FragmentDemuxedStream.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 com.pivotshare.hls.loader {
import flash.display.DisplayObject;
import flash.events.*;
import flash.net.*;
import flash.utils.ByteArray;
import flash.utils.getTimer;
import flash.utils.Timer;
import com.pivotshare.hls.loader.FragmentStream;
import org.mangui.hls.constant.HLSLoaderTypes;
import org.mangui.hls.demux.Demuxer;
import org.mangui.hls.demux.DemuxHelper;
import org.mangui.hls.demux.ID3Tag;
import org.mangui.hls.event.HLSError;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.event.HLSLoadMetrics;
import org.mangui.hls.flv.FLVTag;
import org.mangui.hls.HLS;
import org.mangui.hls.model.AudioTrack;
import org.mangui.hls.model.Fragment;
import org.mangui.hls.model.FragmentData;
import org.mangui.hls.utils.AES;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
import org.mangui.hls.utils.Hex;
}
/**
* HLS Fragment Demuxed Streamer.
* Tries to parallel URLStream design pattern, but is incomplete.
*
* This class encapsulates Demuxing, but in an inefficient way. This is not
* meant to be performant for sequential Fragments in play.
*
* @class FragmentDemuxedStream
* @extends EventDispatcher
* @author HGPA
*/
public class FragmentDemuxedStream extends EventDispatcher {
/*
* DisplayObject needed by AES decrypter.
*/
private var _displayObject : DisplayObject;
/*
* Fragment being loaded.
*/
private var _fragment : Fragment;
/*
* URLStream used to download current Fragment.
*/
private var _fragmentStream : FragmentStream;
/*
* Metrics for this stream.
*/
private var _metrics : HLSLoadMetrics;
/*
* Demuxer needed for this Fragment.
*/
private var _demux : Demuxer;
/*
* Options for streaming and demuxing.
*/
private var _options : Object;
//
//
//
// Public Methods
//
//
//
/**
* Create a FragmentStream.
*
* This constructor takes a reference to main DisplayObject, e.g. stage,
* necessary for AES decryption control.
*
* TODO: It would be more appropriate to create a factory that itself
* takes the DisplayObject (or a more flexible version of AES).
*
* @constructor
* @param {DisplayObject} displayObject
*/
public function FragmentDemuxedStream(displayObject : DisplayObject) : void {
_displayObject = displayObject;
_fragment = null;
_fragmentStream = null;
_metrics = null;
_demux = null;
_options = new Object();
};
/*
* Return FragmentData of Fragment currently being downloaded.
* Of immediate interest is the `bytes` field.
*
* @method getFragment
* @return {Fragment}
*/
public function getFragment() : Fragment {
return _fragment;
}
/*
* Close the stream.
*
* @method close
*/
public function close() : void {
if (_fragmentStream) {
_fragmentStream.close();
}
if (_demux) {
_demux.cancel();
_demux = null;
}
}
/**
* Load a Fragment.
*
* This class/methods DOES NOT user reference of parameter. Instead it
* clones the Fragment and manipulates this internally.
*
* @method load
* @param {Fragment} fragment - Fragment with details (cloned)
* @param {ByteArray} key - Encryption Key
* @return {HLSLoadMetrics}
*/
public function load(fragment : Fragment, key : ByteArray, options : Object) : HLSLoadMetrics {
_options = options;
// Clone Fragment, with new initilizations of deep fields
// Passing around references is what is causing problems.
// FragmentData is initialized as part of construction
_fragment = new Fragment(
fragment.url,
fragment.duration,
fragment.level,
fragment.seqnum,
fragment.start_time,
fragment.continuity,
fragment.program_date,
fragment.decrypt_url,
fragment.decrypt_iv, // We need this reference
fragment.byterange_start_offset,
fragment.byterange_end_offset,
new Vector.<String>()
)
_fragmentStream = new FragmentStream(_displayObject);
_fragmentStream.addEventListener(IOErrorEvent.IO_ERROR, onStreamError);
_fragmentStream.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onStreamError);
_fragmentStream.addEventListener(ProgressEvent.PROGRESS, onStreamProgress);
_fragmentStream.addEventListener(Event.COMPLETE, onStreamComplete);
CONFIG::LOGGING {
var fragmentString : String = "Fragment[" + _fragment.level + "][" + _fragment.seqnum + "]";
Log.debug("FragmentDemuxedStream#load: " + fragmentString);
}
_metrics = _fragmentStream.load(_fragment, key);
return _metrics;
}
//
//
//
// FragmentStream Event Listeners
//
//
//
/**
*
* @method onFragmentStreamProgress
* @param {ProgressEvent} evt
*/
private function onStreamProgress(evt : ProgressEvent) : void {
_fragment = _fragmentStream.getFragment();
CONFIG::LOGGING {
var fragmentString : String = "Fragment[" + _fragment.level + "][" + _fragment.seqnum + "]";
Log.debug("FragmentDemuxedStream#onStreamProgress: " +
fragmentString + " Progress - " + evt.bytesLoaded + " of " + evt.bytesTotal);
Log.debug("FragmentDemuxedStream#onStreamProgress: " +
fragmentString + " Fragment status - bytes.position / bytes.length / bytesLoaded " +
_fragment.data.bytes.position + " / " +
_fragment.data.bytes.length + " / " +
_fragment.data.bytesLoaded);
}
// If we are loading a partial Fragment then only parse when it has
// completed loading to desired portion (See onFragmentStreamComplete)
/*
if (fragment.byterange_start_offset != -1) {
return;
}
*/
// START PARSING METRICS
if (_metrics.parsing_begin_time == 0) {
_metrics.parsing_begin_time = getTimer();
}
// Demuxer has not yet been initialized as this is probably first
// call to onFragmentStreamProgress, but demuxer may also be/remain
// null due to unknown Fragment type. Probe is synchronous.
if (_demux == null) {
// It is possible we have run onFragmentStreamProgress before
// without having sufficient data to probe
//bytes.position = bytes.length;
//bytes.writeBytes(byteArray);
//byteArray = bytes;
CONFIG::LOGGING {
var fragmentString : String = "Fragment[" + _fragment.level + "][" + _fragment.seqnum + "]";
Log.debug("FragmentDemuxedStream#onStreamProgress: Need a Demuxer for " + fragmentString);
}
_demux = DemuxHelper.probe(
_fragment.data.bytes,
null,
_onDemuxAudioTrackRequested,
_onDemuxProgress,
_onDemuxComplete,
_onDemuxVideoMetadata,
_onDemuxID3TagFound,
false
);
}
if (_demux) {
// Demuxer expects the ByteArray delta
var byteArray : ByteArray = new ByteArray();
_fragment.data.bytes.readBytes(byteArray, 0, _fragment.data.bytes.length - _fragment.data.bytes.position);
byteArray.position = 0;
_demux.append(byteArray);
}
}
/**
* Called when FragmentStream completes.
*
* @method onStreamComplete
* @param {Event} evt
*/
private function onStreamComplete(evt : Event) : void {
// If demuxer is still null, then the Fragment type was invalid
if (_demux == null) {
CONFIG::LOGGING {
Log.error("FragmentDemuxedStream#onStreamComplete: unknown fragment type");
_fragment.data.bytes.position = 0;
var bytes2 : ByteArray = new ByteArray();
_fragment.data.bytes.readBytes(bytes2, 0, 512);
Log.debug2("FragmentDemuxedStream#onStreamComplete: frag dump(512 bytes)");
Log.debug2(Hex.fromArray(bytes2));
}
var err : ErrorEvent = new ErrorEvent(
ErrorEvent.ERROR,
false,
false,
"Unknown Fragment Type"
);
dispatchEvent(err);
} else {
_demux.notifycomplete();
}
}
/**
* Called when FragmentStream has errored.
*
* @method onStreamError
* @param {ProgressEvent} evt
*/
private function onStreamError(evt : ErrorEvent) : void {
CONFIG::LOGGING {
Log.error("FragmentDemuxedStream#onStreamError: " + evt.text);
}
dispatchEvent(evt);
}
//
//
//
// Demuxer Callbacks
//
//
//
/**
* Called when Demuxer needs to know which AudioTrack to parse for.
*
* FIXME: This callback simply returns the first audio track!
* We need to pass this class the appropriate callback propogated from
* UI layer. Yuck.
*
* @method _onDemuxAudioTrackRequested
* @param {Vector<AudioTrack} audioTrackList - List of AudioTracks
* @return {AudioTrack} - AudioTrack to parse
*/
private function _onDemuxAudioTrackRequested(audioTrackList : Vector.<AudioTrack>) : AudioTrack {
if (audioTrackList.length > 0) {
return audioTrackList[0];
} else {
return null;
}
}
/**
* Called when Demuxer parsed portion of Fragment.
*
* @method _onDemuxProgress
* @param {Vector<FLVTag} tags
*/
private function _onDemuxProgress(tags : Vector.<FLVTag>) : void {
CONFIG::LOGGING {
Log.debug("FragmentDemuxedStream#_onDemuxProgress");
}
_fragment.data.appendTags(tags);
// TODO: Options to parse only portion of Fragment
// FIXME: bytesLoaded and bytesTotal represent stats of the current
// FragmentStream, not Demuxer, which is no longer bytes-relative.
// What should we define here?
var progressEvent : ProgressEvent = new ProgressEvent(
ProgressEvent.PROGRESS,
false,
false,
_fragment.data.bytes.length, // bytesLoaded
_fragment.data.bytesTotal // bytesTotal
);
dispatchEvent(progressEvent);
};
/**
* Called when Demuxer has finished parsing Fragment.
*
* @method _onDemuxComplete
*/
private function _onDemuxComplete() : void {
CONFIG::LOGGING {
Log.debug("FragmentDemuxedStream#_onDemuxComplete");
}
_metrics.parsing_end_time = getTimer();
var completeEvent : Event = new ProgressEvent(Event.COMPLETE);
dispatchEvent(completeEvent);
};
/**
* Called when Video metadata is parsed.
*
* Specifically, when Sequence Parameter Set (SPS) is found.
*
* @method _onDemuxVideoMetadata
* @param {uint} width
* @param {uint} height
*/
private function _onDemuxVideoMetadata(width : uint, height : uint) : void {
if (_fragment.data.video_width == 0) {
CONFIG::LOGGING {
Log.debug("FragmentDemuxedStream#_onDemuxVideoMetadata: AVC SPS = " + width + "x" + height);
}
_fragment.data.video_width = width;
_fragment.data.video_height = height;
}
}
/**
* Called when ID3 tags are found.
*
* @method _onDemuxID3TagFound
* @param {Vector.<ID3Tag>} id3_tags - ID3 Tags
*/
private function _onDemuxID3TagFound(id3_tags : Vector.<ID3Tag>) : void {
_fragment.data.id3_tags = id3_tags;
}
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package com.pivotshare.hls.loader {
import flash.display.DisplayObject;
import flash.events.*;
import flash.net.*;
import flash.utils.ByteArray;
import flash.utils.getTimer;
import flash.utils.Timer;
import com.pivotshare.hls.loader.FragmentStream;
import org.mangui.hls.constant.HLSLoaderTypes;
import org.mangui.hls.demux.Demuxer;
import org.mangui.hls.demux.DemuxHelper;
import org.mangui.hls.demux.ID3Tag;
import org.mangui.hls.event.HLSError;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.event.HLSLoadMetrics;
import org.mangui.hls.flv.FLVTag;
import org.mangui.hls.HLS;
import org.mangui.hls.model.AudioTrack;
import org.mangui.hls.model.Fragment;
import org.mangui.hls.model.FragmentData;
import org.mangui.hls.utils.AES;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
import org.mangui.hls.utils.Hex;
}
/**
* HLS Fragment Demuxed Streamer.
* Tries to parallel URLStream design pattern, but is incomplete.
*
* This class encapsulates Demuxing, but in an inefficient way. This is not
* meant to be performant for sequential Fragments in play.
*
* @class FragmentDemuxedStream
* @extends EventDispatcher
* @author HGPA
*/
public class FragmentDemuxedStream extends EventDispatcher {
/*
* DisplayObject needed by AES decrypter.
*/
private var _displayObject : DisplayObject;
/*
* Fragment being loaded.
*/
private var _fragment : Fragment;
/*
* URLStream used to download current Fragment.
*/
private var _fragmentStream : FragmentStream;
/*
* Metrics for this stream.
*/
private var _metrics : HLSLoadMetrics;
/*
* Demuxer needed for this Fragment.
*/
private var _demux : Demuxer;
/*
* Options for streaming and demuxing.
*/
private var _options : Object;
//
//
//
// Public Methods
//
//
//
/**
* Create a FragmentStream.
*
* This constructor takes a reference to main DisplayObject, e.g. stage,
* necessary for AES decryption control.
*
* TODO: It would be more appropriate to create a factory that itself
* takes the DisplayObject (or a more flexible version of AES).
*
* @constructor
* @param {DisplayObject} displayObject
*/
public function FragmentDemuxedStream(displayObject : DisplayObject) : void {
_displayObject = displayObject;
_fragment = null;
_fragmentStream = null;
_metrics = null;
_demux = null;
_options = new Object();
};
/*
* Return FragmentData of Fragment currently being downloaded.
* Of immediate interest is the `bytes` field.
*
* @method getFragment
* @return {Fragment}
*/
public function getFragment() : Fragment {
return _fragment;
}
/*
* Close the stream.
*
* @method close
*/
public function close() : void {
if (_fragmentStream) {
_fragmentStream.close();
}
if (_demux) {
_demux.cancel();
_demux = null;
}
}
/**
* Load a Fragment.
*
* This class/methods DOES NOT user reference of parameter. Instead it
* clones the Fragment and manipulates this internally.
*
* @method load
* @param {Fragment} fragment - Fragment with details (cloned)
* @param {ByteArray} key - Encryption Key
* @return {HLSLoadMetrics}
*/
public function load(fragment : Fragment, key : ByteArray, options : Object) : HLSLoadMetrics {
_options = options;
// Clone Fragment, with new initilizations of deep fields
// Passing around references is what is causing problems.
// FragmentData is initialized as part of construction
_fragment = new Fragment(
fragment.url,
fragment.duration,
fragment.level,
fragment.seqnum,
fragment.start_time,
fragment.continuity,
fragment.program_date,
fragment.decrypt_url,
fragment.decrypt_iv, // We need this reference
fragment.byterange_start_offset,
fragment.byterange_end_offset,
new Vector.<String>()
)
_fragmentStream = new FragmentStream(_displayObject);
_fragmentStream.addEventListener(IOErrorEvent.IO_ERROR, onStreamError);
_fragmentStream.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onStreamError);
_fragmentStream.addEventListener(ProgressEvent.PROGRESS, onStreamProgress);
_fragmentStream.addEventListener(Event.COMPLETE, onStreamComplete);
CONFIG::LOGGING {
var fragmentString : String = "Fragment[" + _fragment.level + "][" + _fragment.seqnum + "]";
Log.debug("FragmentDemuxedStream#load: " + fragmentString);
}
_metrics = _fragmentStream.load(_fragment, key);
return _metrics;
}
//
//
//
// FragmentStream Event Listeners
//
//
//
/**
*
* @method onFragmentStreamProgress
* @param {ProgressEvent} evt
*/
private function onStreamProgress(evt : ProgressEvent) : void {
_fragment = _fragmentStream.getFragment();
CONFIG::LOGGING {
var fragmentString : String = "Fragment[" + _fragment.level + "][" + _fragment.seqnum + "]";
Log.debug2("FragmentDemuxedStream#onStreamProgress: " +
fragmentString + " Progress - " + evt.bytesLoaded + " of " + evt.bytesTotal);
Log.debug2("FragmentDemuxedStream#onStreamProgress: " +
fragmentString + " Fragment status - bytes.position / bytes.length / bytesLoaded " +
_fragment.data.bytes.position + " / " +
_fragment.data.bytes.length + " / " +
_fragment.data.bytesLoaded);
}
// If we are loading a partial Fragment then only parse when it has
// completed loading to desired portion (See onFragmentStreamComplete)
/*
if (fragment.byterange_start_offset != -1) {
return;
}
*/
// START PARSING METRICS
if (_metrics.parsing_begin_time == 0) {
_metrics.parsing_begin_time = getTimer();
}
// Demuxer has not yet been initialized as this is probably first
// call to onFragmentStreamProgress, but demuxer may also be/remain
// null due to unknown Fragment type. Probe is synchronous.
if (_demux == null) {
// It is possible we have run onFragmentStreamProgress before
// without having sufficient data to probe
//bytes.position = bytes.length;
//bytes.writeBytes(byteArray);
//byteArray = bytes;
CONFIG::LOGGING {
var fragmentString : String = "Fragment[" + _fragment.level + "][" + _fragment.seqnum + "]";
Log.debug2("FragmentDemuxedStream#onStreamProgress: Need a Demuxer for " + fragmentString);
}
_demux = DemuxHelper.probe(
_fragment.data.bytes,
null,
_onDemuxAudioTrackRequested,
_onDemuxProgress,
_onDemuxComplete,
_onDemuxVideoMetadata,
_onDemuxID3TagFound,
false
);
}
if (_demux) {
// Demuxer expects the ByteArray delta
var byteArray : ByteArray = new ByteArray();
_fragment.data.bytes.readBytes(byteArray, 0, _fragment.data.bytes.length - _fragment.data.bytes.position);
byteArray.position = 0;
_demux.append(byteArray);
}
}
/**
* Called when FragmentStream completes.
*
* @method onStreamComplete
* @param {Event} evt
*/
private function onStreamComplete(evt : Event) : void {
// If demuxer is still null, then the Fragment type was invalid
if (_demux == null) {
CONFIG::LOGGING {
Log.error("FragmentDemuxedStream#onStreamComplete: unknown fragment type");
_fragment.data.bytes.position = 0;
var bytes2 : ByteArray = new ByteArray();
_fragment.data.bytes.readBytes(bytes2, 0, 512);
Log.debug2("FragmentDemuxedStream#onStreamComplete: frag dump(512 bytes)");
Log.debug2(Hex.fromArray(bytes2));
}
var err : ErrorEvent = new ErrorEvent(
ErrorEvent.ERROR,
false,
false,
"Unknown Fragment Type"
);
dispatchEvent(err);
} else {
_demux.notifycomplete();
}
}
/**
* Called when FragmentStream has errored.
*
* @method onStreamError
* @param {ProgressEvent} evt
*/
private function onStreamError(evt : ErrorEvent) : void {
CONFIG::LOGGING {
Log.error("FragmentDemuxedStream#onStreamError: " + evt.text);
}
dispatchEvent(evt);
}
//
//
//
// Demuxer Callbacks
//
//
//
/**
* Called when Demuxer needs to know which AudioTrack to parse for.
*
* FIXME: This callback simply returns the first audio track!
* We need to pass this class the appropriate callback propogated from
* UI layer. Yuck.
*
* @method _onDemuxAudioTrackRequested
* @param {Vector<AudioTrack} audioTrackList - List of AudioTracks
* @return {AudioTrack} - AudioTrack to parse
*/
private function _onDemuxAudioTrackRequested(audioTrackList : Vector.<AudioTrack>) : AudioTrack {
if (audioTrackList.length > 0) {
return audioTrackList[0];
} else {
return null;
}
}
/**
* Called when Demuxer parsed portion of Fragment.
*
* @method _onDemuxProgress
* @param {Vector<FLVTag} tags
*/
private function _onDemuxProgress(tags : Vector.<FLVTag>) : void {
CONFIG::LOGGING {
Log.debug2("FragmentDemuxedStream#_onDemuxProgress");
}
_fragment.data.appendTags(tags);
// TODO: Options to parse only portion of Fragment
// FIXME: bytesLoaded and bytesTotal represent stats of the current
// FragmentStream, not Demuxer, which is no longer bytes-relative.
// What should we define here?
var progressEvent : ProgressEvent = new ProgressEvent(
ProgressEvent.PROGRESS,
false,
false,
_fragment.data.bytes.length, // bytesLoaded
_fragment.data.bytesTotal // bytesTotal
);
dispatchEvent(progressEvent);
};
/**
* Called when Demuxer has finished parsing Fragment.
*
* @method _onDemuxComplete
*/
private function _onDemuxComplete() : void {
CONFIG::LOGGING {
Log.debug2("FragmentDemuxedStream#_onDemuxComplete");
}
_metrics.parsing_end_time = getTimer();
var completeEvent : Event = new ProgressEvent(Event.COMPLETE);
dispatchEvent(completeEvent);
};
/**
* Called when Video metadata is parsed.
*
* Specifically, when Sequence Parameter Set (SPS) is found.
*
* @method _onDemuxVideoMetadata
* @param {uint} width
* @param {uint} height
*/
private function _onDemuxVideoMetadata(width : uint, height : uint) : void {
if (_fragment.data.video_width == 0) {
CONFIG::LOGGING {
Log.debug2("FragmentDemuxedStream#_onDemuxVideoMetadata: AVC SPS = " + width + "x" + height);
}
_fragment.data.video_width = width;
_fragment.data.video_height = height;
}
}
/**
* Called when ID3 tags are found.
*
* @method _onDemuxID3TagFound
* @param {Vector.<ID3Tag>} id3_tags - ID3 Tags
*/
private function _onDemuxID3TagFound(id3_tags : Vector.<ID3Tag>) : void {
_fragment.data.id3_tags = id3_tags;
}
}
}
|
Make all logging debug2
|
[FragmentDemuxedStream] Make all logging debug2
|
ActionScript
|
mpl-2.0
|
codex-corp/flashls,codex-corp/flashls
|
f9034f7851b8c485c444d3a7e7fce28cb9d39195
|
src/com/merlinds/miracle_tool/viewer/ViewerView.as
|
src/com/merlinds/miracle_tool/viewer/ViewerView.as
|
/**
* User: MerlinDS
* Date: 18.07.2014
* Time: 17:42
*/
package com.merlinds.miracle_tool.viewer {
import com.bit101.components.List;
import com.bit101.components.Window;
import com.merlinds.debug.log;
import com.merlinds.miracle.Miracle;
import com.merlinds.miracle.animations.AnimationHelper;
import com.merlinds.miracle.display.MiracleAnimation;
import com.merlinds.miracle.display.MiracleDisplayObject;
import com.merlinds.miracle.geom.Color;
import com.merlinds.miracle.utils.Asset;
import com.merlinds.miracle.utils.MafReader;
import com.merlinds.miracle_tool.models.AppModel;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.utils.ByteArray;
import flash.utils.setTimeout;
[SWF(backgroundColor="0x333333", frameRate=60)]
public class ViewerView extends Sprite {
private var _model:AppModel;
private var _assets:Vector.<Asset>;
private var _window:Window;
private var _name:String;
private var _current:MiracleAnimation;
public function ViewerView(model:AppModel = null) {
super();
_model = model;
if(_model == null){
_model = new AppModel();
}
this.addEventListener(Event.ADDED_TO_STAGE, this.initialize);
}
//==============================================================================
//{region PUBLIC METHODS
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
private function initialize(event:Event):void {
this.removeEventListener(event.type, this.initialize);
this.stage.scaleMode = StageScaleMode.NO_SCALE;
this.stage.align = StageAlign.TOP_LEFT;
Miracle.start(this.stage, this.createHandler, true);
}
private function choseAnimation():void {
//find animation asset and add all of animations to chose list
var n:int = _assets.length;
for(var i:int = 0; i < n; i++){
var asset:Asset = _assets[i];
if(asset.type == Asset.TIMELINE_TYPE){
//parse output
_window = new Window(this, 0, 0, "Chose animation");
var list:List = new List(_window, 0, 0, this.getAnimations(asset.output));
_window.x = this.stage.stageWidth - _window.width;
_window.setSize(_window.height, list.height + 20);
list.addEventListener(Event.SELECT, this.selectAnimationHandler);
}
}
var w2:Window = new Window(this, _window.x, _window.y + _window.height + 10, "FPS");
list = new List(w2, 0, 0, [1, 5, 16, 24, 30, 35, 40, 60]);
w2.height = 120;
list.addEventListener(Event.SELECT, this.selectFpsHandler);
}
[Inline]
private function getAnimations(bytes:ByteArray):Array {
var result:Array = [];
var reader:MafReader = new MafReader();
reader.execute(bytes, 1);
var animations:Vector.<AnimationHelper> = reader.animations;
for each(var animation:AnimationHelper in animations){
result.push(animation.name);
}
return result;
}
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
private function createHandler(animation:Boolean = false):void {
//\TODO: Show view if it exit
if(animation || _model.viewerInput == null){
_model.viewerInput = _model.lastFileDirection;
_model.viewerInput.addEventListener(Event.SELECT, this.selectFileHandler);
_model.viewerInput.browseForOpen("Open " + animation ? "Animation" : "Sprite"
+ "file that you want to view");
}
}
private function selectFileHandler(event:Event):void {
_model.viewerInput.removeEventListener(event.type, this.selectFileHandler);
_model.lastFileDirection = _model.viewerInput.parent;
var byteArray:ByteArray = new ByteArray();
var stream:FileStream = new FileStream();
stream.open(_model.viewerInput, FileMode.READ);
stream.readBytes(byteArray);
stream.close();
//parse
if(_assets == null)_assets = new <Asset>[];
var asset:Asset = new Asset(_model.viewerInput.name, byteArray);
if(asset.type == Asset.TIMELINE_TYPE){
_name = asset.name;
}
_assets.push(asset);
if(_assets.length > 1){
this.choseAnimation();
Miracle.createScene(_assets, 1);
Miracle.resume();
}else{
this.createHandler(true);
}
}
private function selectAnimationHandler(event:Event):void {
var list:List = event.target as List;
//add animation to miracle
var animation:String = list.selectedItem.toString();
log(this, "selectAnimationHandler", animation);
var mesh:String = animation.substr(0, animation.lastIndexOf("."));
animation = animation.substr(animation.lastIndexOf(".") + 1);
if(_current == null){
_current = Miracle.currentScene.createAnimation(mesh, animation, 60);
_current.moveTO(this.stage.stageWidth >> 1, this.stage.stageHeight >> 1);
_current.addEventListener(Event.ADDED_TO_STAGE, this.imageAddedToStage);
}else{
_current.mesh = mesh;
_current.animation = animation;
_current.play();
}
}
private function imageAddedToStage(event:Event):void {
trace("Added to stage");
}
private function selectFpsHandler(event:Event):void {
var list:List = event.target as List;
//add animation to miracle
if(_current != null){
_current.fps = int(list.selectedItem);
}
}
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
|
/**
* User: MerlinDS
* Date: 18.07.2014
* Time: 17:42
*/
package com.merlinds.miracle_tool.viewer {
import com.bit101.components.List;
import com.bit101.components.Window;
import com.merlinds.debug.log;
import com.merlinds.miracle.Miracle;
import com.merlinds.miracle.animations.AnimationHelper;
import com.merlinds.miracle.display.MiracleAnimation;
import com.merlinds.miracle.display.MiracleDisplayObject;
import com.merlinds.miracle.geom.Color;
import com.merlinds.miracle.utils.Asset;
import com.merlinds.miracle.utils.MafReader;
import com.merlinds.miracle_tool.models.AppModel;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.utils.ByteArray;
import flash.utils.setTimeout;
[SWF(backgroundColor="0x333333", frameRate=60)]
public class ViewerView extends Sprite {
private var _model:AppModel;
private var _assets:Vector.<Asset>;
private var _window:Window;
private var _name:String;
private var _current:MiracleAnimation;
public function ViewerView(model:AppModel = null) {
super();
_model = model;
if(_model == null){
_model = new AppModel();
}
this.addEventListener(Event.ADDED_TO_STAGE, this.initialize);
}
//==============================================================================
//{region PUBLIC METHODS
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
private function initialize(event:Event):void {
this.removeEventListener(event.type, this.initialize);
this.stage.scaleMode = StageScaleMode.NO_SCALE;
this.stage.align = StageAlign.TOP_LEFT;
Miracle.start(this.stage, this.createHandler, true);
}
private function choseAnimation():void {
//find animation asset and add all of animations to chose list
var n:int = _assets.length;
for(var i:int = 0; i < n; i++){
var asset:Asset = _assets[i];
if(asset.type == Asset.TIMELINE_TYPE){
//parse output
_window = new Window(this, 0, 0, "Chose animation");
var list:List = new List(_window, 0, 0, this.getAnimations(asset.output));
_window.x = this.stage.stageWidth - _window.width;
_window.setSize(_window.height, list.height + 20);
list.addEventListener(Event.SELECT, this.selectAnimationHandler);
}
}
var w2:Window = new Window(this, _window.x, _window.y + _window.height + 10, "FPS");
list = new List(w2, 0, 0, [1, 5, 16, 24, 30, 35, 40, 60]);
w2.height = 120;
list.addEventListener(Event.SELECT, this.selectFpsHandler);
}
[Inline]
private function getAnimations(bytes:ByteArray):Array {
var result:Array = [];
var reader:MafReader = new MafReader();
reader.execute(bytes, 1);
var animations:Vector.<AnimationHelper> = reader.animations;
for each(var animation:AnimationHelper in animations){
result.push(animation.name);
}
return result;
}
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
private function createHandler(animation:Boolean = false):void {
//\TODO: Show view if it exit
if(animation || _model.viewerInput == null){
_model.viewerInput = _model.lastFileDirection;
_model.viewerInput.addEventListener(Event.SELECT, this.selectFileHandler);
_model.viewerInput.browseForOpen("Open " + animation ? "Animation" : "Sprite"
+ "file that you want to view");
}
}
private function selectFileHandler(event:Event):void {
_model.viewerInput.removeEventListener(event.type, this.selectFileHandler);
_model.lastFileDirection = _model.viewerInput.parent;
var byteArray:ByteArray = new ByteArray();
var stream:FileStream = new FileStream();
stream.open(_model.viewerInput, FileMode.READ);
stream.readBytes(byteArray);
stream.close();
//parse
if(_assets == null)_assets = new <Asset>[];
var asset:Asset = new Asset(_model.viewerInput.name, byteArray);
if(asset.type == Asset.TIMELINE_TYPE){
_name = asset.name;
}
_assets.push(asset);
if(_assets.length > 1){
this.choseAnimation();
Miracle.createScene(_assets,null, 1);
Miracle.resume();
}else{
this.createHandler(true);
}
}
private function selectAnimationHandler(event:Event):void {
var list:List = event.target as List;
//add animation to miracle
var animation:String = list.selectedItem.toString();
log(this, "selectAnimationHandler", animation);
var mesh:String = animation.substr(0, animation.lastIndexOf("."));
animation = animation.substr(animation.lastIndexOf(".") + 1);
if(_current == null){
_current = Miracle.currentScene.createAnimation(mesh, animation, 60);
_current.moveTO(this.stage.stageWidth >> 1, this.stage.stageHeight >> 1);
_current.addEventListener(Event.ADDED_TO_STAGE, this.imageAddedToStage);
}else{
_current.mesh = mesh;
_current.animation = animation;
_current.play();
}
}
private function imageAddedToStage(event:Event):void {
trace("Added to stage");
}
private function selectFpsHandler(event:Event):void {
var list:List = event.target as List;
//add animation to miracle
if(_current != null){
_current.fps = int(list.selectedItem);
}
}
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
|
change initialization
|
change initialization
|
ActionScript
|
mit
|
MerlinDS/miracle_tool
|
ee3fc7f1d063431f07718cbda10af7cb12a18b2d
|
src/battlecode/client/viewer/render/DrawRobot.as
|
src/battlecode/client/viewer/render/DrawRobot.as
|
package battlecode.client.viewer.render {
import battlecode.common.ActionType;
import battlecode.common.Direction;
import battlecode.common.MapLocation;
import battlecode.common.RobotType;
import battlecode.common.Team;
import battlecode.events.RobotEvent;
import mx.containers.Canvas;
import mx.controls.Image;
import mx.core.UIComponent;
[Event(name="indicatorStringChange", type="battlecode.events.RobotEvent")]
public class DrawRobot extends Canvas implements DrawObject {
private var actions:Vector.<DrawAction>;
private var broadcastAnimation:BroadcastAnimation;
private var explosionAnimation:ExplosionAnimation;
private var overlayCanvas:UIComponent;
private var imageCanvas:UIComponent;
private var image:Image;
// size
private var overrideSize:Number;
// indicator strings
private var indicatorStrings:Vector.<String> = new Vector.<String>(3, true);
// movement animation
private var drawX:Number, drawY:Number;
private var movementDelay:uint;
// attack animation
private var targetLocation:MapLocation;
private var selected:Boolean = false;
private var robotID:uint;
private var type:String;
private var team:String;
private var location:MapLocation;
private var direction:String;
private var energon:Number = 0;
private var maxEnergon:Number = 0;
private var flux:Number = 0;
private var maxFlux:Number = 0;
private var aura:String;
private var alive:Boolean = true;
public function DrawRobot(robotID:uint, type:String, team:String, overrideSize:Number = 0) {
this.robotID = robotID;
this.type = type;
this.team = team;
this.maxEnergon = RobotType.maxEnergon(type);
this.maxFlux = RobotType.maxFlux(type);
this.actions = new Vector.<DrawAction>();
this.overrideSize = overrideSize;
// set the unit avatar image
var avatarClass:Class = getUnitAvatar(type, team);
this.imageCanvas = new UIComponent();
this.image = new Image();
this.image.source = avatarClass;
this.image.width = getImageSize(true);
this.image.height = getImageSize(true);
this.image.x = -this.image.width / 2;
this.image.y = -this.image.height / 2;
this.imageCanvas.addChild(image);
this.addChild(imageCanvas);
this.width = this.image.width;
this.height = this.image.height;
this.overlayCanvas = new UIComponent();
this.addChild(overlayCanvas);
// set the hit area for click selection
this.hitArea = imageCanvas;
// animations
this.broadcastAnimation = new BroadcastAnimation(0, team);
this.addChild(broadcastAnimation);
this.explosionAnimation = new ExplosionAnimation();
this.addChild(explosionAnimation);
}
public function clone():DrawObject {
var d:DrawRobot = new DrawRobot(robotID, type, team, overrideSize);
d.location = location;
d.energon = energon;
d.movementDelay = movementDelay;
d.targetLocation = targetLocation;
d.alive = alive;
d.actions = new Vector.<DrawAction>(actions.length);
for each (var o:DrawAction in actions) {
d.actions.push(o.clone());
}
d.removeChild(d.broadcastAnimation);
d.removeChild(d.explosionAnimation);
d.broadcastAnimation = broadcastAnimation.clone() as BroadcastAnimation;
d.explosionAnimation = explosionAnimation.clone() as ExplosionAnimation;
d.addChild(d.broadcastAnimation);
d.addChild(d.explosionAnimation);
return d;
}
private function addAction(d:DrawAction):void {
actions.push(d);
}
public function getRobotID():uint {
return robotID;
}
public function getType():String {
return type;
}
public function getTeam():String {
return team;
}
public function getLocation():MapLocation {
return location;
}
public function getSelected():Boolean {
return selected;
}
public function getIndicatorString(index:uint):String {
return indicatorStrings[index];
}
public function setLocation(location:MapLocation):void {
this.location = location;
}
public function setEnergon(amt:Number):void {
this.energon = Math.min(Math.max(0, amt), maxEnergon);
}
public function setSelected(val:Boolean):void {
this.selected = val;
}
public function setIndicatorString(str:String, index:uint):void {
indicatorStrings[index] = str;
dispatchEvent(new RobotEvent(RobotEvent.INDICATOR_STRING_CHANGE, false, false, this));
}
public function setOverrideSize(overrideSize:Number):void {
this.overrideSize = overrideSize;
this.draw(true);
}
public function attack(targetLocation:MapLocation):void {
this.targetLocation = targetLocation;
this.addAction(new DrawAction(ActionType.ATTACKING, RobotType.attackDelay(type)));
}
public function broadcast():void {
this.broadcastAnimation.broadcast();
}
public function destroyUnit():void {
this.explosionAnimation.explode();
this.alive = false;
}
public function moveToLocation(location:MapLocation):void {
this.movementDelay = Direction.isDiagonal(direction) ?
RobotType.movementDelayDiagonal(type) :
RobotType.movementDelay(type);
this.location = location;
this.addAction(new DrawAction(ActionType.MOVING, movementDelay));
}
public function isAlive():Boolean {
return alive || explosionAnimation.isAlive();
}
public function updateRound():void {
// update actions
for (var i:uint = 0; i < actions.length; i++) {
var o:DrawAction = actions[i];
o.decreaseRound();
if (o.getRounds() <= 0) {
actions.splice(i, 1);
i--;
}
}
// clear aura
aura = null;
// update animations
broadcastAnimation.updateRound();
explosionAnimation.updateRound();
}
public function draw(force:Boolean = false):void {
if (explosionAnimation.isExploding()) {
this.imageCanvas.visible = false;
this.overlayCanvas.visible = false;
this.graphics.clear();
explosionAnimation.draw(force);
return;
}
// draw direction
this.imageCanvas.rotation = directionToRotation(direction);
if (force) {
this.image.width = getImageSize(true);
this.image.height = getImageSize(true);
this.image.x = -this.image.width / 2;
this.image.y = -this.image.height / 2;
}
// clear the graphics object once
this.graphics.clear();
this.overlayCanvas.graphics.clear();
var o:DrawAction;
var movementRounds:uint = 0;
for each (o in actions) {
if (o.getType() == ActionType.MOVING) {
movementRounds = o.getRounds();
break;
}
}
drawX = calculateDrawX(movementRounds);
drawY = calculateDrawY(movementRounds);
for each (o in actions) {
switch (o.getType()) {
case ActionType.ATTACKING:
drawAttack();
break;
case ActionType.MOVING:
drawMovement();
break;
}
}
drawEnergonBar();
drawSelected();
// draw animations
broadcastAnimation.draw(force);
}
///////////////////////////////////////////////////////
////////////// DRAWING HELPER FUNCTIONS ///////////////
///////////////////////////////////////////////////////
private function drawEnergonBar():void {
if (!RenderConfiguration.showEnergon())
return;
var ratio:Number = RobotType.isEncampment(type) ? (flux / maxFlux) : (energon / maxEnergon);
var size:Number = getImageSize();
this.graphics.lineStyle();
this.graphics.beginFill(0x00FF00, 0.8);
this.graphics.drawRect(-size / 2, size / 2, ratio * size, 5 * getImageScale());
this.graphics.endFill();
this.graphics.beginFill(0x000000, 0.8);
this.graphics.drawRect(-size / 2 + ratio * size, size / 2, (1 - ratio) * size, 5 * getImageScale());
this.graphics.endFill();
}
private function drawAttack():void {
var targetOffsetX:Number = (targetLocation.getX() - location.getX()) * getImageSize();
var targetOffsetY:Number = (targetLocation.getY() - location.getY()) * getImageSize();
this.graphics.lineStyle(2, team == Team.A ? 0xFF0000 : 0x0000FF);
this.graphics.moveTo(0, 0);
this.graphics.lineTo(targetOffsetX - drawX, targetOffsetY - drawY);
this.graphics.drawCircle(targetOffsetX - drawX, targetOffsetY - drawY, getImageSize() / 2 * .6);
}
private function drawMovement():void {
if (RenderConfiguration.showDiscrete()) return;
this.x += drawX;
this.y += drawY;
}
private function drawSelected():void {
var size:Number = getImageSize();
if (selected) {
this.graphics.lineStyle(2, 0xFFFFFF);
this.graphics.drawRect(-size / 2, -size / 2, size, size);
}
}
///////////////////////////////////////////////////////
////////////// PRIVATE HELPER FUNCTIONS ///////////////
///////////////////////////////////////////////////////
private function getImageSize(scale:Boolean = false):Number {
if (overrideSize)
return overrideSize;
return RenderConfiguration.getGridSize() * (scale ? getUnitScale(type) : 1.0);
}
private function getImageScale():Number {
if (overrideSize)
return 1.0;
return RenderConfiguration.getScalingFactor();
}
private function getUnitAvatar(type:String, team:String):Class {
return ImageAssets[type + "_" + team];
}
private function getUnitScale(type:String):Number {
switch (type) {
case RobotType.HQ:
return 1.4;
case RobotType.SOLDIER:
return 1.0;
default:
return 1.0;
}
}
private function getUnitOffset(type:String):Number {
return 0;
}
private function directionToRotation(dir:String):int {
switch (dir) {
case Direction.NORTH:
return -90;
case Direction.NORTH_EAST:
return -45;
case Direction.EAST:
return 0;
case Direction.SOUTH_EAST:
return 45;
case Direction.SOUTH:
return 90;
case Direction.SOUTH_WEST:
return 135;
case Direction.WEST:
return 180;
case Direction.NORTH_WEST:
return -135;
default:
return 0;
}
}
private function directionOffsetX(dir:String):int {
switch (dir) {
case Direction.NORTH_EAST:
return +1;
case Direction.NORTH_WEST:
return -1;
case Direction.SOUTH_EAST:
return +1;
case Direction.SOUTH_WEST:
return -1;
case Direction.NORTH:
return 0;
case Direction.SOUTH:
return 0;
case Direction.EAST:
return +1;
case Direction.WEST:
return -1;
default:
return 0;
}
}
private function directionOffsetY(dir:String):int {
switch (dir) {
case Direction.NORTH_EAST:
return -1;
case Direction.NORTH_WEST:
return -1;
case Direction.SOUTH_EAST:
return +1;
case Direction.SOUTH_WEST:
return +1;
case Direction.NORTH:
return -1;
case Direction.SOUTH:
return +1;
case Direction.EAST:
return 0;
case Direction.WEST:
return 0;
default:
return 0;
}
}
private function calculateDrawX(rounds:uint):Number {
if (RenderConfiguration.showDiscrete()) return 0;
return getImageSize() * directionOffsetX(direction) * (rounds / movementDelay);
}
private function calculateDrawY(rounds:uint):Number {
if (RenderConfiguration.showDiscrete()) return 0;
return getImageSize() * directionOffsetY(direction) * (rounds / movementDelay);
}
}
}
|
package battlecode.client.viewer.render {
import battlecode.common.ActionType;
import battlecode.common.Direction;
import battlecode.common.MapLocation;
import battlecode.common.RobotType;
import battlecode.common.Team;
import battlecode.events.RobotEvent;
import mx.containers.Canvas;
import mx.controls.Image;
import mx.core.UIComponent;
[Event(name="indicatorStringChange", type="battlecode.events.RobotEvent")]
public class DrawRobot extends Canvas implements DrawObject {
private var actions:Vector.<DrawAction>;
private var broadcastAnimation:BroadcastAnimation;
private var explosionAnimation:ExplosionAnimation;
private var overlayCanvas:UIComponent;
private var imageCanvas:UIComponent;
private var image:Image;
// size
private var overrideSize:Number;
// indicator strings
private var indicatorStrings:Vector.<String> = new Vector.<String>(3, true);
// movement animation
private var drawX:Number, drawY:Number;
private var movementDelay:uint;
// attack animation
private var targetLocation:MapLocation;
private var selected:Boolean = false;
private var robotID:uint;
private var type:String;
private var team:String;
private var location:MapLocation;
private var direction:String;
private var energon:Number = 0;
private var maxEnergon:Number = 0;
private var flux:Number = 0;
private var maxFlux:Number = 0;
private var aura:String;
private var alive:Boolean = true;
public function DrawRobot(robotID:uint, type:String, team:String, overrideSize:Number = 0) {
this.robotID = robotID;
this.type = type;
this.team = team;
this.maxEnergon = RobotType.maxEnergon(type);
this.maxFlux = RobotType.maxFlux(type);
this.actions = new Vector.<DrawAction>();
this.overrideSize = overrideSize;
// set the unit avatar image
var avatarClass:Class = getUnitAvatar(type, team);
this.imageCanvas = new UIComponent();
this.image = new Image();
this.image.source = avatarClass;
this.image.width = getImageSize(true);
this.image.height = getImageSize(true);
this.image.x = -this.image.width / 2;
this.image.y = -this.image.height / 2;
this.imageCanvas.addChild(image);
this.addChild(imageCanvas);
this.width = this.image.width;
this.height = this.image.height;
this.overlayCanvas = new UIComponent();
this.addChild(overlayCanvas);
// set the hit area for click selection
this.hitArea = imageCanvas;
// animations
this.broadcastAnimation = new BroadcastAnimation(0, team);
this.addChild(broadcastAnimation);
this.explosionAnimation = new ExplosionAnimation();
this.addChild(explosionAnimation);
}
public function clone():DrawObject {
var d:DrawRobot = new DrawRobot(robotID, type, team, overrideSize);
d.location = location;
d.energon = energon;
d.movementDelay = movementDelay;
d.targetLocation = targetLocation;
d.alive = alive;
d.actions = new Vector.<DrawAction>(actions.length);
for each (var o:DrawAction in actions) {
d.actions.push(o.clone());
}
d.removeChild(d.broadcastAnimation);
d.removeChild(d.explosionAnimation);
d.broadcastAnimation = broadcastAnimation.clone() as BroadcastAnimation;
d.explosionAnimation = explosionAnimation.clone() as ExplosionAnimation;
d.addChild(d.broadcastAnimation);
d.addChild(d.explosionAnimation);
return d;
}
private function addAction(d:DrawAction):void {
actions.push(d);
}
public function getRobotID():uint {
return robotID;
}
public function getType():String {
return type;
}
public function getTeam():String {
return team;
}
public function getLocation():MapLocation {
return location;
}
public function getSelected():Boolean {
return selected;
}
public function getIndicatorString(index:uint):String {
return indicatorStrings[index];
}
public function setLocation(location:MapLocation):void {
this.location = location;
}
public function setEnergon(amt:Number):void {
this.energon = Math.min(Math.max(0, amt), maxEnergon);
}
public function setSelected(val:Boolean):void {
this.selected = val;
}
public function setIndicatorString(str:String, index:uint):void {
indicatorStrings[index] = str;
dispatchEvent(new RobotEvent(RobotEvent.INDICATOR_STRING_CHANGE, false, false, this));
}
public function setOverrideSize(overrideSize:Number):void {
this.overrideSize = overrideSize;
this.draw(true);
}
public function attack(targetLocation:MapLocation):void {
this.targetLocation = targetLocation;
this.addAction(new DrawAction(ActionType.ATTACKING, RobotType.attackDelay(type)));
}
public function broadcast():void {
this.broadcastAnimation.broadcast();
}
public function destroyUnit():void {
this.explosionAnimation.explode();
this.alive = false;
}
public function moveToLocation(location:MapLocation):void {
this.movementDelay = Direction.isDiagonal(direction) ?
RobotType.movementDelayDiagonal(type) :
RobotType.movementDelay(type);
this.location = location;
this.addAction(new DrawAction(ActionType.MOVING, movementDelay));
}
public function isAlive():Boolean {
return alive || explosionAnimation.isAlive();
}
public function updateRound():void {
// update actions
for (var i:uint = 0; i < actions.length; i++) {
var o:DrawAction = actions[i];
o.decreaseRound();
if (o.getRounds() <= 0) {
actions.splice(i, 1);
i--;
}
}
// clear aura
aura = null;
// update animations
broadcastAnimation.updateRound();
explosionAnimation.updateRound();
}
public function draw(force:Boolean = false):void {
if (explosionAnimation.isExploding()) {
this.imageCanvas.visible = false;
this.overlayCanvas.visible = false;
this.graphics.clear();
explosionAnimation.draw(force);
return;
}
// draw direction
this.imageCanvas.rotation = directionToRotation(direction);
if (force) {
this.image.width = getImageSize(true);
this.image.height = getImageSize(true);
this.image.x = -this.image.width / 2;
this.image.y = -this.image.height / 2;
}
// clear the graphics object once
this.graphics.clear();
this.overlayCanvas.graphics.clear();
var o:DrawAction;
var movementRounds:uint = 0;
for each (o in actions) {
if (o.getType() == ActionType.MOVING) {
movementRounds = o.getRounds();
break;
}
}
drawX = calculateDrawX(movementRounds);
drawY = calculateDrawY(movementRounds);
for each (o in actions) {
switch (o.getType()) {
case ActionType.ATTACKING:
drawAttack();
break;
case ActionType.MOVING:
drawMovement();
break;
}
}
drawEnergonBar();
drawSelected();
// draw animations
broadcastAnimation.draw(force);
}
///////////////////////////////////////////////////////
////////////// DRAWING HELPER FUNCTIONS ///////////////
///////////////////////////////////////////////////////
private function drawEnergonBar():void {
if (!RenderConfiguration.showEnergon())
return;
var ratio:Number = RobotType.isEncampment(type) ? (flux / maxFlux) : (energon / maxEnergon);
var size:Number = getImageSize();
this.graphics.lineStyle();
this.graphics.beginFill(0x00FF00, 0.8);
this.graphics.drawRect(-size / 2, size / 2, ratio * size, 5 * getImageScale());
this.graphics.endFill();
this.graphics.beginFill(0x000000, 0.8);
this.graphics.drawRect(-size / 2 + ratio * size, size / 2, (1 - ratio) * size, 5 * getImageScale());
this.graphics.endFill();
}
private function drawAttack():void {
var targetOffsetX:Number = (targetLocation.getX() - location.getX()) * getImageSize();
var targetOffsetY:Number = (targetLocation.getY() - location.getY()) * getImageSize();
this.graphics.lineStyle(2, team == Team.A ? 0xFF0000 : 0x0000FF);
this.graphics.moveTo(0, 0);
this.graphics.lineTo(targetOffsetX - drawX, targetOffsetY - drawY);
this.graphics.drawCircle(targetOffsetX - drawX, targetOffsetY - drawY, getImageSize() / 2 * .6);
}
private function drawMovement():void {
if (RenderConfiguration.showDiscrete()) return;
this.x += drawX;
this.y += drawY;
}
private function drawSelected():void {
var size:Number = getImageSize();
if (selected) {
this.graphics.lineStyle(2, 0xFFFFFF);
this.graphics.drawRect(-size / 2, -size / 2, size, size);
}
}
///////////////////////////////////////////////////////
////////////// PRIVATE HELPER FUNCTIONS ///////////////
///////////////////////////////////////////////////////
private function getImageSize(scale:Boolean = false):Number {
if (overrideSize)
return overrideSize;
return RenderConfiguration.getGridSize() * (scale ? getUnitScale(type) : 1.0);
}
private function getImageScale():Number {
if (overrideSize)
return 1.0;
return RenderConfiguration.getScalingFactor();
}
private function getUnitAvatar(type:String, team:String):Class {
return ImageAssets[type + "_" + team];
}
private function getUnitScale(type:String):Number {
switch (type) {
case RobotType.HQ:
return 2.0;
case RobotType.SOLDIER:
return 1.0;
default:
return 1.6;
}
}
private function getUnitOffset(type:String):Number {
return 0;
}
private function directionToRotation(dir:String):int {
switch (dir) {
case Direction.NORTH:
return -90;
case Direction.NORTH_EAST:
return -45;
case Direction.EAST:
return 0;
case Direction.SOUTH_EAST:
return 45;
case Direction.SOUTH:
return 90;
case Direction.SOUTH_WEST:
return 135;
case Direction.WEST:
return 180;
case Direction.NORTH_WEST:
return -135;
default:
return 0;
}
}
private function directionOffsetX(dir:String):int {
switch (dir) {
case Direction.NORTH_EAST:
return +1;
case Direction.NORTH_WEST:
return -1;
case Direction.SOUTH_EAST:
return +1;
case Direction.SOUTH_WEST:
return -1;
case Direction.NORTH:
return 0;
case Direction.SOUTH:
return 0;
case Direction.EAST:
return +1;
case Direction.WEST:
return -1;
default:
return 0;
}
}
private function directionOffsetY(dir:String):int {
switch (dir) {
case Direction.NORTH_EAST:
return -1;
case Direction.NORTH_WEST:
return -1;
case Direction.SOUTH_EAST:
return +1;
case Direction.SOUTH_WEST:
return +1;
case Direction.NORTH:
return -1;
case Direction.SOUTH:
return +1;
case Direction.EAST:
return 0;
case Direction.WEST:
return 0;
default:
return 0;
}
}
private function calculateDrawX(rounds:uint):Number {
if (RenderConfiguration.showDiscrete()) return 0;
return getImageSize() * directionOffsetX(direction) * (rounds / movementDelay);
}
private function calculateDrawY(rounds:uint):Number {
if (RenderConfiguration.showDiscrete()) return 0;
return getImageSize() * directionOffsetY(direction) * (rounds / movementDelay);
}
}
}
|
make hq's and encampments more visible (larger)
|
make hq's and encampments more visible (larger)
|
ActionScript
|
mit
|
trun/battlecode-webclient
|
3a736c00adb4f18051ce7a552872003ba2157429
|
src/org/mangui/basic/Player.as
|
src/org/mangui/basic/Player.as
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.basic {
import org.mangui.hls.HLS;
import org.mangui.hls.event.HLSEvent;
import flash.display.Sprite;
import flash.media.Video;
public class Player extends Sprite {
private var hls : HLS = null;
private var video : Video = null;
public function Player() {
hls = new HLS();
video = new Video(640, 480);
addChild(video);
video.x = 0;
video.y = 0;
video.smoothing = true;
video.attachNetStream(hls.stream);
hls.addEventListener(HLSEvent.MANIFEST_LOADED, manifestHandler);
hls.load("http://domain.com/hls/m1.m3u8");
}
public function manifestHandler(event : HLSEvent) : void {
hls.stream.play();
};
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.basic {
import org.mangui.hls.HLS;
import org.mangui.hls.event.HLSEvent;
import flash.display.Sprite;
import flash.media.Video;
public class Player extends Sprite {
private var hls : HLS = null;
private var video : Video = null;
public function Player() {
hls = new HLS();
hls.stage = this.stage;
video = new Video(640, 480);
addChild(video);
video.x = 0;
video.y = 0;
video.smoothing = true;
video.attachNetStream(hls.stream);
hls.addEventListener(HLSEvent.MANIFEST_LOADED, manifestHandler);
hls.load("http://domain.com/hls/m1.m3u8");
}
public function manifestHandler(event : HLSEvent) : void {
hls.stream.play(null, -1);
};
}
}
|
set stage
|
basic/Player.as: set stage
|
ActionScript
|
mpl-2.0
|
dighan/flashls,tedconf/flashls,loungelogic/flashls,aevange/flashls,codex-corp/flashls,Peer5/flashls,Peer5/flashls,aevange/flashls,loungelogic/flashls,viktorot/flashls,dighan/flashls,Corey600/flashls,aevange/flashls,viktorot/flashls,NicolasSiver/flashls,NicolasSiver/flashls,Corey600/flashls,jlacivita/flashls,suuhas/flashls,clappr/flashls,codex-corp/flashls,JulianPena/flashls,clappr/flashls,suuhas/flashls,neilrackett/flashls,mangui/flashls,jlacivita/flashls,Peer5/flashls,vidible/vdb-flashls,JulianPena/flashls,fixedmachine/flashls,suuhas/flashls,thdtjsdn/flashls,thdtjsdn/flashls,viktorot/flashls,aevange/flashls,vidible/vdb-flashls,fixedmachine/flashls,Boxie5/flashls,suuhas/flashls,hola/flashls,Peer5/flashls,tedconf/flashls,neilrackett/flashls,Boxie5/flashls,mangui/flashls,hola/flashls
|
015475b48bc32bc4b5bb270d23243951be8dd93a
|
src/aerys/minko/scene/controller/TransformController.as
|
src/aerys/minko/scene/controller/TransformController.as
|
package aerys.minko.scene.controller
{
import aerys.minko.scene.data.TransformDataProvider;
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.math.Matrix4x4;
public final class TransformController extends AbstractController
{
private var _node : ISceneNode;
private var _data : TransformDataProvider;
public function TransformController()
{
super();
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : TransformController,
node : ISceneNode) : void
{
if (_node)
throw new Error();
_node = node;
_node.transform.changed.add(transformChangedHandler);
_node.added.add(addedHandler);
_node.removed.add(removedHandler);
if (_node is Mesh)
{
_node.addedToScene.add(meshAddedToSceneHandler);
_node.removedFromScene.add(meshRemovedFromSceneHandler);
}
transformChangedHandler(_node.transform);
}
private function targetRemovedHandler(ctrl : TransformController,
node : ISceneNode) : void
{
if (_node is Mesh)
{
_node.addedToScene.remove(meshAddedToSceneHandler);
_node.removedFromScene.remove(meshRemovedFromSceneHandler);
}
_node.removed.remove(removedHandler);
_node.added.remove(addedHandler);
_node.transform.changed.remove(transformChangedHandler);
_node = null;
}
private function meshAddedToSceneHandler(mesh : Mesh, scene : Scene) : void
{
_data = new TransformDataProvider(mesh.localToWorld, mesh.worldToLocal);
mesh.bindings.addProvider(_data);
}
private function meshRemovedFromSceneHandler(mesh : Mesh, scene : Scene) : void
{
mesh.bindings.removeProvider(_data);
_data = null;
}
private function transformChangedHandler(transform : Matrix4x4) : void
{
var parent : ISceneNode = _node.parent;
_node.worldToLocal.lock();
_node.localToWorld.lock();
_node.localToWorld.copyFrom(_node.transform);
if (_node.parent)
_node.localToWorld.append(parent.localToWorld);
_node.worldToLocal
.copyFrom(_node.localToWorld)
.invert();
_node.worldToLocal.unlock();
_node.localToWorld.unlock();
}
private function addedHandler(node : ISceneNode, parent : Group) : void
{
if (node === _node)
{
parent.localToWorld.changed.add(transformChangedHandler);
transformChangedHandler(_node.transform);
}
}
private function removedHandler(node : ISceneNode, parent : Group) : void
{
if (node === _node)
{
parent.localToWorld.changed.remove(transformChangedHandler);
transformChangedHandler(_node.transform);
}
}
}
}
|
package aerys.minko.scene.controller
{
import aerys.minko.scene.data.TransformDataProvider;
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.math.Matrix4x4;
public final class TransformController extends AbstractController
{
private var _node : ISceneNode;
private var _data : TransformDataProvider;
public function TransformController()
{
super();
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : TransformController,
node : ISceneNode) : void
{
if (_node)
throw new Error();
_node = node;
_node.transform.changed.add(transformChangedHandler);
_node.added.add(addedHandler);
_node.removed.add(removedHandler);
if (_node is Mesh)
{
_node.addedToScene.add(meshAddedToSceneHandler);
_node.removedFromScene.add(meshRemovedFromSceneHandler);
}
transformChangedHandler(_node.transform);
}
private function targetRemovedHandler(ctrl : TransformController,
node : ISceneNode) : void
{
if (_node is Mesh)
{
_node.addedToScene.remove(meshAddedToSceneHandler);
_node.removedFromScene.remove(meshRemovedFromSceneHandler);
}
_node.removed.remove(removedHandler);
_node.added.remove(addedHandler);
_node.transform.changed.remove(transformChangedHandler);
_node = null;
}
private function meshAddedToSceneHandler(mesh : Mesh, scene : Scene) : void
{
_data = new TransformDataProvider(mesh.localToWorld, mesh.worldToLocal);
mesh.bindings.addProvider(_data);
}
private function meshRemovedFromSceneHandler(mesh : Mesh, scene : Scene) : void
{
mesh.bindings.removeProvider(_data);
_data = null;
}
private function transformChangedHandler(transform : Matrix4x4) : void
{
var parent : ISceneNode = _node.parent;
_node.worldToLocal.lock();
_node.localToWorld.lock();
_node.localToWorld.copyFrom(_node.transform);
if (_node.parent)
_node.localToWorld.append(parent.localToWorld);
_node.worldToLocal
.copyFrom(_node.localToWorld)
.invert();
_node.worldToLocal.unlock();
_node.localToWorld.unlock();
}
private function addedHandler(node : ISceneNode, ancestor : Group) : void
{
if (node === _node && ancestor === _node.parent)
{
ancestor.localToWorld.changed.add(transformChangedHandler);
transformChangedHandler(_node.transform);
}
}
private function removedHandler(node : ISceneNode, ancestor : Group) : void
{
if (node === _node && !_node.parent)
{
ancestor.localToWorld.changed.remove(transformChangedHandler);
transformChangedHandler(_node.transform);
}
}
}
}
|
fix TransformController.removedHandler() and TransformController.addedHandler() to fit to the corresponding signals new propagation rules
|
fix TransformController.removedHandler() and TransformController.addedHandler() to fit to the corresponding signals new propagation rules
|
ActionScript
|
mit
|
aerys/minko-as3
|
5c1b053947e75f433cc9eb0bf8ae5bfbaacb6f0e
|
src/org/igniterealtime/xiff/core/XMPPBOSHConnection.as
|
src/org/igniterealtime/xiff/core/XMPPBOSHConnection.as
|
/*
* License
*/
package org.igniterealtime.xiff.core
{
import flash.events.TimerEvent;
import flash.utils.ByteArray;
import flash.utils.Timer;
import flash.xml.XMLDocument;
import flash.xml.XMLNode;
import mx.logging.ILogger;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import org.igniterealtime.xiff.events.*;
import org.igniterealtime.xiff.logging.LoggerFactory;
import org.igniterealtime.xiff.util.Callback;
/**
* Bidirectional-streams Over Synchronous HTTP (BOSH)
* @see http://xmpp.org/extensions/xep-0206.html
*/
public class XMPPBOSHConnection extends XMPPConnection
{
private static const BOSH_VERSION:String = "1.6";
private static const HTTPS_PORT:int = 7443;
private static const HTTP_PORT:int = 7070;
private static const headers:Object = {
"post": [],
"get": [ 'Cache-Control',
'no-store',
'Cache-Control',
'no-cache',
'Pragma', 'no-cache' ]
};
private static const logger:ILogger = LoggerFactory.getLogger( "org.igniterealtime.xiff.core.XMPPBOSHConnection" );
private var _boshPath:String = "http-bind/";
private var _hold:uint = 1;
private var _maxConcurrentRequests:uint = 2;
private var _port:Number;
private var _secure:Boolean;
private var _wait:uint = 20;
private var boshPollingInterval:uint = 10000;
private var inactivity:uint;
private var isDisconnecting:Boolean = false;
private var lastPollTime:Date = null;
private var maxPause:uint;
private var pauseEnabled:Boolean = false;
private var pauseTimer:Timer;
private var pollingEnabled:Boolean = false;
private var requestCount:int = 0;
private var requestQueue:Array = [];
private var responseQueue:Array = [];
private const responseTimer:Timer = new Timer( 0.0, 1 );
private var rid:Number;
private var sid:String;
private var streamRestarted:Boolean;
/**
*
* @param secure
*/
public function XMPPBOSHConnection( secure:Boolean = false ):void
{
super();
this.secure = secure;
}
override public function connect( streamType:String = null ):Boolean
{
logger.debug( "BOSH connect()" );
var attrs:Object = {
"xml:lang": "en",
"xmlns": "http://jabber.org/protocol/httpbind",
"xmlns:xmpp": "urn:xmpp:xbosh",
"xmpp:version": "1.0",
"hold": hold,
"rid": nextRID,
"secure": secure,
"wait": wait,
"ver": BOSH_VERSION,
"to": domain
};
var result:XMLNode = new XMLNode( 1, "body" );
result.attributes = attrs;
sendRequests( result );
return true;
}
override public function disconnect():void
{
if ( active )
{
var data:XMLNode = createRequest();
data.attributes.type = "terminate";
sendRequests( data );
active = false;
loggedIn = false;
dispatchEvent( new DisconnectionEvent());
}
}
/**
* @return true if pause request is sent
*/
public function pauseSession( seconds:uint ):Boolean
{
logger.debug( "Pausing session for {0} seconds", seconds );
var pauseDuration:uint = seconds * 1000;
if ( !pauseEnabled || pauseDuration > maxPause || pauseDuration <= boshPollingInterval )
return false;
pollingEnabled = false;
var data:XMLNode = createRequest();
data.attributes[ "pause" ] = seconds;
sendRequests( data );
pauseTimer = new Timer( pauseDuration - 2000, 1 );
pauseTimer.addEventListener( TimerEvent.TIMER, handlePauseTimeout );
pauseTimer.start();
return true;
}
public function processConnectionResponse( responseBody:XMLNode ):void
{
dispatchEvent( new ConnectionSuccessEvent());
var attributes:Object = responseBody.attributes;
sid = attributes.sid;
wait = attributes.wait;
if ( attributes.polling )
{
boshPollingInterval = attributes.polling * 1000;
}
if ( attributes.inactivity )
{
inactivity = attributes.inactivity * 1000;
}
if ( attributes.maxpause )
{
maxPause = attributes.maxpause * 1000;
pauseEnabled = true;
}
if ( attributes.requests )
{
maxConcurrentRequests = attributes.requests;
}
logger.debug( "Polling interval: {0}", boshPollingInterval );
logger.debug( "Inactivity timeout: {0}", inactivity );
logger.debug( "Max requests: {0}", maxConcurrentRequests );
logger.debug( "Max pause: {0}", maxPause );
active = true;
addEventListener( LoginEvent.LOGIN, handleLogin );
responseTimer.addEventListener( TimerEvent.TIMER_COMPLETE, processResponse );
}
//do nothing, we use polling instead
override public function sendKeepAlive():void
{
}
override protected function restartStream():void
{
var data:XMLNode = createRequest();
data.attributes[ "xmpp:restart" ] = "true";
data.attributes[ "xmlns:xmpp" ] = "urn:xmpp:xbosh";
data.attributes[ "xml:lang" ] = "en";
data.attributes[ "to" ] = domain;
sendRequests( data );
streamRestarted = true;
}
override protected function sendXML( body:* ):void
{
sendQueuedRequests( body );
}
private function createRequest( bodyContent:Array = null ):XMLNode
{
var attrs:Object = {
"xmlns": "http://jabber.org/protocol/httpbind",
"rid": nextRID,
"sid": sid
};
var req:XMLNode = new XMLNode( 1, "body" );
if ( bodyContent )
{
for each ( var content:XMLNode in bodyContent )
{
req.appendChild( content );
}
}
req.attributes = attrs;
return req;
}
private function handleLogin( e:LoginEvent ):void
{
pollingEnabled = true;
pollServer();
}
private function handlePauseTimeout( event:TimerEvent ):void
{
logger.debug( "handlePauseTimeout" );
pollingEnabled = true;
pollServer();
}
private function httpError( req:XMLNode, isPollResponse:Boolean, event:FaultEvent ):void
{
disconnect();
dispatchError( "Unknown HTTP Error", event.fault.rootCause.text, "",
-1 );
}
private function httpResponse( req:XMLNode, isPollResponse:Boolean, event:ResultEvent ):void
{
requestCount--;
var rawXML:String = event.result as String;
logger.info( "INCOMING {0}", rawXML );
var xmlData:XMLDocument = new XMLDocument();
xmlData.ignoreWhite = this.ignoreWhite;
xmlData.parseXML( rawXML );
var bodyNode:XMLNode = xmlData.firstChild;
var byteData:ByteArray = new ByteArray();
byteData.writeUTFBytes(xmlData.toString());
var incomingEvent:IncomingDataEvent = new IncomingDataEvent();
incomingEvent.data = byteData;
dispatchEvent( incomingEvent );
if ( streamRestarted && !bodyNode.hasChildNodes())
{
streamRestarted = false;
bindConnection();
}
if ( bodyNode.attributes[ "type" ] == "terminate" )
{
dispatchError( "BOSH Error", bodyNode.attributes[ "condition" ],
"", -1 );
active = false;
}
if ( bodyNode.attributes[ "sid" ] && !loggedIn )
{
processConnectionResponse( bodyNode );
var featuresFound:Boolean = false;
for each ( var child:XMLNode in bodyNode.childNodes )
{
if ( child.nodeName == "stream:features" )
featuresFound = true;
}
if ( !featuresFound )
{
pollingEnabled = true;
pollServer();
}
}
for each ( var childNode:XMLNode in bodyNode.childNodes )
{
responseQueue.push( childNode );
}
resetResponseProcessor();
//if we have no outstanding requests, then we're free to send a poll at the next opportunity
if ( requestCount == 0 && !sendQueuedRequests())
pollServer();
}
private function pollServer():void
{
//We shouldn't poll if the connection is dead, if we had requests to send instead, or if there's already one in progress
if ( !isActive() || !pollingEnabled || sendQueuedRequests() || requestCount >
0 )
return;
//this should be safe since sendRequests checks to be sure it's not over the concurrent requests limit, and we just ensured that the queue is empty by calling sendQueuedRequests()
sendRequests( null, true );
}
private function processResponse( event:TimerEvent = null ):void
{
// Read the data and send it to the appropriate parser
var currentNode:XMLNode = responseQueue.shift();
var nodeName:String = currentNode.nodeName.toLowerCase();
switch ( nodeName )
{
case "stream:features":
handleStreamFeatures( currentNode );
streamRestarted = false; //avoid triggering the old server workaround
break;
case "stream:error":
handleStreamError( currentNode );
break;
case "iq":
handleIQ( currentNode );
break;
case "message":
handleMessage( currentNode );
break;
case "presence":
handlePresence( currentNode );
break;
case "success":
handleAuthentication( currentNode );
break;
case "failure":
handleAuthentication( currentNode );
break;
default:
dispatchError( "undefined-condition", "Unknown Error", "modify",
500 );
break;
}
resetResponseProcessor();
}
private function resetResponseProcessor():void
{
if ( responseQueue.length > 0 )
{
responseTimer.reset();
responseTimer.start();
}
}
private function sendQueuedRequests( body:* = null ):Boolean
{
if ( body )
{
requestQueue.push( body );
}
else if ( requestQueue.length == 0 )
{
return false;
}
return sendRequests();
}
//returns true if any requests were sent
private function sendRequests( data:XMLNode = null, isPoll:Boolean = false ):Boolean
{
if ( requestCount >= maxConcurrentRequests )
{
return false;
}
requestCount++;
if ( !data )
{
if ( isPoll )
{
data = createRequest();
}
else
{
var temp:Array = [];
for ( var i:uint = 0; i < 10 && requestQueue.length > 0; ++i )
{
temp.push( requestQueue.shift());
}
data = createRequest( temp );
}
}
// TODO: Could this be replaced with URLLoader ?
//build the http request
var request:HTTPService = new HTTPService();
request.method = "post";
request.headers = headers[ request.method ];
request.url = httpServer;
request.resultFormat = HTTPService.RESULT_FORMAT_TEXT;
request.contentType = "text/xml";
var responseCallback:Callback = new Callback( this, httpResponse, data,
isPoll );
var errorCallback:Callback = new Callback( this, httpError, data, isPoll );
request.addEventListener( ResultEvent.RESULT, responseCallback.call,
false );
request.addEventListener( FaultEvent.FAULT, errorCallback.call, false );
request.send( data );
var byteData:ByteArray = new ByteArray();
byteData.writeUTFBytes(data.toString());
var event:OutgoingDataEvent = new OutgoingDataEvent();
event.data = byteData;
dispatchEvent( event );
if ( isPoll )
{
lastPollTime = new Date();
logger.info( "Polling" );
}
logger.info( "OUTGOING {0}", data );
return true;
}
public function get boshPath():String
{
return _boshPath;
}
public function set boshPath( value:String ):void
{
_boshPath = value;
}
private function get nextRID():Number
{
if ( !rid )
rid = Math.floor( Math.random() * 1000000 );
return ++rid;
}
public function get wait():uint
{
return _wait;
}
public function set wait( value:uint ):void
{
_wait = value;
}
public function get secure():Boolean
{
return _secure;
}
public function set secure( flag:Boolean ):void
{
logger.debug( "set secure: {0}", flag );
_secure = flag;
port = _secure ? HTTPS_PORT : HTTP_PORT;
}
override public function get port():Number
{
return _port;
}
override public function set port( portnum:Number ):void
{
logger.debug( "set port: {0}", portnum );
_port = portnum;
}
public function get hold():uint
{
return _hold;
}
public function set hold( value:uint ):void
{
_hold = value;
}
public function get httpServer():String
{
return ( secure ? "https" : "http" ) + "://" + server + ":" + port +
"/" + boshPath;
}
public function get maxConcurrentRequests():uint
{
return _maxConcurrentRequests;
}
public function set maxConcurrentRequests( value:uint ):void
{
_maxConcurrentRequests = value;
}
}
}
|
/*
* License
*/
package org.igniterealtime.xiff.core
{
import flash.events.*;
import flash.net.*;
import flash.utils.ByteArray;
import flash.utils.Timer;
import flash.xml.XMLDocument;
import flash.xml.XMLNode;
import mx.logging.ILogger;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import org.igniterealtime.xiff.events.*;
import org.igniterealtime.xiff.logging.LoggerFactory;
import org.igniterealtime.xiff.util.Callback;
/**
* Bidirectional-streams Over Synchronous HTTP (BOSH)
* @see http://xmpp.org/extensions/xep-0206.html
*/
public class XMPPBOSHConnection extends XMPPConnection
{
private static const BOSH_VERSION:String = "1.6";
private static const HTTPS_PORT:int = 7443;
private static const HTTP_PORT:int = 7070;
/**
* Keys should match URLRequestMethod constants.
*/
private static const headers:Object = {
"post": [],
"get": [ 'Cache-Control',
'no-store',
'Cache-Control',
'no-cache',
'Pragma', 'no-cache' ]
};
private static const logger:ILogger = LoggerFactory.getLogger( "org.igniterealtime.xiff.core.XMPPBOSHConnection" );
private var _boshPath:String = "http-bind/";
private var _hold:uint = 1;
private var _maxConcurrentRequests:uint = 2;
private var _port:Number;
private var _secure:Boolean;
private var _wait:uint = 20;
private var boshPollingInterval:uint = 10000;
private var inactivity:uint;
private var isDisconnecting:Boolean = false;
private var lastPollTime:Date = null;
private var maxPause:uint;
private var pauseEnabled:Boolean = false;
private var pauseTimer:Timer;
private var pollingEnabled:Boolean = false;
private var requestCount:int = 0;
private var requestQueue:Array = [];
private var responseQueue:Array = [];
private var responseTimer:Timer;
private var rid:Number;
private var sid:String;
private var streamRestarted:Boolean;
/**
*
* @param secure
*/
public function XMPPBOSHConnection( secure:Boolean = false ):void
{
super();
this.secure = secure;
responseTimer = new Timer( 0.0, 1 );
}
override public function connect( streamType:String = null ):Boolean
{
logger.debug( "BOSH connect()" );
var attrs:Object = {
"xml:lang": "en",
"xmlns": "http://jabber.org/protocol/httpbind",
"xmlns:xmpp": "urn:xmpp:xbosh",
"xmpp:version": "1.0",
"hold": hold,
"rid": nextRID,
"secure": secure,
"wait": wait,
"ver": BOSH_VERSION,
"to": domain
};
var result:XMLNode = new XMLNode( 1, "body" );
result.attributes = attrs;
sendRequests( result );
return true;
}
override public function disconnect():void
{
if ( active )
{
var data:XMLNode = createRequest();
data.attributes.type = "terminate";
sendRequests( data );
active = false;
loggedIn = false;
dispatchEvent( new DisconnectionEvent());
}
}
/**
* @return true if pause request is sent
*/
public function pauseSession( seconds:uint ):Boolean
{
logger.debug( "Pausing session for {0} seconds", seconds );
var pauseDuration:uint = seconds * 1000;
if ( !pauseEnabled || pauseDuration > maxPause || pauseDuration <= boshPollingInterval )
return false;
pollingEnabled = false;
var data:XMLNode = createRequest();
data.attributes[ "pause" ] = seconds;
sendRequests( data );
pauseTimer = new Timer( pauseDuration - 2000, 1 );
pauseTimer.addEventListener( TimerEvent.TIMER, handlePauseTimeout );
pauseTimer.start();
return true;
}
public function processConnectionResponse( responseBody:XMLNode ):void
{
dispatchEvent( new ConnectionSuccessEvent());
var attributes:Object = responseBody.attributes;
sid = attributes.sid;
wait = attributes.wait;
if ( attributes.polling )
{
boshPollingInterval = attributes.polling * 1000;
}
if ( attributes.inactivity )
{
inactivity = attributes.inactivity * 1000;
}
if ( attributes.maxpause )
{
maxPause = attributes.maxpause * 1000;
pauseEnabled = true;
}
if ( attributes.requests )
{
maxConcurrentRequests = attributes.requests;
}
logger.debug( "Polling interval: {0}", boshPollingInterval );
logger.debug( "Inactivity timeout: {0}", inactivity );
logger.debug( "Max requests: {0}", maxConcurrentRequests );
logger.debug( "Max pause: {0}", maxPause );
active = true;
addEventListener( LoginEvent.LOGIN, handleLogin );
responseTimer.addEventListener( TimerEvent.TIMER_COMPLETE, processResponse );
}
//do nothing, we use polling instead
override public function sendKeepAlive():void
{
}
override protected function restartStream():void
{
var data:XMLNode = createRequest();
data.attributes[ "xmpp:restart" ] = "true";
data.attributes[ "xmlns:xmpp" ] = "urn:xmpp:xbosh";
data.attributes[ "xml:lang" ] = "en";
data.attributes[ "to" ] = domain;
sendRequests( data );
streamRestarted = true;
}
override protected function sendXML( body:* ):void
{
sendQueuedRequests( body );
}
private function createRequest( bodyContent:Array = null ):XMLNode
{
var attrs:Object = {
"xmlns": "http://jabber.org/protocol/httpbind",
"rid": nextRID,
"sid": sid
};
var req:XMLNode = new XMLNode( 1, "body" );
if ( bodyContent )
{
for each ( var content:XMLNode in bodyContent )
{
req.appendChild( content );
}
}
req.attributes = attrs;
return req;
}
private function handleLogin( e:LoginEvent ):void
{
pollingEnabled = true;
pollServer();
}
private function handlePauseTimeout( event:TimerEvent ):void
{
logger.debug( "handlePauseTimeout" );
pollingEnabled = true;
pollServer();
}
private function httpError( req:XMLNode, isPollResponse:Boolean, event:FaultEvent ):void
{
disconnect();
dispatchError( "Unknown HTTP Error", event.fault.rootCause.text, "",
-1 );
}
private function httpResponse( req:XMLNode, isPollResponse:Boolean, event:ResultEvent ):void
{
requestCount--;
var rawXML:String = event.result as String;
logger.info( "INCOMING {0}", rawXML );
var xmlData:XMLDocument = new XMLDocument();
xmlData.ignoreWhite = this.ignoreWhite;
xmlData.parseXML( rawXML );
var bodyNode:XMLNode = xmlData.firstChild;
var byteData:ByteArray = new ByteArray();
byteData.writeUTFBytes(xmlData.toString());
var incomingEvent:IncomingDataEvent = new IncomingDataEvent();
incomingEvent.data = byteData;
dispatchEvent( incomingEvent );
if ( streamRestarted && !bodyNode.hasChildNodes())
{
streamRestarted = false;
bindConnection();
}
if ( bodyNode.attributes[ "type" ] == "terminate" )
{
dispatchError( "BOSH Error", bodyNode.attributes[ "condition" ],
"", -1 );
active = false;
}
if ( bodyNode.attributes[ "sid" ] && !loggedIn )
{
processConnectionResponse( bodyNode );
var featuresFound:Boolean = false;
for each ( var child:XMLNode in bodyNode.childNodes )
{
if ( child.nodeName == "stream:features" )
featuresFound = true;
}
if ( !featuresFound )
{
pollingEnabled = true;
pollServer();
}
}
for each ( var childNode:XMLNode in bodyNode.childNodes )
{
responseQueue.push( childNode );
}
resetResponseProcessor();
//if we have no outstanding requests, then we're free to send a poll at the next opportunity
if ( requestCount == 0 && !sendQueuedRequests())
pollServer();
}
private function pollServer():void
{
//We shouldn't poll if the connection is dead, if we had requests to send instead, or if there's already one in progress
if ( !isActive() || !pollingEnabled || sendQueuedRequests() || requestCount >
0 )
return;
//this should be safe since sendRequests checks to be sure it's not over the concurrent requests limit, and we just ensured that the queue is empty by calling sendQueuedRequests()
sendRequests( null, true );
}
private function processResponse( event:TimerEvent = null ):void
{
// Read the data and send it to the appropriate parser
var currentNode:XMLNode = responseQueue.shift();
var nodeName:String = currentNode.nodeName.toLowerCase();
switch ( nodeName )
{
case "stream:features":
handleStreamFeatures( currentNode );
streamRestarted = false; //avoid triggering the old server workaround
break;
case "stream:error":
handleStreamError( currentNode );
break;
case "iq":
handleIQ( currentNode );
break;
case "message":
handleMessage( currentNode );
break;
case "presence":
handlePresence( currentNode );
break;
case "success":
handleAuthentication( currentNode );
break;
case "failure":
handleAuthentication( currentNode );
break;
default:
dispatchError( "undefined-condition", "Unknown Error", "modify",
500 );
break;
}
resetResponseProcessor();
}
private function resetResponseProcessor():void
{
if ( responseQueue.length > 0 )
{
responseTimer.reset();
responseTimer.start();
}
}
private function sendQueuedRequests( body:* = null ):Boolean
{
if ( body )
{
requestQueue.push( body );
}
else if ( requestQueue.length == 0 )
{
return false;
}
return sendRequests();
}
//returns true if any requests were sent
private function sendRequests( data:XMLNode = null, isPoll:Boolean = false ):Boolean
{
if ( requestCount >= maxConcurrentRequests )
{
return false;
}
requestCount++;
if ( !data )
{
if ( isPoll )
{
data = createRequest();
}
else
{
var temp:Array = [];
for ( var i:uint = 0; i < 10 && requestQueue.length > 0; ++i )
{
temp.push( requestQueue.shift());
}
data = createRequest( temp );
}
}
/*
var req:URLRequest = new URLRequest(httpServer);
req.method = URLRequestMethod.POST;
req.contentType = "text/xml";
req.requestHeaders = headers[ req.method ];
req.data = data;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.addEventListener(Event.COMPLETE, onRequestComplete);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, socketSecurityError);
loader.addEventListener(IOErrorEvent.IO_ERROR, socketIOError);
loader.load(req);
*/
// TODO: Could this be replaced with URLLoader ?
//build the http request
var request:HTTPService = new HTTPService();
request.method = "post";
request.headers = headers[ request.method ];
request.url = httpServer;
request.resultFormat = HTTPService.RESULT_FORMAT_TEXT;
request.contentType = "text/xml";
var responseCallback:Callback = new Callback( this, httpResponse, data,
isPoll );
var errorCallback:Callback = new Callback( this, httpError, data, isPoll );
request.addEventListener( ResultEvent.RESULT, responseCallback.call,
false );
request.addEventListener( FaultEvent.FAULT, errorCallback.call, false );
request.send( data );
var byteData:ByteArray = new ByteArray();
byteData.writeUTFBytes(data.toString());
var event:OutgoingDataEvent = new OutgoingDataEvent();
event.data = byteData;
dispatchEvent( event );
if ( isPoll )
{
lastPollTime = new Date();
logger.info( "Polling" );
}
logger.info( "OUTGOING {0}", data );
return true;
}
public function get boshPath():String
{
return _boshPath;
}
public function set boshPath( value:String ):void
{
_boshPath = value;
}
private function get nextRID():Number
{
if ( !rid )
rid = Math.floor( Math.random() * 1000000 );
return ++rid;
}
public function get wait():uint
{
return _wait;
}
public function set wait( value:uint ):void
{
_wait = value;
}
public function get secure():Boolean
{
return _secure;
}
public function set secure( flag:Boolean ):void
{
logger.debug( "set secure: {0}", flag );
_secure = flag;
port = _secure ? HTTPS_PORT : HTTP_PORT;
}
override public function get port():Number
{
return _port;
}
override public function set port( portnum:Number ):void
{
logger.debug( "set port: {0}", portnum );
_port = portnum;
}
public function get hold():uint
{
return _hold;
}
public function set hold( value:uint ):void
{
_hold = value;
}
public function get httpServer():String
{
return ( secure ? "https" : "http" ) + "://" + server + ":" + port +
"/" + boshPath;
}
public function get maxConcurrentRequests():uint
{
return _maxConcurrentRequests;
}
public function set maxConcurrentRequests( value:uint ):void
{
_maxConcurrentRequests = value;
}
}
}
|
Rewrite work in progress...
|
Rewrite work in progress...
git-svn-id: c197267f952b24206666de142881703007ca05d5@11143 b35dd754-fafc-0310-a699-88a17e54d16e
|
ActionScript
|
apache-2.0
|
nazoking/xiff
|
204de3504e1b3cae22aa8c330def9dbc869e6ad2
|
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);
}
protected function initialize() : void
{
_started = new Dictionary(true);
}
override protected function targetAddedToSceneHandler(target : ISceneNode,
scene : Scene) : void
{
if (_scene && scene != _scene)
throw new Error(
'The same ScriptController instance can not be used in more than one scene ' +
'at a time.'
);
_scene = scene;
}
override protected function targetRemovedFromSceneHandler(target : ISceneNode,
scene : Scene) : void
{
if (numTargetsInScene == 0)
_scene = null;
}
override protected function sceneEnterFrameHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
_viewport = viewport;
_deltaTime = _lastTime - time;
_lastTime = time;
beforeUpdate();
var numTargets : uint = this.numTargets;
for (var i : uint = 0; i < numTargets; ++i)
{
var target : ISceneNode = getTarget(i);
if (target.scene)
{
if (!_started[target])
{
_started[target] = true;
start(target);
}
update(target);
}
else if (_started[target])
{
_started[target] = false;
stop(target);
}
}
afterUpdate();
}
/**
* The 'start' method is called on a script target at the first frame occuring after it
* has been added to the scene.
*
* @param target
*
*/
protected function start(target : ISceneNode) : void
{
// nothing
}
/**
* The 'beforeUpdate' method is called before each target is updated via the 'update'
* method.
*
*/
protected function beforeUpdate() : void
{
// nothing
}
protected function update(target : ISceneNode) : void
{
// nothing
}
/**
* The 'afterUpdate' method is called after each target has been updated via the 'update'
* method.
*
*/
protected function afterUpdate() : void
{
// nothing
}
/**
* The 'start' method is called on a script target at the first frame occuring after it
* has been removed from the scene.
*
* @param target
*
*/
protected function stop(target : ISceneNode) : void
{
// nothing
}
}
}
|
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
}
}
}
|
fix missing init of ScriptController._started
|
fix missing init of ScriptController._started
|
ActionScript
|
mit
|
aerys/minko-as3
|
c1d6883557271455d2d6f042c429c6f6f91661da
|
src/org/mangui/hls/demux/ID3.as
|
src/org/mangui/hls/demux/ID3.as
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls.demux {
import flash.utils.ByteArray;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
public class ID3 {
public var len : int;
public var hasTimestamp : Boolean = false;
public var timestamp : Number;
public var tags : Vector.<ID3Tag> = new Vector.<ID3Tag>();
/* create ID3 object by parsing ByteArray, looking for ID3 tag length, and timestamp */
public function ID3(data : ByteArray) {
var tagSize : uint = 0;
try {
var pos : uint = data.position;
var header : String;
do {
header = data.readUTFBytes(3);
if (header == 'ID3') {
// skip 24 bits
data.position += 3;
// retrieve tag(s) length
var byte1 : uint = data.readUnsignedByte() & 0x7f;
var byte2 : uint = data.readUnsignedByte() & 0x7f;
var byte3 : uint = data.readUnsignedByte() & 0x7f;
var byte4 : uint = data.readUnsignedByte() & 0x7f;
tagSize = (byte1 << 21) + (byte2 << 14) + (byte3 << 7) + byte4;
var endPos : uint = data.position + tagSize;
CONFIG::LOGGING {
Log.debug2("ID3 tag found, size/end pos:" + tagSize + "/" + endPos);
}
// read ID3 tags
_parseID3Frames(data, endPos);
data.position = endPos;
} else if (header == '3DI') {
// http://id3.org/id3v2.4.0-structure chapter 3.4. ID3v2 footer
data.position += 7;
CONFIG::LOGGING {
Log.debug2("3DI footer found, end pos:" + data.position);
}
} else {
data.position -= 3;
len = data.position - pos;
CONFIG::LOGGING {
if (len) {
Log.debug2("ID3 len:" + len);
if (!hasTimestamp) {
Log.warn("ID3 tag found, but no timestamp");
}
}
}
return;
}
} while (true);
} catch(e : Error) {
}
len = 0;
return;
};
/* Each Elementary Audio Stream segment MUST signal the timestamp of
its first sample with an ID3 PRIV tag [ID3] at the beginning of
the segment. The ID3 PRIV owner identifier MUST be
"com.apple.streaming.transportStreamTimestamp". The ID3 payload
MUST be a 33-bit MPEG-2 Program Elementary Stream timestamp
expressed as a big-endian eight-octet number, with the upper 31
bits set to zero.
*/
private function _parseID3Frames(data : ByteArray, endPos : uint) : void {
while(data.position + 8 <= endPos) {
var tag_id : String = data.readUTFBytes(4);
var tag_len : int = data.readUnsignedInt();
var tag_flags : int = data.readUnsignedShort();
CONFIG::LOGGING {
Log.debug("ID3 tag id:" + tag_id);
}
switch(tag_id) {
case "PRIV":
// owner should be "com.apple.streaming.transportStreamTimestamp"
if (data.readUTFBytes(44) == 'com.apple.streaming.transportStreamTimestamp') {
// smelling even better ! we found the right descriptor
// skip null character (string end) + 3 first bytes
data.position += 4;
// timestamp is 33 bit expressed as a big-endian eight-octet number, with the upper 31 bits set to zero.
var pts_33_bit : int = data.readUnsignedByte() & 0x1;
hasTimestamp = true;
timestamp = (data.readUnsignedInt() / 90);
if (pts_33_bit) {
timestamp += 47721858.84; // 2^32 / 90
}
CONFIG::LOGGING {
Log.debug("ID3 timestamp found:" + timestamp);
}
}
break;
default:
var tag_data : *;
var firstChar : String = tag_id.charAt(0);
if(firstChar == 'T' || firstChar == 'W') {
tag_data = new Array();
var cur_tag_pos : int;
var end_tag_pos : int = data.position + tag_len;
// skip character encoding byte
data.position++;
while(data.position < end_tag_pos - 1) {
cur_tag_pos = data.position;
var text : String = data.readUTFBytes(end_tag_pos-cur_tag_pos);
CONFIG::LOGGING {
Log.debug("text:" + text);
}
data.position = cur_tag_pos + text.length + 1;
tag_data.push(text);
}
data.position = end_tag_pos;
} else {
tag_data = new ByteArray();
data.readBytes(tag_data, 0, tag_len);
}
tags.push(new ID3Tag(tag_id,tag_flags,tag_data));
break;
}
}
}
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls.demux {
import flash.utils.ByteArray;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
public class ID3 {
public var len : int;
public var hasTimestamp : Boolean = false;
public var timestamp : Number;
public var tags : Vector.<ID3Tag> = new Vector.<ID3Tag>();
/* create ID3 object by parsing ByteArray, looking for ID3 tag length, and timestamp */
public function ID3(data : ByteArray) {
var tagSize : uint = 0;
try {
var pos : uint = data.position;
var header : String;
do {
header = data.readUTFBytes(3);
if (header == 'ID3') {
// skip 24 bits
data.position += 3;
// retrieve tag(s) length
var byte1 : uint = data.readUnsignedByte() & 0x7f;
var byte2 : uint = data.readUnsignedByte() & 0x7f;
var byte3 : uint = data.readUnsignedByte() & 0x7f;
var byte4 : uint = data.readUnsignedByte() & 0x7f;
tagSize = (byte1 << 21) + (byte2 << 14) + (byte3 << 7) + byte4;
var endPos : uint = data.position + tagSize;
CONFIG::LOGGING {
Log.debug2("ID3 tag found, size/end pos:" + tagSize + "/" + endPos);
}
// read ID3 tags
_parseID3Frames(data, endPos);
data.position = endPos;
} else if (header == '3DI') {
// http://id3.org/id3v2.4.0-structure chapter 3.4. ID3v2 footer
data.position += 7;
CONFIG::LOGGING {
Log.debug2("3DI footer found, end pos:" + data.position);
}
} else {
data.position -= 3;
len = data.position - pos;
CONFIG::LOGGING {
if (len) {
Log.debug2("ID3 len:" + len);
if (!hasTimestamp) {
Log.warn("ID3 tag found, but no timestamp");
}
}
}
return;
}
} while (true);
} catch(e : Error) {
}
len = 0;
return;
};
/* Each Elementary Audio Stream segment MUST signal the timestamp of
its first sample with an ID3 PRIV tag [ID3] at the beginning of
the segment. The ID3 PRIV owner identifier MUST be
"com.apple.streaming.transportStreamTimestamp". The ID3 payload
MUST be a 33-bit MPEG-2 Program Elementary Stream timestamp
expressed as a big-endian eight-octet number, with the upper 31
bits set to zero.
*/
private function _parseID3Frames(data : ByteArray, endPos : uint) : void {
while(data.position + 8 <= endPos) {
var tag_id : String = data.readUTFBytes(4);
var tag_len : int = data.readUnsignedInt();
var tag_flags : int = data.readUnsignedShort();
CONFIG::LOGGING {
Log.debug("ID3 tag id:" + tag_id);
}
switch(tag_id) {
case "PRIV":
// owner should be "com.apple.streaming.transportStreamTimestamp"
if (data.readUTFBytes(44) == 'com.apple.streaming.transportStreamTimestamp') {
// smelling even better ! we found the right descriptor
// skip null character (string end) + 3 first bytes
data.position += 4;
// timestamp is 33 bit expressed as a big-endian eight-octet number, with the upper 31 bits set to zero.
var pts_33_bit : int = data.readUnsignedByte() & 0x1;
hasTimestamp = true;
timestamp = (data.readUnsignedInt() / 90);
if (pts_33_bit) {
timestamp += 47721858.84; // 2^32 / 90
}
timestamp = Math.round(timestamp);
CONFIG::LOGGING {
Log.debug("ID3 timestamp found:" + timestamp);
}
}
break;
default:
var tag_data : *;
var firstChar : String = tag_id.charAt(0);
if(firstChar == 'T' || firstChar == 'W') {
tag_data = new Array();
var cur_tag_pos : int;
var end_tag_pos : int = data.position + tag_len;
// skip character encoding byte
data.position++;
while(data.position < end_tag_pos - 1) {
cur_tag_pos = data.position;
var text : String = data.readUTFBytes(end_tag_pos-cur_tag_pos);
CONFIG::LOGGING {
Log.debug("text:" + text);
}
data.position = cur_tag_pos + text.length + 1;
tag_data.push(text);
}
data.position = end_tag_pos;
} else {
tag_data = new ByteArray();
data.readBytes(tag_data, 0, tag_len);
}
tags.push(new ID3Tag(tag_id,tag_flags,tag_data));
break;
}
}
}
}
}
|
fix multiple FRAGMENT_PLAYING event sent with audio only playlists round timestamp so that METADATA tag PTS is similar to first AAC tag PTS
|
fix multiple FRAGMENT_PLAYING event sent with audio only playlists
round timestamp so that METADATA tag PTS is similar to first AAC tag PTS
|
ActionScript
|
mpl-2.0
|
Peer5/flashls,Peer5/flashls,dighan/flashls,Corey600/flashls,Corey600/flashls,codex-corp/flashls,fixedmachine/flashls,hola/flashls,thdtjsdn/flashls,JulianPena/flashls,neilrackett/flashls,vidible/vdb-flashls,neilrackett/flashls,tedconf/flashls,mangui/flashls,vidible/vdb-flashls,fixedmachine/flashls,tedconf/flashls,clappr/flashls,Boxie5/flashls,aevange/flashls,NicolasSiver/flashls,NicolasSiver/flashls,Peer5/flashls,hola/flashls,dighan/flashls,aevange/flashls,JulianPena/flashls,jlacivita/flashls,thdtjsdn/flashls,loungelogic/flashls,Peer5/flashls,clappr/flashls,aevange/flashls,aevange/flashls,loungelogic/flashls,Boxie5/flashls,jlacivita/flashls,mangui/flashls,codex-corp/flashls
|
3f0bddf871c9434c21a9385e2164180de4eacc94
|
src/aerys/minko/scene/controller/mesh/MeshController.as
|
src/aerys/minko/scene/controller/mesh/MeshController.as
|
package aerys.minko.scene.controller.mesh
{
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.math.Matrix4x4;
public final class MeshController extends AbstractController
{
private var _data : DataProvider;
private var _worldToLocal : Matrix4x4;
public function MeshController()
{
super(Mesh);
_worldToLocal = new Matrix4x4();
}
private function targetAddedHandler(ctrl : MeshController,
target : Mesh) : void
{
target.addedToScene.add(targetAddedToSceneHandler);
}
private function targetAddedToSceneHandler(target : Mesh,
scene : Scene) : void
{
_data = new DataProvider();
_data.setProperty('localToWorld', target.getLocalToWorldTransform());
_data.setProperty('worldToLocal', target.getWorldToLocalTransform(_worldToLocal));
target.bindings.addProvider(_data);
target.localToWorldTransformChanged.add(localToWorldChangedHandler);
}
private function localToWorldChangedHandler(mesh : Mesh, localToWorld : Matrix4x4) : void
{
_data.setProperty('localToWorld', localToWorld);
_data.setProperty('worldToLocal', _worldToLocal.copyFrom(localToWorld).invert());
}
}
}
|
package aerys.minko.scene.controller.mesh
{
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.math.Matrix4x4;
public final class MeshController extends AbstractController
{
private var _data : DataProvider;
private var _worldToLocal : Matrix4x4;
public function MeshController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
_worldToLocal = new Matrix4x4();
targetAdded.add(targetAddedHandler);
}
private function targetAddedHandler(ctrl : MeshController,
target : Mesh) : void
{
target.addedToScene.add(targetAddedToSceneHandler);
target.removedFromScene.add(targetRemovedFromSceneHandler);
}
private function targetAddedToSceneHandler(target : Mesh,
scene : Scene) : void
{
_data = new DataProvider();
_data.setProperty('localToWorld', target.getLocalToWorldTransform());
_data.setProperty('worldToLocal', target.getWorldToLocalTransform(_worldToLocal));
target.bindings.addProvider(_data);
target.localToWorldTransformChanged.add(localToWorldChangedHandler);
}
private function targetRemovedFromSceneHandler(target : Mesh,
scene : Scene) : void
{
target.localToWorldTransformChanged.remove(localToWorldChangedHandler);
target.bindings.removeProvider(_data);
_data = null;
}
private function localToWorldChangedHandler(mesh : Mesh, localToWorld : Matrix4x4) : void
{
_data.setProperty('localToWorld', localToWorld);
_data.setProperty('worldToLocal', _worldToLocal.copyFrom(localToWorld).invert());
}
}
}
|
fix missing init. of MeshController
|
fix missing init. of MeshController
|
ActionScript
|
mit
|
aerys/minko-as3
|
361d5aeb6178f5a57af9a2dbfa6eae8db7139191
|
src/as/com/threerings/flash/video/SimpleVideoDisplay.as
|
src/as/com/threerings/flash/video/SimpleVideoDisplay.as
|
//
// $Id#
package com.threerings.flash.video {
import flash.display.DisplayObject;
import flash.display.Graphics;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.geom.Rectangle;
import com.threerings.util.Log;
import com.threerings.util.ValueEvent;
/**
*
* @eventType com.threerings.flash.video.VideoPlayerCodes.SIZE
*/
[Event(name="size", type="com.threerings.util.ValueEvent")]
/**
* A simple video display.
*/
public class SimpleVideoDisplay extends Sprite
{
public static const NATIVE_WIDTH :int = 320;
public static const NATIVE_HEIGHT :int = 240;
/**
* Create a video displayer.
*/
public function SimpleVideoDisplay (player :VideoPlayer)
{
_player = player;
_player.addEventListener(VideoPlayerCodes.STATE, handlePlayerState);
_player.addEventListener(VideoPlayerCodes.SIZE, handlePlayerSize);
_player.addEventListener(VideoPlayerCodes.DURATION, handlePlayerDuration);
_player.addEventListener(VideoPlayerCodes.POSITION, handlePlayerPosition);
_player.addEventListener(VideoPlayerCodes.ERROR, handlePlayerError);
addChild(_player.getDisplay());
_mask = new Shape();
this.mask = _mask;
addChild(_mask);
addEventListener(MouseEvent.ROLL_OVER, handleRollOver);
addEventListener(MouseEvent.ROLL_OUT, handleRollOut);
_hud = new Sprite();
_hud.addEventListener(MouseEvent.CLICK, handleClick);
redrawHUD();
// create the mask...
var g :Graphics = _mask.graphics;
g.clear();
g.beginFill(0xFFFFFF);
g.drawRect(0, 0, NATIVE_WIDTH, NATIVE_HEIGHT);
g.endFill();
g = this.graphics;
g.beginFill(0xFF000000);
g.drawRect(0, 0, NATIVE_WIDTH, NATIVE_HEIGHT);
g.endFill();
// and update the HUD location (even if not currently showing)
_hud.x = NATIVE_WIDTH/2;
_hud.y = NATIVE_HEIGHT/2;
_track = new Sprite();
_track.x = PAD - _hud.x;
_track.y = NATIVE_HEIGHT - PAD - TRACK_HEIGHT - _hud.y;
g = _track.graphics;
g.beginFill(0x000000, .7);
g.drawRect(0, 0, TRACK_WIDTH, TRACK_HEIGHT);
g.endFill();
g.lineStyle(2, 0xFFFFFF);
g.drawRect(0, 0, TRACK_WIDTH, TRACK_HEIGHT);
// _track is not added to _hud until we know the duration
const trackMask :Shape = new Shape();
g = trackMask.graphics;
g.beginFill(0xFFFFFF);
g.drawRect(0, 0, TRACK_WIDTH, TRACK_HEIGHT);
_track.addChild(trackMask);
_track.mask = trackMask;
_knob = new Sprite();
_knob.y = TRACK_HEIGHT / 2;
g = _knob.graphics;
g.lineStyle(1, 0xFFFFFF);
g.beginFill(0x000099);
g.drawCircle(0, 0, TRACK_HEIGHT/2 - 1);
// _knob is not added to _track until we know the position
_track.addEventListener(MouseEvent.CLICK, handleTrackClick);
_knob.addEventListener(MouseEvent.MOUSE_DOWN, handleKnobDown);
}
/**
* Stop playing our video.
*/
public function unload () :void
{
_player.unload();
}
protected function handleRollOver (event :MouseEvent) :void
{
showHUD(true);
}
protected function handleRollOut (event :MouseEvent) :void
{
showHUD(false);
}
protected function handleClick (event :MouseEvent) :void
{
// the buck stops here!
event.stopImmediatePropagation();
switch (_player.getState()) {
case VideoPlayerCodes.STATE_READY:
case VideoPlayerCodes.STATE_PAUSED:
_player.play();
break;
case VideoPlayerCodes.STATE_PLAYING:
_player.pause();
break;
default:
log.info("Click while player in unhandled state: " + _player.getState());
break;
}
}
protected function handleTrackClick (event :MouseEvent) :void
{
event.stopImmediatePropagation();
adjustSeek(event.localX);
}
protected function handleKnobDown (event :MouseEvent) :void
{
event.stopImmediatePropagation();
_dragging = true;
_knob.startDrag(false, new Rectangle(0, TRACK_HEIGHT/2, TRACK_WIDTH, 0));
addEventListener(Event.ENTER_FRAME, handleKnobSeekCheck);
addEventListener(MouseEvent.MOUSE_UP, handleKnobUp);
}
protected function handleKnobUp (event :MouseEvent) :void
{
event.stopImmediatePropagation();
_dragging = false;
_knob.stopDrag();
removeEventListener(Event.ENTER_FRAME, handleKnobSeekCheck);
removeEventListener(MouseEvent.MOUSE_UP, handleKnobUp);
handleKnobSeekCheck(null);
}
protected function handleKnobSeekCheck (event :Event) :void
{
adjustSeek(_knob.x);
}
protected function handlePlayerState (event :ValueEvent) :void
{
redrawHUD();
}
protected function handlePlayerSize (event :ValueEvent) :void
{
const size :Point = Point(event.value);
const disp :DisplayObject = _player.getDisplay();
// TODO: siggggghhhhh
// disp.scaleX = NATIVE_WIDTH / size.x;
// disp.scaleY = NATIVE_HEIGHT / size.y;
disp.width = NATIVE_WIDTH;
disp.height = NATIVE_HEIGHT;
// and, we redispatch
dispatchEvent(event);
}
protected function handlePlayerDuration (event :ValueEvent) :void
{
_hud.addChild(_track);
}
protected function handlePlayerPosition (event :ValueEvent) :void
{
if (_dragging) {
return;
}
_lastKnobX = int.MIN_VALUE;
const pos :Number = Number(event.value);
_knob.x = (pos / _player.getDuration()) * TRACK_WIDTH;
if (_knob.parent == null) {
_track.addChild(_knob);
}
}
protected function handlePlayerError (event :ValueEvent) :void
{
// TODO.. maybe just redispatch
log.warning("player error: " + event.value);
}
protected function adjustSeek (trackX :Number) :void
{
// see if we can seek to a position
const dur :Number = _player.getDuration();
if (isNaN(dur)) {
log.debug("Duration is NaN, not seeking.");
return;
}
if (trackX == _lastKnobX) {
return;
}
_lastKnobX = trackX;
var perc :Number = trackX / TRACK_WIDTH;
perc = Math.max(0, Math.min(1, perc));
log.debug("Seek", "x", trackX, "perc", perc, "pos", (perc * dur));
_player.seek(perc * dur);
}
protected function showHUD (show :Boolean) :void
{
if (show == (_hud.parent == null)) {
if (show) {
addChild(_hud);
} else {
removeChild(_hud);
}
}
}
protected function redrawHUD () :void
{
const state :int = _player.getState();
const g :Graphics = _hud.graphics;
g.clear();
if ((state != VideoPlayerCodes.STATE_READY) &&
(state != VideoPlayerCodes.STATE_PLAYING) &&
(state != VideoPlayerCodes.STATE_PAUSED)) {
// draw something loading-like
// TODO animated swf
g.beginFill(0x000033);
g.drawCircle(5, 5, 10);
g.drawCircle(-5, 5, 10);
g.drawCircle(-5, -5, 10);
g.drawCircle(5, -5, 10);
g.endFill();
return;
}
// draw a nice circle
g.beginFill(0x000000, .7);
g.drawCircle(0, 0, 20);
g.endFill();
g.lineStyle(2, 0xFFFFFF);
g.drawCircle(0, 0, 20);
if (state == VideoPlayerCodes.STATE_PLAYING) {
g.lineStyle(2, 0x00FF00);
g.moveTo(-4, -10);
g.lineTo(-4, 10);
g.moveTo(4, -10);
g.lineTo(4, 10);
} else { // READY or PAUSED
g.lineStyle(0, 0, 0);
g.beginFill(0x00FF00);
g.moveTo(-4, -10);
g.lineTo(4, 0);
g.lineTo(-4, 10);
g.lineTo(-4, -10);
g.endFill();
}
}
protected const log :Log = Log.getLog(this);
protected var _player :VideoPlayer;
protected var _hud :Sprite;
protected var _track :Sprite;
/** The seek selector knob, positioned on the hud. */
protected var _knob :Sprite;
protected var _lastKnobX :int = int.MIN_VALUE;
protected var _dragging :Boolean;
/** Our mask, also defines our boundaries for clicking. */
protected var _mask :Shape;
protected static const PAD :int = 10;
protected static const TRACK_HEIGHT :int = 20;
protected static const TRACK_WIDTH :int = NATIVE_WIDTH - (PAD * 2);
}
}
|
//
// $Id#
package com.threerings.flash.video {
import flash.display.DisplayObject;
import flash.display.Graphics;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.geom.Rectangle;
import com.threerings.util.Log;
import com.threerings.util.ValueEvent;
/**
*
* @eventType com.threerings.flash.video.VideoPlayerCodes.SIZE
*/
[Event(name="size", type="com.threerings.util.ValueEvent")]
/**
* A simple video display.
*/
public class SimpleVideoDisplay extends Sprite
{
public static const NATIVE_WIDTH :int = 320;
public static const NATIVE_HEIGHT :int = 240;
/**
* Create a video displayer.
*/
public function SimpleVideoDisplay (player :VideoPlayer)
{
_player = player;
_player.addEventListener(VideoPlayerCodes.STATE, handlePlayerState);
_player.addEventListener(VideoPlayerCodes.SIZE, handlePlayerSize);
_player.addEventListener(VideoPlayerCodes.DURATION, handlePlayerDuration);
_player.addEventListener(VideoPlayerCodes.POSITION, handlePlayerPosition);
_player.addEventListener(VideoPlayerCodes.ERROR, handlePlayerError);
addChild(_player.getDisplay());
_mask = new Shape();
this.mask = _mask;
addChild(_mask);
addEventListener(MouseEvent.ROLL_OVER, handleRollOver);
addEventListener(MouseEvent.ROLL_OUT, handleRollOut);
_hud = new Sprite();
_hud.addEventListener(MouseEvent.CLICK, handleClick);
redrawHUD();
// create the mask...
var g :Graphics = _mask.graphics;
g.clear();
g.beginFill(0xFFFFFF);
g.drawRect(0, 0, NATIVE_WIDTH, NATIVE_HEIGHT);
g.endFill();
g = this.graphics;
g.beginFill(0xFF000000);
g.drawRect(0, 0, NATIVE_WIDTH, NATIVE_HEIGHT);
g.endFill();
// and update the HUD location (even if not currently showing)
_hud.x = NATIVE_WIDTH/2;
_hud.y = NATIVE_HEIGHT/2;
_track = new Sprite();
_track.x = PAD - _hud.x;
_track.y = NATIVE_HEIGHT - PAD - TRACK_HEIGHT - _hud.y;
g = _track.graphics;
g.beginFill(0x000000, .7);
g.drawRect(0, 0, TRACK_WIDTH, TRACK_HEIGHT);
g.endFill();
g.lineStyle(2, 0xFFFFFF);
g.drawRect(0, 0, TRACK_WIDTH, TRACK_HEIGHT);
// _track is not added to _hud until we know the duration
const trackMask :Shape = new Shape();
g = trackMask.graphics;
g.beginFill(0xFFFFFF);
g.drawRect(0, 0, TRACK_WIDTH, TRACK_HEIGHT);
_track.addChild(trackMask);
_track.mask = trackMask;
_knob = new Sprite();
_knob.y = TRACK_HEIGHT / 2;
g = _knob.graphics;
g.lineStyle(1, 0xFFFFFF);
g.beginFill(0x000099);
g.drawCircle(0, 0, TRACK_HEIGHT/2 - 1);
// _knob is not added to _track until we know the position
_track.addEventListener(MouseEvent.CLICK, handleTrackClick);
_knob.addEventListener(MouseEvent.MOUSE_DOWN, handleKnobDown);
}
/**
* Stop playing our video.
*/
public function unload () :void
{
_player.unload();
}
protected function handleRollOver (event :MouseEvent) :void
{
showHUD(true);
}
protected function handleRollOut (event :MouseEvent) :void
{
showHUD(false);
}
protected function handleClick (event :MouseEvent) :void
{
// the buck stops here!
event.stopImmediatePropagation();
switch (_player.getState()) {
case VideoPlayerCodes.STATE_READY:
case VideoPlayerCodes.STATE_PAUSED:
_player.play();
break;
case VideoPlayerCodes.STATE_PLAYING:
_player.pause();
break;
default:
log.info("Click while player in unhandled state: " + _player.getState());
break;
}
}
protected function handleTrackClick (event :MouseEvent) :void
{
event.stopImmediatePropagation();
adjustSeek(event.localX);
}
protected function handleKnobDown (event :MouseEvent) :void
{
event.stopImmediatePropagation();
_dragging = true;
_knob.startDrag(false, new Rectangle(0, TRACK_HEIGHT/2, TRACK_WIDTH, 0));
addEventListener(Event.ENTER_FRAME, handleKnobSeekCheck);
addEventListener(MouseEvent.MOUSE_UP, handleKnobUp);
}
protected function handleKnobUp (event :MouseEvent) :void
{
event.stopImmediatePropagation();
_dragging = false;
_knob.stopDrag();
removeEventListener(Event.ENTER_FRAME, handleKnobSeekCheck);
removeEventListener(MouseEvent.MOUSE_UP, handleKnobUp);
handleKnobSeekCheck(null);
}
protected function handleKnobSeekCheck (event :Event) :void
{
adjustSeek(_knob.x);
}
protected function handlePlayerState (event :ValueEvent) :void
{
redrawHUD();
}
protected function handlePlayerSize (event :ValueEvent) :void
{
const size :Point = Point(event.value);
const disp :DisplayObject = _player.getDisplay();
// TODO: siggggghhhhh
// disp.scaleX = NATIVE_WIDTH / size.x;
// disp.scaleY = NATIVE_HEIGHT / size.y;
disp.width = NATIVE_WIDTH;
disp.height = NATIVE_HEIGHT;
// and, we redispatch
dispatchEvent(event);
}
protected function handlePlayerDuration (event :ValueEvent) :void
{
// TODO: temporarily disabled
// _hud.addChild(_track);
}
protected function handlePlayerPosition (event :ValueEvent) :void
{
if (_dragging) {
return;
}
_lastKnobX = int.MIN_VALUE;
const pos :Number = Number(event.value);
_knob.x = (pos / _player.getDuration()) * TRACK_WIDTH;
if (_knob.parent == null) {
_track.addChild(_knob);
}
}
protected function handlePlayerError (event :ValueEvent) :void
{
// TODO.. maybe just redispatch
log.warning("player error: " + event.value);
}
protected function adjustSeek (trackX :Number) :void
{
// see if we can seek to a position
const dur :Number = _player.getDuration();
if (isNaN(dur)) {
log.debug("Duration is NaN, not seeking.");
return;
}
if (trackX == _lastKnobX) {
return;
}
_lastKnobX = trackX;
var perc :Number = trackX / TRACK_WIDTH;
perc = Math.max(0, Math.min(1, perc));
log.debug("Seek", "x", trackX, "perc", perc, "pos", (perc * dur));
_player.seek(perc * dur);
}
protected function showHUD (show :Boolean) :void
{
if (show == (_hud.parent == null)) {
if (show) {
addChild(_hud);
} else {
removeChild(_hud);
}
}
}
protected function redrawHUD () :void
{
const state :int = _player.getState();
const g :Graphics = _hud.graphics;
g.clear();
if ((state != VideoPlayerCodes.STATE_READY) &&
(state != VideoPlayerCodes.STATE_PLAYING) &&
(state != VideoPlayerCodes.STATE_PAUSED)) {
// draw something loading-like
// TODO animated swf
g.beginFill(0x000033);
g.drawCircle(5, 5, 10);
g.drawCircle(-5, 5, 10);
g.drawCircle(-5, -5, 10);
g.drawCircle(5, -5, 10);
g.endFill();
return;
}
// draw a nice circle
g.beginFill(0x000000, .7);
g.drawCircle(0, 0, 20);
g.endFill();
g.lineStyle(2, 0xFFFFFF);
g.drawCircle(0, 0, 20);
if (state == VideoPlayerCodes.STATE_PLAYING) {
g.lineStyle(2, 0x00FF00);
g.moveTo(-4, -10);
g.lineTo(-4, 10);
g.moveTo(4, -10);
g.lineTo(4, 10);
} else { // READY or PAUSED
g.lineStyle(0, 0, 0);
g.beginFill(0x00FF00);
g.moveTo(-4, -10);
g.lineTo(4, 0);
g.lineTo(-4, 10);
g.lineTo(-4, -10);
g.endFill();
}
}
protected const log :Log = Log.getLog(this);
protected var _player :VideoPlayer;
protected var _hud :Sprite;
protected var _track :Sprite;
/** The seek selector knob, positioned on the hud. */
protected var _knob :Sprite;
protected var _lastKnobX :int = int.MIN_VALUE;
protected var _dragging :Boolean;
/** Our mask, also defines our boundaries for clicking. */
protected var _mask :Shape;
protected static const PAD :int = 10;
protected static const TRACK_HEIGHT :int = 20;
protected static const TRACK_WIDTH :int = NATIVE_WIDTH - (PAD * 2);
}
}
|
Comment out the advanced controls, they're not ready for prime-time.
|
Comment out the advanced controls, they're not ready for prime-time.
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@687 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
6e98a7929526c374adc82bb9fa2d95dec1bd3fbd
|
flash/src/com/adobe/serialization/json/JSONTokenizer.as
|
flash/src/com/adobe/serialization/json/JSONTokenizer.as
|
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.serialization.json {
import ruby.internals.RubyCore;
public class JSONTokenizer {
/** The object that will get parsed from the JSON string */
private var obj:Object;
/** The JSON string to be parsed */
private var jsonString:String;
/** The current parsing location in the JSON string */
private var loc:int;
/** The current character in the JSON string during parsing */
private var ch:String;
private var rc:RubyCore;
/**
* Constructs a new JSONDecoder to parse a JSON string
* into a native object.
*
* @param s The JSON string to be converted
* into a native object
*/
public function JSONTokenizer( s:String, rc:RubyCore ) {
jsonString = s;
loc = 0;
this.rc = rc;
// prime the pump by getting the first character
nextChar();
}
/**
* Gets the next token in the input sting and advances
* the character to the next character after the token
*/
public function getNextToken():JSONToken {
var token:JSONToken = new JSONToken();
// skip any whitespace / comments since the last
// token was read
skipIgnored();
// examine the new character and see what we have...
switch ( ch ) {
case '{':
token.type = JSONTokenType.LEFT_BRACE;
token.value = '{';
nextChar();
break
case '}':
token.type = JSONTokenType.RIGHT_BRACE;
token.value = '}';
nextChar();
break
case '[':
token.type = JSONTokenType.LEFT_BRACKET;
token.value = '[';
nextChar();
break
case ']':
token.type = JSONTokenType.RIGHT_BRACKET;
token.value = ']';
nextChar();
break
case ',':
token.type = JSONTokenType.COMMA;
token.value = ',';
nextChar();
break
case ':':
token.type = JSONTokenType.COLON;
token.value = ':';
nextChar();
break;
case 't': // attempt to read true
var possibleTrue:String = "t" + nextChar() + nextChar() + nextChar();
if ( possibleTrue == "true" ) {
token.type = JSONTokenType.TRUE;
token.value = true;
nextChar();
} else {
parseError( "Expecting 'true' but found " + possibleTrue );
}
break;
case 'f': // attempt to read false
var possibleFalse:String = "f" + nextChar() + nextChar() + nextChar() + nextChar();
if ( possibleFalse == "false" ) {
token.type = JSONTokenType.FALSE;
token.value = false;
nextChar();
} else {
parseError( "Expecting 'false' but found " + possibleFalse );
}
break;
case 'n': // attempt to read null
var possibleNull:String = "n" + nextChar() + nextChar() + nextChar();
if ( possibleNull == "null" ) {
token.type = JSONTokenType.NULL;
token.value = rc.Qnil;
nextChar();
} else {
parseError( "Expecting 'null' but found " + possibleNull );
}
break;
case '"': // the start of a string
token = readString();
break;
default:
// see if we can read a number
if ( isDigit( ch ) || ch == '-' ) {
token = readNumber();
} else if ( ch == '' ) {
// check for reading past the end of the string
return null;
} else {
// not sure what was in the input string - it's not
// anything we expected
parseError( "Unexpected " + ch + " encountered" );
}
}
return token;
}
/**
* Attempts to read a string from the input string. Places
* the character location at the first character after the
* string. It is assumed that ch is " before this method is called.
*
* @return the JSONToken with the string value if a string could
* be read. Throws an error otherwise.
*/
private function readString():JSONToken {
// the token for the string we'll try to read
var token:JSONToken = new JSONToken();
token.type = JSONTokenType.STRING;
// the string to store the string we'll try to read
var string:String = "";
// advance past the first "
nextChar();
while ( ch != '"' && ch != '' ) {
// unescape the escape sequences in the string
if ( ch == '\\' ) {
// get the next character so we know what
// to unescape
nextChar();
switch ( ch ) {
case '"': // quotation mark
string += '"';
break;
case '/': // solidus
string += "/";
break;
case '\\': // reverse solidus
string += '\\';
break;
case 'b': // bell
string += '\b';
break;
case 'f': // form feed
string += '\f';
break;
case 'n': // newline
string += '\n';
break;
case 'r': // carriage return
string += '\r';
break;
case 't': // horizontal tab
string += '\t'
break;
case 'u':
// convert a unicode escape sequence
// to it's character value - expecting
// 4 hex digits
// save the characters as a string we'll convert to an int
var hexValue:String = "";
// try to find 4 hex characters
for ( var i:int = 0; i < 4; i++ ) {
// get the next character and determine
// if it's a valid hex digit or not
if ( !isHexDigit( nextChar() ) ) {
parseError( " Excepted a hex digit, but found: " + ch );
}
// valid, add it to the value
hexValue += ch;
}
// convert hexValue to an integer, and use that
// integrer value to create a character to add
// to our string.
string += String.fromCharCode( parseInt( hexValue, 16 ) );
break;
default:
// couldn't unescape the sequence, so just
// pass it through
string += '\\' + ch;
}
} else {
// didn't have to unescape, so add the character to the string
string += ch;
}
// move to the next character
nextChar();
}
// we read past the end of the string without closing it, which
// is a parse error
if ( ch == '' ) {
parseError( "Unterminated string literal" );
}
// move past the closing " in the input string
nextChar();
// attach to the string to the token so we can return it
token.value = string;
return token;
}
/**
* Attempts to read a number from the input string. Places
* the character location at the first character after the
* number.
*
* @return The JSONToken with the number value if a number could
* be read. Throws an error otherwise.
*/
private function readNumber():JSONToken {
// the token for the number we'll try to read
var token:JSONToken = new JSONToken();
token.type = JSONTokenType.NUMBER;
// the string to accumulate the number characters
// into that we'll convert to a number at the end
var input:String = "";
// check for a negative number
if ( ch == '-' ) {
input += '-';
nextChar();
}
// the number must start with a digit
if ( !isDigit( ch ) )
{
parseError( "Expecting a digit" );
}
// 0 can only be the first digit if it
// is followed by a decimal point
if ( ch == '0' )
{
input += ch;
nextChar();
// make sure no other digits come after 0
if ( isDigit( ch ) )
{
parseError( "A digit cannot immediately follow 0" );
}
// Commented out - this should only be available when "strict" is false
// // unless we have 0x which starts a hex number\
// else if ( ch == 'x' )
// {
// // include the x in the input
// input += ch;
// nextChar();
//
// // need at least one hex digit after 0x to
// // be valid
// if ( isHexDigit( ch ) )
// {
// input += ch;
// nextChar();
// }
// else
// {
// parseError( "Number in hex format require at least one hex digit after \"0x\"" );
// }
//
// // consume all of the hex values
// while ( isHexDigit( ch ) )
// {
// input += ch;
// nextChar();
// }
// }
}
else
{
// read numbers while we can
while ( isDigit( ch ) ) {
input += ch;
nextChar();
}
}
// check for a decimal value
if ( ch == '.' ) {
input += '.';
nextChar();
// after the decimal there has to be a digit
if ( !isDigit( ch ) )
{
parseError( "Expecting a digit" );
}
// read more numbers to get the decimal value
while ( isDigit( ch ) ) {
input += ch;
nextChar();
}
}
// check for scientific notation
if ( ch == 'e' || ch == 'E' )
{
input += "e"
nextChar();
// check for sign
if ( ch == '+' || ch == '-' )
{
input += ch;
nextChar();
}
// require at least one number for the exponent
// in this case
if ( !isDigit( ch ) )
{
parseError( "Scientific notation number needs exponent value" );
}
// read in the exponent
while ( isDigit( ch ) )
{
input += ch;
nextChar();
}
}
// convert the string to a number value
var num:Number = Number( input );
if ( isFinite( num ) && !isNaN( num ) ) {
token.value = num;
return token;
} else {
parseError( "Number " + num + " is not valid!" );
}
return null;
}
/**
* Reads the next character in the input
* string and advances the character location.
*
* @return The next character in the input string, or
* null if we've read past the end.
*/
private function nextChar():String {
return ch = jsonString.charAt( loc++ );
}
/**
* Advances the character location past any
* sort of white space and comments
*/
private function skipIgnored():void
{
var originalLoc:int;
// keep trying to skip whitespace and comments as long
// as we keep advancing past the original location
do
{
originalLoc = loc;
skipWhite();
skipComments();
}
while ( originalLoc != loc );
}
/**
* Skips comments in the input string, either
* single-line or multi-line. Advances the character
* to the first position after the end of the comment.
*/
private function skipComments():void {
if ( ch == '/' ) {
// Advance past the first / to find out what type of comment
nextChar();
switch ( ch ) {
case '/': // single-line comment, read through end of line
// Loop over the characters until we find
// a newline or until there's no more characters left
do {
nextChar();
} while ( ch != '\n' && ch != '' )
// move past the \n
nextChar();
break;
case '*': // multi-line comment, read until closing */
// move past the opening *
nextChar();
// try to find a trailing */
while ( true ) {
if ( ch == '*' ) {
// check to see if we have a closing /
nextChar();
if ( ch == '/') {
// move past the end of the closing */
nextChar();
break;
}
} else {
// move along, looking if the next character is a *
nextChar();
}
// when we're here we've read past the end of
// the string without finding a closing */, so error
if ( ch == '' ) {
parseError( "Multi-line comment not closed" );
}
}
break;
// Can't match a comment after a /, so it's a parsing error
default:
parseError( "Unexpected " + ch + " encountered (expecting '/' or '*' )" );
}
}
}
/**
* Skip any whitespace in the input string and advances
* the character to the first character after any possible
* whitespace.
*/
private function skipWhite():void {
// As long as there are spaces in the input
// stream, advance the current location pointer
// past them
while ( isWhiteSpace( ch ) ) {
nextChar();
}
}
/**
* Determines if a character is whitespace or not.
*
* @return True if the character passed in is a whitespace
* character
*/
private function isWhiteSpace( ch:String ):Boolean {
return ( ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' );
}
/**
* Determines if a character is a digit [0-9].
*
* @return True if the character passed in is a digit
*/
private function isDigit( ch:String ):Boolean {
return ( ch >= '0' && ch <= '9' );
}
/**
* Determines if a character is a digit [0-9].
*
* @return True if the character passed in is a digit
*/
private function isHexDigit( ch:String ):Boolean {
// get the uppercase value of ch so we only have
// to compare the value between 'A' and 'F'
var uc:String = ch.toUpperCase();
// a hex digit is a digit of A-F, inclusive ( using
// our uppercase constraint )
return ( isDigit( ch ) || ( uc >= 'A' && uc <= 'F' ) );
}
/**
* Raises a parsing error with a specified message, tacking
* on the error location and the original string.
*
* @param message The message indicating why the error occurred
*/
public function parseError( message:String ):void {
throw new JSONParseError( message, loc, jsonString );
}
}
}
|
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.serialization.json {
import ruby.internals.RubyCore;
public class JSONTokenizer {
/** The object that will get parsed from the JSON string */
private var obj:Object;
/** The JSON string to be parsed */
private var jsonString:String;
/** The current parsing location in the JSON string */
private var loc:int;
/** The current character in the JSON string during parsing */
private var ch:String;
private var rc:RubyCore;
/**
* Constructs a new JSONDecoder to parse a JSON string
* into a native object.
*
* @param s The JSON string to be converted
* into a native object
*/
public function JSONTokenizer( s:String, rc:RubyCore ) {
jsonString = s;
loc = 0;
this.rc = rc;
// prime the pump by getting the first character
nextChar();
}
/**
* Gets the next token in the input sting and advances
* the character to the next character after the token
*/
public function getNextToken():JSONToken {
var token:JSONToken = new JSONToken();
// skip any whitespace / comments since the last
// token was read
skipIgnored();
// examine the new character and see what we have...
switch ( ch ) {
case '{':
token.type = JSONTokenType.LEFT_BRACE;
token.value = '{';
nextChar();
break
case '}':
token.type = JSONTokenType.RIGHT_BRACE;
token.value = '}';
nextChar();
break
case '[':
token.type = JSONTokenType.LEFT_BRACKET;
token.value = '[';
nextChar();
break
case ']':
token.type = JSONTokenType.RIGHT_BRACKET;
token.value = ']';
nextChar();
break
case ',':
token.type = JSONTokenType.COMMA;
token.value = ',';
nextChar();
break
case ':':
token.type = JSONTokenType.COLON;
token.value = ':';
nextChar();
break;
case 't': // attempt to read true
var possibleTrue:String = "t" + nextChar() + nextChar() + nextChar();
if ( possibleTrue == "true" ) {
token.type = JSONTokenType.TRUE;
token.value = rc.Qtrue;
nextChar();
} else {
parseError( "Expecting 'true' but found " + possibleTrue );
}
break;
case 'f': // attempt to read false
var possibleFalse:String = "f" + nextChar() + nextChar() + nextChar() + nextChar();
if ( possibleFalse == "false" ) {
token.type = JSONTokenType.FALSE;
token.value = rc.Qfalse;
nextChar();
} else {
parseError( "Expecting 'false' but found " + possibleFalse );
}
break;
case 'n': // attempt to read null
var possibleNull:String = "n" + nextChar() + nextChar() + nextChar();
if ( possibleNull == "null" ) {
token.type = JSONTokenType.NULL;
token.value = rc.Qnil;
nextChar();
} else {
parseError( "Expecting 'null' but found " + possibleNull );
}
break;
case '"': // the start of a string
token = readString();
break;
default:
// see if we can read a number
if ( isDigit( ch ) || ch == '-' ) {
token = readNumber();
} else if ( ch == '' ) {
// check for reading past the end of the string
return null;
} else {
// not sure what was in the input string - it's not
// anything we expected
parseError( "Unexpected " + ch + " encountered" );
}
}
return token;
}
/**
* Attempts to read a string from the input string. Places
* the character location at the first character after the
* string. It is assumed that ch is " before this method is called.
*
* @return the JSONToken with the string value if a string could
* be read. Throws an error otherwise.
*/
private function readString():JSONToken {
// the token for the string we'll try to read
var token:JSONToken = new JSONToken();
token.type = JSONTokenType.STRING;
// the string to store the string we'll try to read
var string:String = "";
// advance past the first "
nextChar();
while ( ch != '"' && ch != '' ) {
// unescape the escape sequences in the string
if ( ch == '\\' ) {
// get the next character so we know what
// to unescape
nextChar();
switch ( ch ) {
case '"': // quotation mark
string += '"';
break;
case '/': // solidus
string += "/";
break;
case '\\': // reverse solidus
string += '\\';
break;
case 'b': // bell
string += '\b';
break;
case 'f': // form feed
string += '\f';
break;
case 'n': // newline
string += '\n';
break;
case 'r': // carriage return
string += '\r';
break;
case 't': // horizontal tab
string += '\t'
break;
case 'u':
// convert a unicode escape sequence
// to it's character value - expecting
// 4 hex digits
// save the characters as a string we'll convert to an int
var hexValue:String = "";
// try to find 4 hex characters
for ( var i:int = 0; i < 4; i++ ) {
// get the next character and determine
// if it's a valid hex digit or not
if ( !isHexDigit( nextChar() ) ) {
parseError( " Excepted a hex digit, but found: " + ch );
}
// valid, add it to the value
hexValue += ch;
}
// convert hexValue to an integer, and use that
// integrer value to create a character to add
// to our string.
string += String.fromCharCode( parseInt( hexValue, 16 ) );
break;
default:
// couldn't unescape the sequence, so just
// pass it through
string += '\\' + ch;
}
} else {
// didn't have to unescape, so add the character to the string
string += ch;
}
// move to the next character
nextChar();
}
// we read past the end of the string without closing it, which
// is a parse error
if ( ch == '' ) {
parseError( "Unterminated string literal" );
}
// move past the closing " in the input string
nextChar();
// attach to the string to the token so we can return it
token.value = string;
return token;
}
/**
* Attempts to read a number from the input string. Places
* the character location at the first character after the
* number.
*
* @return The JSONToken with the number value if a number could
* be read. Throws an error otherwise.
*/
private function readNumber():JSONToken {
// the token for the number we'll try to read
var token:JSONToken = new JSONToken();
token.type = JSONTokenType.NUMBER;
// the string to accumulate the number characters
// into that we'll convert to a number at the end
var input:String = "";
// check for a negative number
if ( ch == '-' ) {
input += '-';
nextChar();
}
// the number must start with a digit
if ( !isDigit( ch ) )
{
parseError( "Expecting a digit" );
}
// 0 can only be the first digit if it
// is followed by a decimal point
if ( ch == '0' )
{
input += ch;
nextChar();
// make sure no other digits come after 0
if ( isDigit( ch ) )
{
parseError( "A digit cannot immediately follow 0" );
}
// Commented out - this should only be available when "strict" is false
// // unless we have 0x which starts a hex number\
// else if ( ch == 'x' )
// {
// // include the x in the input
// input += ch;
// nextChar();
//
// // need at least one hex digit after 0x to
// // be valid
// if ( isHexDigit( ch ) )
// {
// input += ch;
// nextChar();
// }
// else
// {
// parseError( "Number in hex format require at least one hex digit after \"0x\"" );
// }
//
// // consume all of the hex values
// while ( isHexDigit( ch ) )
// {
// input += ch;
// nextChar();
// }
// }
}
else
{
// read numbers while we can
while ( isDigit( ch ) ) {
input += ch;
nextChar();
}
}
// check for a decimal value
if ( ch == '.' ) {
input += '.';
nextChar();
// after the decimal there has to be a digit
if ( !isDigit( ch ) )
{
parseError( "Expecting a digit" );
}
// read more numbers to get the decimal value
while ( isDigit( ch ) ) {
input += ch;
nextChar();
}
}
// check for scientific notation
if ( ch == 'e' || ch == 'E' )
{
input += "e"
nextChar();
// check for sign
if ( ch == '+' || ch == '-' )
{
input += ch;
nextChar();
}
// require at least one number for the exponent
// in this case
if ( !isDigit( ch ) )
{
parseError( "Scientific notation number needs exponent value" );
}
// read in the exponent
while ( isDigit( ch ) )
{
input += ch;
nextChar();
}
}
// convert the string to a number value
var num:Number = Number( input );
if ( isFinite( num ) && !isNaN( num ) ) {
token.value = num;
return token;
} else {
parseError( "Number " + num + " is not valid!" );
}
return null;
}
/**
* Reads the next character in the input
* string and advances the character location.
*
* @return The next character in the input string, or
* null if we've read past the end.
*/
private function nextChar():String {
return ch = jsonString.charAt( loc++ );
}
/**
* Advances the character location past any
* sort of white space and comments
*/
private function skipIgnored():void
{
var originalLoc:int;
// keep trying to skip whitespace and comments as long
// as we keep advancing past the original location
do
{
originalLoc = loc;
skipWhite();
skipComments();
}
while ( originalLoc != loc );
}
/**
* Skips comments in the input string, either
* single-line or multi-line. Advances the character
* to the first position after the end of the comment.
*/
private function skipComments():void {
if ( ch == '/' ) {
// Advance past the first / to find out what type of comment
nextChar();
switch ( ch ) {
case '/': // single-line comment, read through end of line
// Loop over the characters until we find
// a newline or until there's no more characters left
do {
nextChar();
} while ( ch != '\n' && ch != '' )
// move past the \n
nextChar();
break;
case '*': // multi-line comment, read until closing */
// move past the opening *
nextChar();
// try to find a trailing */
while ( true ) {
if ( ch == '*' ) {
// check to see if we have a closing /
nextChar();
if ( ch == '/') {
// move past the end of the closing */
nextChar();
break;
}
} else {
// move along, looking if the next character is a *
nextChar();
}
// when we're here we've read past the end of
// the string without finding a closing */, so error
if ( ch == '' ) {
parseError( "Multi-line comment not closed" );
}
}
break;
// Can't match a comment after a /, so it's a parsing error
default:
parseError( "Unexpected " + ch + " encountered (expecting '/' or '*' )" );
}
}
}
/**
* Skip any whitespace in the input string and advances
* the character to the first character after any possible
* whitespace.
*/
private function skipWhite():void {
// As long as there are spaces in the input
// stream, advance the current location pointer
// past them
while ( isWhiteSpace( ch ) ) {
nextChar();
}
}
/**
* Determines if a character is whitespace or not.
*
* @return True if the character passed in is a whitespace
* character
*/
private function isWhiteSpace( ch:String ):Boolean {
return ( ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' );
}
/**
* Determines if a character is a digit [0-9].
*
* @return True if the character passed in is a digit
*/
private function isDigit( ch:String ):Boolean {
return ( ch >= '0' && ch <= '9' );
}
/**
* Determines if a character is a digit [0-9].
*
* @return True if the character passed in is a digit
*/
private function isHexDigit( ch:String ):Boolean {
// get the uppercase value of ch so we only have
// to compare the value between 'A' and 'F'
var uc:String = ch.toUpperCase();
// a hex digit is a digit of A-F, inclusive ( using
// our uppercase constraint )
return ( isDigit( ch ) || ( uc >= 'A' && uc <= 'F' ) );
}
/**
* Raises a parsing error with a specified message, tacking
* on the error location and the original string.
*
* @param message The message indicating why the error occurred
*/
public function parseError( message:String ):void {
throw new JSONParseError( message, loc, jsonString );
}
}
}
|
Add Qfalse and Qtrue support to tokenizer.
|
Add Qfalse and Qtrue support to tokenizer.
|
ActionScript
|
mit
|
jonathanbranam/redsun,jonathanbranam/redsun,jonathanbranam/redsun,jonathanbranam/redsun
|
3b1b48b74289870d6999ba2f863e7fa806802fd7
|
src/aerys/minko/render/material/phong/PhongProperties.as
|
src/aerys/minko/render/material/phong/PhongProperties.as
|
package aerys.minko.render.material.phong
{
public final class PhongProperties
{
public static const RECEPTION_MASK : String = 'lightReceptionMask';
public static const LIGHT_MAP : String = 'lightMap';
public static const SPECULAR_MAP : String = 'specularMap';
public static const HEIGHT_MAP : String = 'heightMap';
public static const LIGHTMAP_MULTIPLIER : String = 'lightMapMultiplier';
public static const AMBIENT_MULTIPLIER : String = 'ambientMultiplier';
public static const DIFFUSE_MULTIPLIER : String = 'aiffuseMultiplier';
public static const SPECULAR : String = 'specular';
public static const SHININESS : String = 'shininess';
public static const NORMAL_MAPPING_TYPE : String = 'normalMappingType';
public static const NORMAL_MAP : String = 'normalMap';
public static const NORMAL_MAP_FILTERING : String = 'normalMapFiltering';
public static const NORMAL_MAP_MIPMAPPING : String = 'normalMapMipMapping';
public static const NORMAL_MAP_FORMAT : String = 'normalMapFormat';
public static const PARALLAX_MAPPING_NBSTEPS : String = 'parallaxMappingNbSteps';
public static const PARALLAX_MAPPING_BUMP_SCALE : String = 'parallaxMappingBumpScale';
public static const SHADOW_BIAS : String = 'shadowBias';
public static const CAST_SHADOWS : String = 'castShadows';
public static const RECEIVE_SHADOWS : String = 'receiveShadows';
}
}
|
package aerys.minko.render.material.phong
{
public final class PhongProperties
{
public static const RECEPTION_MASK : String = 'lightReceptionMask';
public static const LIGHT_MAP : String = 'lightMap';
public static const SPECULAR_MAP : String = 'specularMap';
public static const HEIGHT_MAP : String = 'heightMap';
public static const LIGHTMAP_MULTIPLIER : String = 'lightMapMultiplier';
public static const AMBIENT_MULTIPLIER : String = 'ambientMultiplier';
public static const DIFFUSE_MULTIPLIER : String = 'diffuseMultiplier';
public static const SPECULAR : String = 'specular';
public static const SHININESS : String = 'shininess';
public static const NORMAL_MAPPING_TYPE : String = 'normalMappingType';
public static const NORMAL_MAP : String = 'normalMap';
public static const NORMAL_MAP_FILTERING : String = 'normalMapFiltering';
public static const NORMAL_MAP_MIPMAPPING : String = 'normalMapMipMapping';
public static const NORMAL_MAP_FORMAT : String = 'normalMapFormat';
public static const PARALLAX_MAPPING_NBSTEPS : String = 'parallaxMappingNbSteps';
public static const PARALLAX_MAPPING_BUMP_SCALE : String = 'parallaxMappingBumpScale';
public static const SHADOW_BIAS : String = 'shadowBias';
public static const CAST_SHADOWS : String = 'castShadows';
public static const RECEIVE_SHADOWS : String = 'receiveShadows';
}
}
|
fix typo
|
fix typo
|
ActionScript
|
mit
|
aerys/minko-as3
|
7f727252e5475cd06187cf0d7d1d2c9bf80dfcf7
|
dolly-framework/src/main/actionscript/dolly/Copier.as
|
dolly-framework/src/main/actionscript/dolly/Copier.as
|
package dolly {
import dolly.core.dolly_internal;
import dolly.core.metadata.MetadataName;
import org.as3commons.reflect.Accessor;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.IMetadataContainer;
import org.as3commons.reflect.Type;
import org.as3commons.reflect.Variable;
use namespace dolly_internal;
public class Copier {
private static function isVariableCopyable(variable:Variable, skipMetadataChecking:Boolean = true):Boolean {
return !variable.isStatic && (skipMetadataChecking || variable.hasMetadata(MetadataName.COPYABLE));
}
private static function isAccessorCopyable(accessor:Accessor, skipMetadataChecking:Boolean = true):Boolean {
return !accessor.isStatic && accessor.isReadable() && accessor.isWriteable() &&
(skipMetadataChecking || accessor.hasMetadata(MetadataName.COPYABLE));
}
dolly_internal static function findCopyableFieldsForType(type:Type):Vector.<Field> {
const result:Vector.<Field> = new Vector.<Field>();
var variable:Variable;
var accessor:Accessor;
const isTypeCloneable:Boolean = type.hasMetadata(MetadataName.COPYABLE);
if (isTypeCloneable) {
for each(variable in type.variables) {
if (isVariableCopyable(variable)) {
result.push(variable);
}
}
for each(accessor in type.accessors) {
if (isAccessorCopyable(accessor)) {
result.push(accessor);
}
}
} else {
const metadataContainers:Array = type.getMetadataContainers(MetadataName.COPYABLE);
for each(var metadataContainer:IMetadataContainer in metadataContainers) {
if (metadataContainer is Variable) {
variable = metadataContainer as Variable;
if (isVariableCopyable(variable, false)) {
result.push(variable);
}
} else if (metadataContainer is Accessor) {
accessor = metadataContainer as Accessor;
if (isAccessorCopyable(accessor, false)) {
result.push(accessor);
}
}
}
}
return result;
}
public static function copy(source:*):* {
const type:Type = Type.forInstance(source);
const copy:* = new (type.clazz)();
const fieldsToCopy:Vector.<Field> = findCopyableFieldsForType(type);
var name:String;
for each(var field:Field in fieldsToCopy) {
name = field.name;
copy[name] = source[name];
}
return copy;
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import dolly.core.metadata.MetadataName;
import org.as3commons.reflect.Accessor;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.IMetadataContainer;
import org.as3commons.reflect.Type;
import org.as3commons.reflect.Variable;
use namespace dolly_internal;
public class Copier {
private static function isAccessorCopyable(accessor:Accessor, skipMetadataChecking:Boolean = true):Boolean {
return !accessor.isStatic && accessor.isReadable() && accessor.isWriteable() &&
(skipMetadataChecking || accessor.hasMetadata(MetadataName.COPYABLE));
}
dolly_internal static function findCopyableFieldsForType(type:Type):Vector.<Field> {
const result:Vector.<Field> = new Vector.<Field>();
var variable:Variable;
var accessor:Accessor;
const isTypeCloneable:Boolean = type.hasMetadata(MetadataName.COPYABLE);
if (isTypeCloneable) {
for each(variable in type.variables) {
if (!variable.isStatic) {
result.push(variable);
}
}
for each(accessor in type.accessors) {
if (isAccessorCopyable(accessor)) {
result.push(accessor);
}
}
} else {
const metadataContainers:Array = type.getMetadataContainers(MetadataName.COPYABLE);
for each(var metadataContainer:IMetadataContainer in metadataContainers) {
if (metadataContainer is Variable) {
variable = metadataContainer as Variable;
if (!variable.isStatic && variable.hasMetadata(MetadataName.COPYABLE)) {
result.push(variable);
}
} else if (metadataContainer is Accessor) {
accessor = metadataContainer as Accessor;
if (isAccessorCopyable(accessor, false)) {
result.push(accessor);
}
}
}
}
return result;
}
public static function copy(source:*):* {
const type:Type = Type.forInstance(source);
const copy:* = new (type.clazz)();
const fieldsToCopy:Vector.<Field> = findCopyableFieldsForType(type);
var name:String;
for each(var field:Field in fieldsToCopy) {
name = field.name;
copy[name] = source[name];
}
return copy;
}
}
}
|
Remove private static method Copier.isVariableCopyable().
|
Remove private static method Copier.isVariableCopyable().
|
ActionScript
|
mit
|
Yarovoy/dolly
|
0f9cafac8f3cb7e5a4ad51c02b9936474e7529ff
|
src/org/swiftsuspenders/typedescriptions/MethodInjectionPoint.as
|
src/org/swiftsuspenders/typedescriptions/MethodInjectionPoint.as
|
/*
* Copyright (c) 2012 the original author or authors
*
* Permission is hereby granted to use, modify, and distribute this file
* in accordance with the terms of the license agreement accompanying it.
*/
package org.swiftsuspenders.typedescriptions
{
import avmplus.getQualifiedClassName;
import flash.utils.Dictionary;
import org.swiftsuspenders.Injector;
import org.swiftsuspenders.errors.InjectorMissingMappingError;
import org.swiftsuspenders.dependencyproviders.DependencyProvider;
import org.swiftsuspenders.utils.SsInternal;
public class MethodInjectionPoint extends InjectionPoint
{
//---------------------- Private / Protected Properties ----------------------//
private static const _parameterValues : Array = [];
protected var _parameterMappingIDs : Array;
protected var _requiredParameters : int;
private var _isOptional : Boolean;
private var _methodName : String;
//---------------------- Public Methods ----------------------//
public function MethodInjectionPoint(methodName : String, parameters : Array,
requiredParameters : uint, isOptional : Boolean, injectParameters : Dictionary)
{
_methodName = methodName;
_parameterMappingIDs = parameters;
_requiredParameters = requiredParameters;
_isOptional = isOptional;
this.injectParameters = injectParameters;
}
override public function applyInjection(
target : Object, targetType : Class, injector : Injector) : void
{
var p : Array = gatherParameterValues(target, targetType, injector);
if (p.length >= _requiredParameters)
{
(target[_methodName] as Function).apply(target, p);
}
p.length = 0;
}
//---------------------- Private / Protected Methods ----------------------//
protected function gatherParameterValues(
target : Object, targetType : Class, injector : Injector) : Array
{
var length : int = _parameterMappingIDs.length;
var parameters : Array = _parameterValues;
parameters.length = length;
for (var i : int = 0; i < length; i++)
{
var parameterMappingId : String = _parameterMappingIDs[i];
var provider : DependencyProvider =
injector.SsInternal::getProvider(parameterMappingId);
if (!provider)
{
if (i >= _requiredParameters || _isOptional)
{
break;
}
throw(new InjectorMissingMappingError(
'Injector is missing a mapping to handle injection into target "' +
target + '" of type "' + getQualifiedClassName(targetType) + '". \
Target dependency: ' + parameterMappingId +
', method: ' + _methodName + ', parameter: ' + (i + 1)
));
}
parameters[i] = provider.apply(targetType, injector, injectParameters);
}
return parameters;
}
}
}
|
/*
* Copyright (c) 2012 the original author or authors
*
* Permission is hereby granted to use, modify, and distribute this file
* in accordance with the terms of the license agreement accompanying it.
*/
package org.swiftsuspenders.typedescriptions
{
import avmplus.getQualifiedClassName;
import flash.utils.Dictionary;
import org.swiftsuspenders.Injector;
import org.swiftsuspenders.errors.InjectorMissingMappingError;
import org.swiftsuspenders.dependencyproviders.DependencyProvider;
import org.swiftsuspenders.utils.SsInternal;
public class MethodInjectionPoint extends InjectionPoint
{
//---------------------- Private / Protected Properties ----------------------//
protected var _parameterMappingIDs : Array;
protected var _requiredParameters : int;
private var _isOptional : Boolean;
private var _methodName : String;
//---------------------- Public Methods ----------------------//
public function MethodInjectionPoint(methodName : String, parameters : Array,
requiredParameters : uint, isOptional : Boolean, injectParameters : Dictionary)
{
_methodName = methodName;
_parameterMappingIDs = parameters;
_requiredParameters = requiredParameters;
_isOptional = isOptional;
this.injectParameters = injectParameters;
}
override public function applyInjection(
target : Object, targetType : Class, injector : Injector) : void
{
var p : Array = gatherParameterValues(target, targetType, injector);
if (p.length >= _requiredParameters)
{
(target[_methodName] as Function).apply(target, p);
}
p.length = 0;
}
//---------------------- Private / Protected Methods ----------------------//
protected function gatherParameterValues(
target : Object, targetType : Class, injector : Injector) : Array
{
var length : int = _parameterMappingIDs.length;
var parameters : Array = [];
parameters.length = length;
for (var i : int = 0; i < length; i++)
{
var parameterMappingId : String = _parameterMappingIDs[i];
var provider : DependencyProvider =
injector.SsInternal::getProvider(parameterMappingId);
if (!provider)
{
if (i >= _requiredParameters || _isOptional)
{
break;
}
throw(new InjectorMissingMappingError(
'Injector is missing a mapping to handle injection into target "' +
target + '" of type "' + getQualifiedClassName(targetType) + '". \
Target dependency: ' + parameterMappingId +
', method: ' + _methodName + ', parameter: ' + (i + 1)
));
}
parameters[i] = provider.apply(targetType, injector, injectParameters);
}
return parameters;
}
}
}
|
Fix for a bug in MethodInjectionPoint
|
Fix for a bug in MethodInjectionPoint
The global Array _parameterValues was incorrectly shared between
reentrant calls to MethodInjectionPoint.applyInjection, thus losing
some dependencies for injection.
|
ActionScript
|
mit
|
LordXaoca/SwiftSuspenders,rshiue/swiftsuspenders,robotlegs/swiftsuspenders,robotlegs/swiftsuspenders,rshiue/swiftsuspenders,tschneidereit/SwiftSuspenders,tschneidereit/SwiftSuspenders,LordXaoca/SwiftSuspenders
|
1c8859f2835abea5deb42bb5b5218ee561b95ab4
|
FlexUnit4/src/flex/lang/reflect/builders/MethodBuilder.as
|
FlexUnit4/src/flex/lang/reflect/builders/MethodBuilder.as
|
/**
* Copyright (c) 2010 Digital Primates
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* @author Michael Labriola
* @version
**/
package flex.lang.reflect.builders {
import flash.utils.Dictionary;
import flex.lang.reflect.Method;
import flex.lang.reflect.cache.ClassDataCache;
import flex.lang.reflect.utils.MetadataTools;
/**
* Object responsible for building method objects
*
* @author mlabriola
*
*/
public class MethodBuilder {
/**
* @private
*/
private var classXML:XML;
/**
* @private
*/
private var inheritance:Array;
/**
* @private
*/
private var methodMap:Object;
/**
* @private
*/
private function buildMethod( methodData:XML, isStatic:Boolean ):Method {
return new Method( methodData, isStatic );
}
/**
* @private
*/
private function buildMethods( parentBlock:XML, isStatic:Boolean = false ):Array {
var methods:Array = new Array();
var methodList:XMLList = new XMLList();
if ( parentBlock ) {
methodList = MetadataTools.getMethodsList( parentBlock );
}
for ( var i:int=0; i<methodList.length(); i++ ) {
methods.push( buildMethod( methodList[ i ], isStatic ) );
}
return methods;
}
/**
* @private
*/
private function addMetaDataToMethod( subClassMethod:Method, superClassMethod:Method ):void {
var subMetaDataArray:Array = subClassMethod.metadata;
var superMetaDataArray:Array = superClassMethod.metadata;
for ( var i:int=0; i<superMetaDataArray.length; i++ ) {
subMetaDataArray.push( superMetaDataArray[ i ] );
}
}
/**
* @private
*/
private function addMetaDataPerSuperClass( methodMap:Object, superXML:XML ):void {
var methods:Array;
var superMethod:Method;
var instanceMethod:Method;
if ( superXML.factory ) {
methods = buildMethods( superXML.factory[ 0 ], false );
for ( var i:int=0; i<methods.length; i++ ) {
superMethod = methods[ i ] as Method;
instanceMethod = methodMap[ superMethod.name ];
if ( instanceMethod ) {
//This one exists in the subclass, meaning it was overriden
//Time to apply any metadata to the subclass method
addMetaDataToMethod( instanceMethod, superMethod );
}
}
}
}
/**
* Builds all Methods in this class, considering methods defined or overriden in this class and through inheritance
* @return An array of Method instances
*
*/
public function buildAllMethods():Array {
var methods:Array = new Array();
var method:Method;
if ( classXML.factory ) {
methods = methods.concat( buildMethods( classXML.factory[ 0 ], false ) );
}
methods = methods.concat( buildMethods( classXML, true ) );
//If this object inherits from a class other than just Object
if ( inheritance && ( inheritance.length > 1 ) ) {
//Record all of these methods in an object so that we can check the inheritance hierarchy
for ( var i:int=0; i<methods.length; i++ ) {
method = methods[ i ] as Method;
methodMap[ method.name ] = method;
}
for ( var j:int=0; j<inheritance.length; j++ ) {
addMetaDataPerSuperClass( methodMap, ClassDataCache.describeType( inheritance[ j ] ) );
}
}
return methods;
}
/**
* Resposible for building method instances from XML descriptions
* @param classXML
* @param inheritance
*
*/
public function MethodBuilder( classXML:XML, inheritance:Array ) {
this.classXML = classXML;
this.inheritance = inheritance;
methodMap = new Object();
}
}
}
|
/**
* Copyright (c) 2010 Digital Primates
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* @author Michael Labriola
* @version
**/
package flex.lang.reflect.builders {
import flash.utils.Dictionary;
import flex.lang.reflect.Method;
import flex.lang.reflect.cache.ClassDataCache;
import flex.lang.reflect.utils.MetadataTools;
/**
* Object responsible for building method objects
*
* @author mlabriola
*
*/
public class MethodBuilder {
/**
* @private
*/
private var classXML:XML;
/**
* @private
*/
private var inheritance:Array;
/**
* @private
*/
private var methodMap:Object;
/**
* @private
*/
private function buildMethod( methodData:XML, isStatic:Boolean ):Method {
return new Method( methodData, isStatic );
}
/**
* @private
*/
private function buildMethods( parentBlock:XML, isStatic:Boolean = false ):Array {
var methods:Array = new Array();
var methodList:XMLList = new XMLList();
if ( parentBlock ) {
methodList = MetadataTools.getMethodsList( parentBlock );
}
for ( var i:int=0; i<methodList.length(); i++ ) {
methods.push( buildMethod( methodList[ i ], isStatic ) );
}
return methods;
}
/**
* @private
*/
private function addMetaDataToMethod( subClassMethod:Method, superClassMethod:Method ):void {
var subMetaDataArray:Array = subClassMethod.metadata;
var superMetaDataArray:Array = superClassMethod.metadata;
for ( var i:int=0; i<superMetaDataArray.length; i++ ) {
subMetaDataArray.push( superMetaDataArray[ i ] );
}
}
/**
* @private
*/
private function addMetaDataPerSuperClass( methodMap:Object, superXML:XML ):void {
var methods:Array;
var superMethod:Method;
var instanceMethod:Method;
if ( superXML.factory ) {
methods = buildMethods( superXML.factory[ 0 ], false );
for ( var i:int=0; i<methods.length; i++ ) {
superMethod = methods[ i ] as Method;
instanceMethod = methodMap[ superMethod.name ];
if ( instanceMethod ) {
//This one exists in the subclass, meaning it was overriden
//Time to apply any metadata to the subclass method
addMetaDataToMethod( instanceMethod, superMethod );
}
}
}
}
/**
* Builds all Methods in this class, considering methods defined or overriden in this class and through inheritance
* @return An array of Method instances
*
*/
public function buildAllMethods():Array {
var methods:Array = new Array();
var method:Method;
if ( classXML.factory ) {
methods = methods.concat( buildMethods( classXML.factory[ 0 ], false ) );
}
methods = methods.concat( buildMethods( classXML, true ) );
//If this object inherits from a class other than just Object
if ( inheritance && ( inheritance.length > 1 ) ) {
//Record all of these methods in an object so that we can check the inheritance hierarchy
for ( var i:int=0; i<methods.length; i++ ) {
method = methods[ i ] as Method;
methodMap[ method.name ] = method;
}
for ( var j:int=0; j<inheritance.length; j++ ) {
if ( inheritance[ j ] != Object ) {
addMetaDataPerSuperClass( methodMap, ClassDataCache.describeType( inheritance[ j ] ) );
}
}
}
return methods;
}
/**
* Resposible for building method instances from XML descriptions
* @param classXML
* @param inheritance
*
*/
public function MethodBuilder( classXML:XML, inheritance:Array ) {
this.classXML = classXML;
this.inheritance = inheritance;
methodMap = new Object();
}
}
}
|
Fix for release mode swfs
|
Fix for release mode swfs
|
ActionScript
|
apache-2.0
|
apache/flex-flexunit,SlavaRa/flex-flexunit,apache/flex-flexunit,SlavaRa/flex-flexunit,apache/flex-flexunit,apache/flex-flexunit,SlavaRa/flex-flexunit,SlavaRa/flex-flexunit
|
086e18d77510440f453a098504a8c67c639f5245
|
src/avm2/tests/regress/correctness/pass/default.as
|
src/avm2/tests/regress/correctness/pass/default.as
|
function foo(a = 1, b = 2, c = 3) {
return a + b + c;
}
trace(foo(1));
|
function car(a = 1, b = 2) {
return a + b;
}
trace(car(1));
function foo(a = 1, b = 2, c = 3) {
return a + b + c;
}
trace(foo(1));
function bar(a = 1, b = 2, c = 3, d = 4) {
return a + b + c + d;
}
trace(bar(1));
|
Update test case.
|
Update test case.
|
ActionScript
|
apache-2.0
|
yurydelendik/shumway,mbebenita/shumway,mozilla/shumway,mozilla/shumway,mozilla/shumway,tschneidereit/shumway,tschneidereit/shumway,yurydelendik/shumway,yurydelendik/shumway,mbebenita/shumway,mbebenita/shumway,mozilla/shumway,mozilla/shumway,yurydelendik/shumway,yurydelendik/shumway,mbebenita/shumway,mbebenita/shumway,tschneidereit/shumway,tschneidereit/shumway,tschneidereit/shumway,tschneidereit/shumway,yurydelendik/shumway,mbebenita/shumway,mbebenita/shumway,mozilla/shumway,mozilla/shumway,mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway,mozilla/shumway,yurydelendik/shumway,tschneidereit/shumway
|
8ac8a8c6ea5eb828252c89e332e7440109ac9817
|
src/as/com/threerings/parlor/game/client/FlexGameConfigurator.as
|
src/as/com/threerings/parlor/game/client/FlexGameConfigurator.as
|
//
// $Id$
//
// Vilya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/vilya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.parlor.game.client {
import mx.core.Container;
import mx.core.UIComponent;
import mx.containers.Grid;
import mx.containers.GridItem;
import mx.containers.GridRow;
import mx.containers.HBox;
import com.threerings.parlor.game.data.GameConfig;
import com.threerings.parlor.util.ParlorContext;
/**
* Provides the base from which interfaces can be built to configure games prior to starting them.
* Derived classes would extend the base configurator adding interface elements and wiring them up
* properly to allow the user to configure an instance of their game.
*
* <p> Clients that use the game configurator will want to instantiate one based on the class
* returned from the {@link GameConfig} and then initialize it with a call to {@link #init}.
*/
public /*abstract*/ class FlexGameConfigurator extends GameConfigurator
{
/**
* Configures the number of columns to use when laying out our controls. This must be called
* before any calls to {@link #addControl}.
*/
public function setColumns (columns :int) :void
{
_columns = columns;
}
/**
* Get the Container that contains the UI elements for this configurator.
*/
public function getContainer () :Container
{
return _grid;
}
/**
* Add a control to the interface. This should be the standard way that configurator controls
* are added, but note also that external entities may add their own controls that are related
* to the game, but do not directly alter the game config, so that all the controls are added
* in a uniform manner and are well aligned.
*/
public function addControl (label :UIComponent, control :UIComponent) :void
{
if (_gridRow == null) {
_gridRow = new GridRow();
_grid.addChild(_gridRow);
}
_gridRow.addChild(wrapItem(label));
_gridRow.addChild(wrapItem(control));
if (_gridRow.numChildren == _columns * 2) {
_gridRow = null;
}
}
protected function wrapItem (component :UIComponent) :GridItem
{
var item :GridItem = new GridItem();
item.addChild(component);
return item;
}
/** The grid on which the config options are placed. */
protected var _grid :Grid = new Grid();
/** The current row to which we're adding controls. */
protected var _gridRow :GridRow;
/** The number of columns in which to lay out our configuration. */
protected var _columns :int = 2;
}
}
|
//
// $Id$
//
// Vilya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/vilya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.parlor.game.client {
import mx.core.Container;
import mx.core.UIComponent;
import mx.containers.Grid;
import mx.containers.GridRow;
import mx.containers.HBox;
import com.threerings.flex.GridUtil;
import com.threerings.parlor.game.data.GameConfig;
import com.threerings.parlor.util.ParlorContext;
/**
* Provides the base from which interfaces can be built to configure games prior to starting them.
* Derived classes would extend the base configurator adding interface elements and wiring them up
* properly to allow the user to configure an instance of their game.
*
* <p> Clients that use the game configurator will want to instantiate one based on the class
* returned from the {@link GameConfig} and then initialize it with a call to {@link #init}.
*/
public /*abstract*/ class FlexGameConfigurator extends GameConfigurator
{
/**
* Configures the number of columns to use when laying out our controls. This must be called
* before any calls to {@link #addControl}.
*/
public function setColumns (columns :int) :void
{
_columns = columns;
}
/**
* Get the Container that contains the UI elements for this configurator.
*/
public function getContainer () :Container
{
return _grid;
}
/**
* Add a control to the interface. This should be the standard way that configurator controls
* are added, but note also that external entities may add their own controls that are related
* to the game, but do not directly alter the game config, so that all the controls are added
* in a uniform manner and are well aligned.
*/
public function addControl (label :UIComponent, control :UIComponent) :void
{
if (_gridRow == null) {
_gridRow = new GridRow();
_grid.addChild(_gridRow);
}
GridUtil.addToRow(_gridRow, label);
GridUtil.addToRow(_gridRow, control);
if (_gridRow.numChildren == _columns * 2) {
_gridRow = null;
}
}
/** The grid on which the config options are placed. */
protected var _grid :Grid = new Grid();
/** The current row to which we're adding controls. */
protected var _gridRow :GridRow;
/** The number of columns in which to lay out our configuration. */
protected var _columns :int = 2;
}
}
|
Use GridUtil.
|
Use GridUtil.
git-svn-id: a3e1eb16dde062992de22c830ed8045c8013209a@496 c613c5cb-e716-0410-b11b-feb51c14d237
|
ActionScript
|
lgpl-2.1
|
threerings/vilya,threerings/vilya
|
755ed103ec7efe5110e353642502f1734666d04f
|
frameworks/projects/Binding/as/src/org/apache/flex/binding/ConstantBinding.as
|
frameworks/projects/Binding/as/src/org/apache/flex/binding/ConstantBinding.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.binding
{
import org.apache.flex.core.IBead;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IDocument;
/**
* The ConstantBinding class is lightweight data-binding class that
* is optimized for simple assignments of one object's constant to
* another object's property.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class ConstantBinding implements IBead, IDocument
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function ConstantBinding()
{
}
/**
* The source object who's property has the value we want.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected var source:Object;
/**
* The host mxml document for the source and
* destination objects. The source object
* is either this document for simple bindings
* like {foo} where foo is a property on
* the mxml documnet, or found as document[sourceID]
* for simple bindings like {someid.someproperty}
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected var document:Object;
/**
* The destination object. It is always the same
* as the strand. ConstantBindings are attached to
* the strand of the destination object.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var destination:Object;
/**
* If not null, the id of the mxml tag who's property
* is being watched for changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var sourceID:String;
/**
* If not null, the name of a property on the
* mxml document that is being watched for changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var sourcePropertyName:String;
/**
* The name of the property on the strand that
* is set when the source property changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var destinationPropertyName:String;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
if (destination == null)
destination = value;
if (sourceID != null)
source = document[sourceID];
else
source = document;
var val:*;
try
{
val = source[sourcePropertyName];
destination[destinationPropertyName] = val;
}
catch (e:Error)
{
try {
val = source.constructor[sourcePropertyName];
destination[destinationPropertyName] = val;
}
catch (e2:Error)
{
}
}
}
/**
* @copy org.apache.flex.core.IDocument#setDocument()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function setDocument(document:Object, id:String = null):void
{
this.document = document;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.binding
{
import org.apache.flex.core.IBead;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IDocument;
/**
* The ConstantBinding class is lightweight data-binding class that
* is optimized for simple assignments of one object's constant to
* another object's property.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class ConstantBinding implements IBead, IDocument
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function ConstantBinding()
{
}
/**
* The source object who's property has the value we want.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected var source:Object;
/**
* The host mxml document for the source and
* destination objects. The source object
* is either this document for simple bindings
* like {foo} where foo is a property on
* the mxml documnet, or found as document[sourceID]
* for simple bindings like {someid.someproperty}
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected var document:Object;
/**
* The destination object. It is always the same
* as the strand. ConstantBindings are attached to
* the strand of the destination object.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var destination:Object;
/**
* If not null, the id of the mxml tag who's property
* is being watched for changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var sourceID:String;
/**
* If not null, the name of a property on the
* mxml document that is being watched for changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var sourcePropertyName:String;
/**
* The name of the property on the strand that
* is set when the source property changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var destinationPropertyName:String;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
if (destination == null)
destination = value;
if (sourceID != null)
source = document[sourceID];
else
source = document;
var val:*;
if (sourcePropertyName in source)
{
try {
val = source[sourcePropertyName];
destination[destinationPropertyName] = val;
}
catch (e:Error)
{
}
}
else if (sourcePropertyName in source.constructor)
{
try {
val = source.constructor[sourcePropertyName];
destination[destinationPropertyName] = val;
}
catch (e2:Error)
{
}
}
}
/**
* @copy org.apache.flex.core.IDocument#setDocument()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function setDocument(document:Object, id:String = null):void
{
this.document = document;
}
}
}
|
use 'in' since a missing property won't always throw
|
use 'in' since a missing property won't always throw
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
250ef712d3bba79191d5ae7f4612d391c78f52f8
|
as3/smartform/src/com/rpath/raf/views/CompoundInputItem.as
|
as3/smartform/src/com/rpath/raf/views/CompoundInputItem.as
|
/*
#
# Copyright (c) 2009 rPath, Inc.
#
# This program is distributed under the terms of the MIT License as found
# in a file called LICENSE. If it is not present, the license
# is always available at http://www.opensource.org/licenses/mit-license.php.
#
# This program is distributed in the hope that it will be useful, but
# without any warranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the MIT License for full details.
*/
package com.rpath.raf.views
{
import mx.core.UIComponent;
import mx.events.ValidationResultEvent;
import spark.components.Group;
public class CompoundInputItem extends Group
{
public function CompoundInputItem()
{
super();
// force height computation
minHeight = 0;
}
[Bindable]
public var inputFields:Array;
public override function validationResultHandler(event:ValidationResultEvent):void
{
// let our specific input controls mark themselves appropriately
for each (var elem:UIComponent in inputFields)
{
elem.validationResultHandler(event);
}
// propagate events beyond ourselves
super.validationResultHandler(event);
}
}
}
|
/*
#
# Copyright (c) 2009 rPath, Inc.
#
# This program is distributed under the terms of the MIT License as found
# in a file called LICENSE. If it is not present, the license
# is always available at http://www.opensource.org/licenses/mit-license.php.
#
# This program is distributed in the hope that it will be useful, but
# without any warranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the MIT License for full details.
*/
package com.rpath.raf.views
{
import mx.core.UIComponent;
import mx.events.ValidationResultEvent;
import spark.components.Group;
public class CompoundInputItem extends Group
{
public function CompoundInputItem()
{
super();
// force height computation
minHeight = 0;
}
[Bindable]
public var inputFields:Array;
public override function validationResultHandler(event:ValidationResultEvent):void
{
// let our specific input controls mark themselves appropriately
for each (var elem:UIComponent in inputFields)
{
if (elem)
elem.validationResultHandler(event);
}
// propagate events beyond ourselves
super.validationResultHandler(event);
}
}
}
|
Handle null in validation elem iteration
|
Handle null in validation elem iteration
|
ActionScript
|
apache-2.0
|
sassoftware/smartform
|
a29d9651bd38f9266c609600e76fda90f4743ed9
|
frameworks/projects/mobilecomponents/src/spark/components/MobileBusyIndicator.as
|
frameworks/projects/mobilecomponents/src/spark/components/MobileBusyIndicator.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 components
{
import flash.events.Event;
import mx.core.IUIComponent;
import mx.core.IVisualElement;
import mx.events.FlexEvent;
import mx.states.State;
import spark.components.supportClasses.SkinnableComponent;
[SkinState("rotatingState")]
[SkinState("notRotatingState")]
public class MobileBusyIndicator extends SkinnableComponent
{
private var effectiveVisibility:Boolean = false;
private var effectiveVisibilityChanged:Boolean = true;
public function BusyIndicator()
{
super();
// Listen to added to stage and removed from stage.
// Start rotating when we are on the stage and stop
// when we are removed from the stage.
addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
addEventListener(Event.REMOVED_FROM_STAGE, removedFromStageHandler);
states = [
new State({name:"notRotatingState"}),
new State({name:"rotatingState"})
];
}
override protected function getCurrentSkinState():String
{
return currentState;
}
private function addedToStageHandler(event:Event):void
{
// Check our visibility here since we haven't added
// visibility listeners yet.
computeEffectiveVisibility();
if (canRotate())
currentState = "rotatingState";
addVisibilityListeners();
invalidateSkinState();
}
private function removedFromStageHandler(event:Event):void
{
currentState = "notRotatingState";
removeVisibilityListeners();
invalidateSkinState();
}
private function computeEffectiveVisibility():void
{
// Check our design layer first.
if (designLayer && !designLayer.effectiveVisibility)
{
effectiveVisibility = false;
return;
}
// Start out with true visibility and enablement
// then loop up parent-chain to see if any of them are false.
effectiveVisibility = true;
var current:IVisualElement = this;
while (current)
{
if (!current.visible)
{
if (!(current is IUIComponent) || !IUIComponent(current).isPopUp)
{
// Treat all pop ups as if they were visible. This is to
// fix a bug where the BusyIndicator does not spin when it
// is inside modal popup. The problem is in we do not get
// an event when the modal window is made visible in
// PopUpManagerImpl.fadeInEffectEndHandler(). When the modal
// window is made visible, setVisible() is passed "true" so
// as to not send an event. When do get events when the
// non-modal windows are popped up. Only modal windows are
// a problem.
// The downside of this fix is BusyIndicator components that are
// inside of hidden, non-modal, popup windows will paint themselves
// on a timer.
effectiveVisibility = false;
break;
}
}
current = current.parent as IVisualElement;
}
}
/**
* The BusyIndicator can be rotated if it is both on the display list and
* visible.
*
* @returns true if the BusyIndicator can be rotated, false otherwise.
*/
private function canRotate():Boolean
{
if (effectiveVisibility && stage != null)
return true;
return false;
}
/**
* @private
* Add event listeners for SHOW and HIDE on all the ancestors up the parent chain.
* Adding weak event listeners just to be safe.
*/
private function addVisibilityListeners():void
{
var current:IVisualElement = this.parent as IVisualElement;
while (current)
{
// add visibility listeners to the parent
current.addEventListener(FlexEvent.HIDE, visibilityChangedHandler, false, 0, true);
current.addEventListener(FlexEvent.SHOW, visibilityChangedHandler, false, 0, true);
current = current.parent as IVisualElement;
}
}
/**
* @private
* Remove event listeners for SHOW and HIDE on all the ancestors up the parent chain.
*/
private function removeVisibilityListeners():void
{
var current:IVisualElement = this;
while (current)
{
current.removeEventListener(FlexEvent.HIDE, visibilityChangedHandler, false);
current.removeEventListener(FlexEvent.SHOW, visibilityChangedHandler, false);
current = current.parent as IVisualElement;
}
}
/**
* @private
* Event call back whenever the visibility of us or one of our ancestors
* changes
*/
private function visibilityChangedHandler(event:FlexEvent):void
{
effectiveVisibilityChanged = true;
invalidateProperties();
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package spark.components
{
import flash.events.Event;
import mx.core.IUIComponent;
import mx.core.IVisualElement;
import mx.events.FlexEvent;
import mx.states.State;
import spark.components.supportClasses.SkinnableComponent;
[SkinState("rotatingState")]
[SkinState("notRotatingState")]
public class MobileBusyIndicator extends SkinnableComponent
{
private var effectiveVisibility:Boolean = false;
private var effectiveVisibilityChanged:Boolean = true;
public function MobileBusyIndicator()
{
super();
// Listen to added to stage and removed from stage.
// Start rotating when we are on the stage and stop
// when we are removed from the stage.
addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
addEventListener(Event.REMOVED_FROM_STAGE, removedFromStageHandler);
states = [
new State({name:"notRotatingState"}),
new State({name:"rotatingState"})
];
}
override protected function getCurrentSkinState():String
{
return currentState;
}
private function addedToStageHandler(event:Event):void
{
// Check our visibility here since we haven't added
// visibility listeners yet.
computeEffectiveVisibility();
if (canRotate())
currentState = "rotatingState";
addVisibilityListeners();
invalidateSkinState();
}
private function removedFromStageHandler(event:Event):void
{
currentState = "notRotatingState";
removeVisibilityListeners();
invalidateSkinState();
}
private function computeEffectiveVisibility():void
{
// Check our design layer first.
if (designLayer && !designLayer.effectiveVisibility)
{
effectiveVisibility = false;
return;
}
// Start out with true visibility and enablement
// then loop up parent-chain to see if any of them are false.
effectiveVisibility = true;
var current:IVisualElement = this;
while (current)
{
if (!current.visible)
{
if (!(current is IUIComponent) || !IUIComponent(current).isPopUp)
{
// Treat all pop ups as if they were visible. This is to
// fix a bug where the BusyIndicator does not spin when it
// is inside modal popup. The problem is in we do not get
// an event when the modal window is made visible in
// PopUpManagerImpl.fadeInEffectEndHandler(). When the modal
// window is made visible, setVisible() is passed "true" so
// as to not send an event. When do get events when the
// non-modal windows are popped up. Only modal windows are
// a problem.
// The downside of this fix is BusyIndicator components that are
// inside of hidden, non-modal, popup windows will paint themselves
// on a timer.
effectiveVisibility = false;
break;
}
}
current = current.parent as IVisualElement;
}
}
/**
* The BusyIndicator can be rotated if it is both on the display list and
* visible.
*
* @returns true if the BusyIndicator can be rotated, false otherwise.
*/
private function canRotate():Boolean
{
if (effectiveVisibility && stage != null)
return true;
return false;
}
/**
* @private
* Add event listeners for SHOW and HIDE on all the ancestors up the parent chain.
* Adding weak event listeners just to be safe.
*/
private function addVisibilityListeners():void
{
var current:IVisualElement = this.parent as IVisualElement;
while (current)
{
// add visibility listeners to the parent
current.addEventListener(FlexEvent.HIDE, visibilityChangedHandler, false, 0, true);
current.addEventListener(FlexEvent.SHOW, visibilityChangedHandler, false, 0, true);
current = current.parent as IVisualElement;
}
}
/**
* @private
* Remove event listeners for SHOW and HIDE on all the ancestors up the parent chain.
*/
private function removeVisibilityListeners():void
{
var current:IVisualElement = this;
while (current)
{
current.removeEventListener(FlexEvent.HIDE, visibilityChangedHandler, false);
current.removeEventListener(FlexEvent.SHOW, visibilityChangedHandler, false);
current = current.parent as IVisualElement;
}
}
/**
* @private
* Event call back whenever the visibility of us or one of our ancestors
* changes
*/
private function visibilityChangedHandler(event:FlexEvent):void
{
effectiveVisibilityChanged = true;
invalidateProperties();
}
}
}
|
Fix package name of spark/components/MobileBusyIndicator.as Fix constructor name
|
Fix package name of spark/components/MobileBusyIndicator.as
Fix constructor name
|
ActionScript
|
apache-2.0
|
adufilie/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk
|
282e0c5177e4bcf16e8594d9d97d97b2d63dd94c
|
ImpetusSound.as
|
ImpetusSound.as
|
package io.github.jwhile.impetus
{
import flash.media.Sound;
import flash.media.SoundChannel;
public class ImpetusSound
{
private var url:String;
private var sound:Sound;
private var channels:Vector.<SoundChannel>;
public function ImpetusSound(url:String):void
{
this.url = url;
this.sound = new Sound();
this.channels = new Vector.<SoundChannel>;
}
}
}
|
package io.github.jwhile.impetus
{
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.net.URLRequest;
public class ImpetusSound
{
private var sound:Sound;
private var channels:Vector.<SoundChannel>;
public function ImpetusSound(url:String):void
{
this.sound = new Sound();
this.channels = new Vector.<SoundChannel>;
this.sound.load(new URLRequest(url));
}
}
}
|
Load sound directly on constructor
|
Load sound directly on constructor
|
ActionScript
|
mit
|
Julow/Impetus
|
8ed3b54ba6602edb30de68b31f854f25d5dd2e0a
|
src/aerys/minko/render/shader/compiler/graph/nodes/leaf/Constant.as
|
src/aerys/minko/render/shader/compiler/graph/nodes/leaf/Constant.as
|
package aerys.minko.render.shader.compiler.graph.nodes.leaf
{
import aerys.minko.render.shader.compiler.CRC32;
import aerys.minko.render.shader.compiler.Serializer;
import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode;
/**
* @private
* @author Romain Gilliotte
*
*/
public class Constant extends AbstractNode
{
private var _value : Vector.<Number>
public function get value() : Vector.<Number>
{
return _value;
}
public function set value(v : Vector.<Number>) : void
{
_value = v;
}
public function Constant(value : Vector.<Number>)
{
super(new <AbstractNode>[], new <uint>[]);
_value = value;
}
override protected function computeSize() : uint
{
return _value.length;
}
override protected function computeHash() : uint
{
return CRC32.computeForNumberVector(_value);
}
override public function toString() : String
{
return 'Constant';
}
override public function clone() : AbstractNode
{
return new Constant(_value.slice());
}
}
}
|
package aerys.minko.render.shader.compiler.graph.nodes.leaf
{
import aerys.minko.render.shader.compiler.CRC32;
import aerys.minko.render.shader.compiler.Serializer;
import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode;
/**
* @private
* @author Romain Gilliotte
*
*/
public class Constant extends AbstractNode
{
private var _value : Vector.<Number>;
public function get value() : Vector.<Number>
{
return _value;
}
public function set value(v : Vector.<Number>) : void
{
_value = v;
}
public function Constant(value : Vector.<Number>)
{
super(new <AbstractNode>[], new <uint>[]);
_value = value;
}
override protected function computeSize() : uint
{
return _value.length;
}
override protected function computeHash() : uint
{
return CRC32.computeForNumberVector(_value);
}
override public function toString() : String
{
return 'Constant';
}
override public function clone() : AbstractNode
{
return new Constant(_value.slice());
}
}
}
|
fix missing ;
|
fix missing ;
|
ActionScript
|
mit
|
aerys/minko-as3
|
a6a587dcb1036ab6da6dd051b6a674b19086758b
|
src/flash/utils/Timer.as
|
src/flash/utils/Timer.as
|
package flash.utils
{
import flash.events.*;
[Event(name = "timerComplete", type = "flash.events.TimerEvent")]
[Event(name = "timer", type = "flash.events.TimerEvent")]
public class Timer extends EventDispatcher
{
private var m_delay:Number;
private var m_repeatCount:int;
private var m_iteration:int;
private var intervalID:int;
public function Timer(delay:Number, repeatCount:int = 0)
{
super();
if (delay < 0 || !isFinite(delay))
{
Error.throwError(RangeError, 2066);
}
this.m_delay = delay;
this.m_repeatCount = repeatCount;
}
public function get delay():Number
{
return this.m_delay;
}
public function get repeatCount():int
{
return this.m_repeatCount;
}
public function set repeatCount(value:int):void
{
this.m_repeatCount = value;
if (this.running && this.m_repeatCount != 0 && this.m_iteration >= this.m_repeatCount)
{
this.stop();
}
}
public function get currentCount():int
{
return this.m_iteration;
}
public function get running():Boolean
{
return false;
}
public function set delay(value:Number):void
{
if (value < 0 || !isFinite(value))
{
Error.throwError(RangeError, 2066);
}
this.m_delay = value;
if (this.running)
{
this.stop();
this.start();
}
}
private function tick():void
{
this.m_iteration++;
this._timerDispatch();
if (this.m_repeatCount != 0 && this.m_iteration >= this.m_repeatCount)
{
this.stop();
dispatchEvent(new TimerEvent(TimerEvent.TIMER_COMPLETE, false, false));
}
}
public function start():void
{
if (!this.running)
{
this._start(this.m_delay, this.tick);
}
}
public function reset():void
{
if (this.running)
{
this.stop();
}
this.m_iteration = 0;
}
private function _start(m_delay:Number, m_tick:Function):void
{
intervalID=setInterval(m_tick, m_delay);
}
private function _timerDispatch():void
{
dispatchEvent(new TimerEvent(TimerEvent.TIMER));
}
public function stop():void
{
clearInterval(intervalID);
}
}
}
|
package flash.utils
{
import flash.events.*;
[Event(name = "timerComplete", type = "flash.events.TimerEvent")]
[Event(name = "timer", type = "flash.events.TimerEvent")]
public class Timer extends EventDispatcher
{
private var m_delay:Number;
private var m_repeatCount:int;
private var m_iteration:int;
private var intervalID:int;
public function Timer(delay:Number, repeatCount:int = 0)
{
super();
if (delay < 0 || !isFinite(delay))
{
Error.throwError(RangeError, 2066);
}
this.m_delay = delay;
this.m_repeatCount = repeatCount;
this.m_iteration = 0;
}
public function get delay():Number
{
return this.m_delay;
}
public function get repeatCount():int
{
return this.m_repeatCount;
}
public function set repeatCount(value:int):void
{
this.m_repeatCount = value;
if (this.running && this.m_repeatCount != 0 && this.m_iteration >= this.m_repeatCount)
{
this.stop();
}
}
public function get currentCount():int
{
return this.m_iteration;
}
public function get running():Boolean
{
return false;
}
public function set delay(value:Number):void
{
if (value < 0 || !isFinite(value))
{
Error.throwError(RangeError, 2066);
}
this.m_delay = value;
if (this.running)
{
this.stop();
this.start();
}
}
private function tick():void
{
this.m_iteration++;
this._timerDispatch();
if (this.m_repeatCount != 0 && this.m_iteration >= this.m_repeatCount)
{
this.stop();
dispatchEvent(new TimerEvent(TimerEvent.TIMER_COMPLETE, false, false));
}
}
public function start():void
{
if (!this.running)
{
this._start(this.m_delay, this.tick);
}
}
public function reset():void
{
if (this.running)
{
this.stop();
}
this.m_iteration = 0;
}
private function _start(m_delay:Number, m_tick:Function):void
{
intervalID=setInterval(m_tick, m_delay);
}
private function _timerDispatch():void
{
dispatchEvent(new TimerEvent(TimerEvent.TIMER));
}
public function stop():void
{
clearInterval(intervalID);
}
}
}
|
Fix small bug when setInterval never stops.
|
Fix small bug when setInterval never stops.
|
ActionScript
|
mit
|
matrix3d/spriteflexjs,matrix3d/spriteflexjs
|
a80620c59f41b3e749215bb0046fd1f06885cacd
|
src/aerys/minko/render/material/basic/BasicMaterial.as
|
src/aerys/minko/render/material/basic/BasicMaterial.as
|
package aerys.minko.render.material.basic
{
import aerys.minko.render.Effect;
import aerys.minko.render.material.Material;
import aerys.minko.render.resource.texture.TextureResource;
public class BasicMaterial extends Material
{
public static const DEFAULT_NAME : String = 'BasicMaterial';
public static const DEFAULT_BASIC_SHADER : BasicShader = new BasicShader();
public static const DEFAULT_EFFECT : Effect = new Effect(DEFAULT_BASIC_SHADER);
public function get blending() : uint
{
return getProperty(BasicProperties.BLENDING);
}
public function set blending(value : uint) : void
{
setProperty(BasicProperties.BLENDING, value);
}
public function get triangleCulling() : uint
{
return getProperty(BasicProperties.TRIANGLE_CULLING);
}
public function set triangleCulling(value : uint) : void
{
setProperty(BasicProperties.TRIANGLE_CULLING, value);
}
public function get diffuseColor() : uint
{
return getProperty(BasicProperties.DIFFUSE_COLOR);
}
public function set diffuseColor(value : uint) : void
{
setProperty(BasicProperties.DIFFUSE_COLOR, value);
}
public function get diffuseMap() : TextureResource
{
return getProperty(BasicProperties.DIFFUSE_MAP);
}
public function set diffuseMap(value : TextureResource) : void
{
setProperty(BasicProperties.DIFFUSE_MAP, value);
}
public function get alphaThreshold() : Number
{
return getProperty(BasicProperties.ALPHA_THRESHOLD);
}
public function set alphaThreshold(value : Number) : void
{
setProperty(BasicProperties.ALPHA_THRESHOLD, value);
}
public function get depthTest() : uint
{
return getProperty(BasicProperties.DEPTH_TEST);
}
public function set depthTest(value : uint) : void
{
setProperty(BasicProperties.DEPTH_TEST, value);
}
public function get depthWriteEnabled() : Boolean
{
return getProperty(BasicProperties.DEPTH_WRITE_ENABLED);
}
public function set depthWriteEnabled(value : Boolean) : void
{
setProperty(BasicProperties.DEPTH_WRITE_ENABLED, value);
}
public function get stencilTriangleFace() : uint
{
return getProperty(BasicProperties.STENCIL_TRIANGLE_FACE);
}
public function set stencilTriangleFace(value : uint) : void
{
setProperty(BasicProperties.STENCIL_TRIANGLE_FACE, value);
}
public function get stencilCompareMode() : uint
{
return getProperty(BasicProperties.STENCIL_COMPARE_MODE);
}
public function set stencilCompareMode(value : uint) : void
{
setProperty(BasicProperties.STENCIL_COMPARE_MODE, value);
}
public function get stencilActionBothPass() : uint
{
return getProperty(BasicProperties.STENCIL_ACTION_BOTH_PASS);
}
public function set stencilActionBothPass(value : uint) : void
{
setProperty(BasicProperties.STENCIL_ACTION_BOTH_PASS, value);
}
public function get stencilActionDepthFail() : uint
{
return getProperty(BasicProperties.STENCIL_ACTION_DEPTH_FAIL);
}
public function set stencilActionDepthFail(value : uint) : void
{
setProperty(BasicProperties.STENCIL_ACTION_DEPTH_FAIL, value);
}
public function get stencilActionDepthPassStencilFail() : uint
{
return getProperty(BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL);
}
public function set stencilActionDepthPassStencilFail(value : uint) : void
{
setProperty(BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL, value);
}
public function get stencilReferenceValue() : Number
{
return getProperty(BasicProperties.STENCIL_REFERENCE_VALUE);
}
public function set stencilReferenceValue(value : Number) : void
{
setProperty(BasicProperties.STENCIL_REFERENCE_VALUE, value);
}
public function get stencilReadMask() : uint
{
return getProperty(BasicProperties.STENCIL_READ_MASK);
}
public function set stencilReadMask(value : uint) : void
{
setProperty(BasicProperties.STENCIL_READ_MASK, value);
}
public function get stencilWriteMask() : uint
{
return getProperty(BasicProperties.STENCIL_WRITE_MASK);
}
public function set stencilWriteMask(value : uint) : void
{
setProperty(BasicProperties.STENCIL_WRITE_MASK, value);
}
public function BasicMaterial(properties : Object = null, name : String = DEFAULT_NAME)
{
super(DEFAULT_EFFECT, properties, name);
}
}
}
|
package aerys.minko.render.material.basic
{
import aerys.minko.render.Effect;
import aerys.minko.render.material.Material;
import aerys.minko.render.resource.texture.TextureResource;
public class BasicMaterial extends Material
{
public static const DEFAULT_NAME : String = 'BasicMaterial';
public static const DEFAULT_BASIC_SHADER : BasicShader = new BasicShader();
public static const DEFAULT_EFFECT : Effect = new Effect(DEFAULT_BASIC_SHADER);
public function get blending() : uint
{
return getProperty(BasicProperties.BLENDING);
}
public function set blending(value : uint) : void
{
setProperty(BasicProperties.BLENDING, value);
}
public function get triangleCulling() : uint
{
return getProperty(BasicProperties.TRIANGLE_CULLING);
}
public function set triangleCulling(value : uint) : void
{
setProperty(BasicProperties.TRIANGLE_CULLING, value);
}
public function get diffuseColor() : uint
{
return getProperty(BasicProperties.DIFFUSE_COLOR);
}
public function set diffuseColor(value : uint) : void
{
setProperty(BasicProperties.DIFFUSE_COLOR, value);
}
public function get diffuseMap() : TextureResource
{
return getProperty(BasicProperties.DIFFUSE_MAP);
}
public function set diffuseMap(value : TextureResource) : void
{
setProperty(BasicProperties.DIFFUSE_MAP, value);
}
public function get alphaThreshold() : Number
{
return getProperty(BasicProperties.ALPHA_THRESHOLD);
}
public function set alphaThreshold(value : Number) : void
{
setProperty(BasicProperties.ALPHA_THRESHOLD, value);
}
public function get depthTest() : uint
{
return getProperty(BasicProperties.DEPTH_TEST);
}
public function set depthTest(value : uint) : void
{
setProperty(BasicProperties.DEPTH_TEST, value);
}
public function get depthWriteEnabled() : Boolean
{
return getProperty(BasicProperties.DEPTH_WRITE_ENABLED);
}
public function set depthWriteEnabled(value : Boolean) : void
{
setProperty(BasicProperties.DEPTH_WRITE_ENABLED, value);
}
public function get stencilTriangleFace() : uint
{
return getProperty(BasicProperties.STENCIL_TRIANGLE_FACE);
}
public function set stencilTriangleFace(value : uint) : void
{
setProperty(BasicProperties.STENCIL_TRIANGLE_FACE, value);
}
public function get stencilCompareMode() : uint
{
return getProperty(BasicProperties.STENCIL_COMPARE_MODE);
}
public function set stencilCompareMode(value : uint) : void
{
setProperty(BasicProperties.STENCIL_COMPARE_MODE, value);
}
public function get stencilActionBothPass() : uint
{
return getProperty(BasicProperties.STENCIL_ACTION_BOTH_PASS);
}
public function set stencilActionBothPass(value : uint) : void
{
setProperty(BasicProperties.STENCIL_ACTION_BOTH_PASS, value);
}
public function get stencilActionDepthFail() : uint
{
return getProperty(BasicProperties.STENCIL_ACTION_DEPTH_FAIL);
}
public function set stencilActionDepthFail(value : uint) : void
{
setProperty(BasicProperties.STENCIL_ACTION_DEPTH_FAIL, value);
}
public function get stencilActionDepthPassStencilFail() : uint
{
return getProperty(BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL);
}
public function set stencilActionDepthPassStencilFail(value : uint) : void
{
setProperty(BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL, value);
}
public function get stencilReferenceValue() : Number
{
return getProperty(BasicProperties.STENCIL_REFERENCE_VALUE);
}
public function set stencilReferenceValue(value : Number) : void
{
setProperty(BasicProperties.STENCIL_REFERENCE_VALUE, value);
}
public function get stencilReadMask() : uint
{
return getProperty(BasicProperties.STENCIL_READ_MASK);
}
public function set stencilReadMask(value : uint) : void
{
setProperty(BasicProperties.STENCIL_READ_MASK, value);
}
public function get stencilWriteMask() : uint
{
return getProperty(BasicProperties.STENCIL_WRITE_MASK);
}
public function set stencilWriteMask(value : uint) : void
{
setProperty(BasicProperties.STENCIL_WRITE_MASK, value);
}
public function BasicMaterial(properties : Object = null, effect : Effect = null, name : String = DEFAULT_NAME)
{
super(effect || DEFAULT_EFFECT, properties, name);
}
}
}
|
add optional Effect argument to BasicMaterial constructor
|
add optional Effect argument to BasicMaterial constructor
|
ActionScript
|
mit
|
aerys/minko-as3
|
86bbdcf0ba7c7564f0eef164f20908d3b78df1e0
|
src/org/mangui/hls/HLSJS.as
|
src/org/mangui/hls/HLSJS.as
|
package org.mangui.hls
{
import flash.external.ExternalInterface;
import org.hola.ZExternalInterface;
import org.hola.JSAPI;
import org.hola.HSettings;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.constant.HLSPlayStates;
import org.mangui.hls.model.Level;
import org.mangui.hls.model.Fragment;
import flash.utils.setTimeout;
import flash.net.NetStreamAppendBytesAction;
public class HLSJS
{
private static var _inited:Boolean = false;
private static var _duration:Number;
private static var _bandwidth:Number = -1;
private static var _url:String;
private static var _state:String;
private static var _hls:HLS;
private static var _silence: Boolean = false;
public static function init():void{
if (_inited || !ZExternalInterface.avail())
return;
_inited = true;
JSAPI.init();
ExternalInterface.addCallback("hola_version", hola_version);
ExternalInterface.addCallback("hola_hls_get_video_url",
hola_hls_get_video_url);
ExternalInterface.addCallback("hola_hls_get_position",
hola_hls_get_position);
ExternalInterface.addCallback("hola_hls_get_duration",
hola_hls_get_duration);
ExternalInterface.addCallback("hola_hls_get_buffer_sec",
hola_hls_get_buffer_sec);
ExternalInterface.addCallback("hola_hls_get_state",
hola_hls_get_state);
ExternalInterface.addCallback("hola_hls_get_levels",
hola_hls_get_levels);
ExternalInterface.addCallback("hola_hls_get_levels_async",
hola_hls_get_levels_async);
ExternalInterface.addCallback("hola_hls_get_segment_info",
hola_hls_get_segment_info);
ExternalInterface.addCallback("hola_hls_get_level",
hola_hls_get_level);
ExternalInterface.addCallback("hola_hls_get_bitrate",
hola_hls_get_bitrate);
ExternalInterface.addCallback("hola_hls_get_decoded_frames",
hola_hls_get_decoded_frames);
ExternalInterface.addCallback("hola_setBandwidth",
hola_setBandwidth);
ExternalInterface.addCallback("hola_hls_get_type",
hola_hls_get_type);
ExternalInterface.addCallback("hola_hls_load_fragment", hola_hls_load_fragment);
ExternalInterface.addCallback("hola_hls_abort_fragment", hola_hls_abort_fragment);
ExternalInterface.addCallback("hola_hls_load_level", hola_hls_load_level);
ExternalInterface.addCallback('hola_hls_flush_stream', hola_hls_flush_stream);
}
public static function HLSnew(hls:HLS):void{
_hls = hls;
_state = HLSPlayStates.IDLE;
// track duration events
hls.addEventListener(HLSEvent.MANIFEST_LOADED,
on_manifest_loaded);
hls.addEventListener(HLSEvent.PLAYLIST_DURATION_UPDATED,
on_playlist_duration_updated);
// track playlist-url/state
hls.addEventListener(HLSEvent.MANIFEST_LOADING,
on_manifest_loading);
hls.addEventListener(HLSEvent.PLAYBACK_STATE, on_playback_state);
// notify js events
hls.addEventListener(HLSEvent.MANIFEST_LOADING, on_event);
hls.addEventListener(HLSEvent.MANIFEST_PARSED, on_event);
hls.addEventListener(HLSEvent.MANIFEST_LOADED, on_event);
hls.addEventListener(HLSEvent.LEVEL_LOADING, on_event);
hls.addEventListener(HLSEvent.LEVEL_LOADING_ABORTED, on_event);
hls.addEventListener(HLSEvent.LEVEL_LOADED, on_level_loaded);
hls.addEventListener(HLSEvent.LEVEL_SWITCH, on_event);
hls.addEventListener(HLSEvent.LEVEL_ENDLIST, on_event);
hls.addEventListener(HLSEvent.FRAGMENT_LOADING, on_event);
hls.addEventListener(HLSEvent.FRAGMENT_LOADED, on_event);
hls.addEventListener(HLSEvent.FRAGMENT_LOAD_EMERGENCY_ABORTED,
on_event);
hls.addEventListener(HLSEvent.FRAGMENT_PLAYING, on_event);
hls.addEventListener(HLSEvent.FRAGMENT_SKIPPED, on_event);
hls.addEventListener(HLSEvent.AUDIO_TRACKS_LIST_CHANGE, on_event);
hls.addEventListener(HLSEvent.AUDIO_TRACK_SWITCH, on_event);
hls.addEventListener(HLSEvent.AUDIO_LEVEL_LOADING, on_event);
hls.addEventListener(HLSEvent.AUDIO_LEVEL_LOADED, on_event);
hls.addEventListener(HLSEvent.TAGS_LOADED, on_event);
hls.addEventListener(HLSEvent.LAST_VOD_FRAGMENT_LOADED, on_event);
hls.addEventListener(HLSEvent.WARNING, on_event);
hls.addEventListener(HLSEvent.ERROR, on_event);
hls.addEventListener(HLSEvent.MEDIA_TIME, on_event);
hls.addEventListener(HLSEvent.PLAYBACK_STATE, on_event);
hls.addEventListener(HLSEvent.SEEK_STATE, on_event);
hls.addEventListener(HLSEvent.STREAM_TYPE_DID_CHANGE, on_event);
hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, on_event);
hls.addEventListener(HLSEvent.PLAYLIST_DURATION_UPDATED,
on_event);
hls.addEventListener(HLSEvent.ID3_UPDATED, on_event);
hls.addEventListener(HLSEvent.FPS_DROP, on_event);
hls.addEventListener(HLSEvent.FPS_DROP_LEVEL_CAPPING, on_event);
hls.addEventListener(HLSEvent.FPS_DROP_SMOOTH_LEVEL_SWITCH,
on_event);
hls.addEventListener(HLSEvent.LIVE_LOADING_STALLED, on_event);
JSAPI.postMessage('flashls.hlsNew');
}
public static function HLSdispose(hls:HLS):void{
JSAPI.postMessage('flashls.hlsDispose');
_duration = 0;
_bandwidth = -1;
_url = null;
_state = HLSPlayStates.IDLE;
_hls = null;
}
public static function get bandwidth():Number{
return HSettings.gets('mode')=='adaptive' ? _bandwidth : -1;
}
private static function on_manifest_loaded(e:HLSEvent):void{
_duration = e.levels[_hls.startLevel].duration;
}
private static function on_playlist_duration_updated(e:HLSEvent):void{
_duration = e.duration;
}
private static function on_manifest_loading(e:HLSEvent):void{
_url = e.url;
_state = "LOADING";
on_event(new HLSEvent(HLSEvent.PLAYBACK_STATE, _state));
}
private static function on_playback_state(e:HLSEvent):void{
_state = e.state;
}
private static function on_level_loaded(e: HLSEvent): void
{
JSAPI.postMessage('flashls.'+e.type, {level: level_to_object(_hls.levels[e.loadMetrics.level])});
}
private static function on_event(e:HLSEvent):void{
if (_silence)
return;
JSAPI.postMessage('flashls.'+e.type, {url: e.url, level: e.level,
duration: e.duration, levels: e.levels, error: e.error,
loadMetrics: e.loadMetrics, playMetrics: e.playMetrics,
mediatime: e.mediatime, state: e.state,
audioTrack: e.audioTrack, streamType: e.streamType});
}
private static function hola_version():Object{
return {
flashls_version: '0.4.4.20',
patch_version: '2.0.13'
};
}
private static function hola_hls_get_video_url():String{
return _url;
}
private static function hola_hls_get_position():Number{
return _hls.position;
}
private static function hola_hls_get_duration():Number{
return _duration;
}
private static function hola_hls_get_decoded_frames(): Number
{
return _hls.stream.decodedFrames;
}
private static function hola_hls_get_buffer_sec():Number{
return _hls.stream.bufferLength;
}
private static function hola_hls_get_state():String{
return _state;
}
private static function hola_hls_get_type():String{
return _hls.type;
}
private static function hola_hls_load_fragment(level: Number, frag: Number, url: String): Object
{
if (HSettings.gets('mode')!='hola_adaptive')
return 0;
return _hls.loadFragment(level, frag, url);
}
private static function hola_hls_flush_stream(): void
{
_silence = true;
_hls.stream.close();
_hls.stream.play();
_hls.stream.pause();
_silence = false;
}
private static function hola_hls_abort_fragment(ldr_id: String): void
{
if (HSettings.gets('mode')!='hola_adaptive')
return;
_hls.abortFragment(ldr_id);
}
private static function hola_hls_load_level(level: Number): void
{
if (HSettings.gets('mode')!='hola_adaptive')
return;
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_SWITCH, level));
}
private static function level_to_object(l: Level): Object
{
var fragments: Array = [];
for (var i: int = 0; i<l.fragments.length; i++)
{
var fragment: Fragment = l.fragments[i];
fragments.push({url: fragment.url,
duration: fragment.duration, seqnum: fragment.seqnum});
}
return {url: l.url, bitrate: l.bitrate, fragments: fragments,
index: l.index, width: l.width, height: l.height, audio: l.audio};
}
private static function hola_hls_get_levels():Object{
var levels:Vector.<Object> =
new Vector.<Object>(_hls.levels.length);
for (var i:int = 0; i<_hls.levels.length; i++)
{
var l:Level = _hls.levels[i];
// no fragments returned, use get_segment_info for fragm.info
levels[i] = Object({url: l.url, bitrate: l.bitrate,
index: l.index, fragments: []});
}
return levels;
}
private static function hola_hls_get_levels_async(): void
{
setTimeout(function(): void
{
var levels: Array = [];
for (var i: int = 0; i<_hls.levels.length; i++)
levels.push(level_to_object(_hls.levels[i]));
JSAPI.postMessage('flashls.hlsAsyncMessage', {type: 'get_levels', msg: levels});
}, 0);
}
private static function hola_hls_get_segment_info(url:String):Object{
for (var i:int = 0; i<_hls.levels.length; i++)
{
var l:Level = _hls.levels[i];
for (var j:int = 0; j<l.fragments.length; j++)
{
if (url==l.fragments[j].url)
{
return Object({fragment: l.fragments[j],
level: Object({url: l.url, bitrate: l.bitrate,
index: l.index})});
}
}
}
return undefined;
}
private static function hola_hls_get_bitrate(): Number
{
return _hls.loadLevel<_hls.levels.length ? _hls.levels[_hls.loadLevel].bitrate : 0;
}
private static function hola_hls_get_level(): String
{
return _hls.loadLevel<_hls.levels.length ? _hls.levels[_hls.loadLevel].url : undefined;
}
private static function hola_setBandwidth(bandwidth:Number):void{
_bandwidth = bandwidth;
}
}
}
|
package org.mangui.hls
{
import flash.external.ExternalInterface;
import org.hola.ZExternalInterface;
import org.hola.JSAPI;
import org.hola.HSettings;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.constant.HLSPlayStates;
import org.mangui.hls.model.Level;
import org.mangui.hls.model.Fragment;
import flash.utils.setTimeout;
import flash.net.NetStreamAppendBytesAction;
public class HLSJS
{
private static var _inited:Boolean = false;
private static var _duration:Number;
private static var _bandwidth:Number = -1;
private static var _url:String;
private static var _state:String;
private static var _hls:HLS;
private static var _silence: Boolean = false;
public static function init():void{
if (_inited || !ZExternalInterface.avail())
return;
_inited = true;
JSAPI.init();
ExternalInterface.addCallback("hola_version", hola_version);
ExternalInterface.addCallback("hola_hls_get_video_url",
hola_hls_get_video_url);
ExternalInterface.addCallback("hola_hls_get_position",
hola_hls_get_position);
ExternalInterface.addCallback("hola_hls_get_duration",
hola_hls_get_duration);
ExternalInterface.addCallback("hola_hls_get_buffer_sec",
hola_hls_get_buffer_sec);
ExternalInterface.addCallback("hola_hls_get_state",
hola_hls_get_state);
ExternalInterface.addCallback("hola_hls_get_levels",
hola_hls_get_levels);
ExternalInterface.addCallback("hola_hls_get_levels_async",
hola_hls_get_levels_async);
ExternalInterface.addCallback("hola_hls_get_segment_info",
hola_hls_get_segment_info);
ExternalInterface.addCallback("hola_hls_get_level",
hola_hls_get_level);
ExternalInterface.addCallback("hola_hls_get_bitrate",
hola_hls_get_bitrate);
ExternalInterface.addCallback("hola_hls_get_decoded_frames",
hola_hls_get_decoded_frames);
ExternalInterface.addCallback("hola_setBandwidth",
hola_setBandwidth);
ExternalInterface.addCallback("hola_hls_get_type",
hola_hls_get_type);
ExternalInterface.addCallback("hola_hls_load_fragment", hola_hls_load_fragment);
ExternalInterface.addCallback("hola_hls_abort_fragment", hola_hls_abort_fragment);
ExternalInterface.addCallback("hola_hls_load_level", hola_hls_load_level);
ExternalInterface.addCallback('hola_hls_flush_stream', hola_hls_flush_stream);
}
public static function HLSnew(hls:HLS):void{
_hls = hls;
_state = HLSPlayStates.IDLE;
// track duration events
hls.addEventListener(HLSEvent.MANIFEST_LOADED,
on_manifest_loaded);
hls.addEventListener(HLSEvent.PLAYLIST_DURATION_UPDATED,
on_playlist_duration_updated);
// track playlist-url/state
hls.addEventListener(HLSEvent.MANIFEST_LOADING,
on_manifest_loading);
hls.addEventListener(HLSEvent.PLAYBACK_STATE, on_playback_state);
hls.addEventListener(HLSEvent.SEEK_STATE, on_seek_state);
// notify js events
hls.addEventListener(HLSEvent.MANIFEST_LOADING, on_event);
hls.addEventListener(HLSEvent.MANIFEST_PARSED, on_event);
hls.addEventListener(HLSEvent.MANIFEST_LOADED, on_event);
hls.addEventListener(HLSEvent.LEVEL_LOADING, on_event);
hls.addEventListener(HLSEvent.LEVEL_LOADING_ABORTED, on_event);
hls.addEventListener(HLSEvent.LEVEL_LOADED, on_level_loaded);
hls.addEventListener(HLSEvent.LEVEL_SWITCH, on_event);
hls.addEventListener(HLSEvent.LEVEL_ENDLIST, on_event);
hls.addEventListener(HLSEvent.FRAGMENT_LOADING, on_event);
hls.addEventListener(HLSEvent.FRAGMENT_LOADED, on_event);
hls.addEventListener(HLSEvent.FRAGMENT_LOAD_EMERGENCY_ABORTED,
on_event);
hls.addEventListener(HLSEvent.FRAGMENT_PLAYING, on_event);
hls.addEventListener(HLSEvent.FRAGMENT_SKIPPED, on_event);
hls.addEventListener(HLSEvent.AUDIO_TRACKS_LIST_CHANGE, on_event);
hls.addEventListener(HLSEvent.AUDIO_TRACK_SWITCH, on_event);
hls.addEventListener(HLSEvent.AUDIO_LEVEL_LOADING, on_event);
hls.addEventListener(HLSEvent.AUDIO_LEVEL_LOADED, on_event);
hls.addEventListener(HLSEvent.TAGS_LOADED, on_event);
hls.addEventListener(HLSEvent.LAST_VOD_FRAGMENT_LOADED, on_event);
hls.addEventListener(HLSEvent.WARNING, on_event);
hls.addEventListener(HLSEvent.ERROR, on_event);
hls.addEventListener(HLSEvent.MEDIA_TIME, on_event);
hls.addEventListener(HLSEvent.PLAYBACK_STATE, on_event);
hls.addEventListener(HLSEvent.STREAM_TYPE_DID_CHANGE, on_event);
hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, on_event);
hls.addEventListener(HLSEvent.PLAYLIST_DURATION_UPDATED,
on_event);
hls.addEventListener(HLSEvent.ID3_UPDATED, on_event);
hls.addEventListener(HLSEvent.FPS_DROP, on_event);
hls.addEventListener(HLSEvent.FPS_DROP_LEVEL_CAPPING, on_event);
hls.addEventListener(HLSEvent.FPS_DROP_SMOOTH_LEVEL_SWITCH,
on_event);
hls.addEventListener(HLSEvent.LIVE_LOADING_STALLED, on_event);
JSAPI.postMessage('flashls.hlsNew');
}
public static function HLSdispose(hls:HLS):void{
JSAPI.postMessage('flashls.hlsDispose');
_duration = 0;
_bandwidth = -1;
_url = null;
_state = HLSPlayStates.IDLE;
_hls = null;
}
public static function get bandwidth():Number{
return HSettings.gets('mode')=='adaptive' ? _bandwidth : -1;
}
private static function on_manifest_loaded(e:HLSEvent):void{
_duration = e.levels[_hls.startLevel].duration;
}
private static function on_playlist_duration_updated(e:HLSEvent):void{
_duration = e.duration;
}
private static function on_manifest_loading(e:HLSEvent):void{
_url = e.url;
_state = "LOADING";
on_event(new HLSEvent(HLSEvent.PLAYBACK_STATE, _state));
}
private static function on_playback_state(e:HLSEvent):void{
_state = e.state;
}
private static function on_level_loaded(e: HLSEvent): void
{
JSAPI.postMessage('flashls.'+e.type, {level: level_to_object(_hls.levels[e.loadMetrics.level])});
}
private static function on_seek_state(e: HLSEvent): void
{
JSAPI.postMessage('flashls.'+e.type, {state: e.state, seek_pos: _hls.position});
}
private static function on_event(e:HLSEvent):void{
if (_silence)
return;
JSAPI.postMessage('flashls.'+e.type, {url: e.url, level: e.level,
duration: e.duration, levels: e.levels, error: e.error,
loadMetrics: e.loadMetrics, playMetrics: e.playMetrics,
mediatime: e.mediatime, state: e.state,
audioTrack: e.audioTrack, streamType: e.streamType});
}
private static function hola_version():Object{
return {
flashls_version: '0.4.4.20',
patch_version: '2.0.13'
};
}
private static function hola_hls_get_video_url():String{
return _url;
}
private static function hola_hls_get_position():Number{
return _hls.position;
}
private static function hola_hls_get_duration():Number{
return _duration;
}
private static function hola_hls_get_decoded_frames(): Number
{
return _hls.stream.decodedFrames;
}
private static function hola_hls_get_buffer_sec():Number{
return _hls.stream.bufferLength;
}
private static function hola_hls_get_state():String{
return _state;
}
private static function hola_hls_get_type():String{
return _hls.type;
}
private static function hola_hls_load_fragment(level: Number, frag: Number, url: String): Object
{
if (HSettings.gets('mode')!='hola_adaptive')
return 0;
return _hls.loadFragment(level, frag, url);
}
private static function hola_hls_flush_stream(): void
{
_silence = true;
_hls.stream.close();
_hls.stream.play();
_hls.stream.pause();
_silence = false;
}
private static function hola_hls_abort_fragment(ldr_id: String): void
{
if (HSettings.gets('mode')!='hola_adaptive')
return;
_hls.abortFragment(ldr_id);
}
private static function hola_hls_load_level(level: Number): void
{
if (HSettings.gets('mode')!='hola_adaptive')
return;
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_SWITCH, level));
}
private static function level_to_object(l: Level): Object
{
var fragments: Array = [];
for (var i: int = 0; i<l.fragments.length; i++)
{
var fragment: Fragment = l.fragments[i];
fragments.push({url: fragment.url,
duration: fragment.duration, seqnum: fragment.seqnum});
}
return {url: l.url, bitrate: l.bitrate, fragments: fragments,
index: l.index, width: l.width, height: l.height, audio: l.audio};
}
private static function hola_hls_get_levels():Object{
var levels:Vector.<Object> =
new Vector.<Object>(_hls.levels.length);
for (var i:int = 0; i<_hls.levels.length; i++)
{
var l:Level = _hls.levels[i];
// no fragments returned, use get_segment_info for fragm.info
levels[i] = Object({url: l.url, bitrate: l.bitrate,
index: l.index, fragments: []});
}
return levels;
}
private static function hola_hls_get_levels_async(): void
{
setTimeout(function(): void
{
var levels: Array = [];
for (var i: int = 0; i<_hls.levels.length; i++)
levels.push(level_to_object(_hls.levels[i]));
JSAPI.postMessage('flashls.hlsAsyncMessage', {type: 'get_levels', msg: levels});
}, 0);
}
private static function hola_hls_get_segment_info(url:String):Object{
for (var i:int = 0; i<_hls.levels.length; i++)
{
var l:Level = _hls.levels[i];
for (var j:int = 0; j<l.fragments.length; j++)
{
if (url==l.fragments[j].url)
{
return Object({fragment: l.fragments[j],
level: Object({url: l.url, bitrate: l.bitrate,
index: l.index})});
}
}
}
return undefined;
}
private static function hola_hls_get_bitrate(): Number
{
return _hls.loadLevel<_hls.levels.length ? _hls.levels[_hls.loadLevel].bitrate : 0;
}
private static function hola_hls_get_level(): String
{
return _hls.loadLevel<_hls.levels.length ? _hls.levels[_hls.loadLevel].url : undefined;
}
private static function hola_setBandwidth(bandwidth:Number):void{
_bandwidth = bandwidth;
}
}
}
|
add info about seeking_position to SEEK_STATE event
|
add info about seeking_position to SEEK_STATE event
|
ActionScript
|
mpl-2.0
|
hola/flashls,hola/flashls
|
1792496facb4d112806fec7abac828790db03812
|
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.Minko;
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.log.DebugLevel;
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
{
public static const MAX_NUM_INFLUENCES : uint = 8;
public static const MAX_NUM_JOINTS : uint = 51;
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;
}
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);
if (!_skinningHelper)
{
var numInfluences : uint = AbstractSkinningHelper.getNumInfluences(
mesh.geometry.format
);
if (_joints.length > MAX_NUM_JOINTS || numInfluences > MAX_NUM_INFLUENCES)
{
_method = SkinningMethod.SOFTWARE_MATRIX;
Minko.log(
DebugLevel.SKINNING,
'Too many influences/joints: switching to SkinningMethod.SOFTWARE.'
);
}
if (skinningMethod != SkinningMethod.SOFTWARE_MATRIX)
{
try
{
_skinningHelper = new HardwareSkinningHelper(
_method, _bindShapeMatrix, _invBindMatrices
);
}
catch (e : Error)
{
Minko.log(
DebugLevel.SKINNING,
'Falling back to software skinning: ' + e.message,
this
);
_method = SkinningMethod.SOFTWARE_MATRIX;
}
}
_skinningHelper ||= new SoftwareSkinningHelper(
_method, _bindShapeMatrix, _invBindMatrices
);
}
_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);
}
}
}
|
package aerys.minko.scene.controller.mesh.skinning
{
import aerys.minko.Minko;
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.log.DebugLevel;
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
{
public static const MAX_NUM_INFLUENCES : uint = 8;
public static const MAX_NUM_JOINTS : uint = 51;
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);
if (!skeletonRoot)
throw new Error('skeletonRoot cannot be null');
_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;
}
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);
if (!_skinningHelper)
{
var numInfluences : uint = AbstractSkinningHelper.getNumInfluences(
mesh.geometry.format
);
if (_joints.length > MAX_NUM_JOINTS || numInfluences > MAX_NUM_INFLUENCES)
{
_method = SkinningMethod.SOFTWARE_MATRIX;
Minko.log(
DebugLevel.SKINNING,
'Too many influences/joints: switching to SkinningMethod.SOFTWARE.'
);
}
if (skinningMethod != SkinningMethod.SOFTWARE_MATRIX)
{
try
{
_skinningHelper = new HardwareSkinningHelper(
_method, _bindShapeMatrix, _invBindMatrices
);
}
catch (e : Error)
{
Minko.log(
DebugLevel.SKINNING,
'Falling back to software skinning: ' + e.message,
this
);
_method = SkinningMethod.SOFTWARE_MATRIX;
}
}
_skinningHelper ||= new SoftwareSkinningHelper(
_method, _bindShapeMatrix, _invBindMatrices
);
}
_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);
}
}
}
|
throw an error when the skeletonRoot passed to SkinningController constructor is null
|
throw an error when the skeletonRoot passed to SkinningController constructor is null
|
ActionScript
|
mit
|
aerys/minko-as3
|
1424dda4080ca2cd67a723f5a7018d786c31cfa2
|
src/aerys/minko/render/material/phong/PhongEffect.as
|
src/aerys/minko/render/material/phong/PhongEffect.as
|
package aerys.minko.render.material.phong
{
import aerys.minko.render.DataBindingsProxy;
import aerys.minko.render.Effect;
import aerys.minko.render.RenderTarget;
import aerys.minko.render.resource.texture.CubeTextureResource;
import aerys.minko.render.resource.texture.ITextureResource;
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.render.shader.Shader;
import aerys.minko.scene.data.LightDataProvider;
import aerys.minko.scene.node.light.AmbientLight;
import aerys.minko.scene.node.light.DirectionalLight;
import aerys.minko.scene.node.light.PointLight;
import aerys.minko.type.enum.ShadowMappingQuality;
import aerys.minko.type.enum.ShadowMappingType;
public class PhongEffect extends Effect
{
private var _singlePassShader : Shader;
private var _baseShader : Shader;
public function PhongEffect(singlePassShader : Shader = null,
baseShader : Shader = null)
{
super();
_singlePassShader = singlePassShader || new PhongSinglePassShader(null, 0);
_baseShader = baseShader || new PhongBaseShader(null, .5);
}
override protected function initializePasses(sceneBindings : DataBindingsProxy,
meshBindings : DataBindingsProxy) : Vector.<Shader>
{
var passes : Vector.<Shader> = super.initializePasses(sceneBindings, meshBindings);
for (var lightId : uint = 0;
lightPropertyExists(sceneBindings, lightId, 'enabled');
++lightId)
{
if (lightPropertyExists(sceneBindings, lightId, 'shadowCastingType'))
{
var lightType : uint = getLightProperty(sceneBindings, lightId, 'type');
var shadowMappingType : uint = getLightProperty(
sceneBindings, lightId, 'shadowCastingType'
);
switch (shadowMappingType)
{
case ShadowMappingType.PCF:
if (lightType == PointLight.LIGHT_TYPE)
pushCubeShadowMappingPass(sceneBindings, lightId, passes);
else
pushPCFShadowMappingPass(sceneBindings, lightId, passes);
break ;
case ShadowMappingType.DUAL_PARABOLOID:
pushDualParaboloidShadowMappingPass(sceneBindings, lightId, passes);
break ;
case ShadowMappingType.VARIANCE:
pushVarianceShadowMappingPass(sceneBindings, lightId, passes);
break ;
case ShadowMappingType.EXPONENTIAL:
pushExponentialShadowMappingPass(sceneBindings, lightId, passes);
break ;
}
}
}
passes.push(_singlePassShader);
return passes;
}
override protected function initializeFallbackPasses(sceneBindings : DataBindingsProxy,
meshBindings : DataBindingsProxy) : Vector.<Shader>
{
var passes : Vector.<Shader> = super.initializeFallbackPasses(sceneBindings, meshBindings);
var discardDirectional : Boolean = true;
for (var lightId : uint = 0;
lightPropertyExists(sceneBindings, lightId, 'enabled');
++lightId)
{
var lightType : uint = getLightProperty(sceneBindings, lightId, 'type');
if (lightType != AmbientLight.LIGHT_TYPE
&& getLightProperty(sceneBindings, lightId, 'enabled'))
{
if (lightType == DirectionalLight.LIGHT_TYPE && discardDirectional)
discardDirectional = false;
else
passes.push(new PhongAdditionalShader(null, 0, lightId));
}
if (lightPropertyExists(sceneBindings, lightId, 'shadowCastingType'))
{
var shadowMappingType : uint = getLightProperty(
sceneBindings, lightId, 'shadowCastingType'
);
switch (shadowMappingType)
{
case ShadowMappingType.PCF:
if (lightType == PointLight.LIGHT_TYPE)
pushCubeShadowMappingPass(sceneBindings, lightId, passes);
else
pushPCFShadowMappingPass(sceneBindings, lightId, passes);
break ;
case ShadowMappingType.DUAL_PARABOLOID:
pushDualParaboloidShadowMappingPass(sceneBindings, lightId, passes);
break ;
case ShadowMappingType.VARIANCE:
pushVarianceShadowMappingPass(sceneBindings, lightId, passes);
break ;
case ShadowMappingType.EXPONENTIAL:
pushExponentialShadowMappingPass(sceneBindings, lightId, passes);
break ;
}
}
}
passes.push(_baseShader);
return passes;
}
private function pushPCFShadowMappingPass(sceneBindings : DataBindingsProxy,
lightId : uint,
passes : Vector.<Shader>) : void
{
var textureResource : TextureResource = getLightProperty(
sceneBindings, lightId, 'shadowMap'
);
var renderTarget : RenderTarget = new RenderTarget(
textureResource.width, textureResource.height, textureResource, 0, 0xffffffff
);
passes.push(new PCFShadowMapShader(lightId, lightId + 1, renderTarget));
}
private function pushDualParaboloidShadowMappingPass(sceneBindings : DataBindingsProxy,
lightId : uint,
passes : Vector.<Shader>) : void
{
var frontTextureResource : TextureResource = getLightProperty(
sceneBindings, lightId, 'shadowMapFront'
);
var backTextureResource : TextureResource = getLightProperty(
sceneBindings, lightId, 'shadowMapBack'
);
var size : uint = frontTextureResource.width;
var frontRenderTarget : RenderTarget = new RenderTarget(
size, size, frontTextureResource, 0, 0xffffffff
);
var backRenderTarget : RenderTarget = new RenderTarget(
size, size, backTextureResource, 0, 0xffffffff
);
passes.push(
new ParaboloidShadowMapShader(lightId, true, lightId + 0.5, frontRenderTarget),
new ParaboloidShadowMapShader(lightId, false, lightId + 1, backRenderTarget)
);
}
private function pushCubeShadowMappingPass(sceneBindings : DataBindingsProxy,
lightId : uint,
passes : Vector.<Shader>) : void
{
var cubeTexture : CubeTextureResource = getLightProperty(
sceneBindings, lightId, 'shadowMap'
);
var textureSize : uint = cubeTexture.size;
for (var i : uint = 0; i < 6; ++i)
passes.push(new PCFShadowMapShader(
lightId,
lightId + .1 * i,
new RenderTarget(textureSize, textureSize, cubeTexture, i, 0xffffffff),
i
));
}
private function pushVarianceShadowMappingPass(sceneBindings : DataBindingsProxy,
lightId : uint,
passes : Vector.<Shader>) : void
{
var lightType : uint = getLightProperty(
sceneBindings, lightId, 'type'
);
if (lightType != PointLight.LIGHT_TYPE)
{
var textureResource : ITextureResource = null;
var renderTarget : RenderTarget = null;
if (hasShadowBlurPass(sceneBindings, lightId))
textureResource = getLightProperty(sceneBindings, lightId, 'rawShadowMap');
else
textureResource = getLightProperty(sceneBindings, lightId, 'shadowMap');
renderTarget = new RenderTarget(
textureResource.width, textureResource.height, textureResource, 0, 0xffffffff
);
passes.push(new VarianceShadowMapShader(lightId, 4, lightId + 1, renderTarget));
}
else
{
var cubeTexture : CubeTextureResource = getLightProperty(
sceneBindings, lightId, 'shadowMap'
);
var textureSize : uint = cubeTexture.size;
for (var i : uint = 0; i < 6; ++i)
passes.push(new VarianceShadowMapShader(
lightId,
i,
lightId + .1 * i,
new RenderTarget(textureSize, textureSize, cubeTexture, i, 0xffffffff)
));
}
}
private function pushExponentialShadowMappingPass(sceneBindings : DataBindingsProxy,
lightId : uint,
passes : Vector.<Shader>):void
{
var lightType : uint = getLightProperty(
sceneBindings, lightId, 'type'
);
if (lightType != PointLight.LIGHT_TYPE)
{
var textureResource : ITextureResource = null;
var renderTarget : RenderTarget = null;
if (hasShadowBlurPass(sceneBindings, lightId))
textureResource = getLightProperty(sceneBindings, lightId, 'rawShadowMap');
else
textureResource = getLightProperty(sceneBindings, lightId, 'shadowMap');
renderTarget = new RenderTarget(
textureResource.width, textureResource.height, textureResource, 0, 0xffffffff
);
passes.push(new ExponentialShadowMapShader(lightId, 4, lightId + 1, renderTarget));
}
else
{
var cubeTexture : CubeTextureResource = getLightProperty(
sceneBindings, lightId, 'shadowMap'
);
var textureSize : uint = cubeTexture.size;
for (var i : uint = 0; i < 6; ++i)
passes.push(new ExponentialShadowMapShader(
lightId,
i,
lightId + .1 * i,
new RenderTarget(textureSize, textureSize, cubeTexture, i, 0xffffffff)
));
}
}
private function hasShadowBlurPass(sceneBindings : DataBindingsProxy,
lightId : uint) : Boolean
{
var quality : uint = getLightProperty(sceneBindings, lightId, 'shadowQuality');
return quality > ShadowMappingQuality.HARD;
}
private function lightPropertyExists(sceneBindings : DataBindingsProxy,
lightId : uint,
propertyName : String) : Boolean
{
return sceneBindings.propertyExists(
LightDataProvider.getLightPropertyName(propertyName, lightId)
);
}
private function getLightProperty(sceneBindings : DataBindingsProxy,
lightId : uint,
propertyName : String) : *
{
return sceneBindings.getProperty(
LightDataProvider.getLightPropertyName(propertyName, lightId)
);
}
}
}
|
package aerys.minko.render.material.phong
{
import aerys.minko.render.DataBindingsProxy;
import aerys.minko.render.Effect;
import aerys.minko.render.RenderTarget;
import aerys.minko.render.resource.texture.CubeTextureResource;
import aerys.minko.render.resource.texture.ITextureResource;
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.render.shader.Shader;
import aerys.minko.scene.data.LightDataProvider;
import aerys.minko.scene.node.light.AmbientLight;
import aerys.minko.scene.node.light.DirectionalLight;
import aerys.minko.scene.node.light.PointLight;
import aerys.minko.type.enum.ShadowMappingQuality;
import aerys.minko.type.enum.ShadowMappingType;
/**
* <p>The PhongEffect using the Phong lighting model to render the geometry according to
* the lighting setup of the scene. It supports an infinite number of lights/projected
* shadows and will automatically switch between singlepass and multipass rendering
* in order to give the best performances whenever possible.</p>
*
* </p>Because of the Stage3D restrictions regarding the number of shader operations or
* the number of available registers, the number of lights might be to big to allow them
* to be rendered in a single pass. In this situation, the PhongEffect will automatically
* fallback and use multipass rendering.</p>
*
* <p>Multipass rendering is done as follow:</p>
* <ul>
* <li>The "base" pass renders objects with one per-pixel directional lights with shadows,
* the lightmap and the ambient/emissive lighting.</li>
* <li>Each "additional" pass (one per light) will render a single light with shadows and
* blend it using additive blending.</li>
* </ul>
*
* The singlepass rendering will mimic this behavior in order to get preserve consistency.
*
* @author Jean-Marc Le Roux
*
*/
public class PhongEffect extends Effect
{
private var _singlePassShader : Shader;
private var _baseShader : Shader;
public function PhongEffect(singlePassShader : Shader = null,
baseShader : Shader = null)
{
super();
_singlePassShader = singlePassShader || new PhongSinglePassShader(null, 0);
_baseShader = baseShader || new PhongBaseShader(null, .5);
}
override protected function initializePasses(sceneBindings : DataBindingsProxy,
meshBindings : DataBindingsProxy) : Vector.<Shader>
{
var passes : Vector.<Shader> = super.initializePasses(sceneBindings, meshBindings);
for (var lightId : uint = 0;
lightPropertyExists(sceneBindings, lightId, 'enabled');
++lightId)
{
if (lightPropertyExists(sceneBindings, lightId, 'shadowCastingType'))
{
var lightType : uint = getLightProperty(sceneBindings, lightId, 'type');
var shadowMappingType : uint = getLightProperty(
sceneBindings, lightId, 'shadowCastingType'
);
switch (shadowMappingType)
{
case ShadowMappingType.PCF:
if (lightType == PointLight.LIGHT_TYPE)
pushCubeShadowMappingPass(sceneBindings, lightId, passes);
else
pushPCFShadowMappingPass(sceneBindings, lightId, passes);
break ;
case ShadowMappingType.DUAL_PARABOLOID:
pushDualParaboloidShadowMappingPass(sceneBindings, lightId, passes);
break ;
case ShadowMappingType.VARIANCE:
pushVarianceShadowMappingPass(sceneBindings, lightId, passes);
break ;
case ShadowMappingType.EXPONENTIAL:
pushExponentialShadowMappingPass(sceneBindings, lightId, passes);
break ;
}
}
}
passes.push(_singlePassShader);
return passes;
}
override protected function initializeFallbackPasses(sceneBindings : DataBindingsProxy,
meshBindings : DataBindingsProxy) : Vector.<Shader>
{
var passes : Vector.<Shader> = super.initializeFallbackPasses(sceneBindings, meshBindings);
var discardDirectional : Boolean = true;
for (var lightId : uint = 0;
lightPropertyExists(sceneBindings, lightId, 'enabled');
++lightId)
{
var lightType : uint = getLightProperty(sceneBindings, lightId, 'type');
if (lightType != AmbientLight.LIGHT_TYPE
&& getLightProperty(sceneBindings, lightId, 'enabled'))
{
if (lightType == DirectionalLight.LIGHT_TYPE && discardDirectional)
discardDirectional = false;
else
passes.push(new PhongAdditionalShader(null, 0, lightId));
}
if (lightPropertyExists(sceneBindings, lightId, 'shadowCastingType'))
{
var shadowMappingType : uint = getLightProperty(
sceneBindings, lightId, 'shadowCastingType'
);
switch (shadowMappingType)
{
case ShadowMappingType.PCF:
if (lightType == PointLight.LIGHT_TYPE)
pushCubeShadowMappingPass(sceneBindings, lightId, passes);
else
pushPCFShadowMappingPass(sceneBindings, lightId, passes);
break ;
case ShadowMappingType.DUAL_PARABOLOID:
pushDualParaboloidShadowMappingPass(sceneBindings, lightId, passes);
break ;
case ShadowMappingType.VARIANCE:
pushVarianceShadowMappingPass(sceneBindings, lightId, passes);
break ;
case ShadowMappingType.EXPONENTIAL:
pushExponentialShadowMappingPass(sceneBindings, lightId, passes);
break ;
}
}
}
passes.push(_baseShader);
return passes;
}
private function pushPCFShadowMappingPass(sceneBindings : DataBindingsProxy,
lightId : uint,
passes : Vector.<Shader>) : void
{
var textureResource : TextureResource = getLightProperty(
sceneBindings, lightId, 'shadowMap'
);
var renderTarget : RenderTarget = new RenderTarget(
textureResource.width, textureResource.height, textureResource, 0, 0xffffffff
);
passes.push(new PCFShadowMapShader(lightId, lightId + 1, renderTarget));
}
private function pushDualParaboloidShadowMappingPass(sceneBindings : DataBindingsProxy,
lightId : uint,
passes : Vector.<Shader>) : void
{
var frontTextureResource : TextureResource = getLightProperty(
sceneBindings, lightId, 'shadowMapFront'
);
var backTextureResource : TextureResource = getLightProperty(
sceneBindings, lightId, 'shadowMapBack'
);
var size : uint = frontTextureResource.width;
var frontRenderTarget : RenderTarget = new RenderTarget(
size, size, frontTextureResource, 0, 0xffffffff
);
var backRenderTarget : RenderTarget = new RenderTarget(
size, size, backTextureResource, 0, 0xffffffff
);
passes.push(
new ParaboloidShadowMapShader(lightId, true, lightId + 0.5, frontRenderTarget),
new ParaboloidShadowMapShader(lightId, false, lightId + 1, backRenderTarget)
);
}
private function pushCubeShadowMappingPass(sceneBindings : DataBindingsProxy,
lightId : uint,
passes : Vector.<Shader>) : void
{
var cubeTexture : CubeTextureResource = getLightProperty(
sceneBindings, lightId, 'shadowMap'
);
var textureSize : uint = cubeTexture.size;
for (var i : uint = 0; i < 6; ++i)
passes.push(new PCFShadowMapShader(
lightId,
lightId + .1 * i,
new RenderTarget(textureSize, textureSize, cubeTexture, i, 0xffffffff),
i
));
}
private function pushVarianceShadowMappingPass(sceneBindings : DataBindingsProxy,
lightId : uint,
passes : Vector.<Shader>) : void
{
var lightType : uint = getLightProperty(
sceneBindings, lightId, 'type'
);
if (lightType != PointLight.LIGHT_TYPE)
{
var textureResource : ITextureResource = null;
var renderTarget : RenderTarget = null;
if (hasShadowBlurPass(sceneBindings, lightId))
textureResource = getLightProperty(sceneBindings, lightId, 'rawShadowMap');
else
textureResource = getLightProperty(sceneBindings, lightId, 'shadowMap');
renderTarget = new RenderTarget(
textureResource.width, textureResource.height, textureResource, 0, 0xffffffff
);
passes.push(new VarianceShadowMapShader(lightId, 4, lightId + 1, renderTarget));
}
else
{
var cubeTexture : CubeTextureResource = getLightProperty(
sceneBindings, lightId, 'shadowMap'
);
var textureSize : uint = cubeTexture.size;
for (var i : uint = 0; i < 6; ++i)
passes.push(new VarianceShadowMapShader(
lightId,
i,
lightId + .1 * i,
new RenderTarget(textureSize, textureSize, cubeTexture, i, 0xffffffff)
));
}
}
private function pushExponentialShadowMappingPass(sceneBindings : DataBindingsProxy,
lightId : uint,
passes : Vector.<Shader>):void
{
var lightType : uint = getLightProperty(
sceneBindings, lightId, 'type'
);
if (lightType != PointLight.LIGHT_TYPE)
{
var textureResource : ITextureResource = null;
var renderTarget : RenderTarget = null;
if (hasShadowBlurPass(sceneBindings, lightId))
textureResource = getLightProperty(sceneBindings, lightId, 'rawShadowMap');
else
textureResource = getLightProperty(sceneBindings, lightId, 'shadowMap');
renderTarget = new RenderTarget(
textureResource.width, textureResource.height, textureResource, 0, 0xffffffff
);
passes.push(new ExponentialShadowMapShader(lightId, 4, lightId + 1, renderTarget));
}
else
{
var cubeTexture : CubeTextureResource = getLightProperty(
sceneBindings, lightId, 'shadowMap'
);
var textureSize : uint = cubeTexture.size;
for (var i : uint = 0; i < 6; ++i)
passes.push(new ExponentialShadowMapShader(
lightId,
i,
lightId + .1 * i,
new RenderTarget(textureSize, textureSize, cubeTexture, i, 0xffffffff)
));
}
}
private function hasShadowBlurPass(sceneBindings : DataBindingsProxy,
lightId : uint) : Boolean
{
var quality : uint = getLightProperty(sceneBindings, lightId, 'shadowQuality');
return quality > ShadowMappingQuality.HARD;
}
private function lightPropertyExists(sceneBindings : DataBindingsProxy,
lightId : uint,
propertyName : String) : Boolean
{
return sceneBindings.propertyExists(
LightDataProvider.getLightPropertyName(propertyName, lightId)
);
}
private function getLightProperty(sceneBindings : DataBindingsProxy,
lightId : uint,
propertyName : String) : *
{
return sceneBindings.getProperty(
LightDataProvider.getLightPropertyName(propertyName, lightId)
);
}
}
}
|
add ASDoc to explain the behavior of PhongEffect
|
add ASDoc to explain the behavior of PhongEffect
|
ActionScript
|
mit
|
aerys/minko-as3
|
369541a0665f59c93ae5961576784d683688df5f
|
frameworks/projects/HTML/as/src/org/apache/flex/html/Panel.as
|
frameworks/projects/HTML/as/src/org/apache/flex/html/Panel.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html
{
import org.apache.flex.core.IPanelModel;
[Event(name="close", type="org.apache.flex.events.Event")]
/**
* The Panel class is a Container component capable of parenting other
* components. The Panel has a TitleBar. If you want to a Panel with
* a ControlBar, use PanelWithControlBar which
* will instantiate, by default, an ControlBar.
* The Panel uses the following bead types:
*
* org.apache.flex.core.IBeadModel: the data model for the Panel that includes the title and whether
* or not to display the close button.
* org.apache.flex.core.IBeadView: creates the parts of the Panel.
* org.apache.flex.core.IBorderBead: if present, draws a border around the Panel.
* org.apache.flex.core.IBackgroundBead: if present, provides a colored background for the Panel.
*
* @see PanelWithControlBar
* @see ControlBar
* @see TitleBar
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class Panel extends Container
{
/**
* constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function Panel()
{
super();
}
/**
* The string to display in the org.apache.flex.html.TitleBar.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get title():String
{
return IPanelModel(model).title;
}
public function set title(value:String):void
{
IPanelModel(model).title = value;
}
/**
* The HTML string to display in the org.apache.flex.html.TitleBar.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get htmlTitle():String
{
return IPanelModel(model).htmlTitle;
}
public function set htmlTitle(value:String):void
{
IPanelModel(model).htmlTitle = value;
}
/**
* Whether or not to show a Close button in the org.apache.flex.html.TitleBar.
*/
public function get showCloseButton():Boolean
{
return IPanelModel(model).showCloseButton;
}
public function set showCloseButton(value:Boolean):void
{
IPanelModel(model).showCloseButton = 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
{
import org.apache.flex.core.IPanelModel;
COMPILE::JS
{
import org.apache.flex.core.WrappedHTMLElement;
}
[Event(name="close", type="org.apache.flex.events.Event")]
/**
* The Panel class is a Container component capable of parenting other
* components. The Panel has a TitleBar. If you want to a Panel with
* a ControlBar, use PanelWithControlBar which
* will instantiate, by default, an ControlBar.
* The Panel uses the following bead types:
*
* org.apache.flex.core.IBeadModel: the data model for the Panel that includes the title and whether
* or not to display the close button.
* org.apache.flex.core.IBeadView: creates the parts of the Panel.
* org.apache.flex.core.IBorderBead: if present, draws a border around the Panel.
* org.apache.flex.core.IBackgroundBead: if present, provides a colored background for the Panel.
*
* @see PanelWithControlBar
* @see ControlBar
* @see TitleBar
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class Panel extends Container
{
/**
* constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function Panel()
{
super();
}
/**
* The string to display in the org.apache.flex.html.TitleBar.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get title():String
{
return IPanelModel(model).title;
}
public function set title(value:String):void
{
IPanelModel(model).title = value;
}
/**
* The HTML string to display in the org.apache.flex.html.TitleBar.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get htmlTitle():String
{
return IPanelModel(model).htmlTitle;
}
public function set htmlTitle(value:String):void
{
IPanelModel(model).htmlTitle = value;
}
/**
* Whether or not to show a Close button in the org.apache.flex.html.TitleBar.
*/
public function get showCloseButton():Boolean
{
return IPanelModel(model).showCloseButton;
}
public function set showCloseButton(value:Boolean):void
{
IPanelModel(model).showCloseButton = value;
}
COMPILE::JS
override protected function createElement():WrappedHTMLElement
{
super.createElement();
element.className = "Panel";
typeNames = "Panel";
return element;
}
}
}
|
fix panel background styling
|
fix panel background styling
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
009dbdceb749a44cda7e4a603bd7f4a96e07918c
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/Application.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/Application.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.core
{
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.IOErrorEvent;
import flash.system.ApplicationDomain;
import flash.utils.getQualifiedClassName;
import org.apache.flex.events.Event;
import org.apache.flex.utils.MXMLDataInterpreter;
//--------------------------------------
// Events
//--------------------------------------
/**
* Dispatched at startup. Attributes and sub-instances of
* the MXML document have been created and assigned.
* The component lifecycle is different
* than the Flex SDK. There is no creationComplete event.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="initialize", type="org.apache.flex.events.Event")]
/**
* Dispatched at startup after the initial view has been
* put on the display list.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="viewChanged", type="org.apache.flex.events.Event")]
/**
* Dispatched at startup after the initial view has been
* put on the display list.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="applicationComplete", type="org.apache.flex.events.Event")]
/**
* The Application class is the main class and entry point for a FlexJS
* application. This Application class is different than the
* Flex SDK's mx:Application or spark:Application in that it does not contain
* user interface elements. Those UI elements go in the views. This
* Application class expects there to be a main model, a controller, and
* an initial view.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class Application extends Sprite implements IStrand, IFlexInfo, IParent
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function Application()
{
super();
if (stage)
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
}
loaderInfo.addEventListener(flash.events.Event.INIT, initHandler);
}
/**
* The document property is used to provide
* a property lookup context for non-display objects.
* For Application, it points to itself.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var document:Object = this;
private function initHandler(event:flash.events.Event):void
{
ValuesManager.valuesImpl = valuesImpl;
ValuesManager.valuesImpl.init(this);
dispatchEvent(new Event("initialize"));
if (initialView)
{
initialView.applicationModel = model;
this.addElement(initialView);
dispatchEvent(new Event("viewChanged"));
}
dispatchEvent(new Event("applicationComplete"));
}
/**
* The org.apache.flex.core.IValuesImpl that will
* determine the default values and other values
* for the application. The most common choice
* is org.apache.flex.core.SimpleCSSValuesImpl.
*
* @see org.apache.flex.core.SimpleCSSValuesImpl
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var valuesImpl:IValuesImpl;
/**
* The initial view.
*
* @see org.apache.flex.core.ViewBase
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var initialView:ViewBase;
/**
* The data model (for the initial view).
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var model:Object;
/**
* The controller. The controller typically watches
* the UI for events and updates the model accordingly.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var controller:Object;
/**
* An array of data that describes the MXML attributes
* and tags in an MXML document. This data is usually
* decoded by an MXMLDataInterpreter
*
* @see org.apache.flex.utils.MXMLDataInterpreter
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get MXMLDescriptor():Array
{
return null;
}
/**
* An method called by the compiler's generated
* code to kick off the setting of MXML attribute
* values and instantiation of child tags.
*
* The call has to be made in the generated code
* in order to ensure that the constructors have
* completed first.
*
* @param data The encoded data representing the
* MXML attributes.
*
* @see org.apache.flex.utils.MXMLDataInterpreter
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function generateMXMLAttributes(data:Array):void
{
MXMLDataInterpreter.generateMXMLProperties(this, data);
}
/**
* The array property that is used to add additional
* beads to an MXML tag. From ActionScript, just
* call addBead directly.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var beads:Array;
private var _beads:Vector.<IBead>;
/**
* @copy org.apache.flex.core.IStrand#addBead()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function addBead(bead:IBead):void
{
if (!_beads)
_beads = new Vector.<IBead>;
_beads.push(bead);
bead.strand = this;
}
/**
* @copy org.apache.flex.core.IStrand#getBeadByType()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function getBeadByType(classOrInterface:Class):IBead
{
for each (var bead:IBead in _beads)
{
if (bead is classOrInterface)
return bead;
}
return null;
}
/**
* @copy org.apache.flex.core.IStrand#removeBead()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function removeBead(value:IBead):IBead
{
var n:int = _beads.length;
for (var i:int = 0; i < n; i++)
{
var bead:IBead = _beads[i];
if (bead == value)
{
_beads.splice(i, 1);
return bead;
}
}
return null;
}
private var _info:Object;
/**
* An Object containing information generated
* by the compiler that is useful at startup time.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function info():Object
{
if (!_info)
{
var mainClassName:String = getQualifiedClassName(this);
var initClassName:String = "_" + mainClassName + "_FlexInit";
var c:Class = ApplicationDomain.currentDomain.getDefinition(initClassName) as Class;
_info = c.info();
}
return _info;
}
/**
* @copy org.apache.flex.core.IParent#addElement()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function addElement(c:Object):void
{
if (c is IUIBase)
{
addChild(IUIBase(c).element as DisplayObject);
IUIBase(c).addedToParent();
}
else
addChild(c as DisplayObject);
}
/**
* @copy org.apache.flex.core.IParent#addElementAt()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function addElementAt(c:Object, index:int):void
{
if (c is IUIBase)
{
addChildAt(IUIBase(c).element as DisplayObject, index);
IUIBase(c).addedToParent();
}
else
addChildAt(c as DisplayObject, index);
}
/**
* @copy org.apache.flex.core.IParent#getElementIndex()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function getElementIndex(c:Object):int
{
if (c is IUIBase)
return getChildIndex(IUIBase(c).element as DisplayObject);
return getChildIndex(c as DisplayObject);
}
/**
* @copy org.apache.flex.core.IParent#removeElement()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function removeElement(c:Object):void
{
if (c is IUIBase)
{
removeChild(IUIBase(c).element as DisplayObject);
}
else
removeChild(c as DisplayObject);
}
/**
* @copy org.apache.flex.core.IParent#numElements
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get numElements():int
{
return numChildren;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.core
{
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageQuality;
import flash.display.StageScaleMode;
import flash.events.IOErrorEvent;
import flash.system.ApplicationDomain;
import flash.utils.getQualifiedClassName;
import org.apache.flex.events.Event;
import org.apache.flex.utils.MXMLDataInterpreter;
//--------------------------------------
// Events
//--------------------------------------
/**
* Dispatched at startup. Attributes and sub-instances of
* the MXML document have been created and assigned.
* The component lifecycle is different
* than the Flex SDK. There is no creationComplete event.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="initialize", type="org.apache.flex.events.Event")]
/**
* Dispatched at startup after the initial view has been
* put on the display list.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="viewChanged", type="org.apache.flex.events.Event")]
/**
* Dispatched at startup after the initial view has been
* put on the display list.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="applicationComplete", type="org.apache.flex.events.Event")]
/**
* The Application class is the main class and entry point for a FlexJS
* application. This Application class is different than the
* Flex SDK's mx:Application or spark:Application in that it does not contain
* user interface elements. Those UI elements go in the views. This
* Application class expects there to be a main model, a controller, and
* an initial view.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class Application extends Sprite implements IStrand, IFlexInfo, IParent
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function Application()
{
super();
if (stage)
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.quality = StageQuality.HIGH_16X16_LINEAR;
trace("working");
}
loaderInfo.addEventListener(flash.events.Event.INIT, initHandler);
}
/**
* The document property is used to provide
* a property lookup context for non-display objects.
* For Application, it points to itself.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var document:Object = this;
private function initHandler(event:flash.events.Event):void
{
ValuesManager.valuesImpl = valuesImpl;
ValuesManager.valuesImpl.init(this);
dispatchEvent(new Event("initialize"));
if (initialView)
{
initialView.applicationModel = model;
this.addElement(initialView);
dispatchEvent(new Event("viewChanged"));
}
dispatchEvent(new Event("applicationComplete"));
}
/**
* The org.apache.flex.core.IValuesImpl that will
* determine the default values and other values
* for the application. The most common choice
* is org.apache.flex.core.SimpleCSSValuesImpl.
*
* @see org.apache.flex.core.SimpleCSSValuesImpl
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var valuesImpl:IValuesImpl;
/**
* The initial view.
*
* @see org.apache.flex.core.ViewBase
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var initialView:ViewBase;
/**
* The data model (for the initial view).
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var model:Object;
/**
* The controller. The controller typically watches
* the UI for events and updates the model accordingly.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var controller:Object;
/**
* An array of data that describes the MXML attributes
* and tags in an MXML document. This data is usually
* decoded by an MXMLDataInterpreter
*
* @see org.apache.flex.utils.MXMLDataInterpreter
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get MXMLDescriptor():Array
{
return null;
}
/**
* An method called by the compiler's generated
* code to kick off the setting of MXML attribute
* values and instantiation of child tags.
*
* The call has to be made in the generated code
* in order to ensure that the constructors have
* completed first.
*
* @param data The encoded data representing the
* MXML attributes.
*
* @see org.apache.flex.utils.MXMLDataInterpreter
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function generateMXMLAttributes(data:Array):void
{
MXMLDataInterpreter.generateMXMLProperties(this, data);
}
/**
* The array property that is used to add additional
* beads to an MXML tag. From ActionScript, just
* call addBead directly.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var beads:Array;
private var _beads:Vector.<IBead>;
/**
* @copy org.apache.flex.core.IStrand#addBead()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function addBead(bead:IBead):void
{
if (!_beads)
_beads = new Vector.<IBead>;
_beads.push(bead);
bead.strand = this;
}
/**
* @copy org.apache.flex.core.IStrand#getBeadByType()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function getBeadByType(classOrInterface:Class):IBead
{
for each (var bead:IBead in _beads)
{
if (bead is classOrInterface)
return bead;
}
return null;
}
/**
* @copy org.apache.flex.core.IStrand#removeBead()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function removeBead(value:IBead):IBead
{
var n:int = _beads.length;
for (var i:int = 0; i < n; i++)
{
var bead:IBead = _beads[i];
if (bead == value)
{
_beads.splice(i, 1);
return bead;
}
}
return null;
}
private var _info:Object;
/**
* An Object containing information generated
* by the compiler that is useful at startup time.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function info():Object
{
if (!_info)
{
var mainClassName:String = getQualifiedClassName(this);
var initClassName:String = "_" + mainClassName + "_FlexInit";
var c:Class = ApplicationDomain.currentDomain.getDefinition(initClassName) as Class;
_info = c.info();
}
return _info;
}
/**
* @copy org.apache.flex.core.IParent#addElement()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function addElement(c:Object):void
{
if (c is IUIBase)
{
addChild(IUIBase(c).element as DisplayObject);
IUIBase(c).addedToParent();
}
else
addChild(c as DisplayObject);
}
/**
* @copy org.apache.flex.core.IParent#addElementAt()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function addElementAt(c:Object, index:int):void
{
if (c is IUIBase)
{
addChildAt(IUIBase(c).element as DisplayObject, index);
IUIBase(c).addedToParent();
}
else
addChildAt(c as DisplayObject, index);
}
/**
* @copy org.apache.flex.core.IParent#getElementIndex()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function getElementIndex(c:Object):int
{
if (c is IUIBase)
return getChildIndex(IUIBase(c).element as DisplayObject);
return getChildIndex(c as DisplayObject);
}
/**
* @copy org.apache.flex.core.IParent#removeElement()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function removeElement(c:Object):void
{
if (c is IUIBase)
{
removeChild(IUIBase(c).element as DisplayObject);
}
else
removeChild(c as DisplayObject);
}
/**
* @copy org.apache.flex.core.IParent#numElements
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get numElements():int
{
return numChildren;
}
}
}
|
Set Application.stageQuality to HIGH_16X16_LINEAR
|
Set Application.stageQuality to HIGH_16X16_LINEAR
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
4d623322f2a4f7d68c749d2e61886f94e32322db
|
as3/xobjas3/src/com/rpath/xobj/XObjArrayCollection.as
|
as3/xobjas3/src/com/rpath/xobj/XObjArrayCollection.as
|
/*
#
# Copyright (c) 2007-2011 rPath, Inc.
#
# All rights reserved
#
*/
package com.rpath.xobj
{
import flash.utils.Dictionary;
import mx.collections.ArrayCollection;
public class XObjArrayCollection extends ArrayCollection implements IXObjCollection
{
public function XObjArrayCollection(source:Array=null, typeMap:*=null)
{
super(source);
if (!typeMap)
this.type = {};
this.type = typeMap;
}
// the type of objects we expect in the collection
// null means unknown type. Can be a single Class
// or a Dictionary of typeMap entries
[xobjTransient]
public function get type():*
{
return _type;
}
private var _type:*;
public function set type(t:*):void
{
_type = t;
}
public function elementType():Class
{
return (type as Class);
}
public function typeMap():Dictionary
{
return (type as Dictionary);
}
public function elementTypeForElementName(name:String):Class
{
return XObjTypeMap.elementTypeForElementName(type, name);
}
public function elementTagForMember(member:*):String
{
return XObjTypeMap.elementTagForMember(type, member);
}
public function addItemIfAbsent(value:Object):Boolean
{
if (getItemIndex(value) == -1)
{
addItem(value);
return true;
}
return false;
}
public function removeItemIfPresent(object:Object):Boolean
{
return XObjUtils.removeItemIfPresent(this, object);
}
public function isElementMember(propName:String):Boolean
{
return XObjUtils.isElementMember(this, propName);
}
[xobjTransient]
public function get isByReference():Boolean
{
return _isByReference;
}
private var _isByReference:Boolean;
public function set isByReference(b:Boolean):void
{
_isByReference = b;
}
}
}
|
/*
#
# Copyright (c) 2007-2011 rPath, Inc.
#
# All rights reserved
#
*/
package com.rpath.xobj
{
import flash.utils.Dictionary;
import mx.collections.ArrayCollection;
[Bindable]
public class XObjArrayCollection extends ArrayCollection implements IXObjCollection
{
public function XObjArrayCollection(source:Array=null, typeMap:*=null)
{
super(source);
if (!typeMap)
this.type = {};
this.type = typeMap;
}
// the type of objects we expect in the collection
// null means unknown type. Can be a single Class
// or a Dictionary of typeMap entries
[xobjTransient]
public function get type():*
{
return _type;
}
private var _type:*;
public function set type(t:*):void
{
_type = t;
}
public function elementType():Class
{
return (type as Class);
}
public function typeMap():Dictionary
{
return (type as Dictionary);
}
public function elementTypeForElementName(name:String):Class
{
return XObjTypeMap.elementTypeForElementName(type, name);
}
public function elementTagForMember(member:*):String
{
return XObjTypeMap.elementTagForMember(type, member);
}
public function addItemIfAbsent(value:Object):Boolean
{
if (getItemIndex(value) == -1)
{
addItem(value);
return true;
}
return false;
}
public function removeItemIfPresent(object:Object):Boolean
{
return XObjUtils.removeItemIfPresent(this, object);
}
public function isElementMember(propName:String):Boolean
{
return XObjUtils.isElementMember(this, propName);
}
[xobjTransient]
public function get isByReference():Boolean
{
return _isByReference;
}
private var _isByReference:Boolean;
public function set isByReference(b:Boolean):void
{
_isByReference = b;
}
}
}
|
Make XObjArrayCollection bindable
|
Make XObjArrayCollection bindable
|
ActionScript
|
apache-2.0
|
sassoftware/xobj,sassoftware/xobj,sassoftware/xobj,sassoftware/xobj
|
f185862fb741a85cd36ffd8b2fd4b6d3b3e68bc9
|
frameworks/projects/framework/src/mx/binding/Binding.as
|
frameworks/projects/framework/src/mx/binding/Binding.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package mx.binding
{
import mx.collections.errors.ItemPendingError;
import mx.core.mx_internal;
import flash.utils.Dictionary;
use namespace mx_internal;
[ExcludeClass]
/**
* @private
*/
public class Binding
{
include "../core/Version.as";
// Certain errors are normal during binding execution, so we swallow them.
// 1507 - invalid null argument
// 2005 - argument error (null gets converted to 0)
mx_internal static var allowedErrors:Object = generateAllowedErrors();
mx_internal static function generateAllowedErrors():Object
{
var o:Object = {};
o[1507] = 1;
o[2005] = 1;
return o;
}
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Create a Binding object
*
* @param document The document that is the target of all of this work.
*
* @param srcFunc The function that returns us the value
* to use in this Binding.
*
* @param destFunc The function that will take a value
* and assign it to the destination.
*
* @param destString The destination represented as a String.
* We can then tell the ValidationManager to validate this field.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function Binding(document:Object, srcFunc:Function,
destFunc:Function, destString:String,
srcString:String = null)
{
super();
this.document = document;
this.srcFunc = srcFunc;
this.destFunc = destFunc;
this.destString = destString;
this.srcString = srcString;
this.destFuncFailed = false;
if (this.srcFunc == null)
{
this.srcFunc = defaultSrcFunc;
}
if (this.destFunc == null)
{
this.destFunc = defaultDestFunc;
}
_isEnabled = true;
isExecuting = false;
isHandlingEvent = false;
hasHadValue = false;
uiComponentWatcher = -1;
BindingManager.addBinding(document, destString, this);
}
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
/**
* @private
* Internal storage for isEnabled property.
*/
mx_internal var _isEnabled:Boolean;
/**
* @private
* Indicates that a Binding is enabled.
* Used to disable bindings.
*/
mx_internal function get isEnabled():Boolean
{
return _isEnabled;
}
/**
* @private
*/
mx_internal function set isEnabled(value:Boolean):void
{
_isEnabled = value;
if (value)
{
processDisabledRequests();
}
}
/**
* @private
* Indicates that a Binding is executing.
* Used to prevent circular bindings from causing infinite loops.
*/
mx_internal var isExecuting:Boolean;
/**
* @private
* Indicates that the binding is currently handling an event.
* Used to prevent us from infinitely causing an event
* that re-executes the the binding.
*/
mx_internal var isHandlingEvent:Boolean;
/**
* @private
* Queue of watchers that fired while we were disabled.
* We will resynch with our binding if isEnabled is set to true
* and one or more of our watchers fired while we were disabled.
*/
mx_internal var disabledRequests:Dictionary;
/**
* @private
* True as soon as a non-null or non-empty-string value has been used.
* We don't auto-validate until this is true
*/
private var hasHadValue:Boolean;
/**
* @private
* This is no longer used in Flex 3.0, but it is required to load
* Flex 2.0.0 and Flex 2.0.1 modules.
*/
public var uiComponentWatcher:int;
/**
* @private
* It's possible that there is a two-way binding set up, in which case
* we'll do a rudimentary optimization by not executing ourselves
* if our counterpart is already executing.
*/
public var twoWayCounterpart:Binding;
/**
* @private
* If there is a twoWayCounterpart, hasHadValue is false, and
* isTwoWayPrimary is true, then the twoWayCounterpart will be
* executed first.
*/
public var isTwoWayPrimary:Boolean;
/**
* @private
* True if a wrapped function call does not throw an error. This is used by
* innerExecute() to tell if the srcFunc completed successfully.
*/
private var wrappedFunctionSuccessful:Boolean;
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
/**
* All Bindings hang off of a document for now,
* but really it's just the root of where these functions live.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
mx_internal var document:Object;
/**
* The function that will return us the value.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
mx_internal var srcFunc:Function;
/**
* The function that takes the value and assigns it.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
mx_internal var destFunc:Function;
mx_internal var destFuncFailed:Boolean;
/**
* The destination represented as a String.
* This will be used so we can signal validation on a field.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
mx_internal var destString:String;
/**
* The source represented as a String.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 4
*/
mx_internal var srcString:String;
/**
* @private
* Used to suppress calls to destFunc when incoming value is either
* a) an XML node identical to the previously assigned XML node, or
* b) an XMLList containing the identical node sequence as the previously assigned XMLList
*/
private var lastValue:Object;
//--------------------------------------------------------------------------
//
// Methods
//
//--------------------------------------------------------------------------
private function defaultDestFunc(value:Object):void
{
var chain:Array = destString.split(".");
var element:Object = document;
var i:uint = 0;
if (chain[0] == "this")
{
i++;
}
while (i < (chain.length - 1))
{
element = element[chain[i++]];
//if the element does not exist : avoid exception as it's heavy on memory allocations
if (element == null || element == undefined) {
destFuncFailed = true;
if (BindingManager.debugDestinationStrings[destString])
{
trace("Binding: destString = " + destString + ", error = 1009");
}
return;
}
}
element[chain[i]] = value;
}
private function defaultSrcFunc():Object
{
return document[srcString];
}
/**
* Execute the binding.
* Call the source function and get the value we'll use.
* Then call the destination function passing the value as an argument.
* Finally try to validate the destination.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function execute(o:Object = null):void
{
if (!isEnabled)
{
if (o != null)
{
registerDisabledExecute(o);
}
return;
}
if (twoWayCounterpart && !twoWayCounterpart.hasHadValue && twoWayCounterpart.isTwoWayPrimary)
{
twoWayCounterpart.execute();
hasHadValue = true;
return;
}
if (isExecuting || (twoWayCounterpart && twoWayCounterpart.isExecuting))
{
// If there is a twoWayCounterpart already executing, that means that it is
// assigning something of value so even though we won't execute we should be
// sure to mark ourselves as having had a value so that future executions will
// be correct. If isExecuting is true but we re-entered, that means we
// clearly had a value so setting hasHadValue is safe.
hasHadValue = true;
return;
}
try
{
isExecuting = true;
wrapFunctionCall(this, innerExecute, o);
}
catch(error:Error)
{
if (allowedErrors[error.errorID] == null)
throw error;
}
finally
{
isExecuting = false;
}
}
/**
* @private
* Take note of any execute request that occur when we are disabled.
*/
private function registerDisabledExecute(o:Object):void
{
if (o != null)
{
disabledRequests = (disabledRequests != null) ? disabledRequests :
new Dictionary(true);
disabledRequests[o] = true;
}
}
/**
* @private
* Resynch with any watchers that may have updated while we were disabled.
*/
private function processDisabledRequests():void
{
if (disabledRequests != null)
{
for (var key:Object in disabledRequests)
{
execute(key);
}
disabledRequests = null;
}
}
/**
* @private
* Note: use of this wrapper needs to be reexamined. Currently there's at least one situation where a
* wrapped function invokes another wrapped function, which is unnecessary (i.e., only the inner function
* will throw), and also risks future errors due to the 'wrappedFunctionSuccessful' member variable
* being stepped on. Leaving alone for now to minimize pre-GMC volatility, but should be revisited for
* an early dot release.
* Also note that the set of suppressed error codes below is repeated verbatim in Watcher.wrapUpdate.
* These need to be consolidated and the motivations for each need to be documented.
*/
protected function wrapFunctionCall(thisArg:Object, wrappedFunction:Function, object:Object = null, ...args):Object
{
wrappedFunctionSuccessful = false;
try
{
var result:Object = wrappedFunction.apply(thisArg, args);
if (destFuncFailed) {
return null;
}
wrappedFunctionSuccessful = true;
return result;
}
catch(itemPendingError:ItemPendingError)
{
itemPendingError.addResponder(new EvalBindingResponder(this, object));
if (BindingManager.debugDestinationStrings[destString])
{
trace("Binding: destString = " + destString + ", error = " + itemPendingError);
}
}
catch(rangeError:RangeError)
{
if (BindingManager.debugDestinationStrings[destString])
{
trace("Binding: destString = " + destString + ", error = " + rangeError);
}
}
catch(error:Error)
{
// Certain errors are normal when executing a srcFunc or destFunc,
// so we swallow them:
// Error #1006: Call attempted on an object that is not a function.
// Error #1009: null has no properties.
// Error #1010: undefined has no properties.
// Error #1055: - has no properties.
// Error #1069: Property - not found on - and there is no default value
// We allow any other errors to be thrown.
if ((error.errorID != 1006) &&
(error.errorID != 1009) &&
(error.errorID != 1010) &&
(error.errorID != 1055) &&
(error.errorID != 1069))
{
throw error;
}
else
{
if (BindingManager.debugDestinationStrings[destString])
{
trace("Binding: destString = " + destString + ", error = " + error);
}
}
}
return null;
}
/**
* @private
* true iff XMLLists x and y contain the same node sequence.
*/
private function nodeSeqEqual(x:XMLList, y:XMLList):Boolean
{
var n:uint = x.length();
if (n == y.length())
{
for (var i:uint = 0; i < n && x[i] === y[i]; i++)
{
}
return i == n;
}
else
{
return false;
}
}
/**
* @private
*/
private function innerExecute():void
{
var value:Object = wrapFunctionCall(document, srcFunc);
if (BindingManager.debugDestinationStrings[destString])
{
trace("Binding: destString = " + destString + ", srcFunc result = " + value);
}
if (hasHadValue || wrappedFunctionSuccessful)
{
// Suppress binding assignments on non-simple XML: identical single nodes, or
// lists over identical node sequences.
// Note: outer tests are inline for efficiency
if (!(lastValue is XML && lastValue.hasComplexContent() && lastValue === value) &&
!(lastValue is XMLList && lastValue.hasComplexContent() && value is XMLList &&
nodeSeqEqual(lastValue as XMLList, value as XMLList)))
{
destFunc.call(document, value);
if (!destFuncFailed) {
// Note: state is not updated if destFunc throws
lastValue = value;
hasHadValue = true;
}
}
}
}
/**
* This function is called when one of this binding's watchers
* detects a property change.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function watcherFired(commitEvent:Boolean, cloneIndex:int):void
{
if (isHandlingEvent)
return;
try
{
isHandlingEvent = true;
execute(cloneIndex);
}
finally
{
isHandlingEvent = false;
}
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package mx.binding
{
import mx.collections.errors.ItemPendingError;
import mx.core.mx_internal;
import flash.utils.Dictionary;
use namespace mx_internal;
[ExcludeClass]
/**
* @private
*/
public class Binding
{
include "../core/Version.as";
// Certain errors are normal during binding execution, so we swallow them.
// 1507 - invalid null argument
// 2005 - argument error (null gets converted to 0)
mx_internal static var allowedErrors:Object = generateAllowedErrors();
mx_internal static function generateAllowedErrors():Object
{
var o:Object = {};
o[1507] = 1;
o[2005] = 1;
return o;
}
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Create a Binding object
*
* @param document The document that is the target of all of this work.
*
* @param srcFunc The function that returns us the value
* to use in this Binding.
*
* @param destFunc The function that will take a value
* and assign it to the destination.
*
* @param destString The destination represented as a String.
* We can then tell the ValidationManager to validate this field.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function Binding(document:Object, srcFunc:Function,
destFunc:Function, destString:String,
srcString:String = null)
{
super();
this.document = document;
this.srcFunc = srcFunc;
this.destFunc = destFunc;
this.destString = destString;
this.srcString = srcString;
if (this.srcFunc == null)
{
this.srcFunc = defaultSrcFunc;
}
if (this.destFunc == null)
{
this.destFunc = defaultDestFunc;
}
_isEnabled = true;
isExecuting = false;
isHandlingEvent = false;
hasHadValue = false;
uiComponentWatcher = -1;
BindingManager.addBinding(document, destString, this);
}
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
/**
* @private
* Internal storage for isEnabled property.
*/
mx_internal var _isEnabled:Boolean;
/**
* @private
* Indicates that a Binding is enabled.
* Used to disable bindings.
*/
mx_internal function get isEnabled():Boolean
{
return _isEnabled;
}
/**
* @private
*/
mx_internal function set isEnabled(value:Boolean):void
{
_isEnabled = value;
if (value)
{
processDisabledRequests();
}
}
/**
* @private
* Indicates that a Binding is executing.
* Used to prevent circular bindings from causing infinite loops.
*/
mx_internal var isExecuting:Boolean;
/**
* @private
* Indicates that the binding is currently handling an event.
* Used to prevent us from infinitely causing an event
* that re-executes the the binding.
*/
mx_internal var isHandlingEvent:Boolean;
/**
* @private
* Queue of watchers that fired while we were disabled.
* We will resynch with our binding if isEnabled is set to true
* and one or more of our watchers fired while we were disabled.
*/
mx_internal var disabledRequests:Dictionary;
/**
* @private
* True as soon as a non-null or non-empty-string value has been used.
* We don't auto-validate until this is true
*/
private var hasHadValue:Boolean;
/**
* @private
* This is no longer used in Flex 3.0, but it is required to load
* Flex 2.0.0 and Flex 2.0.1 modules.
*/
public var uiComponentWatcher:int;
/**
* @private
* It's possible that there is a two-way binding set up, in which case
* we'll do a rudimentary optimization by not executing ourselves
* if our counterpart is already executing.
*/
public var twoWayCounterpart:Binding;
/**
* @private
* If there is a twoWayCounterpart, hasHadValue is false, and
* isTwoWayPrimary is true, then the twoWayCounterpart will be
* executed first.
*/
public var isTwoWayPrimary:Boolean;
/**
* @private
* True if a wrapped function call does not throw an error. This is used by
* innerExecute() to tell if the srcFunc completed successfully.
*/
private var wrappedFunctionSuccessful:Boolean;
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
/**
* All Bindings hang off of a document for now,
* but really it's just the root of where these functions live.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
mx_internal var document:Object;
/**
* The function that will return us the value.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
mx_internal var srcFunc:Function;
/**
* The function that takes the value and assigns it.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
mx_internal var destFunc:Function;
/**
* The destination represented as a String.
* This will be used so we can signal validation on a field.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
mx_internal var destString:String;
/**
* The source represented as a String.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 4
*/
mx_internal var srcString:String;
/**
* @private
* Used to suppress calls to destFunc when incoming value is either
* a) an XML node identical to the previously assigned XML node, or
* b) an XMLList containing the identical node sequence as the previously assigned XMLList
*/
private var lastValue:Object;
//--------------------------------------------------------------------------
//
// Methods
//
//--------------------------------------------------------------------------
private function defaultDestFunc(value:Object):void
{
var chain:Array = destString.split(".");
var element:Object = document;
var i:uint = 0;
if (chain[0] == "this")
{
i++;
}
while (i < (chain.length - 1))
{
element = element[chain[i++]];
}
element[chain[i]] = value;
}
private function defaultSrcFunc():Object
{
return document[srcString];
}
/**
* Execute the binding.
* Call the source function and get the value we'll use.
* Then call the destination function passing the value as an argument.
* Finally try to validate the destination.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function execute(o:Object = null):void
{
if (!isEnabled)
{
if (o != null)
{
registerDisabledExecute(o);
}
return;
}
if (twoWayCounterpart && !twoWayCounterpart.hasHadValue && twoWayCounterpart.isTwoWayPrimary)
{
twoWayCounterpart.execute();
hasHadValue = true;
return;
}
if (isExecuting || (twoWayCounterpart && twoWayCounterpart.isExecuting))
{
// If there is a twoWayCounterpart already executing, that means that it is
// assigning something of value so even though we won't execute we should be
// sure to mark ourselves as having had a value so that future executions will
// be correct. If isExecuting is true but we re-entered, that means we
// clearly had a value so setting hasHadValue is safe.
hasHadValue = true;
return;
}
try
{
isExecuting = true;
wrapFunctionCall(this, innerExecute, o);
}
catch(error:Error)
{
if (allowedErrors[error.errorID] == null)
throw error;
}
finally
{
isExecuting = false;
}
}
/**
* @private
* Take note of any execute request that occur when we are disabled.
*/
private function registerDisabledExecute(o:Object):void
{
if (o != null)
{
disabledRequests = (disabledRequests != null) ? disabledRequests :
new Dictionary(true);
disabledRequests[o] = true;
}
}
/**
* @private
* Resynch with any watchers that may have updated while we were disabled.
*/
private function processDisabledRequests():void
{
if (disabledRequests != null)
{
for (var key:Object in disabledRequests)
{
execute(key);
}
disabledRequests = null;
}
}
/**
* @private
* Note: use of this wrapper needs to be reexamined. Currently there's at least one situation where a
* wrapped function invokes another wrapped function, which is unnecessary (i.e., only the inner function
* will throw), and also risks future errors due to the 'wrappedFunctionSuccessful' member variable
* being stepped on. Leaving alone for now to minimize pre-GMC volatility, but should be revisited for
* an early dot release.
* Also note that the set of suppressed error codes below is repeated verbatim in Watcher.wrapUpdate.
* These need to be consolidated and the motivations for each need to be documented.
*/
protected function wrapFunctionCall(thisArg:Object, wrappedFunction:Function, object:Object = null, ...args):Object
{
wrappedFunctionSuccessful = false;
try
{
var result:Object = wrappedFunction.apply(thisArg, args);
wrappedFunctionSuccessful = true;
return result;
}
catch(itemPendingError:ItemPendingError)
{
itemPendingError.addResponder(new EvalBindingResponder(this, object));
if (BindingManager.debugDestinationStrings[destString])
{
trace("Binding: destString = " + destString + ", error = " + itemPendingError);
}
}
catch(rangeError:RangeError)
{
if (BindingManager.debugDestinationStrings[destString])
{
trace("Binding: destString = " + destString + ", error = " + rangeError);
}
}
catch(error:Error)
{
// Certain errors are normal when executing a srcFunc or destFunc,
// so we swallow them:
// Error #1006: Call attempted on an object that is not a function.
// Error #1009: null has no properties.
// Error #1010: undefined has no properties.
// Error #1055: - has no properties.
// Error #1069: Property - not found on - and there is no default value
// We allow any other errors to be thrown.
if ((error.errorID != 1006) &&
(error.errorID != 1009) &&
(error.errorID != 1010) &&
(error.errorID != 1055) &&
(error.errorID != 1069))
{
throw error;
}
else
{
if (BindingManager.debugDestinationStrings[destString])
{
trace("Binding: destString = " + destString + ", error = " + error);
}
}
}
return null;
}
/**
* @private
* true iff XMLLists x and y contain the same node sequence.
*/
private function nodeSeqEqual(x:XMLList, y:XMLList):Boolean
{
var n:uint = x.length();
if (n == y.length())
{
for (var i:uint = 0; i < n && x[i] === y[i]; i++)
{
}
return i == n;
}
else
{
return false;
}
}
/**
* @private
*/
private function innerExecute():void
{
var value:Object = wrapFunctionCall(document, srcFunc);
if (BindingManager.debugDestinationStrings[destString])
{
trace("Binding: destString = " + destString + ", srcFunc result = " + value);
}
if (hasHadValue || wrappedFunctionSuccessful)
{
// Suppress binding assignments on non-simple XML: identical single nodes, or
// lists over identical node sequences.
// Note: outer tests are inline for efficiency
if (!(lastValue is XML && lastValue.hasComplexContent() && lastValue === value) &&
!(lastValue is XMLList && lastValue.hasComplexContent() && value is XMLList &&
nodeSeqEqual(lastValue as XMLList, value as XMLList)))
{
destFunc.call(document, value);
// Note: state is not updated if destFunc throws
lastValue = value;
hasHadValue = true;
}
}
}
/**
* This function is called when one of this binding's watchers
* detects a property change.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function watcherFired(commitEvent:Boolean, cloneIndex:int):void
{
if (isHandlingEvent)
return;
try
{
isHandlingEvent = true;
execute(cloneIndex);
}
finally
{
isHandlingEvent = false;
}
}
}
}
|
Revert "FLEX-33874 improve binding performance"
|
Revert "FLEX-33874 improve binding performance"
This reverts commit ccdbfebd403b913c67d58b096f570d4c088fd0c1.
|
ActionScript
|
apache-2.0
|
danteinforno/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk
|
65c9cd04655181187f648868ceaf923efbc0e455
|
lib/src/com/amanitadesign/steam/WorkshopConstants.as
|
lib/src/com/amanitadesign/steam/WorkshopConstants.as
|
/*
* WorkshopConstants.as
* This file is part of FRESteamWorks.
*
* Created by Ventero <http://github.com/Ventero> on 2013-04-24
* Copyright (c) 2013 Level Up Labs, LLC. All rights reserved.
*/
package com.amanitadesign.steam
{
public class WorkshopConstants
{
public static const FILETYPE_Community:int = 0;
public static const FILETYPE_Microtransaction:int = 1;
public static const FILETYPE_Collection:int = 2;
public static const FILETYPE_Art:int = 3;
public static const FILETYPE_Video:int = 4;
public static const FILETYPE_Screenshot:int = 5;
public static const FILETYPE_Game:int = 6;
public static const FILETYPE_Software:int = 7;
public static const FILETYPE_Concept:int = 8;
public static const FILETYPE_WebGuide:int = 9;
public static const FILETYPE_IntegratedGuide:int = 10;
public static const ENUMTYPE_RankedByVote:int = 0;
public static const ENUMTYPE_Recent:int = 1;
public static const ENUMTYPE_Trending:int = 2;
public static const ENUMTYPE_FavoritesOfFriends:int = 3;
public static const ENUMTYPE_VotedByFriends:int = 4;
public static const ENUMTYPE_ContentByFriends:int = 5;
public static const ENUMTYPE_RecentFromFollowedUsers:int = 6;
public static const FILEACTION_Played:int = 0;
public static const FILEACTION_Completed:int = 1;
public static const VISIBILITY_Public:int = 0;
public static const VISIBILITY_FriendsOnly:int = 1;
public static const VISIBILITY_Private:int = 2;
public static const OVERLAYSTOREFLAG_None:int = 0;
public static const OVERLAYSTOREFLAG_AddToCart:int = 1;
public static const OVERLAYSTOREFLAG_AddToCartAndShow:int = 2;
public static const WORKSHOPVOTE_Unvoted:int = 0;
public static const WORKSHOPVOTE_VoteFor:int = 1;
public static const WORKSHOPVOTE_VoteAgainst:int = 2;
public static const FILEUPDATEHANDLE_Invalid:String = "18446744073709551615"; // 0xffffffffffffffffull
public static const UGCHANDLE_Invalid:String = "18446744073709551615"; // 0xffffffffffffffffull
}
}
|
/*
* WorkshopConstants.as
* This file is part of FRESteamWorks.
*
* Created by Ventero <http://github.com/Ventero> on 2013-04-24
* Copyright (c) 2013 Level Up Labs, LLC. All rights reserved.
*/
package com.amanitadesign.steam
{
public class WorkshopConstants
{
public static const FILETYPE_Community:int = 0;
public static const FILETYPE_Microtransaction:int = 1;
public static const FILETYPE_Collection:int = 2;
public static const FILETYPE_Art:int = 3;
public static const FILETYPE_Video:int = 4;
public static const FILETYPE_Screenshot:int = 5;
public static const FILETYPE_Game:int = 6;
public static const FILETYPE_Software:int = 7;
public static const FILETYPE_Concept:int = 8;
public static const FILETYPE_WebGuide:int = 9;
public static const FILETYPE_IntegratedGuide:int = 10;
public static const FILETYPE_Merch:int = 11;
public static const FILETYPE_ControllerBinding:int = 11;
public static const ENUMTYPE_RankedByVote:int = 0;
public static const ENUMTYPE_Recent:int = 1;
public static const ENUMTYPE_Trending:int = 2;
public static const ENUMTYPE_FavoritesOfFriends:int = 3;
public static const ENUMTYPE_VotedByFriends:int = 4;
public static const ENUMTYPE_ContentByFriends:int = 5;
public static const ENUMTYPE_RecentFromFollowedUsers:int = 6;
public static const FILEACTION_Played:int = 0;
public static const FILEACTION_Completed:int = 1;
public static const VISIBILITY_Public:int = 0;
public static const VISIBILITY_FriendsOnly:int = 1;
public static const VISIBILITY_Private:int = 2;
public static const OVERLAYSTOREFLAG_None:int = 0;
public static const OVERLAYSTOREFLAG_AddToCart:int = 1;
public static const OVERLAYSTOREFLAG_AddToCartAndShow:int = 2;
public static const WORKSHOPVOTE_Unvoted:int = 0;
public static const WORKSHOPVOTE_VoteFor:int = 1;
public static const WORKSHOPVOTE_VoteAgainst:int = 2;
public static const FILEUPDATEHANDLE_Invalid:String = "18446744073709551615"; // 0xffffffffffffffffull
public static const UGCHANDLE_Invalid:String = "18446744073709551615"; // 0xffffffffffffffffull
}
}
|
Add new filetypes.
|
Add new filetypes.
|
ActionScript
|
bsd-2-clause
|
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
|
7a3325ab9c54246aeb490f34b4e9b728effbebc5
|
src/aerys/minko/render/shader/part/PostProcessingShaderPart.as
|
src/aerys/minko/render/shader/part/PostProcessingShaderPart.as
|
package aerys.minko.render.shader.part
{
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.ShaderSettings;
import aerys.minko.type.enum.DepthTest;
import aerys.minko.type.enum.SamplerFiltering;
import aerys.minko.type.enum.SamplerMipMapping;
import aerys.minko.type.enum.SamplerWrapping;
public final class PostProcessingShaderPart extends ShaderPart
{
public function get backBufferTexture() : SFloat
{
return sceneBindings.getTextureParameter(
'backBuffer',
SamplerFiltering.LINEAR,
SamplerMipMapping.DISABLE,
SamplerWrapping.CLAMP
);
}
public function get vertexPosition() : SFloat
{
return multiply(vertexXYZ, float4(1, 1, 1, .5));
}
public function get backBufferPixel() : SFloat
{
return sampleBackBuffer(interpolate(vertexUV));
}
public function PostProcessingShaderPart(main : Shader)
{
super(main);
}
public function initializeSettings(settings : ShaderSettings) : void
{
settings.depthWriteEnabled = false;
settings.depthTest = DepthTest.ALWAYS;
}
public function sampleBackBuffer(uv : SFloat) : SFloat
{
return sampleTexture(backBufferTexture, interpolate(vertexUV));
}
}
}
|
package aerys.minko.render.shader.part
{
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.ShaderSettings;
import aerys.minko.type.enum.DepthTest;
import aerys.minko.type.enum.SamplerFiltering;
import aerys.minko.type.enum.SamplerMipMapping;
import aerys.minko.type.enum.SamplerWrapping;
public final class PostProcessingShaderPart extends ShaderPart
{
public function get backBufferTexture() : SFloat
{
return sceneBindings.getTextureParameter(
'backBuffer',
SamplerFiltering.LINEAR,
SamplerMipMapping.DISABLE,
SamplerWrapping.CLAMP
);
}
public function get vertexPosition() : SFloat
{
return multiply(vertexXYZ, float4(1, 1, 1, .5));
}
public function get backBufferPixel() : SFloat
{
return sampleBackBuffer(interpolate(vertexUV));
}
public function PostProcessingShaderPart(main : Shader)
{
super(main);
}
public function initializeSettings(settings : ShaderSettings) : void
{
settings.depthWriteEnabled = false;
settings.depthTest = DepthTest.ALWAYS;
}
public function sampleBackBuffer(uv : SFloat) : SFloat
{
return sampleTexture(backBufferTexture, uv || interpolate(vertexUV));
}
}
}
|
fix PostProcessingShaderPart.sampleBackBuffer() to actually use the uv argument when provided
|
fix PostProcessingShaderPart.sampleBackBuffer() to actually use the uv argument when provided
|
ActionScript
|
mit
|
aerys/minko-as3
|
ddb5ca8bbef60176eb0ef8055a12ff2457deed88
|
src/laml/display/Image.as
|
src/laml/display/Image.as
|
package laml.display {
import flash.display.Bitmap;
import flash.display.Loader;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.geom.Rectangle;
import flash.net.URLRequest;
import laml.events.PayloadEvent;
public class Image extends Component {
private var bitmap:Bitmap;
private var originalWidth:Number;
private var originalHeight:Number;
override protected function initialize():void {
super.initialize();
horizontalAlign = Component.ALIGN_CENTER;
verticalAlign = Component.ALIGN_CENTER;
model.validate_source = validateSource;
}
/**
* @source can be a string URL that the Image should load,
* a Class definition (by reference) that it Image should
* instantiate, or a subclass (or instance) of Bitmap.
*
* The Image will figure out what type of source it just
* received and respond accordingly.
*
* Of course images that need loaded will not be available
* immediately, but attached Bitmaps and classes will update
* preferredHeight and preferredWidth right away.
*/
public function set source(source:*):void {
model.source = source;
}
public function get source():* {
return model.source;
}
public function set maintainAspectRatio(maintain:Boolean):void {
model.maintainAspectRatio = maintain;
}
public function get maintainAspectRatio():Boolean {
return model.maintainAspectRatio;
}
private function validateSource(newValue:*, oldValue:*):void {
if(bitmap) {
view.removeChild(bitmap);
}
newValue = createImageFromValue(newValue);
if(newValue) {
bitmap = newValue;
bitmap.smoothing = true;
view.addChild(bitmap);
preferredWidth = originalWidth = bitmap.width;
preferredHeight = originalHeight = bitmap.height;
}
}
private function createImageFromValue(value:*):Bitmap {
if(value is Bitmap) {
return value;
}
else if(value is Class) {
return new value();
}
else {
loadImage(value);
}
return null;
}
private function loadImage(url:String):void {
//var context:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loadErrorHandler);
loader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, loadErrorHandler);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadCompleteHandler);
loader.load(new URLRequest(url));
}
private function loadCompleteHandler(event:Event):void {
source = event.target.content;
render();
dispatchPayloadEvent(PayloadEvent.LOADING_COMPLETED);
}
private function loadErrorHandler(event:Event):void {
dispatchPayloadEvent(PayloadEvent.ERROR, event);
}
override protected function updateDisplayList(w:Number, h:Number):void {
super.updateDisplayList(w, h);
var availableWidth:Number = w - (paddingLeft + paddingRight);
var availableHeight:Number = h - (paddingTop + paddingBottom);
if(maintainAspectRatio) {
if(bitmap) {
var rect:Rectangle = constrainSize(originalWidth, originalHeight, availableWidth, availableHeight);
var bw:Number = Math.floor(rect.width);
var bh:Number = Math.floor(rect.height);
bitmap.width = bw;
bitmap.height = bh;
switch(horizontalAlign) {
case Component.ALIGN_LEFT :
bitmap.x = paddingLeft;
break;
case Component.ALIGN_RIGHT :
bitmap.x = w - (bw + paddingLeft);
break;
case Component.ALIGN_CENTER :
bitmap.x = w/2 - bw/2;
break;
}
switch(verticalAlign) {
case Component.ALIGN_TOP :
bitmap.y = paddingTop;
break;
case Component.ALIGN_BOTTOM :
bitmap.y = h - (bh + paddingBottom);
break;
case Component.ALIGN_CENTER :
bitmap.y = h/2 - bh/2;
break;
}
}
}
else if(bitmap) {
bitmap.width = w;
bitmap.height = h;
}
}
private function constrainSize(ow:int, oh:int, cw:int, ch:int):Rectangle {
var w:int;
var h:int;
if (ow/oh > cw/ch) {
w = cw;
h = (w/ow) * oh;
}
else if (ow/oh < cw/ch) {
h = ch;
w = (h/oh) * ow;
}
else {
if (ow > oh) {
w = cw;
h = (w/ow)*oh;
}
else {
h = ch;
w = (h/oh)*ow;
}
}
return new Rectangle(0, 0, w, h);
}
}
}
|
package laml.display {
import flash.display.Bitmap;
import flash.display.DisplayObject;
import flash.display.Loader;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.geom.Rectangle;
import flash.net.URLRequest;
import laml.events.PayloadEvent;
public class Image extends Component {
private var bitmap:DisplayObject;
private var originalWidth:Number;
private var originalHeight:Number;
override protected function initialize():void {
super.initialize();
horizontalAlign = Component.ALIGN_CENTER;
verticalAlign = Component.ALIGN_CENTER;
model.validate_source = validateSource;
}
/**
* @source can be a string URL that the Image should load,
* a Class definition (by reference) that it Image should
* instantiate, or a subclass (or instance) of Bitmap.
*
* The Image will figure out what type of source it just
* received and respond accordingly.
*
* Of course images that need loaded will not be available
* immediately, but attached Bitmaps and classes will update
* preferredHeight and preferredWidth right away.
*/
public function set source(source:*):void {
model.source = source;
}
public function get source():* {
return model.source;
}
public function set maintainAspectRatio(maintain:Boolean):void {
model.maintainAspectRatio = maintain;
}
public function get maintainAspectRatio():Boolean {
return model.maintainAspectRatio;
}
private function validateSource(newValue:*, oldValue:*):void {
if(bitmap) {
view.removeChild(bitmap);
}
newValue = createImageFromValue(newValue);
if(newValue) {
bitmap = newValue;
if (bitmap is Bitmap) Bitmap(bitmap).smoothing = true;
view.addChild(bitmap);
preferredWidth = originalWidth = bitmap.width;
preferredHeight = originalHeight = bitmap.height;
}
}
private function createImageFromValue(value:*):DisplayObject {
if(value is DisplayObject) {
return value;
}
else if(value is Class) {
return new value();
}
else {
loadImage(value);
}
return null;
}
private function loadImage(url:String):void {
//var context:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loadErrorHandler);
loader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, loadErrorHandler);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadCompleteHandler);
loader.load(new URLRequest(url));
}
private function loadCompleteHandler(event:Event):void {
source = event.target.content;
render();
dispatchPayloadEvent(PayloadEvent.LOADING_COMPLETED);
}
private function loadErrorHandler(event:Event):void {
dispatchPayloadEvent(PayloadEvent.ERROR, event);
}
override protected function updateDisplayList(w:Number, h:Number):void {
super.updateDisplayList(w, h);
var availableWidth:Number = w - (paddingLeft + paddingRight);
var availableHeight:Number = h - (paddingTop + paddingBottom);
if(maintainAspectRatio) {
if(bitmap) {
var rect:Rectangle = constrainSize(originalWidth, originalHeight, availableWidth, availableHeight);
var bw:Number = Math.floor(rect.width);
var bh:Number = Math.floor(rect.height);
bitmap.width = bw;
bitmap.height = bh;
switch(horizontalAlign) {
case Component.ALIGN_LEFT :
bitmap.x = paddingLeft;
break;
case Component.ALIGN_RIGHT :
bitmap.x = w - (bw + paddingLeft);
break;
case Component.ALIGN_CENTER :
bitmap.x = w/2 - bw/2;
break;
}
switch(verticalAlign) {
case Component.ALIGN_TOP :
bitmap.y = paddingTop;
break;
case Component.ALIGN_BOTTOM :
bitmap.y = h - (bh + paddingBottom);
break;
case Component.ALIGN_CENTER :
bitmap.y = h/2 - bh/2;
break;
}
}
}
else if(bitmap) {
bitmap.width = w;
bitmap.height = h;
}
}
private function constrainSize(ow:int, oh:int, cw:int, ch:int):Rectangle {
var w:int;
var h:int;
if (ow/oh > cw/ch) {
w = cw;
h = (w/ow) * oh;
}
else if (ow/oh < cw/ch) {
h = ch;
w = (h/oh) * ow;
}
else {
if (ow > oh) {
w = cw;
h = (w/ow)*oh;
}
else {
h = ch;
w = (h/oh)*ow;
}
}
return new Rectangle(0, 0, w, h);
}
}
}
|
Support passing in any kind of display object into image source
|
Support passing in any kind of display object into image source
git-svn-id: 02605e11d3a461bc7e12f3f3880edf4b0c8dcfd0@4741 3e7533ad-8678-4d30-8e38-00a379d3f0d0
|
ActionScript
|
mit
|
lukebayes/laml
|
dd210b01228f5238e6ed90637bf225c758c54b59
|
lib/src_linux/com/amanitadesign/steam/FRESteamWorks.as
|
lib/src_linux/com/amanitadesign/steam/FRESteamWorks.as
|
package com.amanitadesign.steam {
import flash.desktop.NativeProcess;
import flash.desktop.NativeProcessStartupInfo;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.StatusEvent;
import flash.filesystem.File;
import flash.utils.ByteArray;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import flash.utils.clearInterval;
import flash.utils.setInterval;
public class FRESteamWorks extends EventDispatcher {
[Event(name="steam_response", type="com.amanitadesign.steam.SteamEvent")]
private static const PATH:String = "NativeApps/Linux/APIWrapper";
private var _file:File;
private var _process:NativeProcess;
private var _tm:int;
public var isReady:Boolean = false;
private static const AIRSteam_Init:int = 0;
private static const AIRSteam_RunCallbacks:int = 1;
private static const AIRSteam_RequestStats:int = 2;
private static const AIRSteam_SetAchievement:int = 3;
private static const AIRSteam_ClearAchievement:int = 4;
private static const AIRSteam_IsAchievement:int = 5;
private static const AIRSteam_GetStatInt:int = 6;
private static const AIRSteam_GetStatFloat:int = 7;
private static const AIRSteam_SetStatInt:int = 8;
private static const AIRSteam_SetStatFloat:int = 9;
private static const AIRSteam_StoreStats:int = 10;
private static const AIRSteam_ResetAllStats:int = 11;
private static const AIRSteam_GetFileCount:int = 12;
private static const AIRSteam_GetFileSize:int = 13;
private static const AIRSteam_FileExists:int = 14;
private static const AIRSteam_FileWrite:int = 15;
private static const AIRSteam_FileRead:int = 16;
private static const AIRSteam_FileDelete:int = 17;
private static const AIRSteam_IsCloudEnabledForApp:int = 18;
private static const AIRSteam_SetCloudEnabledForApp:int = 19;
public function FRESteamWorks (target:IEventDispatcher = null) {
_file = File.applicationDirectory.resolvePath(PATH);
_process = new NativeProcess();
super(target);
}
public function dispose():void {
if(_process.running) {
_process.closeInput();
_process.exit();
}
clearInterval(_tm);
isReady = false;
}
private function startProcess():void {
var startupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
startupInfo.executable = _file;
_process.start(startupInfo);
_process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, eventDispatched);
_process.addEventListener(IOErrorEvent.STANDARD_OUTPUT_IO_ERROR, errorCallback);
}
public function init():Boolean {
if(!_file.exists) return false;
startProcess();
if(!_process.running) return false;
callWrapper(AIRSteam_Init);
isReady = readBoolResponse();
if(isReady) _tm = setInterval(runCallbacks, 100);
return isReady;
}
private function callWrapper(funcName:int, params:Array = null):void{
if(!_process.running) startProcess();
var stdin:IDataOutput = _process.standardInput;
stdin.writeUTFBytes(funcName + "\n");
if(!params) return;
for(var i:int = 0; i < params.length; ++i) {
if(params[i] is ByteArray) {
var length:uint = params[i].length;
// length + 1 for the added newline
stdin.writeUTFBytes(String(length + 1) + "\n");
stdin.writeBytes(params[i]);
stdin.writeUTFBytes("\n");
} else {
stdin.writeUTFBytes(String(params[i]) + "\n");
}
}
}
private function waitForData(output:IDataInput):uint {
while(!output.bytesAvailable) {
// wait
}
return output.bytesAvailable;
}
private function readBoolResponse():Boolean {
if(!_process.running) return false;
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(1);
return (response == "t");
}
private function readIntResponse():int {
if(!_process.running) return 0;
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(avail);
return parseInt(response, 10);
}
private function readFloatResponse():Number {
if(!_process.running) return 0.0;
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(avail)
return parseFloat(response);
}
private function readStringResponse():String {
if(!_process.running) return "";
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(avail)
return response;
}
private function eventDispatched(e:ProgressEvent):void {
var stderr:IDataInput = _process.standardError;
var avail:uint = stderr.bytesAvailable;
var data:String = stderr.readUTFBytes(avail);
var pattern:RegExp = /__event__<(\d+),(\d+)>/g;
var result:Object;
while((result = pattern.exec(data))) {
var req_type:int = new int(result[1]);
var response:int = new int(result[2]);
var steamEvent:SteamEvent = new SteamEvent(SteamEvent.STEAM_RESPONSE, req_type, response);
dispatchEvent(steamEvent);
}
}
private function errorCallback(e:IOErrorEvent):void {
// the process doesn't accept our input anymore, try to restart it
if(_process.running) {
_process.closeInput();
_process.exit();
}
startProcess();
}
public function requestStats():Boolean {
callWrapper(AIRSteam_RequestStats);
return readBoolResponse();
}
public function runCallbacks():Boolean {
callWrapper(AIRSteam_RunCallbacks);
return true;
}
public function setAchievement(id:String):Boolean {
callWrapper(AIRSteam_SetAchievement, [id]);
return readBoolResponse();
}
public function clearAchievement(id:String):Boolean {
callWrapper(AIRSteam_ClearAchievement, [id]);
return readBoolResponse();
}
public function isAchievement(id:String):Boolean {
callWrapper(AIRSteam_IsAchievement, [id]);
return readBoolResponse();
}
public function getStatInt(id:String):int {
callWrapper(AIRSteam_GetStatInt, [id]);
return readIntResponse();
}
public function getStatFloat(id:String):Number {
callWrapper(AIRSteam_GetStatFloat, [id]);
return readFloatResponse();
}
public function setStatInt(id:String, value:int):Boolean {
callWrapper(AIRSteam_SetStatInt, [id, value]);
return readBoolResponse();
}
public function setStatFloat(id:String, value:Number):Boolean {
callWrapper(AIRSteam_SetStatFloat, [id, value]);
return readBoolResponse();
}
public function storeStats():Boolean {
callWrapper(AIRSteam_StoreStats);
return readBoolResponse();
}
public function resetAllStats(bAchievementsToo:Boolean):Boolean {
callWrapper(AIRSteam_ResetAllStats, [bAchievementsToo]);
return readBoolResponse();
}
public function getFileCount():int {
callWrapper(AIRSteam_GetFileCount);
return readIntResponse();
}
public function getFileSize(fileName:String):int {
callWrapper(AIRSteam_GetFileSize, [fileName]);
return readIntResponse();
}
public function fileExists(fileName:String):Boolean {
callWrapper(AIRSteam_FileExists, [fileName]);
return readBoolResponse();
}
public function fileWrite(fileName:String, data:ByteArray):Boolean {
callWrapper(AIRSteam_FileWrite, [fileName, data]);
return readBoolResponse();
}
public function fileRead(fileName:String, data:ByteArray):Boolean {
callWrapper(AIRSteam_FileRead, [fileName]);
var success:Boolean = readBoolResponse();
if(success) {
var content:String = readStringResponse();
data.writeUTFBytes(content);
data.position = 0;
}
return success;
}
public function fileDelete(fileName:String):Boolean {
callWrapper(AIRSteam_FileDelete, [fileName]);
return readBoolResponse();
}
public function isCloudEnabledForApp():Boolean {
callWrapper(AIRSteam_IsCloudEnabledForApp);
return readBoolResponse();
}
public function setCloudEnabledForApp(enabled:Boolean):Boolean {
callWrapper(AIRSteam_SetCloudEnabledForApp, [enabled]);
return readBoolResponse();
}
}
}
|
package com.amanitadesign.steam {
import flash.desktop.NativeProcess;
import flash.desktop.NativeProcessStartupInfo;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.StatusEvent;
import flash.filesystem.File;
import flash.utils.ByteArray;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import flash.utils.clearInterval;
import flash.utils.setInterval;
public class FRESteamWorks extends EventDispatcher {
[Event(name="steam_response", type="com.amanitadesign.steam.SteamEvent")]
private static const PATH:String = "NativeApps/Linux/APIWrapper";
private var _file:File;
private var _process:NativeProcess;
private var _tm:int;
private var _error:Boolean = false;
public var isReady:Boolean = false;
private static const AIRSteam_Init:int = 0;
private static const AIRSteam_RunCallbacks:int = 1;
private static const AIRSteam_RequestStats:int = 2;
private static const AIRSteam_SetAchievement:int = 3;
private static const AIRSteam_ClearAchievement:int = 4;
private static const AIRSteam_IsAchievement:int = 5;
private static const AIRSteam_GetStatInt:int = 6;
private static const AIRSteam_GetStatFloat:int = 7;
private static const AIRSteam_SetStatInt:int = 8;
private static const AIRSteam_SetStatFloat:int = 9;
private static const AIRSteam_StoreStats:int = 10;
private static const AIRSteam_ResetAllStats:int = 11;
private static const AIRSteam_GetFileCount:int = 12;
private static const AIRSteam_GetFileSize:int = 13;
private static const AIRSteam_FileExists:int = 14;
private static const AIRSteam_FileWrite:int = 15;
private static const AIRSteam_FileRead:int = 16;
private static const AIRSteam_FileDelete:int = 17;
private static const AIRSteam_IsCloudEnabledForApp:int = 18;
private static const AIRSteam_SetCloudEnabledForApp:int = 19;
public function FRESteamWorks (target:IEventDispatcher = null) {
_file = File.applicationDirectory.resolvePath(PATH);
_process = new NativeProcess();
_process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, eventDispatched);
_process.addEventListener(IOErrorEvent.STANDARD_INPUT_IO_ERROR, errorCallback);
super(target);
}
public function dispose():void {
if(_process.running) {
_process.closeInput();
_process.exit();
}
clearInterval(_tm);
isReady = false;
}
private function startProcess():void {
var startupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
startupInfo.executable = _file;
_process.start(startupInfo);
}
public function init():Boolean {
if(!_file.exists) return false;
startProcess();
if(!_process.running) return false;
if(!callWrapper(AIRSteam_Init)) return false;
isReady = readBoolResponse();
if(isReady) _tm = setInterval(runCallbacks, 100);
return isReady;
}
private function errorCallback(e:IOErrorEvent):void {
_error = true;
// the process doesn't accept our input anymore, so just stop it
clearInterval(_tm);
if(_process.running) {
try {
_process.closeInput();
} catch(e:*) {
// no-op
}
_process.exit();
}
}
private function callWrapper(funcName:int, params:Array = null):Boolean {
_error = false;
if(!_process.running) return false;
var stdin:IDataOutput = _process.standardInput;
stdin.writeUTFBytes(funcName + "\n");
if (params) {
for(var i:int = 0; i < params.length; ++i) {
if(params[i] is ByteArray) {
var length:uint = params[i].length;
// length + 1 for the added newline
stdin.writeUTFBytes(String(length + 1) + "\n");
stdin.writeBytes(params[i]);
stdin.writeUTFBytes("\n");
} else {
stdin.writeUTFBytes(String(params[i]) + "\n");
}
}
}
return !_error;
}
private function waitForData(output:IDataInput):uint {
while(!output.bytesAvailable) {
// wait
if(!_process.running) return 0;
}
return output.bytesAvailable;
}
private function readBoolResponse():Boolean {
if(!_process.running) return false;
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(1);
return (response == "t");
}
private function readIntResponse():int {
if(!_process.running) return 0;
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(avail);
return parseInt(response, 10);
}
private function readFloatResponse():Number {
if(!_process.running) return 0.0;
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(avail)
return parseFloat(response);
}
private function readStringResponse():String {
if(!_process.running) return "";
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(avail)
return response;
}
private function eventDispatched(e:ProgressEvent):void {
var stderr:IDataInput = _process.standardError;
var avail:uint = stderr.bytesAvailable;
var data:String = stderr.readUTFBytes(avail);
var pattern:RegExp = /__event__<(\d+),(\d+)>/g;
var result:Object;
while((result = pattern.exec(data))) {
var req_type:int = new int(result[1]);
var response:int = new int(result[2]);
var steamEvent:SteamEvent = new SteamEvent(SteamEvent.STEAM_RESPONSE, req_type, response);
dispatchEvent(steamEvent);
}
}
public function requestStats():Boolean {
if(!callWrapper(AIRSteam_RequestStats)) return false;
return readBoolResponse();
}
public function runCallbacks():Boolean {
if(!callWrapper(AIRSteam_RunCallbacks)) return false;
return true;
}
public function setAchievement(id:String):Boolean {
if(!callWrapper(AIRSteam_SetAchievement, [id])) return false;
return readBoolResponse();
}
public function clearAchievement(id:String):Boolean {
if(!callWrapper(AIRSteam_ClearAchievement, [id])) return false;
return readBoolResponse();
}
public function isAchievement(id:String):Boolean {
if(!callWrapper(AIRSteam_IsAchievement, [id])) return false;
return readBoolResponse();
}
public function getStatInt(id:String):int {
if(!callWrapper(AIRSteam_GetStatInt, [id])) return 0;
return readIntResponse();
}
public function getStatFloat(id:String):Number {
if(!callWrapper(AIRSteam_GetStatFloat, [id])) return 0.0;
return readFloatResponse();
}
public function setStatInt(id:String, value:int):Boolean {
if(!callWrapper(AIRSteam_SetStatInt, [id, value])) return false;
return readBoolResponse();
}
public function setStatFloat(id:String, value:Number):Boolean {
if(!callWrapper(AIRSteam_SetStatFloat, [id, value])) return false;
return readBoolResponse();
}
public function storeStats():Boolean {
if(!callWrapper(AIRSteam_StoreStats)) return false;
return readBoolResponse();
}
public function resetAllStats(bAchievementsToo:Boolean):Boolean {
if(!callWrapper(AIRSteam_ResetAllStats, [bAchievementsToo])) return false;
return readBoolResponse();
}
public function getFileCount():int {
if(!callWrapper(AIRSteam_GetFileCount)) return 0;
return readIntResponse();
}
public function getFileSize(fileName:String):int {
if(!callWrapper(AIRSteam_GetFileSize, [fileName])) return 0;
return readIntResponse();
}
public function fileExists(fileName:String):Boolean {
if(!callWrapper(AIRSteam_FileExists, [fileName])) return false;
return readBoolResponse();
}
public function fileWrite(fileName:String, data:ByteArray):Boolean {
if(!callWrapper(AIRSteam_FileWrite, [fileName, data])) return false;
return readBoolResponse();
}
public function fileRead(fileName:String, data:ByteArray):Boolean {
if(!callWrapper(AIRSteam_FileRead, [fileName])) return false;
var success:Boolean = readBoolResponse();
if(success) {
var content:String = readStringResponse();
data.writeUTFBytes(content);
data.position = 0;
}
return success;
}
public function fileDelete(fileName:String):Boolean {
if(!callWrapper(AIRSteam_FileDelete, [fileName])) return false;
return readBoolResponse();
}
public function isCloudEnabledForApp():Boolean {
if(!callWrapper(AIRSteam_IsCloudEnabledForApp)) return false;
return readBoolResponse();
}
public function setCloudEnabledForApp(enabled:Boolean):Boolean {
if(!callWrapper(AIRSteam_SetCloudEnabledForApp, [enabled])) return false;
return readBoolResponse();
}
}
}
|
Improve error handling
|
Improve error handling
|
ActionScript
|
bsd-2-clause
|
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
|
4523974603953af1e042917f0098049dd290ffb2
|
frameworks/projects/spark/src/spark/components/DropDownList.as
|
frameworks/projects/spark/src/spark/components/DropDownList.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package spark.components
{
import mx.core.IVisualElement;
import mx.core.UIComponentGlobals;
import mx.core.mx_internal;
import spark.components.supportClasses.DropDownListBase;
import spark.core.IDisplayText;
import spark.components.supportClasses.TextBase;
import spark.utils.LabelUtil;
use namespace mx_internal;
//--------------------------------------
// Other metadata
//--------------------------------------
[IconFile("DropDownList.png")]
/**
* Because this component does not define a skin for the mobile theme, Adobe
* recommends that you not use it in a mobile application. Alternatively, you
* can define your own mobile skin for the component. For more information,
* see <a href="http://help.adobe.com/en_US/flex/mobileapps/WS19f279b149e7481c698e85712b3011fe73-8000.html">Basics of mobile skinning</a>.
*/
[DiscouragedForProfile("mobileDevice")]
/**
* The DropDownList control contains a drop-down list
* from which the user can select a single value.
* Its functionality is very similar to that of the
* SELECT form element in HTML.
*
* <p>The DropDownList control consists of the anchor button,
* prompt area, and drop-down-list,
* Use the anchor button to open and close the drop-down-list.
* The prompt area displays a prompt String, or the selected item
* in the drop-down-list.</p>
*
* <p>When the drop-down list is open:</p>
* <ul>
* <li>Clicking the anchor button closes the drop-down list
* and commits the currently selected data item.</li>
* <li>Clicking outside of the drop-down list closes the drop-down list
* and commits the currently selected data item.</li>
* <li>Clicking on a data item selects that item and closes the drop-down list.</li>
* <li>If the <code>requireSelection</code> property is <code>false</code>,
* clicking on a data item while pressing the Control key deselects
* the item and closes the drop-down list.</li>
* </ul>
*
* <p><b>Note: </b>The Spark list-based controls (the Spark ListBase class and its subclasses
* such as ButtonBar, ComboBox, DropDownList, List, and TabBar) do not support the BasicLayout class
* as the value of the <code>layout</code> property.
* Do not use BasicLayout with the Spark list-based controls.</p>
*
* <p>To use this component in a list-based component, such as a List or DataGrid,
* create an item renderer.
* For information about creating an item renderer, see
* <a href="http://help.adobe.com/en_US/flex/using/WS4bebcd66a74275c3-fc6548e124e49b51c4-8000.html">
* Custom Spark item renderers</a>. </p>
*
* <p>The DropDownList control has the following default characteristics:</p>
* <table class="innertable">
* <tr><th>Characteristic</th><th>Description</th></tr>
* <tr><td>Default size</td><td>112 pixels wide and 21 pixels high</td></tr>
* <tr><td>Minimum size</td><td>112 pixels wide and 21 pixels high</td></tr>
* <tr><td>Maximum size</td><td>10000 pixels wide and 10000 pixels high</td></tr>
* <tr><td>Default skin class</td><td>spark.skins.spark.DropDownListSkin</td></tr>
* </table>
*
* @mxml <p>The <code><s:DropDownList></code> tag inherits all of the tag
* attributes of its superclass and adds the following tag attributes:</p>
*
* <pre>
* <s:DropDownList
* <strong>Properties</strong>
* prompt=""
* typicalItem="null"
*
* <strong>Events</strong>
* closed="<i>No default</i>"
* open="<i>No default</i>"
* />
* </pre>
*
* @see spark.skins.spark.DropDownListSkin
* @see spark.components.supportClasses.DropDownController
*
* @includeExample examples/DropDownListExample.mxml
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public class DropDownList extends DropDownListBase
{
include "../core/Version.as";
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function DropDownList()
{
super();
}
//--------------------------------------------------------------------------
//
// Skin parts
//
//--------------------------------------------------------------------------
//----------------------------------
// labelDisplay
//----------------------------------
[SkinPart(required="false")]
/**
* An optional skin part that holds the prompt or the text of the selected item.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public var labelDisplay:IDisplayText;
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
private var labelChanged:Boolean = false;
private var labelDisplayExplicitWidth:Number;
private var labelDisplayExplicitHeight:Number;
private var sizeSetByTypicalItem:Boolean;
//--------------------------------------------------------------------------
//
// Overridden properties
//
//--------------------------------------------------------------------------
//----------------------------------
// baselinePosition
//----------------------------------
/**
* @private
*/
override public function get baselinePosition():Number
{
return getBaselinePositionForPart(labelDisplay as IVisualElement);
}
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
//----------------------------------
// prompt
//----------------------------------
/**
* @private
*/
private var _prompt:String = "";
[Inspectable(category="General", defaultValue="")]
/**
* The prompt for the DropDownList control.
* The prompt is a String that is displayed in the
* DropDownList when <code>selectedIndex</code> = -1.
* It is usually a String such as "Select one...".
* Selecting an item in the drop-down list replaces the
* prompt with the text from the selected item.
*
* @default ""
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function get prompt():String
{
return _prompt;
}
/**
* @private
*/
public function set prompt(value:String):void
{
if (_prompt == value)
return;
_prompt = value;
labelChanged = true;
invalidateProperties();
}
//--------------------------------------------------------------------------
//
// Overridden Properties
//
//--------------------------------------------------------------------------
[Inspectable(category="Data")]
/**
* Layouts use the preferred size of the <code>typicalItem</code>
* when fixed row or column sizes are required, but a specific
* <code>rowHeight</code> or <code>columnWidth</code> value is not set.
* Similarly virtual layouts use this item to define the size
* of layout elements that have not been scrolled into view.
*
* <p>The container uses the typical data item, and the associated item renderer,
* to determine the default size of the container children.
* By defining the typical item, the container does not have to size each child
* as it is drawn on the screen.</p>
*
* <p>Setting this property sets the <code>typicalLayoutElement</code> property
* of the layout.</p>
*
* <p>Restriction: if the <code>typicalItem</code> is an IVisualItem, it must not
* also be a member of the data provider.</p>
*
* <p>Note: Setting <code>typicalItem</code> overrides any explicit width or height
* set on the <code>labelDisplay</code> skin part. </p>
*
* @default null
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
override public function set typicalItem(value:Object):void
{
super.typicalItem = value;
invalidateSize();
}
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
override protected function commitProperties():void
{
super.commitProperties();
if (labelChanged)
{
labelChanged = false;
updateLabelDisplay();
}
}
/**
* @private
*/
override protected function partAdded(partName:String, instance:Object):void
{
super.partAdded(partName, instance);
if (instance == labelDisplay)
{
labelChanged = true;
invalidateProperties();
}
}
/**
* @private
*/
override protected function measure():void
{
var labelComp:TextBase = labelDisplay as TextBase;
// If typicalItem is set, then use it for measurement
if (labelComp && typicalItem != null)
{
// Save the labelDisplay's dimensions in case we clear out typicalItem
if (!sizeSetByTypicalItem)
{
labelDisplayExplicitWidth = labelComp.explicitWidth;
labelDisplayExplicitHeight = labelComp.explicitHeight;
sizeSetByTypicalItem = true;
}
labelComp.explicitWidth = NaN;
labelComp.explicitHeight = NaN;
// Swap in the typicalItem into the labelDisplay
updateLabelDisplay(typicalItem);
UIComponentGlobals.layoutManager.validateClient(skin, true);
// Force the labelDisplay to be sized to the measured size
labelComp.width = labelComp.measuredWidth;
labelComp.height = labelComp.measuredHeight;
// Set the labelDisplay back to selectedItem
updateLabelDisplay();
}
else if (labelComp && sizeSetByTypicalItem && typicalItem == null)
{
// Restore the labelDisplay to its original size
labelComp.width = labelDisplayExplicitWidth;
labelComp.height = labelDisplayExplicitHeight;
sizeSetByTypicalItem = false;
}
super.measure();
}
/**
* @private
* Called whenever we need to update the text passed to the labelDisplay skin part
*/
// TODO (jszeto): Make this protected and make the name more generic (passing data to skin)
override mx_internal function updateLabelDisplay(displayItem:* = undefined):void
{
if (labelDisplay)
{
if (displayItem == undefined)
displayItem = selectedItem;
else
labelDisplay.text = displayItem != null ? LabelUtil.itemToLabel(displayItem, labelField, labelFunction) : prompt;
}
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package spark.components
{
import mx.core.IVisualElement;
import mx.core.UIComponentGlobals;
import mx.core.mx_internal;
import spark.components.supportClasses.DropDownListBase;
import spark.core.IDisplayText;
import spark.components.supportClasses.TextBase;
import spark.utils.LabelUtil;
use namespace mx_internal;
//--------------------------------------
// Other metadata
//--------------------------------------
[IconFile("DropDownList.png")]
/**
* Because this component does not define a skin for the mobile theme, Adobe
* recommends that you not use it in a mobile application. Alternatively, you
* can define your own mobile skin for the component. For more information,
* see <a href="http://help.adobe.com/en_US/flex/mobileapps/WS19f279b149e7481c698e85712b3011fe73-8000.html">Basics of mobile skinning</a>.
*/
[DiscouragedForProfile("mobileDevice")]
/**
* The DropDownList control contains a drop-down list
* from which the user can select a single value.
* Its functionality is very similar to that of the
* SELECT form element in HTML.
*
* <p>The DropDownList control consists of the anchor button,
* prompt area, and drop-down-list,
* Use the anchor button to open and close the drop-down-list.
* The prompt area displays a prompt String, or the selected item
* in the drop-down-list.</p>
*
* <p>When the drop-down list is open:</p>
* <ul>
* <li>Clicking the anchor button closes the drop-down list
* and commits the currently selected data item.</li>
* <li>Clicking outside of the drop-down list closes the drop-down list
* and commits the currently selected data item.</li>
* <li>Clicking on a data item selects that item and closes the drop-down list.</li>
* <li>If the <code>requireSelection</code> property is <code>false</code>,
* clicking on a data item while pressing the Control key deselects
* the item and closes the drop-down list.</li>
* </ul>
*
* <p><b>Note: </b>The Spark list-based controls (the Spark ListBase class and its subclasses
* such as ButtonBar, ComboBox, DropDownList, List, and TabBar) do not support the BasicLayout class
* as the value of the <code>layout</code> property.
* Do not use BasicLayout with the Spark list-based controls.</p>
*
* <p>To use this component in a list-based component, such as a List or DataGrid,
* create an item renderer.
* For information about creating an item renderer, see
* <a href="http://help.adobe.com/en_US/flex/using/WS4bebcd66a74275c3-fc6548e124e49b51c4-8000.html">
* Custom Spark item renderers</a>. </p>
*
* <p>The DropDownList control has the following default characteristics:</p>
* <table class="innertable">
* <tr><th>Characteristic</th><th>Description</th></tr>
* <tr><td>Default size</td><td>112 pixels wide and 21 pixels high</td></tr>
* <tr><td>Minimum size</td><td>112 pixels wide and 21 pixels high</td></tr>
* <tr><td>Maximum size</td><td>10000 pixels wide and 10000 pixels high</td></tr>
* <tr><td>Default skin class</td><td>spark.skins.spark.DropDownListSkin</td></tr>
* </table>
*
* @mxml <p>The <code><s:DropDownList></code> tag inherits all of the tag
* attributes of its superclass and adds the following tag attributes:</p>
*
* <pre>
* <s:DropDownList
* <strong>Properties</strong>
* prompt=""
* typicalItem="null"
*
* <strong>Events</strong>
* closed="<i>No default</i>"
* open="<i>No default</i>"
* />
* </pre>
*
* @see spark.skins.spark.DropDownListSkin
* @see spark.components.supportClasses.DropDownController
*
* @includeExample examples/DropDownListExample.mxml
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public class DropDownList extends DropDownListBase
{
include "../core/Version.as";
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function DropDownList()
{
super();
}
//--------------------------------------------------------------------------
//
// Skin parts
//
//--------------------------------------------------------------------------
//----------------------------------
// labelDisplay
//----------------------------------
[SkinPart(required="false")]
/**
* An optional skin part that holds the prompt or the text of the selected item.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public var labelDisplay:IDisplayText;
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
private var labelChanged:Boolean = false;
private var labelDisplayExplicitWidth:Number;
private var labelDisplayExplicitHeight:Number;
private var sizeSetByTypicalItem:Boolean;
//--------------------------------------------------------------------------
//
// Overridden properties
//
//--------------------------------------------------------------------------
//----------------------------------
// baselinePosition
//----------------------------------
/**
* @private
*/
override public function get baselinePosition():Number
{
return getBaselinePositionForPart(labelDisplay as IVisualElement);
}
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
//----------------------------------
// prompt
//----------------------------------
/**
* @private
*/
private var _prompt:String = "";
[Inspectable(category="General", defaultValue="")]
/**
* The prompt for the DropDownList control.
* The prompt is a String that is displayed in the
* DropDownList when <code>selectedIndex</code> = -1.
* It is usually a String such as "Select one...".
* Selecting an item in the drop-down list replaces the
* prompt with the text from the selected item.
*
* @default ""
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function get prompt():String
{
return _prompt;
}
/**
* @private
*/
public function set prompt(value:String):void
{
if (_prompt == value)
return;
_prompt = value;
labelChanged = true;
invalidateProperties();
}
//--------------------------------------------------------------------------
//
// Overridden Properties
//
//--------------------------------------------------------------------------
[Inspectable(category="Data")]
/**
* Layouts use the preferred size of the <code>typicalItem</code>
* when fixed row or column sizes are required, but a specific
* <code>rowHeight</code> or <code>columnWidth</code> value is not set.
* Similarly virtual layouts use this item to define the size
* of layout elements that have not been scrolled into view.
*
* <p>The container uses the typical data item, and the associated item renderer,
* to determine the default size of the container children.
* By defining the typical item, the container does not have to size each child
* as it is drawn on the screen.</p>
*
* <p>Setting this property sets the <code>typicalLayoutElement</code> property
* of the layout.</p>
*
* <p>Restriction: if the <code>typicalItem</code> is an IVisualItem, it must not
* also be a member of the data provider.</p>
*
* <p>Note: Setting <code>typicalItem</code> overrides any explicit width or height
* set on the <code>labelDisplay</code> skin part. </p>
*
* @default null
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
override public function set typicalItem(value:Object):void
{
super.typicalItem = value;
invalidateSize();
}
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
override protected function commitProperties():void
{
super.commitProperties();
if (labelChanged)
{
labelChanged = false;
updateLabelDisplay();
}
}
/**
* @private
*/
override protected function partAdded(partName:String, instance:Object):void
{
super.partAdded(partName, instance);
if (instance == labelDisplay)
{
labelChanged = true;
invalidateProperties();
}
}
/**
* @private
*/
override protected function measure():void
{
var labelComp:TextBase = labelDisplay as TextBase;
// If typicalItem is set, then use it for measurement
if (labelComp && typicalItem != null)
{
// Save the labelDisplay's dimensions in case we clear out typicalItem
if (!sizeSetByTypicalItem)
{
labelDisplayExplicitWidth = labelComp.explicitWidth;
labelDisplayExplicitHeight = labelComp.explicitHeight;
sizeSetByTypicalItem = true;
}
labelComp.explicitWidth = NaN;
labelComp.explicitHeight = NaN;
// Swap in the typicalItem into the labelDisplay
updateLabelDisplay(typicalItem);
UIComponentGlobals.layoutManager.validateClient(skin, true);
// Force the labelDisplay to be sized to the measured size
labelComp.width = labelComp.measuredWidth;
labelComp.height = labelComp.measuredHeight;
// Set the labelDisplay back to selectedItem
updateLabelDisplay();
}
else if (labelComp && sizeSetByTypicalItem && typicalItem == null)
{
// Restore the labelDisplay to its original size
labelComp.width = labelDisplayExplicitWidth;
labelComp.height = labelDisplayExplicitHeight;
sizeSetByTypicalItem = false;
}
super.measure();
}
/**
* @private
* Called whenever we need to update the text passed to the labelDisplay skin part
*/
// TODO (jszeto): Make this protected and make the name more generic (passing data to skin)
override mx_internal function updateLabelDisplay(displayItem:* = undefined):void
{
if (labelDisplay)
{
if (displayItem == undefined)
displayItem = selectedItem;
if (displayItem != null && displayItem != undefined)
labelDisplay.text = LabelUtil.itemToLabel(displayItem, labelField, labelFunction);
else
labelDisplay.text = prompt;
}
}
}
}
|
Fix regression issue. Turns out LabelUtil.itemToLabel has side effects and text was not updated on control unless called
|
Fix regression issue. Turns out LabelUtil.itemToLabel has side effects and text was not updated on control unless called
|
ActionScript
|
apache-2.0
|
apache/flex-sdk,apache/flex-sdk,apache/flex-sdk,apache/flex-sdk,apache/flex-sdk,apache/flex-sdk
|
05af37b27c28e6f236144931cc72e08c28aef1e8
|
src/main/flex/org/servebox/cafe/core/bootstrap/impl/DefaultBootstrapImpl.as
|
src/main/flex/org/servebox/cafe/core/bootstrap/impl/DefaultBootstrapImpl.as
|
package org.servebox.cafe.core.bootstrap.impl
{
import flash.utils.Dictionary;
import org.servebox.cafe.core.bootstrap.IBootstrap;
import org.servebox.cafe.core.modularity.IApplicationUnit;
import org.servebox.cafe.core.spring.IApplicationContext;
public class DefaultBootstrapImpl implements IBootstrap
{
private var _applicationUnits : Array;
public function initialize( context : IApplicationContext ) : void
{
}
public function get applicationUnits() : Array/*Vector.<ApplicationUnit>*/
{
return _applicationUnits;
}
public function set applicationUnits( units : Array/*Vector.<ApplicationUnit>*/ ) : void
{
this._applicationUnits = units;
}
public function getApplicationUnit( clazz : Class ) : IApplicationUnit
{
for each ( var o : IApplicationUnit in applicationUnits )
{
if ( o is clazz )
{
trace ( "return " + 0 );
return o;
}
}
throw new Error(" No application unit " + clazz + " in this cafe application context.");
}
public function postInitialize( context : IApplicationContext ) : void
{
}
}
}
|
package org.servebox.cafe.core.bootstrap.impl
{
import flash.utils.Dictionary;
import org.servebox.cafe.core.bootstrap.IBootstrap;
import org.servebox.cafe.core.modularity.IApplicationUnit;
import org.servebox.cafe.core.spring.IApplicationContext;
public class DefaultBootstrapImpl implements IBootstrap
{
private var _applicationUnits : Array;
public function initialize( context : IApplicationContext ) : void
{
}
public function get applicationUnits() : Array/*Vector.<ApplicationUnit>*/
{
return _applicationUnits;
}
public function set applicationUnits( units : Array/*Vector.<ApplicationUnit>*/ ) : void
{
this._applicationUnits = units;
}
public function getApplicationUnit( clazz : Class ) : IApplicationUnit
{
for each ( var o : IApplicationUnit in applicationUnits )
{
if ( o is clazz )
{
return o;
}
}
throw new Error(" No application unit " + clazz + " in this cafe application context.");
}
public function postInitialize( context : IApplicationContext ) : void
{
}
}
}
|
Remove trace.
|
Remove trace.
|
ActionScript
|
mit
|
servebox/as-cafe
|
ae87a2d648a9221906fa979b365bc2b35ac4a064
|
frameworks/as/src/org/apache/flex/html/staticControls/beads/TextInputBead.as
|
frameworks/as/src/org/apache/flex/html/staticControls/beads/TextInputBead.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.DisplayObject;
import flash.text.TextFieldType;
// this import is not used, but keeps the compiler from
// complaining about explicit usage of flash.events.Event
import flash.events.IOErrorEvent;
import org.apache.flex.core.IStrand;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
public class TextInputBead extends TextFieldBeadBase
{
public function TextInputBead()
{
super();
textField.selectable = true;
textField.type = TextFieldType.INPUT;
textField.mouseEnabled = true;
textField.multiline = false;
textField.wordWrap = false;
}
override public function set strand(value:IStrand):void
{
super.strand = value;
// Default size
var ww:Number = DisplayObject(strand).width;
if( isNaN(ww) || ww == 0 ) DisplayObject(strand).width = 100;
var hh:Number = DisplayObject(strand).height;
if( isNaN(hh) || hh == 0 ) DisplayObject(strand).height = 18;
// for input, listen for changes to the _textField and update
// the model
textField.addEventListener(flash.events.Event.CHANGE, inputChangeHandler);
IEventDispatcher(strand).addEventListener("widthChanged", sizeChangedHandler);
IEventDispatcher(strand).addEventListener("heightChanged", sizeChangedHandler);
sizeChangedHandler(null);
}
private function inputChangeHandler(event:Event):void
{
textModel.text = textField.text;
}
private function sizeChangedHandler(event:Event):void
{
var ww:Number = DisplayObject(strand).width;
if( !isNaN(ww) && ww > 0 ) textField.width = ww;
var hh:Number = DisplayObject(strand).height;
if( !isNaN(hh) && hh > 0 ) textField.height = hh;
}
}
}
|
//
// 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.DisplayObject;
import flash.text.TextFieldType;
// this import is not used, but keeps the compiler from
// complaining about explicit usage of flash.events.Event
import flash.events.IOErrorEvent;
import org.apache.flex.core.IStrand;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
public class TextInputBead extends TextFieldBeadBase
{
public function TextInputBead()
{
super();
textField.selectable = true;
textField.type = TextFieldType.INPUT;
textField.mouseEnabled = true;
textField.multiline = false;
textField.wordWrap = false;
}
override public function set strand(value:IStrand):void
{
super.strand = value;
// Default size
var ww:Number = DisplayObject(strand).width;
if( isNaN(ww) || ww == 0 ) DisplayObject(strand).width = 100;
var hh:Number = DisplayObject(strand).height;
if( isNaN(hh) || hh == 0 ) DisplayObject(strand).height = 18;
// for input, listen for changes to the _textField and update
// the model
textField.addEventListener(flash.events.Event.CHANGE, inputChangeHandler);
IEventDispatcher(strand).addEventListener("widthChanged", sizeChangedHandler);
IEventDispatcher(strand).addEventListener("heightChanged", sizeChangedHandler);
sizeChangedHandler(null);
}
private function inputChangeHandler(event:flash.events.Event):void
{
textModel.text = textField.text;
}
private function sizeChangedHandler(event:Event):void
{
var ww:Number = DisplayObject(strand).width;
if( !isNaN(ww) && ww > 0 ) textField.width = ww;
var hh:Number = DisplayObject(strand).height;
if( !isNaN(hh) && hh > 0 ) textField.height = hh;
}
}
}
|
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
|
34a6d3e9632c1b9a0ddd6b931dd5846091030131
|
src/as/com/threerings/parlor/game/client/FlexGameConfigurator.as
|
src/as/com/threerings/parlor/game/client/FlexGameConfigurator.as
|
//
// $Id$
//
// Vilya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/vilya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.parlor.game.client {
import mx.core.Container;
import mx.core.UIComponent;
import mx.containers.HBox;
import mx.containers.Tile;
import com.threerings.parlor.game.data.GameConfig;
import com.threerings.parlor.util.ParlorContext;
/**
* Provides the base from which interfaces can be built to configure games prior to starting them.
* Derived classes would extend the base configurator adding interface elements and wiring them up
* properly to allow the user to configure an instance of their game.
*
* <p> Clients that use the game configurator will want to instantiate one based on the class
* returned from the {@link GameConfig} and then initialize it with a call to {@link #init}.
*/
public /*abstract*/ class FlexGameConfigurator extends GameConfigurator
{
/**
* Get the Container that contains the UI elements for this configurator.
*/
public function getContainer () :Container
{
return _tile;
}
/**
* Add a control to the interface. This should be the standard way that configurator controls
* are added, but note also that external entities may add their own controls that are related
* to the game, but do not directly alter the game config, so that all the controls are added
* in a uniform manner and are well aligned.
*/
public function addControl (label :UIComponent, control :UIComponent) :void
{
var item :HBox = new HBox();
item.width = 225;
item.setStyle("horizontalGap", 5);
label.width = 95;
item.addChild(label);
control.width = 125;
item.addChild(control);
_tile.addChild(item);
}
/** The grid on which the config options are placed. */
protected var _tile :Tile = new Tile();
}
}
|
//
// $Id$
//
// Vilya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/vilya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.parlor.game.client {
import mx.core.Container;
import mx.core.UIComponent;
import mx.containers.Grid;
import mx.containers.GridItem;
import mx.containers.GridRow;
import mx.containers.HBox;
import com.threerings.parlor.game.data.GameConfig;
import com.threerings.parlor.util.ParlorContext;
/**
* Provides the base from which interfaces can be built to configure games prior to starting them.
* Derived classes would extend the base configurator adding interface elements and wiring them up
* properly to allow the user to configure an instance of their game.
*
* <p> Clients that use the game configurator will want to instantiate one based on the class
* returned from the {@link GameConfig} and then initialize it with a call to {@link #init}.
*/
public /*abstract*/ class FlexGameConfigurator extends GameConfigurator
{
/**
* Configures the number of columns to use when laying out our controls. This must be called
* before any calls to {@link #addControl}.
*/
public function setColumns (columns :int) :void
{
_columns = columns;
}
/**
* Get the Container that contains the UI elements for this configurator.
*/
public function getContainer () :Container
{
return _grid;
}
/**
* Add a control to the interface. This should be the standard way that configurator controls
* are added, but note also that external entities may add their own controls that are related
* to the game, but do not directly alter the game config, so that all the controls are added
* in a uniform manner and are well aligned.
*/
public function addControl (label :UIComponent, control :UIComponent) :void
{
if (_gridRow == null) {
_gridRow = new GridRow();
_grid.addChild(_gridRow);
}
_gridRow.addChild(wrapItem(label));
_gridRow.addChild(wrapItem(control));
if (_gridRow.numChildren == _columns * 2) {
_gridRow = null;
}
}
protected function wrapItem (component :UIComponent) :GridItem
{
var item :GridItem = new GridItem();
item.addChild(component);
return item;
}
/** The grid on which the config options are placed. */
protected var _grid :Grid = new Grid();
/** The current row to which we're adding controls. */
protected var _gridRow :GridRow;
/** The number of columns in which to lay out our configuration. */
protected var _columns :int = 2;
}
}
|
Use Grid instead of Tile as the latter requires hardcoding which blows.
|
Use Grid instead of Tile as the latter requires hardcoding which blows.
git-svn-id: a3e1eb16dde062992de22c830ed8045c8013209a@495 c613c5cb-e716-0410-b11b-feb51c14d237
|
ActionScript
|
lgpl-2.1
|
threerings/vilya,threerings/vilya
|
5090c2129a3f98b2f74a9cea8791fafe168291fb
|
otp.replace.as
|
otp.replace.as
|
#!/bin/ksh -e
typeset -ir makejobs='5'
typeset -ir verbosity='0'
usage()
{
echo "Usage: ${0##*/} otp-name-or-path otp-inst-label" >&2
exit 1
}
[[ $# == 2 ]] || usage
[[ "$2" != */* ]] || usage
typeset -lr otp_name="${2}"
case "$1" in
*/* )
otpsrc="$1"
;;
. )
otpsrc="$(pwd)"
;;
.. )
otpsrc="$(dirname "$(pwd)")"
;;
* )
if [[ -d "$1" ]]
then
otpsrc="$1"
else
otpsrc="$BASHO_PRJ_BASE/$1"
fi
;;
esac
readonly otp_src
[[ -z "$(whence -v kerl_deactivate 2>/dev/null)" ]] || kerl_deactivate
[[ -z "$(whence -v reset_lenv 2>/dev/null)" ]] || reset_lenv
cd "$otpsrc"
unset ERL_TOP ERL_LIBS MAKEFLAGS
. "$LOCAL_ENV_DIR/os.type"
. "$LOCAL_ENV_DIR/otp.install.base"
. "$LOCAL_ENV_DIR/otp.source.version"
arch_flags='-m64 -march=core2 -mcx16'
arch_flags='-m64 -march=native -mcx16'
case "$os_type" in
darwin )
osx_ver="$(/usr/bin/sw_vers -productVersion | /usr/bin/cut -d. -f1,2)"
arch_flags+=" -arch x86_64 -mmacosx-version-min=$osx_ver"
ccands='icc /usr/bin/cc gcc cc'
cccands='/usr/bin/c++ g++ c++'
config_os='--enable-darwin-64bit --with-cocoa'
;;
linux )
ccands='icc gcc cc'
cccands='g++ gcc c++'
config_os='--enable-64bit'
;;
freebsd )
ccands='icc clang37 /usr/bin/cc gcc cc'
cccands='/usr/bin/c++ g++ c++'
config_os='--enable-64bit'
;;
* )
ccands='cc gcc'
cccands='c++ g++'
config_os='--enable-64bit'
;;
esac
for c in $ccands
do
CC="$(whence -p $c || true)"
[[ -z "$CC" ]] || break
done
if [[ "${CC##*/}" == icc || "${CC##*/}" == clang* ]]
then
CXX="$CC"
else
for c in $cccands $CC
do
CXX="$(whence -p $c || true)"
[[ -z "$CXX" ]] || break
done
fi
unset c ccand cccand
[[ -n "$LANG" ]] || LANG='C'
LDFLAGS="$arch_flags -O4"
CFLAGS="$arch_flags -O3"
if [[ $otp_vsn_major -lt 17 ]]
then
CFLAGS+=' -Wno-deprecated-declarations'
CFLAGS+=' -Wno-empty-body'
CFLAGS+=' -Wno-implicit-function-declaration'
CFLAGS+=' -Wno-parentheses-equality'
CFLAGS+=' -Wno-pointer-sign'
CFLAGS+=' -Wno-tentative-definition-incomplete-type'
CFLAGS+=' -Wno-unused-function'
CFLAGS+=' -Wno-unused-value'
CFLAGS+=' -Wno-unused-variable'
fi
CXXFLAGS="$CFLAGS"
export CC CFLAGS CXX CXXFLAGS LANG LDFLAGS
config_opts="$config_os --with-ssl --without-odbc"
[[ $otp_vsn_major -ge 16 ]] || config_opts+=' --without-wx'
[[ $otp_vsn_major -lt 17 ]] || config_opts+=' --without-gs'
[[ $otp_vsn_major -lt 17 ]] || config_opts+=' --enable-dirty-schedulers'
ERL_TOP="$(pwd)"
PATH="$ERL_TOP/bin:$PATH"
export ERL_TOP PATH
for hipe in false true
do
if $hipe
then
otp_label="$otp_name-h1"
hipe_flag='--enable-hipe'
else
otp_label="$otp_name-h0"
hipe_flag='--disable-hipe'
fi
otp_dest="$otp_install_base/$otp_label"
build_cfg="--prefix $otp_dest $config_opts $hipe_flag"
build_log="build.$os_type.$otp_label.txt"
install_log="install.$os_type.$otp_label.txt"
$GIT clean -fdqx -e /env -e /.idea/ -e '*.iml' -e '/*.txt'
[[ $makejobs -lt 2 ]] || export MAKEFLAGS="-j$makejobs"
[[ $verbosity -lt 1 ]] || export V="$verbosity"
/bin/date >"$build_log"
env | sort >>"$build_log"
echo "./otp_build setup -a $build_cfg" | tee -a "$build_log"
./otp_build setup -a $build_cfg 1>>"$build_log" 2>&1
/bin/date >>"$build_log"
unset V MAKEFLAGS
if [[ -d "$otp_dest" ]]
then
rm -rf "$otp_dest/bin" "$otp_dest/lib"
else
mkdir -m 2775 "$otp_dest"
fi
/bin/date >"$install_log"
echo "$MAKE install" | tee -a "$install_log"
$MAKE install 1>>"$install_log" 2>&1
/bin/date >>"$install_log"
cp -p "$build_log" "$install_log" "$otp_dest"
[[ -e "$otp_dest/activate" ]] || \
ln -s "$LOCAL_ENV_DIR/otp.activate" "$otp_dest/activate"
done
|
#!/bin/ksh -e
typeset -ir makejobs='5'
typeset -ir verbosity='0'
usage()
{
echo "Usage: ${0##*/} otp-name-or-path otp-inst-label" >&2
exit 1
}
[[ $# == 2 ]] || usage
[[ "$2" != */* ]] || usage
typeset -lr otp_name="${2}"
case "$1" in
*/* )
otpsrc="$1"
;;
. )
otpsrc="$(pwd)"
;;
.. )
otpsrc="$(dirname "$(pwd)")"
;;
* )
if [[ -d "$1" ]]
then
otpsrc="$1"
else
otpsrc="$BASHO_PRJ_BASE/$1"
fi
;;
esac
readonly otp_src
[[ -z "$(whence -v kerl_deactivate 2>/dev/null)" ]] || kerl_deactivate
[[ -z "$(whence -v reset_lenv 2>/dev/null)" ]] || reset_lenv
cd "$otpsrc"
unset ERL_TOP ERL_LIBS MAKEFLAGS
. "$LOCAL_ENV_DIR/os.type"
. "$LOCAL_ENV_DIR/otp.install.base"
. "$LOCAL_ENV_DIR/otp.source.version"
if [[ $otp_vsn_major -gt 16 ]]
then
hipe_modes='false true'
else
hipe_modes='false'
fi
arch_flags='-m64 -march=core2 -mcx16'
arch_flags='-m64 -march=native -mcx16'
case "$os_type" in
darwin )
osx_ver="$(/usr/bin/sw_vers -productVersion | /usr/bin/cut -d. -f1,2)"
arch_flags+=" -arch x86_64 -mmacosx-version-min=$osx_ver"
ccands='icc /usr/bin/cc gcc cc'
cccands='/usr/bin/c++ g++ c++'
config_os='--enable-darwin-64bit --with-cocoa'
hipe_modes='false'
;;
linux )
ccands='icc gcc cc'
cccands='g++ gcc c++'
config_os='--enable-64bit'
;;
freebsd )
ccands='icc clang37 /usr/bin/cc gcc cc'
cccands='/usr/bin/c++ g++ c++'
config_os='--enable-64bit'
;;
* )
ccands='cc gcc'
cccands='c++ g++'
config_os='--enable-64bit'
;;
esac
for c in $ccands
do
CC="$(whence -p $c || true)"
[[ -z "$CC" ]] || break
done
if [[ "${CC##*/}" == icc || "${CC##*/}" == clang* ]]
then
CXX="$CC"
else
for c in $cccands $CC
do
CXX="$(whence -p $c || true)"
[[ -z "$CXX" ]] || break
done
fi
unset c ccand cccand
[[ -n "$LANG" ]] || LANG='C'
LDFLAGS="$arch_flags -O4"
CFLAGS="$arch_flags -O3"
if [[ $otp_vsn_major -lt 17 ]]
then
CFLAGS+=' -Wno-deprecated-declarations'
CFLAGS+=' -Wno-empty-body'
CFLAGS+=' -Wno-implicit-function-declaration'
CFLAGS+=' -Wno-parentheses-equality'
CFLAGS+=' -Wno-pointer-sign'
CFLAGS+=' -Wno-tentative-definition-incomplete-type'
CFLAGS+=' -Wno-unused-function'
CFLAGS+=' -Wno-unused-value'
CFLAGS+=' -Wno-unused-variable'
fi
CXXFLAGS="$CFLAGS"
export CC CFLAGS CXX CXXFLAGS LANG LDFLAGS
config_opts="$config_os --with-ssl --without-odbc"
[[ $otp_vsn_major -ge 16 ]] || config_opts+=' --without-wx'
[[ $otp_vsn_major -lt 17 ]] || config_opts+=' --without-gs'
[[ $otp_vsn_major -lt 17 ]] || config_opts+=' --enable-dirty-schedulers'
ERL_TOP="$(pwd)"
PATH="$ERL_TOP/bin:$PATH"
export ERL_TOP PATH
for hipe in $hipe_modes
do
if $hipe
then
otp_label="${otp_name}h"
hipe_flag='--enable-hipe'
else
otp_label="$otp_name"
hipe_flag='--disable-hipe'
fi
otp_dest="$otp_install_base/$otp_label"
build_cfg="--prefix $otp_dest $config_opts $hipe_flag"
build_log="build.$os_type.$otp_label.txt"
install_log="install.$os_type.$otp_label.txt"
$GIT clean -fdqx -e /env -e /.idea/ -e '*.iml' -e '/*.txt'
[[ $makejobs -lt 2 ]] || export MAKEFLAGS="-j$makejobs"
[[ $verbosity -lt 1 ]] || export V="$verbosity"
/bin/date >"$build_log"
env | sort >>"$build_log"
echo "./otp_build setup -a $build_cfg" | tee -a "$build_log"
./otp_build setup -a $build_cfg 1>>"$build_log" 2>&1
/bin/date >>"$build_log"
unset V MAKEFLAGS
if [[ -d "$otp_dest" ]]
then
rm -rf "$otp_dest/bin" "$otp_dest/lib"
else
mkdir -m 2775 "$otp_dest"
fi
/bin/date >"$install_log"
echo "$MAKE install" | tee -a "$install_log"
$MAKE install 1>>"$install_log" 2>&1
/bin/date >>"$install_log"
cp -p "$build_log" "$install_log" "$otp_dest"
[[ -e "$otp_dest/activate" ]] || \
ln -s "$LOCAL_ENV_DIR/otp.activate" "$otp_dest/activate"
done
|
adjust whether to build with hHiPE support
|
adjust whether to build with hHiPE support
|
ActionScript
|
isc
|
tburghart/local_env,tburghart/local_env
|
664dc68180110d53b015d4b6e9219859a5f1e8a5
|
src/com/esri/builder/components/serviceBrowser/supportClasses/ServiceDirectoryBuilder.as
|
src/com/esri/builder/components/serviceBrowser/supportClasses/ServiceDirectoryBuilder.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.components.serviceBrowser.supportClasses
{
import com.esri.ags.components.IdentityManager;
import com.esri.ags.components.supportClasses.Credential;
import com.esri.ags.tasks.JSONTask;
import com.esri.builder.components.serviceBrowser.filters.GPTaskFilter;
import com.esri.builder.components.serviceBrowser.filters.GeocoderFilter;
import com.esri.builder.components.serviceBrowser.filters.INodeFilter;
import com.esri.builder.components.serviceBrowser.filters.MapLayerFilter;
import com.esri.builder.components.serviceBrowser.filters.MapServerFilter;
import com.esri.builder.components.serviceBrowser.filters.QueryableLayerFilter;
import com.esri.builder.components.serviceBrowser.filters.RouteLayerFilter;
import com.esri.builder.components.serviceBrowser.nodes.ServiceDirectoryRootNode;
import com.esri.builder.model.Model;
import com.esri.builder.model.PortalModel;
import com.esri.builder.supportClasses.LogUtil;
import flash.events.EventDispatcher;
import flash.net.URLVariables;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.resources.ResourceManager;
import mx.rpc.Fault;
import mx.rpc.Responder;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import mx.utils.URLUtil;
public final class ServiceDirectoryBuilder extends EventDispatcher
{
private static const LOG:ILogger = LogUtil.createLogger(ServiceDirectoryBuilder);
private static const DEFAULT_REQUEST_TIMEOUT_IN_SECONDS:Number = 10;
private var count:int;
private var searchType:String;
private var serviceDirectoryBuildRequest:ServiceDirectoryBuildRequest;
private var hasCrossDomain:Boolean;
private var crossDomainRequest:HTTPService;
private var credential:Credential;
private var rootNode:ServiceDirectoryRootNode;
private var currentNodeFilter:INodeFilter;
private var isServiceSecured:Boolean;
private var securityWarning:String;
private var owningSystemURL:String;
public function buildServiceDirectory(serviceDirectoryBuildRequest:ServiceDirectoryBuildRequest):void
{
if (Log.isInfo())
{
LOG.info("Building service directory");
}
this.serviceDirectoryBuildRequest = serviceDirectoryBuildRequest;
try
{
checkCrossDomainBeforeBuildingDirectory();
}
catch (error:Error)
{
//TODO: handle error
}
}
private function checkCrossDomainBeforeBuildingDirectory():void
{
if (Log.isDebug())
{
LOG.debug("Checking service URL crossdomain.xml");
}
crossDomainRequest = new HTTPService();
crossDomainRequest.url = extractCrossDomainPolicyFileURL(serviceDirectoryBuildRequest.url);
crossDomainRequest.addEventListener(ResultEvent.RESULT, crossDomainRequest_resultHandler);
crossDomainRequest.addEventListener(FaultEvent.FAULT, crossDomainRequest_faultHandler);
crossDomainRequest.requestTimeout = DEFAULT_REQUEST_TIMEOUT_IN_SECONDS;
crossDomainRequest.send();
function crossDomainRequest_resultHandler(event:ResultEvent):void
{
if (Log.isDebug())
{
LOG.debug("Found service crossdomain.xml");
}
crossDomainRequest.removeEventListener(ResultEvent.RESULT, crossDomainRequest_resultHandler);
crossDomainRequest.removeEventListener(FaultEvent.FAULT, crossDomainRequest_faultHandler);
crossDomainRequest = null;
hasCrossDomain = true;
getServiceInfo();
}
function crossDomainRequest_faultHandler(event:FaultEvent):void
{
if (Log.isDebug())
{
LOG.debug("Could not find service crossdomain.xml");
}
crossDomainRequest.removeEventListener(ResultEvent.RESULT, crossDomainRequest_resultHandler);
crossDomainRequest.removeEventListener(FaultEvent.FAULT, crossDomainRequest_faultHandler);
crossDomainRequest = null;
hasCrossDomain = false;
getServiceInfo();
}
}
private function extractCrossDomainPolicyFileURL(url:String):String
{
var baseURL:RegExp = /(https?:\/\/)([^\/]+\/)/
var baseURLMatch:Array = url.match(baseURL);
return baseURLMatch[0] + 'crossdomain.xml';
}
private function getServiceInfo():void
{
var serviceInfoRequest:JSONTask = new JSONTask();
serviceInfoRequest.url = extractServiceInfoURL(serviceDirectoryBuildRequest.url);
const param:URLVariables = new URLVariables();
param.f = 'json';
serviceInfoRequest.execute(param, new Responder(serviceInfoRequest_resultHandler, serviceInfoRequest_faultHandler));
function serviceInfoRequest_resultHandler(serverInfo:Object):void
{
owningSystemURL = serverInfo.owningSystemUrl;
if (isOwnedByPortal(owningSystemURL))
{
if (PortalModel.getInstance().portal.signedIn)
{
IdentityManager.instance.getCredential(
serviceDirectoryBuildRequest.url, false,
new Responder(getCredential_successHandler, getCredential_faultHandler));
function getCredential_successHandler(credential:Credential):void
{
checkIfServiceIsSecure(serverInfo);
}
function getCredential_faultHandler(fault:Fault):void
{
checkIfServiceIsSecure(serverInfo);
}
}
else
{
var credential:Credential = IdentityManager.instance.findCredential(serviceDirectoryBuildRequest.url);
if (credential)
{
credential.destroy();
}
checkIfServiceIsSecure(serverInfo);
}
}
else
{
checkIfServiceIsSecure(serverInfo);
}
}
function serviceInfoRequest_faultHandler(fault:Fault):void
{
checkIfServiceIsSecure(null);
}
}
private function isOwnedByPortal(owningSystemURL:String):Boolean
{
if (owningSystemURL == null)
{
owningSystemURL = "";
}
var owningSystemURLServerNameWithPort:String = URLUtil.getServerName(owningSystemURL);
var portalServerNameWithPort:String = URLUtil.getServerName(PortalModel.getInstance().portalURL);
return (owningSystemURLServerNameWithPort == portalServerNameWithPort);
}
private function checkIfServiceIsSecure(serverInfo:Object):void
{
if (Log.isInfo())
{
LOG.info("Checking if service is secure");
}
if (serverInfo)
{
isServiceSecured = (serverInfo.currentVersion >= 10.01
&& serverInfo.authInfo
&& serverInfo.authInfo.isTokenBasedSecurity);
if (isServiceSecured)
{
if (Log.isDebug())
{
LOG.debug("Service is secure");
}
if (Log.isDebug())
{
LOG.debug("Checking token service crossdomain.xml");
}
const tokenServiceCrossDomainRequest:HTTPService = new HTTPService();
tokenServiceCrossDomainRequest.url = extractCrossDomainPolicyFileURL(serverInfo.authInfo.tokenServicesUrl);
tokenServiceCrossDomainRequest.resultFormat = HTTPService.RESULT_FORMAT_E4X;
tokenServiceCrossDomainRequest.addEventListener(ResultEvent.RESULT, tokenServiceSecurityRequest_resultHandler);
tokenServiceCrossDomainRequest.addEventListener(FaultEvent.FAULT, tokenServiceSecurityRequest_faultHandler);
tokenServiceCrossDomainRequest.send();
function tokenServiceSecurityRequest_resultHandler(event:ResultEvent):void
{
if (Log.isDebug())
{
LOG.debug("Found token service crossdomain.xml");
}
tokenServiceCrossDomainRequest.removeEventListener(ResultEvent.RESULT, tokenServiceSecurityRequest_resultHandler);
tokenServiceCrossDomainRequest.removeEventListener(FaultEvent.FAULT, tokenServiceSecurityRequest_faultHandler);
const startsWithHTTPS:RegExp = /^https/;
if (startsWithHTTPS.test(tokenServiceCrossDomainRequest.url))
{
const tokenServiceCrossDomainXML:XML = event.result as XML;
const hasSecurityEnabled:Boolean =
tokenServiceCrossDomainXML.child("allow-access-from").(attribute("secure") == "false").length() == 0
|| tokenServiceCrossDomainXML.child("allow-http-request-headers-from").(attribute("secure") == "false").length() == 0;
if (hasSecurityEnabled
&& !startsWithHTTPS.test(Model.instance.appDir.url))
{
securityWarning = ResourceManager.getInstance().getString('BuilderStrings', 'serviceBrowser.secureTokenServiceWithSecureCrossDomain');
}
}
}
function tokenServiceSecurityRequest_faultHandler(event:FaultEvent):void
{
if (Log.isDebug())
{
LOG.debug("Could not find token service crossdomain.xml");
}
tokenServiceCrossDomainRequest.removeEventListener(ResultEvent.RESULT, tokenServiceSecurityRequest_resultHandler);
tokenServiceCrossDomainRequest.removeEventListener(FaultEvent.FAULT, tokenServiceSecurityRequest_faultHandler);
securityWarning = ResourceManager.getInstance().getString('BuilderStrings', 'serviceBrowser.secureTokenServiceMissingCrossDomain');
}
}
//continue with building service directory
startBuildingDirectory();
}
else
{
//continue with building service directory
startBuildingDirectory();
}
}
private function extractServiceInfoURL(url:String):String
{
return url.replace('/rest/services', '/rest/info');
}
private function startBuildingDirectory():void
{
if (Log.isInfo())
{
LOG.info('Building serviced directory {0}', serviceDirectoryBuildRequest.url);
}
const servicesDirectoryURL:RegExp = /.+\/rest\/services\/?/;
const serviceURLRootMatch:Array = servicesDirectoryURL.exec(serviceDirectoryBuildRequest.url);
if (!serviceURLRootMatch)
{
return;
}
currentNodeFilter = filterFromSearchType(serviceDirectoryBuildRequest.searchType);
rootNode = new ServiceDirectoryRootNode(serviceDirectoryBuildRequest.url, currentNodeFilter);
rootNode.addEventListener(URLNodeTraversalEvent.END_REACHED, rootNode_completeHandler);
rootNode.addEventListener(FaultEvent.FAULT, rootNode_faultHandler);
credential = IdentityManager.instance.findCredential(serviceURLRootMatch[0]);
if (credential)
{
rootNode.token = credential.token;
}
rootNode.loadChildren();
}
private function filterFromSearchType(searchType:String):INodeFilter
{
if (searchType == ServiceDirectoryBuildRequest.QUERYABLE_LAYER_SEARCH)
{
return new QueryableLayerFilter();
}
else if (searchType == ServiceDirectoryBuildRequest.GEOPROCESSING_TASK_SEARCH)
{
return new GPTaskFilter();
}
else if (searchType == ServiceDirectoryBuildRequest.GEOCODER_SEARCH)
{
return new GeocoderFilter();
}
else if (searchType == ServiceDirectoryBuildRequest.ROUTE_LAYER_SEARCH)
{
return new RouteLayerFilter();
}
else if (searchType == ServiceDirectoryBuildRequest.MAP_SERVER_SEARCH)
{
return new MapServerFilter();
}
else //MAP LAYER SEARCH
{
return new MapLayerFilter();
}
}
private function rootNode_completeHandler(event:URLNodeTraversalEvent):void
{
if (Log.isInfo())
{
LOG.info("Finished building service directory");
}
dispatchEvent(
new ServiceDirectoryBuilderEvent(ServiceDirectoryBuilderEvent.COMPLETE,
new ServiceDirectoryInfo(rootNode,
event.urlNodes,
currentNodeFilter,
hasCrossDomain,
isServiceSecured,
securityWarning,
owningSystemURL)));
}
protected function rootNode_faultHandler(event:FaultEvent):void
{
if (Log.isInfo())
{
LOG.info("Could not build service directory");
}
dispatchEvent(event);
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
// 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.components.serviceBrowser.supportClasses
{
import com.esri.ags.components.IdentityManager;
import com.esri.ags.components.supportClasses.Credential;
import com.esri.ags.tasks.JSONTask;
import com.esri.builder.components.serviceBrowser.filters.GPTaskFilter;
import com.esri.builder.components.serviceBrowser.filters.GeocoderFilter;
import com.esri.builder.components.serviceBrowser.filters.INodeFilter;
import com.esri.builder.components.serviceBrowser.filters.MapLayerFilter;
import com.esri.builder.components.serviceBrowser.filters.MapServerFilter;
import com.esri.builder.components.serviceBrowser.filters.QueryableLayerFilter;
import com.esri.builder.components.serviceBrowser.filters.RouteLayerFilter;
import com.esri.builder.components.serviceBrowser.nodes.ServiceDirectoryRootNode;
import com.esri.builder.model.Model;
import com.esri.builder.model.PortalModel;
import com.esri.builder.supportClasses.LogUtil;
import flash.events.EventDispatcher;
import flash.net.URLVariables;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.resources.ResourceManager;
import mx.rpc.Fault;
import mx.rpc.Responder;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import mx.utils.URLUtil;
public final class ServiceDirectoryBuilder extends EventDispatcher
{
private static const LOG:ILogger = LogUtil.createLogger(ServiceDirectoryBuilder);
private static const DEFAULT_REQUEST_TIMEOUT_IN_SECONDS:Number = 10;
private var serviceDirectoryBuildRequest:ServiceDirectoryBuildRequest;
private var hasCrossDomain:Boolean;
private var crossDomainRequest:HTTPService;
private var credential:Credential;
private var rootNode:ServiceDirectoryRootNode;
private var currentNodeFilter:INodeFilter;
private var isServiceSecured:Boolean;
private var securityWarning:String;
private var owningSystemURL:String;
public function buildServiceDirectory(serviceDirectoryBuildRequest:ServiceDirectoryBuildRequest):void
{
if (Log.isInfo())
{
LOG.info("Building service directory");
}
this.serviceDirectoryBuildRequest = serviceDirectoryBuildRequest;
try
{
checkCrossDomainBeforeBuildingDirectory();
}
catch (error:Error)
{
//TODO: handle error
}
}
private function checkCrossDomainBeforeBuildingDirectory():void
{
if (Log.isDebug())
{
LOG.debug("Checking service URL crossdomain.xml");
}
crossDomainRequest = new HTTPService();
crossDomainRequest.url = extractCrossDomainPolicyFileURL(serviceDirectoryBuildRequest.url);
crossDomainRequest.addEventListener(ResultEvent.RESULT, crossDomainRequest_resultHandler);
crossDomainRequest.addEventListener(FaultEvent.FAULT, crossDomainRequest_faultHandler);
crossDomainRequest.requestTimeout = DEFAULT_REQUEST_TIMEOUT_IN_SECONDS;
crossDomainRequest.send();
function crossDomainRequest_resultHandler(event:ResultEvent):void
{
if (Log.isDebug())
{
LOG.debug("Found service crossdomain.xml");
}
crossDomainRequest.removeEventListener(ResultEvent.RESULT, crossDomainRequest_resultHandler);
crossDomainRequest.removeEventListener(FaultEvent.FAULT, crossDomainRequest_faultHandler);
crossDomainRequest = null;
hasCrossDomain = true;
getServiceInfo();
}
function crossDomainRequest_faultHandler(event:FaultEvent):void
{
if (Log.isDebug())
{
LOG.debug("Could not find service crossdomain.xml");
}
crossDomainRequest.removeEventListener(ResultEvent.RESULT, crossDomainRequest_resultHandler);
crossDomainRequest.removeEventListener(FaultEvent.FAULT, crossDomainRequest_faultHandler);
crossDomainRequest = null;
hasCrossDomain = false;
getServiceInfo();
}
}
private function extractCrossDomainPolicyFileURL(url:String):String
{
var baseURL:RegExp = /(https?:\/\/)([^\/]+\/)/
var baseURLMatch:Array = url.match(baseURL);
return baseURLMatch[0] + 'crossdomain.xml';
}
private function getServiceInfo():void
{
var serviceInfoRequest:JSONTask = new JSONTask();
serviceInfoRequest.url = extractServiceInfoURL(serviceDirectoryBuildRequest.url);
const param:URLVariables = new URLVariables();
param.f = 'json';
serviceInfoRequest.execute(param, new Responder(serviceInfoRequest_resultHandler, serviceInfoRequest_faultHandler));
function serviceInfoRequest_resultHandler(serverInfo:Object):void
{
owningSystemURL = serverInfo.owningSystemUrl;
if (isOwnedByPortal(owningSystemURL))
{
if (PortalModel.getInstance().portal.signedIn)
{
IdentityManager.instance.getCredential(
serviceDirectoryBuildRequest.url, false,
new Responder(getCredential_successHandler, getCredential_faultHandler));
function getCredential_successHandler(credential:Credential):void
{
checkIfServiceIsSecure(serverInfo);
}
function getCredential_faultHandler(fault:Fault):void
{
checkIfServiceIsSecure(serverInfo);
}
}
else
{
var credential:Credential = IdentityManager.instance.findCredential(serviceDirectoryBuildRequest.url);
if (credential)
{
credential.destroy();
}
checkIfServiceIsSecure(serverInfo);
}
}
else
{
checkIfServiceIsSecure(serverInfo);
}
}
function serviceInfoRequest_faultHandler(fault:Fault):void
{
checkIfServiceIsSecure(null);
}
}
private function isOwnedByPortal(owningSystemURL:String):Boolean
{
if (owningSystemURL == null)
{
owningSystemURL = "";
}
var owningSystemURLServerNameWithPort:String = URLUtil.getServerName(owningSystemURL);
var portalServerNameWithPort:String = URLUtil.getServerName(PortalModel.getInstance().portalURL);
return (owningSystemURLServerNameWithPort == portalServerNameWithPort);
}
private function checkIfServiceIsSecure(serverInfo:Object):void
{
if (Log.isInfo())
{
LOG.info("Checking if service is secure");
}
if (serverInfo)
{
isServiceSecured = (serverInfo.currentVersion >= 10.01
&& serverInfo.authInfo
&& serverInfo.authInfo.isTokenBasedSecurity);
if (isServiceSecured)
{
if (Log.isDebug())
{
LOG.debug("Service is secure");
}
if (Log.isDebug())
{
LOG.debug("Checking token service crossdomain.xml");
}
const tokenServiceCrossDomainRequest:HTTPService = new HTTPService();
tokenServiceCrossDomainRequest.url = extractCrossDomainPolicyFileURL(serverInfo.authInfo.tokenServicesUrl);
tokenServiceCrossDomainRequest.resultFormat = HTTPService.RESULT_FORMAT_E4X;
tokenServiceCrossDomainRequest.addEventListener(ResultEvent.RESULT, tokenServiceSecurityRequest_resultHandler);
tokenServiceCrossDomainRequest.addEventListener(FaultEvent.FAULT, tokenServiceSecurityRequest_faultHandler);
tokenServiceCrossDomainRequest.send();
function tokenServiceSecurityRequest_resultHandler(event:ResultEvent):void
{
if (Log.isDebug())
{
LOG.debug("Found token service crossdomain.xml");
}
tokenServiceCrossDomainRequest.removeEventListener(ResultEvent.RESULT, tokenServiceSecurityRequest_resultHandler);
tokenServiceCrossDomainRequest.removeEventListener(FaultEvent.FAULT, tokenServiceSecurityRequest_faultHandler);
const startsWithHTTPS:RegExp = /^https/;
if (startsWithHTTPS.test(tokenServiceCrossDomainRequest.url))
{
const tokenServiceCrossDomainXML:XML = event.result as XML;
const hasSecurityEnabled:Boolean =
tokenServiceCrossDomainXML.child("allow-access-from").(attribute("secure") == "false").length() == 0
|| tokenServiceCrossDomainXML.child("allow-http-request-headers-from").(attribute("secure") == "false").length() == 0;
if (hasSecurityEnabled
&& !startsWithHTTPS.test(Model.instance.appDir.url))
{
securityWarning = ResourceManager.getInstance().getString('BuilderStrings', 'serviceBrowser.secureTokenServiceWithSecureCrossDomain');
}
}
}
function tokenServiceSecurityRequest_faultHandler(event:FaultEvent):void
{
if (Log.isDebug())
{
LOG.debug("Could not find token service crossdomain.xml");
}
tokenServiceCrossDomainRequest.removeEventListener(ResultEvent.RESULT, tokenServiceSecurityRequest_resultHandler);
tokenServiceCrossDomainRequest.removeEventListener(FaultEvent.FAULT, tokenServiceSecurityRequest_faultHandler);
securityWarning = ResourceManager.getInstance().getString('BuilderStrings', 'serviceBrowser.secureTokenServiceMissingCrossDomain');
}
}
//continue with building service directory
startBuildingDirectory();
}
else
{
//continue with building service directory
startBuildingDirectory();
}
}
private function extractServiceInfoURL(url:String):String
{
return url.replace('/rest/services', '/rest/info');
}
private function startBuildingDirectory():void
{
if (Log.isInfo())
{
LOG.info('Building serviced directory {0}', serviceDirectoryBuildRequest.url);
}
const servicesDirectoryURL:RegExp = /.+\/rest\/services\/?/;
const serviceURLRootMatch:Array = servicesDirectoryURL.exec(serviceDirectoryBuildRequest.url);
if (!serviceURLRootMatch)
{
return;
}
currentNodeFilter = filterFromSearchType(serviceDirectoryBuildRequest.searchType);
rootNode = new ServiceDirectoryRootNode(serviceDirectoryBuildRequest.url, currentNodeFilter);
rootNode.addEventListener(URLNodeTraversalEvent.END_REACHED, rootNode_completeHandler);
rootNode.addEventListener(FaultEvent.FAULT, rootNode_faultHandler);
credential = IdentityManager.instance.findCredential(serviceURLRootMatch[0]);
if (credential)
{
rootNode.token = credential.token;
}
rootNode.loadChildren();
}
private function filterFromSearchType(searchType:String):INodeFilter
{
if (searchType == ServiceDirectoryBuildRequest.QUERYABLE_LAYER_SEARCH)
{
return new QueryableLayerFilter();
}
else if (searchType == ServiceDirectoryBuildRequest.GEOPROCESSING_TASK_SEARCH)
{
return new GPTaskFilter();
}
else if (searchType == ServiceDirectoryBuildRequest.GEOCODER_SEARCH)
{
return new GeocoderFilter();
}
else if (searchType == ServiceDirectoryBuildRequest.ROUTE_LAYER_SEARCH)
{
return new RouteLayerFilter();
}
else if (searchType == ServiceDirectoryBuildRequest.MAP_SERVER_SEARCH)
{
return new MapServerFilter();
}
else //MAP LAYER SEARCH
{
return new MapLayerFilter();
}
}
private function rootNode_completeHandler(event:URLNodeTraversalEvent):void
{
if (Log.isInfo())
{
LOG.info("Finished building service directory");
}
dispatchEvent(
new ServiceDirectoryBuilderEvent(ServiceDirectoryBuilderEvent.COMPLETE,
new ServiceDirectoryInfo(rootNode,
event.urlNodes,
currentNodeFilter,
hasCrossDomain,
isServiceSecured,
securityWarning,
owningSystemURL)));
}
protected function rootNode_faultHandler(event:FaultEvent):void
{
if (Log.isInfo())
{
LOG.info("Could not build service directory");
}
dispatchEvent(event);
}
}
}
|
Remove unused fields (ServiceDirectoryBuilder).
|
Remove unused fields (ServiceDirectoryBuilder).
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
cc772dfa52f1ec4cc78fbf554000be2803d67cd2
|
actionscript-cafe/src/main/flex/org/servebox/cafe/core/command/CommandBinding.as
|
actionscript-cafe/src/main/flex/org/servebox/cafe/core/command/CommandBinding.as
|
package org.servebox.cafe.core.command
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import mx.binding.utils.BindingUtils;
import mx.binding.utils.ChangeWatcher;
import mx.core.UIComponent;
public class CommandBinding extends EventDispatcher
{
private var _command : ICommand;
private var _target : IEventDispatcher;
private var _triggerEvents : String;
private var _arTriggerEvents : Array;
private var _parameters : Array;
private var setterWatcher : ChangeWatcher;
public function CommandBinding()
{
super();
}
public function get parameters():Array
{
return _parameters;
}
public function set parameters(value:Array):void
{
_parameters = value;
}
[Bindable("command_Change")]
public function get command():ICommand
{
return _command;
}
public function set command(value:ICommand):void
{
_command = value;
if( _command is IStateCommand )
{
if( setterWatcher )
{
setterWatcher.unwatch();
setterWatcher = null;
}
setterWatcher = BindingUtils.bindSetter( executablePropertyChanged, this, ["command", "executable"] );
}
dispatchEvent( new Event("command_Change") );
}
[Bindable("target_Change")]
public function get target():IEventDispatcher
{
return _target;
}
public function set target(value:IEventDispatcher):void
{
clearEvents();
_target = value;
dispatchEvent( new Event("target_Change") );
for each( var e : String in _arTriggerEvents )
{
_target.addEventListener( e, triggerFired );
}
}
[Bindable]
public function get triggerEvents():String
{
return _triggerEvents;
}
public function set triggerEvents(value:String):void
{
clearEvents();
_triggerEvents = value;
_arTriggerEvents = value.split(",");
}
private function clearEvents() : void
{
if( _target == null )
{
// The target invoker is not set, no need to clear the events.
return;
}
for each( var e : String in _arTriggerEvents )
{
_target.removeEventListener( e, triggerFired );
}
}
public function executablePropertyChanged( value : Boolean ) : void
{
if( _target is UIComponent )
{
UIComponent( _target ).enabled = value;
}
}
public function triggerFired( e : Event ) : void
{
if( _command is IStateCommand && IStateCommand(_command).executable )
{
_command.parameters = parameters;
_command.execute( e );
}
}
}
}
|
package org.servebox.cafe.core.command
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import mx.binding.utils.BindingUtils;
import mx.binding.utils.ChangeWatcher;
import mx.core.UIComponent;
public class CommandBinding extends EventDispatcher
{
private var _command : ICommand;
private var _target : IEventDispatcher;
private var _arTriggerEvents : Array;
private var _parameters : Array;
private var setterWatcher : ChangeWatcher;
public function CommandBinding()
{
super();
}
public function get parameters():Array
{
return _parameters;
}
public function set parameters(value:Array):void
{
_parameters = value;
}
[Bindable("command_Change")]
public function get command():ICommand
{
return _command;
}
public function set command(value:ICommand):void
{
_command = value;
if( _command is IStateCommand )
{
if( setterWatcher )
{
setterWatcher.unwatch();
setterWatcher = null;
}
setterWatcher = BindingUtils.bindSetter( executablePropertyChanged, this, ["command", "executable"] );
}
dispatchEvent( new Event("command_Change") );
}
[Bindable("target_Change")]
public function get target():IEventDispatcher
{
return _target;
}
public function set target(value:IEventDispatcher):void
{
clearEvents( _target );
_target = value;
replaceEvents();
dispatchEvent( new Event("target_Change") );
}
[Bindable]
public function get triggerEvents():String
{
if (_arTriggerEvents == null)
{
_arTriggerEvents = [];
}
return _arTriggerEvents.join(",");
}
public function set triggerEvents(value:String):void
{
_arTriggerEvents = value.split(",");
replaceEvents();
}
private function replaceEvents() : void
{
clearEvents();
if( _target != null )
{
for each( var e : String in _arTriggerEvents )
{
_target.addEventListener( e, triggerFired );
}
}
}
private function clearEvents( targetOverride : IEventDispatcher = null) : void
{
var t : IEventDispatcher = ( targetOverride != null ? targetOverride : _target);
if( t == null )
{
// The target invoker is not set, no need to clear the events.
return;
}
for each( var e : String in _arTriggerEvents )
{
t.removeEventListener( e, triggerFired );
}
}
public function executablePropertyChanged( value : Boolean ) : void
{
if( _target is UIComponent )
{
UIComponent( _target ).enabled = value;
}
}
public function triggerFired( e : Event ) : void
{
if( _command is IStateCommand && IStateCommand(_command).executable )
{
_command.parameters = parameters;
_command.execute( e );
}
}
}
}
|
Update in setting the target of CommandBinding.
|
Update in setting the target of CommandBinding.
|
ActionScript
|
mit
|
servebox/as-cafe
|
c4f0010f494f1e95bc08595b08904af4976e71f9
|
src/ru/kutu/grindplayer/views/mediators/ScrubBarMediator.as
|
src/ru/kutu/grindplayer/views/mediators/ScrubBarMediator.as
|
package ru.kutu.grindplayer.views.mediators {
import org.osmf.events.MetadataEvent;
import org.osmf.media.MediaElement;
import org.osmf.net.StreamType;
import ru.kutu.grind.views.mediators.ScrubBarBaseMediator;
public class ScrubBarMediator extends ScrubBarBaseMediator {
private var isAdvertisement:Boolean;
private var hideScrubBarWhileAdvertisement:Boolean;
override protected function processMediaElementChange(oldMediaElement:MediaElement):void {
super.processMediaElementChange(oldMediaElement);
if (oldMediaElement) {
oldMediaElement.metadata.removeEventListener(MetadataEvent.VALUE_ADD, onMediaMetadataChange);
oldMediaElement.metadata.removeEventListener(MetadataEvent.VALUE_CHANGE, onMediaMetadataChange);
oldMediaElement.metadata.removeEventListener(MetadataEvent.VALUE_REMOVE, onMediaMetadataChange);
}
if (media) {
media.metadata.addEventListener(MetadataEvent.VALUE_ADD, onMediaMetadataChange);
media.metadata.addEventListener(MetadataEvent.VALUE_CHANGE, onMediaMetadataChange);
media.metadata.addEventListener(MetadataEvent.VALUE_REMOVE, onMediaMetadataChange);
}
}
override protected function updateEnabled():void {
view.enabled = isStartPlaying && !isAdvertisement;
view.visible = streamType != StreamType.LIVE && !hideScrubBarWhileAdvertisement;
}
private function onMediaMetadataChange(event:MetadataEvent):void {
if (event.key != "Advertisement") return;
isAdvertisement = event.type != MetadataEvent.VALUE_REMOVE;
hideScrubBarWhileAdvertisement = false;
if (event.value && event.value is Array) {
for each (var item:Object in event.value) {
if ("hideScrubBarWhilePlayingAd" in item && item.hideScrubBarWhilePlayingAd) {
hideScrubBarWhileAdvertisement = true;
break;
}
}
}
updateEnabled();
}
}
}
|
package ru.kutu.grindplayer.views.mediators {
import org.osmf.events.MetadataEvent;
import org.osmf.media.MediaElement;
import org.osmf.net.StreamType;
import ru.kutu.grind.views.mediators.ScrubBarBaseMediator;
public class ScrubBarMediator extends ScrubBarBaseMediator {
private var hideScrubBarWhileAdvertisement:Boolean;
override protected function processMediaElementChange(oldMediaElement:MediaElement):void {
super.processMediaElementChange(oldMediaElement);
if (oldMediaElement) {
oldMediaElement.metadata.removeEventListener(MetadataEvent.VALUE_ADD, onMediaMetadataChange);
oldMediaElement.metadata.removeEventListener(MetadataEvent.VALUE_CHANGE, onMediaMetadataChange);
oldMediaElement.metadata.removeEventListener(MetadataEvent.VALUE_REMOVE, onMediaMetadataChange);
}
if (media) {
media.metadata.addEventListener(MetadataEvent.VALUE_ADD, onMediaMetadataChange);
media.metadata.addEventListener(MetadataEvent.VALUE_CHANGE, onMediaMetadataChange);
media.metadata.addEventListener(MetadataEvent.VALUE_REMOVE, onMediaMetadataChange);
}
}
override protected function updateEnabled():void {
view.enabled = isStartPlaying;
view.visible = streamType != StreamType.LIVE && !hideScrubBarWhileAdvertisement;
}
private function onMediaMetadataChange(event:MetadataEvent):void {
if (event.key != "Advertisement") return;
hideScrubBarWhileAdvertisement = false;
if (event.value && event.value is Array) {
for each (var item:Object in event.value) {
if ("hideScrubBarWhilePlayingAd" in item && item.hideScrubBarWhilePlayingAd) {
hideScrubBarWhileAdvertisement = true;
break;
}
}
}
updateEnabled();
}
}
}
|
remove disabling scrub bar on ads
|
remove disabling scrub bar on ads
|
ActionScript
|
mit
|
kutu/GrindPlayer
|
21f618c09e929a06374d5ec03fed94b1ed21c833
|
src/aerys/minko/render/material/phong/multipass/ZPrepassShader.as
|
src/aerys/minko/render/material/phong/multipass/ZPrepassShader.as
|
package aerys.minko.render.material.phong.multipass
{
import aerys.minko.render.RenderTarget;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.ShaderSettings;
import aerys.minko.render.shader.part.animation.VertexAnimationShaderPart;
import aerys.minko.type.enum.ColorMask;
public class ZPrepassShader extends Shader
{
private var _vertexAnimationPart : VertexAnimationShaderPart;
public function ZPrepassShader(renderTarget : RenderTarget = null,
priority : Number = 0.0)
{
super(renderTarget, priority);
_vertexAnimationPart = new VertexAnimationShaderPart(this);
}
override protected function initializeSettings(settings : ShaderSettings) : void
{
super.initializeSettings(settings);
settings.colorMask = ColorMask.NONE;
}
override protected function getVertexPosition():SFloat
{
return localToScreen(_vertexAnimationPart.getAnimatedVertexPosition());
}
override protected function getPixelColor():SFloat
{
return float4(0, 0, 0, 0);
}
}
}
|
package aerys.minko.render.material.phong.multipass
{
import aerys.minko.render.RenderTarget;
import aerys.minko.render.material.basic.BasicProperties;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.ShaderSettings;
import aerys.minko.render.shader.part.DiffuseShaderPart;
import aerys.minko.render.shader.part.animation.VertexAnimationShaderPart;
import aerys.minko.type.enum.ColorMask;
public class ZPrepassShader extends Shader
{
private var _vertexAnimationPart : VertexAnimationShaderPart;
private var _diffuseShaderPart : DiffuseShaderPart;
public function ZPrepassShader(renderTarget : RenderTarget = null,
priority : Number = 0.0)
{
super(renderTarget, priority);
_diffuseShaderPart = new DiffuseShaderPart(this);
_vertexAnimationPart = new VertexAnimationShaderPart(this);
}
override protected function initializeSettings(settings : ShaderSettings) : void
{
super.initializeSettings(settings);
settings.colorMask = ColorMask.NONE;
}
override protected function getVertexPosition():SFloat
{
return localToScreen(_vertexAnimationPart.getAnimatedVertexPosition());
}
override protected function getPixelColor():SFloat
{
if (meshBindings.propertyExists(BasicProperties.ALPHA_THRESHOLD))
{
var diffuseColor : SFloat = _diffuseShaderPart.getDiffuseColor(false);
var alphaThreshold : SFloat = meshBindings.getParameter(
BasicProperties.ALPHA_THRESHOLD, 1
);
kill(subtract(0.5, lessThan(diffuseColor.w, alphaThreshold)));
}
return float4(0, 0, 0, 0);
}
}
}
|
Fix alpha threshold on multi pass phong effect
|
Fix alpha threshold on multi pass phong effect
|
ActionScript
|
mit
|
aerys/minko-as3
|
e2c1c4cf096086709109d2d147d93e6eb5131c00
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/models/ArraySelectionModel.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/models/ArraySelectionModel.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.models
{
import org.apache.flex.core.IRollOverModel;
import org.apache.flex.core.ISelectionModel;
import org.apache.flex.core.IStrand;
import org.apache.flex.events.Event;
import org.apache.flex.events.EventDispatcher;
/**
* The ArraySelectionModel class is a selection model for
* a dataProvider that is an array. It assumes that items
* can be fetched from the dataProvider
* dataProvider[index]. Other selection models
* would support other kinds of data providers.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class ArraySelectionModel extends EventDispatcher implements ISelectionModel, IRollOverModel
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function ArraySelectionModel()
{
}
private var _strand:IStrand;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
_strand = value;
}
private var _dataProvider:Object;
/**
* @copy org.apache.flex.core.ISelectionModel#dataProvider
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get dataProvider():Object
{
return _dataProvider;
}
/**
* @private
*/
public function set dataProvider(value:Object):void
{
_dataProvider = value;
dispatchEvent(new Event("dataProviderChanged"));
}
private var _selectedIndex:int = -1;
private var _rollOverIndex:int = -1;
private var _labelField:String = null;
/**
* @copy org.apache.flex.core.ISelectionModel#labelField
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get labelField():String
{
return _labelField;
}
/**
* @private
*/
public function set labelField(value:String):void
{
if (value != _labelField) {
_labelField = value;
dispatchEvent(new Event("labelFieldChanged"));
}
}
/**
* @copy org.apache.flex.core.ISelectionModel#selectedIndex
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get selectedIndex():int
{
return _selectedIndex;
}
/**
* @private
*/
public function set selectedIndex(value:int):void
{
_selectedIndex = value;
_selectedItem = (value == -1) ? null : (value < _dataProvider.length) ? _dataProvider[value] : null;
dispatchEvent(new Event("selectedIndexChanged"));
}
/**
* @copy org.apache.flex.core.IRollOverModel#rollOverIndex
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get rollOverIndex():int
{
return _rollOverIndex;
}
/**
* @private
*/
public function set rollOverIndex(value:int):void
{
_rollOverIndex = value;
dispatchEvent(new Event("rollOverIndexChanged"));
}
private var _selectedItem:Object;
/**
* @copy org.apache.flex.core.ISelectionModel#selectedItem
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get selectedItem():Object
{
return _selectedItem;
}
/**
* @private
*/
public function set selectedItem(value:Object):void
{
_selectedItem = value;
var n:int = _dataProvider.length;
for (var i:int = 0; i < n; i++)
{
if (_dataProvider[i] == value)
{
_selectedIndex = i;
break;
}
}
dispatchEvent(new Event("selectedItemChanged"));
dispatchEvent(new Event("selectedIndexChanged"));
}
private var _selectedString:String;
/**
* An alternative to selectedItem for strongly typing the
* the selectedItem if the Array is an Array of Strings.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get selectedString():String
{
return String(_selectedItem);
}
/**
* @private
*/
public function set selectedString(value:String):void
{
_selectedString = value;
var n:int = _dataProvider.length;
for (var i:int = 0; i < n; i++)
{
if (String(_dataProvider[i]) == value)
{
_selectedIndex = i;
break;
}
}
dispatchEvent(new Event("selectedItemChanged"));
dispatchEvent(new Event("selectedIndexChanged"));
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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.models
{
import org.apache.flex.core.IRollOverModel;
import org.apache.flex.core.ISelectionModel;
import org.apache.flex.core.IStrand;
import org.apache.flex.events.Event;
import org.apache.flex.events.EventDispatcher;
/**
* The ArraySelectionModel class is a selection model for
* a dataProvider that is an array. It assumes that items
* can be fetched from the dataProvider
* dataProvider[index]. Other selection models
* would support other kinds of data providers.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class ArraySelectionModel extends EventDispatcher implements ISelectionModel, IRollOverModel
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function ArraySelectionModel()
{
}
private var _strand:IStrand;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
_strand = value;
}
private var _dataProvider:Object;
/**
* @copy org.apache.flex.core.ISelectionModel#dataProvider
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get dataProvider():Object
{
return _dataProvider;
}
/**
* @private
*/
public function set dataProvider(value:Object):void
{
_dataProvider = value;
if (_selectedIndex != -1)
_selectedItem = (_dataProvider == null || _selectedIndex >= _dataProvider.length) ? null :
_dataProvider[value];
dispatchEvent(new Event("dataProviderChanged"));
}
private var _selectedIndex:int = -1;
private var _rollOverIndex:int = -1;
private var _labelField:String = null;
/**
* @copy org.apache.flex.core.ISelectionModel#labelField
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get labelField():String
{
return _labelField;
}
/**
* @private
*/
public function set labelField(value:String):void
{
if (value != _labelField) {
_labelField = value;
dispatchEvent(new Event("labelFieldChanged"));
}
}
/**
* @copy org.apache.flex.core.ISelectionModel#selectedIndex
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get selectedIndex():int
{
return _selectedIndex;
}
/**
* @private
*/
public function set selectedIndex(value:int):void
{
_selectedIndex = value;
_selectedItem = (value == -1 || _dataProvider == null) ? null : (value < _dataProvider.length) ? _dataProvider[value] : null;
dispatchEvent(new Event("selectedIndexChanged"));
}
/**
* @copy org.apache.flex.core.IRollOverModel#rollOverIndex
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get rollOverIndex():int
{
return _rollOverIndex;
}
/**
* @private
*/
public function set rollOverIndex(value:int):void
{
_rollOverIndex = value;
dispatchEvent(new Event("rollOverIndexChanged"));
}
private var _selectedItem:Object;
/**
* @copy org.apache.flex.core.ISelectionModel#selectedItem
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get selectedItem():Object
{
return _selectedItem;
}
/**
* @private
*/
public function set selectedItem(value:Object):void
{
_selectedItem = value;
var n:int = _dataProvider.length;
for (var i:int = 0; i < n; i++)
{
if (_dataProvider[i] == value)
{
_selectedIndex = i;
break;
}
}
dispatchEvent(new Event("selectedItemChanged"));
dispatchEvent(new Event("selectedIndexChanged"));
}
private var _selectedString:String;
/**
* An alternative to selectedItem for strongly typing the
* the selectedItem if the Array is an Array of Strings.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get selectedString():String
{
return String(_selectedItem);
}
/**
* @private
*/
public function set selectedString(value:String):void
{
_selectedString = value;
var n:int = _dataProvider.length;
for (var i:int = 0; i < n; i++)
{
if (String(_dataProvider[i]) == value)
{
_selectedIndex = i;
break;
}
}
dispatchEvent(new Event("selectedItemChanged"));
dispatchEvent(new Event("selectedIndexChanged"));
}
}
}
|
handle having dp set after selectedIndex
|
handle having dp set after selectedIndex
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
980fa3a24502240fbb4b90e6bbad38a4df2343f8
|
src/modules/supportClasses/LayerSettings.as
|
src/modules/supportClasses/LayerSettings.as
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////////
package modules.supportClasses
{
[Bindable]
public class LayerSettings
{
public var name:String;
public var fields:Array = [];
//preserve
private var showObjectId:XML;
private var showGlobalId:XML;
private var exportLocation:XML;
private var showAttachments:XML;
private var showRelatedRecords:XML;
private var columnsOrder:XML;
private var sublayer:XML;
public function fromXML(layerSettingsXML:XML):void
{
name = layerSettingsXML.@name[0];
var parsedFieldSettings:FieldSettings;
for each (var fieldXML:XML in layerSettingsXML.fields.field)
{
parsedFieldSettings = new FieldSettings();
parsedFieldSettings.fromXML(fieldXML);
if (parsedFieldSettings.name)
{
fields.push(parsedFieldSettings);
}
}
showObjectId = layerSettingsXML.showobjectid[0];
showGlobalId = layerSettingsXML.showglobalid[0];
exportLocation = layerSettingsXML.exportlocation[0];
showAttachments = layerSettingsXML.showattachments[0];
showRelatedRecords = layerSettingsXML.showrelatedrecords[0];
columnsOrder = layerSettingsXML.columnsorder[0];
sublayer = layerSettingsXML.sublayer[0];
}
public function toXML():XML
{
var configXML:XML = <layer name={name}/>;
if (fields && fields.length > 0)
{
var fieldsXML:XML = <fields/>;
var fieldXML:XML;
for each (var field:FieldSettings in fields)
{
fieldXML = <field name={field.name}/>;
if (field.alias)
{
fieldXML.@alias = field.alias;
}
if (field.tooltip)
{
fieldXML.@tooltip = field.tooltip;
}
fieldsXML.appendChild(fieldXML);
}
if (fieldsXML.children().length() > 0)
{
configXML.appendChild(fieldsXML);
}
}
if (showObjectId)
{
configXML.appendChild(showObjectId);
}
if (showGlobalId)
{
configXML.appendChild(showGlobalId);
}
if (exportLocation)
{
configXML.appendChild(exportLocation);
}
if (showAttachments)
{
configXML.appendChild(showAttachments);
}
if (showRelatedRecords)
{
configXML.appendChild(showRelatedRecords);
}
if (columnsOrder)
{
configXML.appendChild(columnsOrder);
}
if (sublayer)
{
configXML.appendChild(sublayer);
}
return configXML;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////////
package modules.supportClasses
{
[Bindable]
public class LayerSettings
{
public var name:String;
public var fields:Array = [];
//preserve
private var showObjectId:XML;
private var showGlobalId:XML;
private var exportLocation:XML;
private var showAttachments:XML;
private var showRelatedRecords:XML;
private var columnsOrder:XML;
private var sublayer:XML;
public function fromXML(layerSettingsXML:XML):void
{
name = layerSettingsXML.@name[0];
var parsedFieldSettings:FieldSettings;
for each (var fieldXML:XML in layerSettingsXML.fields.field)
{
parsedFieldSettings = new FieldSettings();
parsedFieldSettings.fromXML(fieldXML);
if (parsedFieldSettings.name)
{
fields.push(parsedFieldSettings);
}
}
showObjectId = layerSettingsXML.showobjectid[0];
showGlobalId = layerSettingsXML.showglobalid[0];
exportLocation = layerSettingsXML.exportlocation[0];
showAttachments = layerSettingsXML.showattachments[0];
showRelatedRecords = layerSettingsXML.showrelatedrecords[0];
columnsOrder = layerSettingsXML.columnsorder[0];
sublayer = layerSettingsXML.sublayer[0];
}
public function toXML():XML
{
var configXML:XML = <layer name={name}/>;
if (fields && fields.length > 0)
{
var fieldsXML:XML = <fields/>;
for each (var field:FieldSettings in fields)
{
fieldsXML.appendChild(field.toXML());
}
if (fieldsXML.children().length() > 0)
{
configXML.appendChild(fieldsXML);
}
}
if (showObjectId)
{
configXML.appendChild(showObjectId);
}
if (showGlobalId)
{
configXML.appendChild(showGlobalId);
}
if (exportLocation)
{
configXML.appendChild(exportLocation);
}
if (showAttachments)
{
configXML.appendChild(showAttachments);
}
if (showRelatedRecords)
{
configXML.appendChild(showRelatedRecords);
}
if (columnsOrder)
{
configXML.appendChild(columnsOrder);
}
if (sublayer)
{
configXML.appendChild(sublayer);
}
return configXML;
}
}
}
|
Remove redundant code.
|
Remove redundant code.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
a878fce619c012fa22eacc67b6b73cf4c41ae293
|
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:ClassMarkedAsCloneable;
private var classWithSomeCloneableFields:ClassWithSomeCloneableFields;
private var classMarkedAsCloneableType:Type;
private var classWithSomeCloneableFieldsType:Type;
[Before]
public function before():void {
classMarkedAsCloneable = new ClassMarkedAsCloneable();
classMarkedAsCloneable.property1 = "value 1";
classMarkedAsCloneable.property2 = "value 2";
classMarkedAsCloneable.property3 = "value 3";
classMarkedAsCloneable.writableField = "value 4";
classWithSomeCloneableFields = new ClassWithSomeCloneableFields();
classWithSomeCloneableFields.property1 = "value 1";
classWithSomeCloneableFields.property2 = "value 2";
classWithSomeCloneableFields.property3 = "value 3";
classWithSomeCloneableFields.writableField = "value 4";
classMarkedAsCloneableType = Type.forInstance(classMarkedAsCloneable);
classWithSomeCloneableFieldsType = Type.forInstance(classWithSomeCloneableFields);
}
[After]
public function after():void {
classMarkedAsCloneable = null;
classWithSomeCloneableFields = null;
classMarkedAsCloneableType = null;
classWithSomeCloneableFieldsType = null;
}
[Test]
public function testGetCloneableFields():void {
var cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(classMarkedAsCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
cloneableFields = Cloner.getCloneableFieldsForType(classWithSomeCloneableFieldsType);
assertNotNull(cloneableFields);
assertEquals(3, cloneableFields.length);
}
[Test]
public function testCloneWithClassLevelMetadata():void {
const clone1:ClassMarkedAsCloneable = Cloner.clone(classMarkedAsCloneable) as ClassMarkedAsCloneable;
assertNotNull(clone1);
assertNotNull(clone1.property1);
assertEquals(clone1.property1, classMarkedAsCloneable.property1);
assertNotNull(clone1.property2);
assertEquals(clone1.property2, classMarkedAsCloneable.property2);
assertNotNull(clone1.property3);
assertEquals(clone1.property3, classMarkedAsCloneable.property3);
assertNotNull(clone1.writableField);
assertEquals(clone1.writableField, classMarkedAsCloneable.writableField);
}
public function testCloneWithPropertyLevelMetadata():void {
const clone2:ClassWithSomeCloneableFields = Cloner.clone(
classWithSomeCloneableFields
) as ClassWithSomeCloneableFields;
assertNotNull(clone2);
assertNull(clone2.property1);
assertNotNull(clone2.property2);
assertEquals(clone2.property2, classWithSomeCloneableFields.property2);
assertNotNull(clone2.property3);
assertEquals(clone2.property3, classWithSomeCloneableFields.property3);
assertNotNull(clone2.writableField);
assertEquals(clone2.writableField, classWithSomeCloneableFields.writableField);
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertNotNull;
import org.flexunit.asserts.assertNull;
use namespace dolly_internal;
public class ClonerTest {
private var classMarkedAsCloneable:ClassMarkedAsCloneable;
private var classWithSomeCloneableFields:ClassWithSomeCloneableFields;
private var classMarkedAsCloneableType:Type;
private var classWithSomeCloneableFieldsType:Type;
[Before]
public function before():void {
classMarkedAsCloneable = new ClassMarkedAsCloneable();
classMarkedAsCloneable.property1 = "value 1";
classMarkedAsCloneable.property2 = "value 2";
classMarkedAsCloneable.property3 = "value 3";
classMarkedAsCloneable.writableField = "value 4";
classWithSomeCloneableFields = new ClassWithSomeCloneableFields();
classWithSomeCloneableFields.property1 = "value 1";
classWithSomeCloneableFields.property2 = "value 2";
classWithSomeCloneableFields.property3 = "value 3";
classWithSomeCloneableFields.writableField = "value 4";
classMarkedAsCloneableType = Type.forInstance(classMarkedAsCloneable);
classWithSomeCloneableFieldsType = Type.forInstance(classWithSomeCloneableFields);
}
[After]
public function after():void {
classMarkedAsCloneable = null;
classWithSomeCloneableFields = null;
classMarkedAsCloneableType = null;
classWithSomeCloneableFieldsType = null;
}
[Test]
public function testGetCloneableFields():void {
var cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(classMarkedAsCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
cloneableFields = Cloner.getCloneableFieldsForType(classWithSomeCloneableFieldsType);
assertNotNull(cloneableFields);
assertEquals(3, cloneableFields.length);
}
[Test]
public function testCloneWithClassLevelMetadata():void {
const clone1:ClassMarkedAsCloneable = Cloner.clone(classMarkedAsCloneable) as ClassMarkedAsCloneable;
assertNotNull(clone1);
assertNotNull(clone1.property1);
assertEquals(clone1.property1, classMarkedAsCloneable.property1);
assertNotNull(clone1.property2);
assertEquals(clone1.property2, classMarkedAsCloneable.property2);
assertNotNull(clone1.property3);
assertEquals(clone1.property3, classMarkedAsCloneable.property3);
assertNotNull(clone1.writableField);
assertEquals(clone1.writableField, classMarkedAsCloneable.writableField);
}
[Test]
public function testCloneWithPropertyLevelMetadata():void {
const clone2:ClassWithSomeCloneableFields = Cloner.clone(
classWithSomeCloneableFields
) as ClassWithSomeCloneableFields;
assertNotNull(clone2);
assertNull(clone2.property1);
assertNotNull(clone2.property2);
assertEquals(clone2.property2, classWithSomeCloneableFields.property2);
assertNotNull(clone2.property3);
assertEquals(clone2.property3, classWithSomeCloneableFields.property3);
assertNotNull(clone2.writableField);
assertEquals(clone2.writableField, classWithSomeCloneableFields.writableField);
}
}
}
|
Add [Test] metadata tag.
|
Add [Test] metadata tag.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
680b127adc2139be9edf0d5ebd66b13395e93ff9
|
src/org/mangui/HLS/muxing/ID3.as
|
src/org/mangui/HLS/muxing/ID3.as
|
package org.mangui.HLS.muxing {
import flash.utils.ByteArray;
import org.mangui.HLS.utils.Log;
public class ID3
{
public var len:Number;
public var hasTimestamp:Boolean = false;
public var timestamp:Number;
/* create ID3 object by parsing ByteArray, looking for ID3 tag length, and timestamp */
public function ID3(data:ByteArray) {
var tagSize:uint = 0;
try {
var pos:Number = data.position;
do {
if(data.readUTFBytes(3) == 'ID3') {
// skip 24 bits
data.position += 3;
// retrieve tag length
var byte1:uint = data.readUnsignedByte() & 0x7f;
var byte2:uint = data.readUnsignedByte() & 0x7f;
var byte3:uint = data.readUnsignedByte() & 0x7f;
var byte4:uint = data.readUnsignedByte() & 0x7f;
tagSize = (byte1 << 21) + (byte2 << 14) + (byte3 << 7) + byte4;
var end_pos:Number = data.position + tagSize;
// read tag
_parseFrame(data);
data.position = end_pos;
} else {
data.position-=3;
Log.debug2("ID3 len:"+ (data.position-pos));
len = data.position-pos;
return;
}
} while (true);
} catch(e:Error)
{
}
len = 0;
return;
};
/* Each Elementary Audio Stream segment MUST signal the timestamp of
its first sample with an ID3 PRIV tag [ID3] at the beginning of
the segment. The ID3 PRIV owner identifier MUST be
"com.apple.streaming.transportStreamTimestamp". The ID3 payload
MUST be a 33-bit MPEG-2 Program Elementary Stream timestamp
expressed as a big-endian eight-octet number, with the upper 31
bits set to zero.
*/
private function _parseFrame(data:ByteArray):void {
if (data.readUTFBytes(4) == "PRIV") {
var frame_len:uint = data.readUnsignedInt();
// smelling good ! 53 is the size of tag we are looking for
if(frame_len == 53) {
// skip flags (2 bytes)
data.position+=2;
// owner should be "com.apple.streaming.transportStreamTimestamp"
if(data.readUTFBytes(44) == 'com.apple.streaming.transportStreamTimestamp') {
// smelling even better ! we found the right descriptor
// skip null character (string end) + 3 first bytes
data.position+=4;
// timestamp is 33 bit expressed as a big-endian eight-octet number, with the upper 31 bits set to zero.
var pts_33_bit:Number = data.readUnsignedByte() & 0x1;
hasTimestamp = true;
timestamp = (data.readUnsignedInt()/90) << pts_33_bit;
Log.debug("ID3 timestamp found:"+timestamp);
}
}
}
}
}
}
|
package org.mangui.HLS.muxing {
import flash.utils.ByteArray;
import org.mangui.HLS.utils.Log;
public class ID3
{
public var len:Number;
public var hasTimestamp:Boolean = false;
public var timestamp:Number;
/* create ID3 object by parsing ByteArray, looking for ID3 tag length, and timestamp */
public function ID3(data:ByteArray) {
var tagSize:uint = 0;
try {
var pos:Number = data.position;
do {
if(data.readUTFBytes(3) == 'ID3') {
// skip 24 bits
data.position += 3;
// retrieve tag length
var byte1:uint = data.readUnsignedByte() & 0x7f;
var byte2:uint = data.readUnsignedByte() & 0x7f;
var byte3:uint = data.readUnsignedByte() & 0x7f;
var byte4:uint = data.readUnsignedByte() & 0x7f;
tagSize = (byte1 << 21) + (byte2 << 14) + (byte3 << 7) + byte4;
var end_pos:Number = data.position + tagSize;
// read tag
_parseFrame(data);
data.position = end_pos;
} else {
data.position-=3;
len = data.position-pos;
if (len) {
Log.debug2("ID3 len:"+ len);
}
return;
}
} while (true);
} catch(e:Error)
{
}
len = 0;
return;
};
/* Each Elementary Audio Stream segment MUST signal the timestamp of
its first sample with an ID3 PRIV tag [ID3] at the beginning of
the segment. The ID3 PRIV owner identifier MUST be
"com.apple.streaming.transportStreamTimestamp". The ID3 payload
MUST be a 33-bit MPEG-2 Program Elementary Stream timestamp
expressed as a big-endian eight-octet number, with the upper 31
bits set to zero.
*/
private function _parseFrame(data:ByteArray):void {
if (data.readUTFBytes(4) == "PRIV") {
var frame_len:uint = data.readUnsignedInt();
// smelling good ! 53 is the size of tag we are looking for
if(frame_len == 53) {
// skip flags (2 bytes)
data.position+=2;
// owner should be "com.apple.streaming.transportStreamTimestamp"
if(data.readUTFBytes(44) == 'com.apple.streaming.transportStreamTimestamp') {
// smelling even better ! we found the right descriptor
// skip null character (string end) + 3 first bytes
data.position+=4;
// timestamp is 33 bit expressed as a big-endian eight-octet number, with the upper 31 bits set to zero.
var pts_33_bit:Number = data.readUnsignedByte() & 0x1;
hasTimestamp = true;
timestamp = (data.readUnsignedInt()/90) << pts_33_bit;
Log.debug("ID3 timestamp found:"+timestamp);
}
}
}
}
}
}
|
reduce log2 verbosity when extracting ID3 tags
|
reduce log2 verbosity when extracting ID3 tags
|
ActionScript
|
mpl-2.0
|
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
|
d0cd3f7079ebc613ad7f1e47cd5b83e77f712ca6
|
frameworks/projects/HTML/asjs/src/org/apache/flex/html/beads/layouts/OneFlexibleChildVerticalLayout.as
|
frameworks/projects/HTML/asjs/src/org/apache/flex/html/beads/layouts/OneFlexibleChildVerticalLayout.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.beads.layouts
{
import org.apache.flex.core.IBeadLayout;
import org.apache.flex.core.IDocument;
import org.apache.flex.core.ILayoutChild;
import org.apache.flex.core.ILayoutParent;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IParentIUIBase;
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 OneFlexibleChildVerticalLayout 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 padding styles. But it
* will size the one child to take up as much or little
* room as possible.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class OneFlexibleChildVerticalLayout implements IBeadLayout, IDocument
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function OneFlexibleChildVerticalLayout()
{
}
/**
* The id of the flexible child
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var flexibleChild:String;
private var actualChild:ILayoutChild;
// the strand/host container is also an ILayoutChild because
// can have its size dictated by the host's parent which is
// important to know for layout optimization
private var host:ILayoutChild;
/**
* @private
* The document.
*/
private var document:Object;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
host = value as ILayoutChild;
}
private var _maxWidth:Number;
/**
* @copy org.apache.flex.core.IBead#maxWidth
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get maxWidth():Number
{
return _maxWidth;
}
/**
* @private
*/
public function set maxWidth(value:Number):void
{
_maxWidth = value;
}
private var _maxHeight:Number;
/**
* @copy org.apache.flex.core.IBead#maxHeight
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get maxHeight():Number
{
return _maxHeight;
}
/**
* @private
*/
public function set maxHeight(value:Number):void
{
_maxHeight = value;
}
/**
* @copy org.apache.flex.core.IBeadLayout#layout
*/
public function layout():Boolean
{
var layoutParent:ILayoutParent = host.getBeadByType(ILayoutParent) as ILayoutParent;
var contentView:IParentIUIBase = layoutParent ? layoutParent.contentView : IParentIUIBase(host);
actualChild = document[flexibleChild];
var ilc:ILayoutChild;
var n:int = contentView.numElements;
var marginLeft:Object;
var marginRight:Object;
var marginTop:Object;
var marginBottom:Object;
var margin:Object;
maxWidth = 0;
var horizontalMargins:Array = new Array(n);
var hh:Number = layoutParent.resizableView.height;
var padding:Object = determinePadding();
if (isNaN(padding.paddingBottom))
padding.paddingBottom = 0;
hh -= padding.paddingTop + padding.paddingBottom;
var yy:int = padding.paddingTop;
var flexChildIndex:int;
var ml:Number;
var mr:Number;
var mt:Number;
var mb:Number;
var lastmb:Number;
var lastmt:Number;
var halign:Object;
for (var i:int = 0; i < n; i++)
{
var child:IUIBase = contentView.getElementAt(i) as IUIBase;
if (child == actualChild)
{
flexChildIndex = i;
break;
}
margin = ValuesManager.valuesImpl.getValue(child, "margin");
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;
}
mt = Number(marginTop);
if (isNaN(mt))
mt = 0;
mb = Number(marginBottom);
if (isNaN(mb))
mb = 0;
if (marginLeft == "auto")
ml = 0;
else
{
ml = Number(marginLeft);
if (isNaN(ml))
ml = 0;
}
if (marginRight == "auto")
mr = 0;
else
{
mr = Number(marginRight);
if (isNaN(mr))
mr = 0;
}
child.x = ml;
if (child is ILayoutChild)
{
ilc = child as ILayoutChild;
if (!isNaN(ilc.percentWidth))
ilc.setWidth(contentView.width * ilc.percentWidth / 100, true);
}
maxWidth = Math.max(maxWidth, ml + child.width + mr);
child.y = yy + mt;
yy += child.height + mt + mb;
lastmb = mb;
halign = ValuesManager.valuesImpl.getValue(child, "horizontal-align");
horizontalMargins[i] = { marginLeft: ml, marginRight: mr, halign: halign };
}
if (n > 0 && n > flexChildIndex)
{
for (i = n - 1; i > flexChildIndex; i--)
{
child = 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;
}
mt = Number(marginTop);
if (isNaN(mt))
mt = 0;
mb = Number(marginBottom);
if (isNaN(mb))
mb = 0;
if (marginLeft == "auto")
ml = 0;
else
{
ml = Number(marginLeft);
if (isNaN(ml))
ml = 0;
}
if (marginRight == "auto")
mr = 0;
else
{
mr = Number(marginRight);
if (isNaN(mr))
mr = 0;
}
child.x = ml;
if (child is ILayoutChild)
{
ilc = child as ILayoutChild;
if (!isNaN(ilc.percentWidth))
ilc.setWidth(contentView.width * ilc.percentWidth / 100, true);
}
maxWidth = Math.max(maxWidth, ml + child.width + mr);
child.y = hh - child.height - mb;
hh -= child.height + mt + mb;
lastmt = mt;
halign = ValuesManager.valuesImpl.getValue(child, "horizontal-align");
horizontalMargins[i] = { marginLeft: ml, marginRight: mr, halign: halign };
}
child = contentView.getElementAt(flexChildIndex) 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;
}
mt = Number(marginTop);
if (isNaN(mt))
mt = 0;
mb = Number(marginBottom);
if (isNaN(mb))
mb = 0;
if (marginLeft == "auto")
ml = 0;
else
{
ml = Number(marginLeft);
if (isNaN(ml))
ml = 0;
}
if (marginRight == "auto")
mr = 0;
else
{
mr = Number(marginRight);
if (isNaN(mr))
mr = 0;
}
child.x = ml;
if (child is ILayoutChild)
{
ilc = child as ILayoutChild;
if (!isNaN(ilc.percentWidth))
ilc.setWidth(contentView.width * ilc.percentWidth / 100, true);
}
maxWidth = Math.max(maxWidth, ml + child.width + mr);
child.y = yy + mt;
child.height = hh - yy - mb;
halign = ValuesManager.valuesImpl.getValue(child, "horizontal-align");
horizontalMargins[flexChildIndex] = { marginLeft: ml, marginRight: mr, halign: halign };
}
for (i = 0; i < n; i++)
{
var obj:Object = horizontalMargins[0]
child = contentView.getElementAt(i) as IUIBase;
if (obj.halign == "center")
child.x = (maxWidth - child.width) / 2;
else if (obj.halign == "bottom")
child.x = maxWidth - child.width - obj.marginRight;
else
child.x = obj.marginLeft;
}
return true;
}
// TODO (aharui): utility class or base class
/**
* Determines the top and left padding values, if any, as set by
* padding style values. This includes "padding" for all padding values
* as well as "padding-left" and "padding-top".
*
* Returns an object with paddingLeft and paddingTop properties.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected function determinePadding():Object
{
var paddingLeft:Object;
var paddingTop:Object;
var paddingRight:Object;
var padding:Object = ValuesManager.valuesImpl.getValue(host, "padding");
if (typeof(padding) == "Array")
{
if (padding.length == 1)
paddingLeft = paddingTop = paddingRight = padding[0];
else if (padding.length <= 3)
{
paddingLeft = padding[1];
paddingTop = padding[0];
paddingRight = padding[1];
}
else if (padding.length == 4)
{
paddingLeft = padding[3];
paddingTop = padding[0];
paddingRight = padding[1];
}
}
else if (padding == null)
{
paddingLeft = ValuesManager.valuesImpl.getValue(host, "padding-left");
paddingTop = ValuesManager.valuesImpl.getValue(host, "padding-top");
paddingRight = ValuesManager.valuesImpl.getValue(host, "padding-right");
}
else
{
paddingLeft = paddingTop = paddingRight = padding;
}
var pl:Number = Number(paddingLeft);
var pt:Number = Number(paddingTop);
var pr:Number = Number(paddingRight);
if (isNaN(pl))
pl = 0;
if (isNaN(pr))
pr = 0;
if (isNaN(pt))
pt = 0;
return {paddingLeft:pl, paddingTop:pt, paddingRight:pr};
}
public function setDocument(document:Object, id:String = null):void
{
this.document = document;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.beads.layouts
{
import org.apache.flex.core.IBeadLayout;
import org.apache.flex.core.IDocument;
import org.apache.flex.core.ILayoutChild;
import org.apache.flex.core.ILayoutParent;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IParentIUIBase;
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 OneFlexibleChildVerticalLayout 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 padding styles. But it
* will size the one child to take up as much or little
* room as possible.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class OneFlexibleChildVerticalLayout implements IBeadLayout, IDocument
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function OneFlexibleChildVerticalLayout()
{
}
/**
* The id of the flexible child
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var flexibleChild:String;
private var actualChild:ILayoutChild;
// the strand/host container is also an ILayoutChild because
// can have its size dictated by the host's parent which is
// important to know for layout optimization
private var host:ILayoutChild;
/**
* @private
* The document.
*/
private var document:Object;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
host = value as ILayoutChild;
}
private var _maxWidth:Number;
/**
* @copy org.apache.flex.core.IBead#maxWidth
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get maxWidth():Number
{
return _maxWidth;
}
/**
* @private
*/
public function set maxWidth(value:Number):void
{
_maxWidth = value;
}
private var _maxHeight:Number;
/**
* @copy org.apache.flex.core.IBead#maxHeight
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get maxHeight():Number
{
return _maxHeight;
}
/**
* @private
*/
public function set maxHeight(value:Number):void
{
_maxHeight = value;
}
/**
* @copy org.apache.flex.core.IBeadLayout#layout
*/
public function layout():Boolean
{
var layoutParent:ILayoutParent = host.getBeadByType(ILayoutParent) as ILayoutParent;
var contentView:IParentIUIBase = layoutParent ? layoutParent.contentView : IParentIUIBase(host);
actualChild = document[flexibleChild];
var ilc:ILayoutChild;
var n:int = contentView.numElements;
var marginLeft:Object;
var marginRight:Object;
var marginTop:Object;
var marginBottom:Object;
var margin:Object;
maxWidth = 0;
var w:Number = contentView.width;
var hh:Number = contentView.height;
var yy:int = 0;
var flexChildIndex:int;
var ml:Number;
var mr:Number;
var mt:Number;
var mb:Number;
var lastmb:Number;
var lastmt:Number;
var halign:Object;
var left:Number;
var right:Number;
for (var i:int = 0; i < n; i++)
{
var child:IUIBase = contentView.getElementAt(i) as IUIBase;
ilc = child as ILayoutChild;
left = ValuesManager.valuesImpl.getValue(child, "left");
right = ValuesManager.valuesImpl.getValue(child, "right");
if (child == actualChild)
{
flexChildIndex = i;
break;
}
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;
}
mt = Number(marginTop);
if (isNaN(mt))
mt = 0;
mb = Number(marginBottom);
if (isNaN(mb))
mb = 0;
if (ilc)
{
if (!isNaN(ilc.percentHeight))
ilc.setHeight(contentView.height * ilc.percentHeight / 100, !isNaN(ilc.percentWidth));
}
if (marginLeft == "auto")
ml = 0;
else
{
ml = Number(marginLeft);
if (isNaN(ml))
ml = 0;
}
if (marginRight == "auto")
mr = 0;
else
{
mr = Number(marginRight);
if (isNaN(mr))
mr = 0;
}
child.x = ml;
if (child is ILayoutChild)
{
ilc = child as ILayoutChild;
if (!isNaN(ilc.percentWidth))
ilc.setWidth(contentView.width * ilc.percentWidth / 100, !isNaN(ilc.percentHeight));
}
maxWidth = Math.max(maxWidth, ml + child.width + mr);
setPositionAndWidth(child, left, ml, right, mr, w);
child.y = yy + mt;
yy += child.height + mt + mb;
lastmb = mb;
}
if (n > 0 && n > flexChildIndex)
{
for (i = n - 1; i > flexChildIndex; i--)
{
child = contentView.getElementAt(i) as IUIBase;
ilc = child as ILayoutChild;
left = ValuesManager.valuesImpl.getValue(child, "left");
right = ValuesManager.valuesImpl.getValue(child, "right");
margin = ValuesManager.valuesImpl.getValue(child, "margin");
if (margin is Array)
{
if (margin.length == 1)
marginLeft = marginTop = marginRight = marginBottom = margin[0];
else if (margin.length <= 3)
{
marginLeft = marginRight = margin[1];
marginTop = marginBottom = margin[0];
}
else if (margin.length == 4)
{
marginLeft = margin[3];
marginBottom = margin[2];
marginRight = margin[1];
marginTop = margin[0];
}
}
else if (margin == null)
{
marginLeft = ValuesManager.valuesImpl.getValue(child, "margin-left");
marginTop = ValuesManager.valuesImpl.getValue(child, "margin-top");
marginRight = ValuesManager.valuesImpl.getValue(child, "margin-right");
marginBottom = ValuesManager.valuesImpl.getValue(child, "margin-bottom");
}
else
{
marginLeft = marginTop = marginBottom = marginRight = margin;
}
mt = Number(marginTop);
if (isNaN(mt))
mt = 0;
mb = Number(marginBottom);
if (isNaN(mb))
mb = 0;
if (ilc)
{
if (!isNaN(ilc.percentHeight))
ilc.setHeight(contentView.height * ilc.percentHeight / 100, !isNaN(ilc.percentWidth));
}
if (marginLeft == "auto")
ml = 0;
else
{
ml = Number(marginLeft);
if (isNaN(ml))
ml = 0;
}
if (marginRight == "auto")
mr = 0;
else
{
mr = Number(marginRight);
if (isNaN(mr))
mr = 0;
}
if (child is ILayoutChild)
{
ilc = child as ILayoutChild;
if (!isNaN(ilc.percentWidth))
ilc.setWidth(contentView.width * ilc.percentWidth / 100, !isNaN(ilc.percentHeight));
}
setPositionAndWidth(child, left, ml, right, mr, w);
maxWidth = Math.max(maxWidth, ml + child.width + mr);
child.y = hh - child.height - mb;
hh -= child.height + mt + mb;
lastmt = mt;
}
}
child = contentView.getElementAt(flexChildIndex) as IUIBase;
ilc = child as ILayoutChild;
left = ValuesManager.valuesImpl.getValue(child, "left");
right = ValuesManager.valuesImpl.getValue(child, "right");
margin = ValuesManager.valuesImpl.getValue(child, "margin");
if (margin is Array)
{
if (margin.length == 1)
marginLeft = marginTop = marginRight = marginBottom = margin[0];
else if (margin.length <= 3)
{
marginLeft = marginRight = margin[1];
marginTop = marginBottom = margin[0];
}
else if (margin.length == 4)
{
marginLeft = margin[3];
marginBottom = margin[2];
marginRight = margin[1];
marginTop = margin[0];
}
}
else if (margin == null)
{
marginLeft = ValuesManager.valuesImpl.getValue(child, "margin-left");
marginTop = ValuesManager.valuesImpl.getValue(child, "margin-top");
marginRight = ValuesManager.valuesImpl.getValue(child, "margin-right");
marginBottom = ValuesManager.valuesImpl.getValue(child, "margin-bottom");
}
else
{
marginLeft = marginTop = marginBottom = marginRight = margin;
}
mt = Number(marginTop);
if (isNaN(mt))
mt = 0;
mb = Number(marginBottom);
if (isNaN(mb))
mb = 0;
if (ilc)
{
if (!isNaN(ilc.percentHeight))
ilc.setHeight(contentView.height * ilc.percentHeight / 100, !isNaN(ilc.percentWidth));
}
if (marginLeft == "auto")
ml = 0;
else
{
ml = Number(marginLeft);
if (isNaN(ml))
ml = 0;
}
if (marginRight == "auto")
mr = 0;
else
{
mr = Number(marginRight);
if (isNaN(mr))
mr = 0;
}
if (child is ILayoutChild)
{
ilc = child as ILayoutChild;
if (!isNaN(ilc.percentWidth))
ilc.setWidth(contentView.width * ilc.percentWidth / 100, !isNaN(ilc.percentHeight));
}
setPositionAndWidth(child, left, ml, right, mr, w);
maxWidth = Math.max(maxWidth, ml + child.width + mr);
child.y = yy + mt;
child.height = hh - yy - mb;
return true;
}
private function setPositionAndWidth(child:IUIBase, left:Number, ml:Number,
right:Number, mr:Number, w:Number):void
{
var widthSet:Boolean = false;
var ww:Number = w;
var ilc:ILayoutChild = child as ILayoutChild;
if (!isNaN(left))
{
child.x = left + ml;
ww -= left + ml;
}
else
{
child.x = ml;
ww -= ml;
}
if (!isNaN(right))
{
if (!isNaN(left))
{
if (ilc)
ilc.setWidth(ww - right - mr, true);
else
{
child.width = ww - right - mr;
widthSet = true;
}
}
else
child.x = w - right - mr - child.width;
}
if (ilc)
{
if (!isNaN(ilc.percentWidth))
ilc.setWidth(w * ilc.percentWidth / 100, true);
}
if (!widthSet)
child.dispatchEvent(new Event("sizeChanged"));
}
public function setDocument(document:Object, id:String = null):void
{
this.document = document;
}
}
}
|
fix up this layout
|
fix up this layout
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
f4cc3e0ecbeea0a22ae5c645a2f5c11f57b5de94
|
src/org/mangui/hls/model/Level.as
|
src/org/mangui/hls/model/Level.as
|
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;
/** Level Bitrate. **/
public var bitrate : Number;
/** Level Name. **/
public var name : String;
/** level index **/
public var 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). **/
public var url : String;
/** 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>();
};
/** 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 frag : Fragment;
// update PTS from previous fragments
for (var i : int = 0; i < len; i++) {
frag = getFragmentfromSeqNum(_fragments[i].seqnum);
if (frag != null && !isNaN(frag.data.pts_start)) {
_fragments[i].data = frag.data;
idx_with_metrics = i;
}
}
updateFragmentsProgramDate(_fragments);
fragments = _fragments;
start_seqnum = _fragments[0].seqnum;
end_seqnum = _fragments[len - 1].seqnum;
if (idx_with_metrics != -1) {
// if at least one fragment contains PTS info, recompute PTS information for all fragments
updateFragment(fragments[idx_with_metrics].seqnum, true, fragments[idx_with_metrics].data.pts_start, fragments[idx_with_metrics].data.pts_start + 1000 * fragments[idx_with_metrics].duration);
} else {
duration = _fragments[len - 1].start_time + _fragments[len - 1].duration;
}
averageduration = duration / len;
}
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) : Number {
// 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;
return frag.start_time;
} else {
CONFIG::LOGGING {
Log.error("updateFragment:seqnum " + seqnum + "not found!");
}
return 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;
/** Level Bitrate. **/
public var bitrate : Number;
/** Level Name. **/
public var name : String;
/** level index **/
public var 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). **/
public var url : String;
/** 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>();
};
/** 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 frag : Fragment;
// update PTS from previous fragments
for (var i : int = 0; i < len; i++) {
frag = getFragmentfromSeqNum(_fragments[i].seqnum);
if (frag != null && !isNaN(frag.data.pts_start)) {
_fragments[i].data = frag.data;
idx_with_metrics = i;
}
}
updateFragmentsProgramDate(_fragments);
fragments = _fragments;
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;
}
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) : Number {
// 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;
return frag.start_time;
} else {
CONFIG::LOGGING {
Log.error("updateFragment:seqnum " + seqnum + " not found!");
}
return 0;
}
}
}
}
|
improve debug logs
|
improve debug logs
|
ActionScript
|
mpl-2.0
|
hola/flashls,stevemayhew/flashls,mangui/flashls,tedconf/flashls,jlacivita/flashls,ryanhefner/flashls,viktorot/flashls,vidible/vdb-flashls,loungelogic/flashls,aevange/flashls,Peer5/flashls,stevemayhew/flashls,aevange/flashls,mangui/flashls,ryanhefner/flashls,neilrackett/flashls,clappr/flashls,Peer5/flashls,School-Improvement-Network/flashls,ryanhefner/flashls,codex-corp/flashls,dighan/flashls,fixedmachine/flashls,suuhas/flashls,ryanhefner/flashls,Corey600/flashls,School-Improvement-Network/flashls,dighan/flashls,thdtjsdn/flashls,stevemayhew/flashls,aevange/flashls,viktorot/flashls,codex-corp/flashls,JulianPena/flashls,viktorot/flashls,stevemayhew/flashls,suuhas/flashls,Corey600/flashls,clappr/flashls,thdtjsdn/flashls,Boxie5/flashls,Peer5/flashls,Boxie5/flashls,fixedmachine/flashls,tedconf/flashls,NicolasSiver/flashls,NicolasSiver/flashls,loungelogic/flashls,suuhas/flashls,vidible/vdb-flashls,Peer5/flashls,hola/flashls,School-Improvement-Network/flashls,neilrackett/flashls,JulianPena/flashls,jlacivita/flashls,suuhas/flashls,aevange/flashls
|
3cdb386f63d98b6f367a9f362e559a2f1811c3d2
|
src/com/rails2u/bridge/JSProxy.as
|
src/com/rails2u/bridge/JSProxy.as
|
package com.rails2u.bridge {
import flash.utils.Proxy;
import flash.external.ExternalInterface;
import flash.utils.flash_proxy;
public dynamic class JSProxy extends Proxy {
use namespace flash_proxy;
public static var proxyLogger:Function = function(...args):void {};
private var _stack:Array;
private var _nextCallIsstack:Boolean = false;
public function JSProxy(stack:Array = null) {
_stack = stack || [];
}
public function get proxy():JSProxy {
return getProperty('proxy');
}
public static function get proxy():JSProxy {
return new JSProxy();
}
flash_proxy override function callProperty(name:*, ...args):* {
var $name:* = $check(name);
if ($name) {
return callJS(newStack($name, args));
} else {
return new JSProxy(newStack(name, args));
}
}
flash_proxy function $check(name:*):* {
if (name.toString().indexOf('$') == 0 && name.toString().length >= 2) {
var r:String = name.toString().replace(/^\$+/, '');
if (name is QName) {
return new QName(name.uri, r);
} else {
return r;
}
} else {
return '';
}
}
flash_proxy override function getProperty(name:*):* {
var $name:* = $check(name);
if ($name) {
return callJS(newStack($name));
} else {
return new JSProxy(newStack(name));
}
}
flash_proxy override function getDescendants(name:*):* {
return callJS(newStack(name));
}
flash_proxy function newStack(name:*, args:Array = null):Array {
var stack:Array = _stack.slice();
if (args != null) {
stack.push([name, args.slice()]);
} else {
stack.push(name);
}
return stack;
}
flash_proxy override function hasProperty(name:*):Boolean {
return callJS(newStack(new QName('', name))) !== undefined;
}
flash_proxy override function setProperty(name:*, value:*):void {
callJSSetProperty(newStack(name), value);
}
flash_proxy override function deleteProperty(name:*):Boolean {
return false;
}
public function toString():String {
var res:Array = createCommand(_stack.slice());
var cmd:String = res[0];
var args:Array = res[1];
return '[JSProxy] ' + cmd + ' :: ' + args.join(', ');
}
flash_proxy function callJSSetProperty(stack:Array, value:*):* {
if (!ExternalInterface.available)
return null;
var res:Array = createCommand(stack);
var cmd:String = res[0];
var args:Array = res[1];
args.push(value);
var argsString:String = createArgsString(args.length);
cmd = "(function(" + argsString + ") {return " + cmd + " = _" + (args.length - 1).toString() + ";})";
proxyLogger(cmd);
return ExternalInterface.call.apply(null, [cmd].concat(args));
}
flash_proxy function callJS(stack:Array):* {
if (!ExternalInterface.available)
return null;
var res:Array = createCommand(stack);
var cmd:String = res[0];
var args:Array = res[1];
var argsString:String = createArgsString(args.length);
if (args.length > 0) {
cmd = "(function(" + argsString + ") {return " + cmd + ";})";
proxyLogger(cmd);
proxyLogger(args);
return ExternalInterface.call.apply(null, [cmd].concat(args));
} else {
cmd = "(function() {return " + cmd + ";})";
proxyLogger(cmd);
return ExternalInterface.call(cmd);
}
}
flash_proxy function createArgsString(len:uint):String {
var res:Array = [];
for (var i:uint = 0; i < len; i++) {
res.push('_' + i);
}
return res.join(', ');
}
flash_proxy function createCommand(stack:Array):Array {
var receivers:Array = [];
var args:Array = [];
var argsStrings:Array = [];
while (stack.length) {
var o:* = stack.shift();
if (o is Array) {
o = o as Array;
var cmd:String = nameToString(o[0]) + '(';
var cmdArgs:Array = [];
var a:Array = o[1].slice();
while (a.length) {
cmdArgs.push('_' + args.length);
args.push(a.shift());
}
cmd += cmdArgs.join(', ');
cmd += ')';
receivers.push(cmd);
} else {
receivers.push(nameToString(o));
}
}
return [receivers.join('.').replace(/\.\[/g, '['), args];
}
flash_proxy function nameToString(name:*):String {
if (name is QName) {
return name.localName.toString();
} else {
return '[' + name.toString() + ']';
}
}
}
}
|
package com.rails2u.bridge {
import flash.utils.Proxy;
import flash.external.ExternalInterface;
import flash.utils.flash_proxy;
public dynamic class JSProxy extends Proxy {
use namespace flash_proxy;
public static var proxyLogger:Function = function(...args):void {};
private var _stack:Array;
private var _nextCallIsstack:Boolean = false;
public function JSProxy(stack:Array = null) {
_stack = stack || [];
}
public function get proxy():JSProxy {
return getProperty('proxy');
}
public static function get proxy():JSProxy {
return new JSProxy();
}
flash_proxy override function callProperty(name:*, ...args):* {
var $name:* = $check(name);
if ($name) {
return callJS(newStack($name, args));
} else {
return new JSProxy(newStack(name, args));
}
}
flash_proxy function $check(name:*):* {
if (name.toString().indexOf('$') == 0 && name.toString().length >= 2) {
var r:String = name.toString().replace(/^\$+/, '');
if (name is QName) {
return new QName(name.uri, r);
} else {
return r;
}
} else {
return '';
}
}
flash_proxy override function getProperty(name:*):* {
var $name:* = $check(name);
if ($name) {
return callJS(newStack($name));
} else {
return new JSProxy(newStack(name));
}
}
flash_proxy override function getDescendants(name:*):* {
return callJS(newStack(name));
}
flash_proxy function newStack(name:*, args:Array = null):Array {
var stack:Array = _stack.slice();
if (args != null) {
stack.push([name, args.slice()]);
} else {
stack.push(name);
}
return stack;
}
flash_proxy override function hasProperty(name:*):Boolean {
return callJS(newStack(new QName('', name))) !== undefined;
}
flash_proxy override function setProperty(name:*, value:*):void {
var $name:* = $check(name);
if ($name) {
callJSSetProperty(newStack($name), value);
} else {
callJSSetProperty(newStack(name), value);
}
}
flash_proxy override function deleteProperty(name:*):Boolean {
return false;
}
public function toString():String {
var res:Array = createCommand(_stack.slice());
var cmd:String = res[0];
var args:Array = res[1];
return '[JSProxy] ' + cmd + ' :: ' + args.join(', ');
}
flash_proxy function callJSSetProperty(stack:Array, value:*):void {
if (!ExternalInterface.available)
return;
var res:Array = createCommand(stack);
var cmd:String = res[0];
var args:Array = res[1];
args.push(value);
var argsString:String = createArgsString(args.length);
cmd = "(function(" + argsString + ") {setTimeout(function(){try{" + cmd + " = _" + (args.length - 1).toString() + "}catch(e){};}, 0);})";
proxyLogger(cmd);
ExternalInterface.call.apply(null, [cmd].concat(args));
}
flash_proxy function callJS(stack:Array):* {
if (!ExternalInterface.available)
return null;
var res:Array = createCommand(stack);
var cmd:String = res[0];
var args:Array = res[1];
var argsString:String = createArgsString(args.length);
if (args.length > 0) {
cmd = "(function(" + argsString + ") {return " + cmd + ";})";
proxyLogger(cmd);
proxyLogger(args);
return ExternalInterface.call.apply(null, [cmd].concat(args));
} else {
cmd = "(function() {return " + cmd + ";})";
proxyLogger(cmd);
return ExternalInterface.call(cmd);
}
}
flash_proxy function createArgsString(len:uint):String {
var res:Array = [];
for (var i:uint = 0; i < len; i++) {
res.push('_' + i);
}
return res.join(', ');
}
flash_proxy function createCommand(stack:Array):Array {
var receivers:Array = [];
var args:Array = [];
var argsStrings:Array = [];
while (stack.length) {
var o:* = stack.shift();
if (o is Array) {
o = o as Array;
var cmd:String = nameToString(o[0]) + '(';
var cmdArgs:Array = [];
var a:Array = o[1].slice();
while (a.length) {
cmdArgs.push('_' + args.length);
args.push(a.shift());
}
cmd += cmdArgs.join(', ');
cmd += ')';
receivers.push(cmd);
} else {
receivers.push(nameToString(o));
}
}
return [receivers.join('.').replace(/\.\[/g, '['), args];
}
flash_proxy function nameToString(name:*):String {
if (name is QName) {
return name.localName.toString();
} else {
return '[' + name.toString() + ']';
}
}
}
}
|
append setter setTimeout()
|
append setter setTimeout()
git-svn-id: 864080e30cc358c5edb906449bbf014f90258007@66 96db6a20-122f-0410-8d9f-89437bbe4005
|
ActionScript
|
mit
|
hotchpotch/as3rails2u,hotchpotch/as3rails2u
|
86af585a12d59369e04acffb07b636be850efd16
|
actionscript/src/com/freshplanet/ane/AirInAppPurchase/InAppPurchase.as
|
actionscript/src/com/freshplanet/ane/AirInAppPurchase/InAppPurchase.as
|
/**
* Copyright 2017 FreshPlanet
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.freshplanet.ane.AirInAppPurchase {
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.system.Capabilities;
/**
*
*/
public class InAppPurchase extends EventDispatcher {
// --------------------------------------------------------------------------------------//
// //
// PUBLIC API //
// //
// --------------------------------------------------------------------------------------//
/**
* If <code>true</code>, logs will be displayed at the ActionScript level.
*/
public static var logEnabled:Boolean = false;
/**
*
*/
public static function get isSupported():Boolean {
return _isIOSOrMacOS() || _isAndroid();
}
/**
*
*/
public static function get instance():InAppPurchase {
return _instance ? _instance : new InAppPurchase();
}
/**
* INIT_SUCCESSFUL
* INIT_ERROR
* @param googlePlayKey
* @param debug
*/
public function init(googlePlayKey:String, debug:Boolean = false):void {
if (!isSupported)
_dispatchEvent(InAppPurchaseEvent.INIT_ERROR, "InAppPurchase not supported");
else
_context.call("initLib", googlePlayKey, debug);
}
/**
* PURCHASE_SUCCESSFUL
* PURCHASE_ERROR
* @param productId
*/
public function makePurchase(productId:String):void {
if (!isSupported)
_dispatchEvent(InAppPurchaseEvent.PURCHASE_ERROR, "InAppPurchase not supported");
else
_context.call("makePurchase", productId);
}
/**
* PURCHASE_SUCCESSFUL
* PURCHASE_ERROR
* @param productId
* @param oldProductId used on Android when upgrading/downgrading subscription - pass in the productId of current user subscription
* @param prorationMode used on Android when upgrading/downgrading subscription
* @param oldSubscriptionPurchaseToken used on Android when upgrading/downgrading subscription
* @param appleDiscountData used on iOS/MacOS when purchasing a subscription with a promotional offer (discount)
*/
public function makeSubscription(productId:String, oldProductId:String = null, prorationMode:InAppPurchaseProrationMode = null, oldSubscriptionPurchaseToken:String = null, appleDiscountData:Object = null):void {
if (!isSupported)
_dispatchEvent(InAppPurchaseEvent.PURCHASE_ERROR, "InAppPurchase not supported");
else
_context.call("makeSubscription", productId, oldProductId ? oldProductId : "", prorationMode ? prorationMode.value : -1, oldSubscriptionPurchaseToken ? oldSubscriptionPurchaseToken : "", appleDiscountData ? JSON.stringify(appleDiscountData) : "");
}
/**
* CONSUME_SUCCESSFUL
* CONSUME_ERROR
* @param productId
* @param receipt
*/
public function removePurchaseFromQueue(productId:String, receipt:String):void {
if (!isSupported)
_dispatchEvent(InAppPurchaseEvent.CONSUME_ERROR, "InAppPurchase not supported");
else {
_context.call("removePurchaseFromQueue", productId, receipt);
if (_isIOSOrMacOS()) {
var filterPurchase:Function = function(jsonPurchase:String, index:int, purchases:Vector.<Object>):Boolean {
try {
var purchase:Object = JSON.parse(jsonPurchase);
return JSON.stringify(purchase.receipt) != receipt;
}
catch (error:Error) {
_log("ERROR", "couldn't parse purchase: " + jsonPurchase);
}
return false;
};
_iosPendingPurchases = _iosPendingPurchases.filter(filterPurchase);
}
}
}
/**
* PRODUCT_INFO_RECEIVED
* PRODUCT_INFO_ERROR
* @param productsIds
* @param subscriptionIds
*/
public function getProductsInfo(productsIds:Array, subscriptionIds:Array):void {
if (!isSupported)
_dispatchEvent(InAppPurchaseEvent.PRODUCT_INFO_ERROR, "InAppPurchase not supported");
else {
productsIds ||= [];
subscriptionIds ||= [];
_context.call("getProductsInfo", productsIds, subscriptionIds);
}
}
/**
* RESTORE_INFO_RECEIVED
* RESTORE_INFO_ERROR
*/
public function restoreTransactions(restoreIOSHistory:Boolean=false):void {
if (!isSupported)
_dispatchEvent(InAppPurchaseEvent.RESTORE_INFO_ERROR, "InAppPurchase not supported");
else if (_isAndroid() || restoreIOSHistory) {
_context.call("restoreTransaction", restoreIOSHistory);
}
else if (_isIOSOrMacOS()) {
var jsonPurchases:String = "[" + _iosPendingPurchases.join(",") + "]";
var jsonData:String = "{ \"purchases\": " + jsonPurchases + "}";
_dispatchEvent(InAppPurchaseEvent.RESTORE_INFO_RECEIVED, jsonData);
}
}
public function clearTransactions():void
{
_iosPendingPurchases = new Vector.<Object>();
if (!isSupported || _isAndroid()) {
_dispatchEvent("CLEAR_TRANSACTIONS_ERROR", "clear transactions not supported");
} else if (_isIOSOrMacOS()) {
_context.call("clearTransactions");
}
}
public function getPendingAppStorePurchase():String {
if (_isIOSOrMacOS()) {
return _context.call("getPendingAppStorePurchase") as String;
}
return null;
}
// --------------------------------------------------------------------------------------//
// //
// PRIVATE API //
// //
// --------------------------------------------------------------------------------------//
private static const EXTENSION_ID:String = "com.freshplanet.ane.AirInAppPurchase";
private static var _instance:InAppPurchase = null;
private var _context:ExtensionContext = null;
private var _iosPendingPurchases:Vector.<Object> = new Vector.<Object>();
/**
* "private" singleton constructor
*/
public function InAppPurchase() {
super();
if (_instance)
throw Error("This is a singleton, use getInstance(), do not call the constructor directly.");
_instance = this;
_context = ExtensionContext.createExtensionContext(EXTENSION_ID, null);
if (!_context)
_log("ERROR", "Extension context is null. Please check if extension.xml is setup correctly.");
else
_context.addEventListener(StatusEvent.STATUS, _onStatus);
}
/**
*
* @param type
* @param eventData
*/
private function _dispatchEvent(type:String, eventData:String):void {
this.dispatchEvent(new InAppPurchaseEvent(type, eventData))
}
/**
*
* @param event
*/
private function _onStatus(event:StatusEvent):void {
if (event.code == InAppPurchaseEvent.PURCHASE_SUCCESSFUL && _isIOSOrMacOS())
_iosPendingPurchases.push(event.level);
else if(event.code == "DEBUG")
_log("DEBUG", event.level);
else if(event.code == "log")
trace(event.level);
_dispatchEvent(event.code, event.level);
}
/**
*
* @param strings
*/
private function _log(...strings):void {
if (logEnabled) {
strings.unshift(EXTENSION_ID);
trace.apply(null, strings);
}
}
/**
*
* @return
*/
private static function _isIOSOrMacOS():Boolean {
return Capabilities.os.indexOf("Mac OS") > -1 || (Capabilities.manufacturer.indexOf("iOS") > -1 && Capabilities.os.indexOf("x86_64") < 0 && Capabilities.os.indexOf("i386") < 0);
}
/**
*
* @return
*/
private static function _isAndroid():Boolean {
return Capabilities.manufacturer.indexOf("Android") > -1;
}
}
}
|
/**
* Copyright 2017 FreshPlanet
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.freshplanet.ane.AirInAppPurchase {
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.system.Capabilities;
/**
*
*/
public class InAppPurchase extends EventDispatcher {
// --------------------------------------------------------------------------------------//
// //
// PUBLIC API //
// //
// --------------------------------------------------------------------------------------//
/**
* If <code>true</code>, logs will be displayed at the ActionScript level.
*/
public static var logEnabled:Boolean = false;
/**
*
*/
public static function get isSupported():Boolean {
return _isIOSOrMacOS() || _isAndroid();
}
/**
*
*/
public static function get instance():InAppPurchase {
return _instance ? _instance : new InAppPurchase();
}
/**
* INIT_SUCCESSFUL
* INIT_ERROR
* @param googlePlayKey
* @param debug
*/
public function init(googlePlayKey:String, debug:Boolean = false):void {
if (!isSupported)
_dispatchEvent(InAppPurchaseEvent.INIT_ERROR, "InAppPurchase not supported");
else
_context.call("initLib", googlePlayKey, debug);
}
/**
* PURCHASE_SUCCESSFUL
* PURCHASE_ERROR
* @param productId
*/
public function makePurchase(productId:String):void {
if (!isSupported)
_dispatchEvent(InAppPurchaseEvent.PURCHASE_ERROR, "InAppPurchase not supported");
else
_context.call("makePurchase", productId);
}
/**
* PURCHASE_SUCCESSFUL
* PURCHASE_ERROR
* @param productId
* @param oldProductId used on Android when upgrading/downgrading subscription - pass in the productId of current user subscription
* @param prorationMode used on Android when upgrading/downgrading subscription
* @param appleDiscountData used on iOS/MacOS when purchasing a subscription with a promotional offer (discount)
*/
public function makeSubscription(productId:String, oldProductId:String = null, prorationMode:InAppPurchaseProrationMode = null, appleDiscountData:Object = null):void {
if (!isSupported)
_dispatchEvent(InAppPurchaseEvent.PURCHASE_ERROR, "InAppPurchase not supported");
else
_context.call("makeSubscription", productId, oldProductId ? oldProductId : "", prorationMode ? prorationMode.value : -1, "", appleDiscountData ? JSON.stringify(appleDiscountData) : "");
}
/**
* CONSUME_SUCCESSFUL
* CONSUME_ERROR
* @param productId
* @param receipt
*/
public function removePurchaseFromQueue(productId:String, receipt:String):void {
if (!isSupported)
_dispatchEvent(InAppPurchaseEvent.CONSUME_ERROR, "InAppPurchase not supported");
else {
_context.call("removePurchaseFromQueue", productId, receipt);
if (_isIOSOrMacOS()) {
var filterPurchase:Function = function(jsonPurchase:String, index:int, purchases:Vector.<Object>):Boolean {
try {
var purchase:Object = JSON.parse(jsonPurchase);
return JSON.stringify(purchase.receipt) != receipt;
}
catch (error:Error) {
_log("ERROR", "couldn't parse purchase: " + jsonPurchase);
}
return false;
};
_iosPendingPurchases = _iosPendingPurchases.filter(filterPurchase);
}
}
}
/**
* PRODUCT_INFO_RECEIVED
* PRODUCT_INFO_ERROR
* @param productsIds
* @param subscriptionIds
*/
public function getProductsInfo(productsIds:Array, subscriptionIds:Array):void {
if (!isSupported)
_dispatchEvent(InAppPurchaseEvent.PRODUCT_INFO_ERROR, "InAppPurchase not supported");
else {
productsIds ||= [];
subscriptionIds ||= [];
_context.call("getProductsInfo", productsIds, subscriptionIds);
}
}
/**
* RESTORE_INFO_RECEIVED
* RESTORE_INFO_ERROR
*/
public function restoreTransactions(restoreIOSHistory:Boolean=false):void {
if (!isSupported)
_dispatchEvent(InAppPurchaseEvent.RESTORE_INFO_ERROR, "InAppPurchase not supported");
else if (_isAndroid() || restoreIOSHistory) {
_context.call("restoreTransaction", restoreIOSHistory);
}
else if (_isIOSOrMacOS()) {
var jsonPurchases:String = "[" + _iosPendingPurchases.join(",") + "]";
var jsonData:String = "{ \"purchases\": " + jsonPurchases + "}";
_dispatchEvent(InAppPurchaseEvent.RESTORE_INFO_RECEIVED, jsonData);
}
}
public function clearTransactions():void
{
_iosPendingPurchases = new Vector.<Object>();
if (!isSupported || _isAndroid()) {
_dispatchEvent("CLEAR_TRANSACTIONS_ERROR", "clear transactions not supported");
} else if (_isIOSOrMacOS()) {
_context.call("clearTransactions");
}
}
public function getPendingAppStorePurchase():String {
if (_isIOSOrMacOS()) {
return _context.call("getPendingAppStorePurchase") as String;
}
return null;
}
// --------------------------------------------------------------------------------------//
// //
// PRIVATE API //
// //
// --------------------------------------------------------------------------------------//
private static const EXTENSION_ID:String = "com.freshplanet.ane.AirInAppPurchase";
private static var _instance:InAppPurchase = null;
private var _context:ExtensionContext = null;
private var _iosPendingPurchases:Vector.<Object> = new Vector.<Object>();
/**
* "private" singleton constructor
*/
public function InAppPurchase() {
super();
if (_instance)
throw Error("This is a singleton, use getInstance(), do not call the constructor directly.");
_instance = this;
_context = ExtensionContext.createExtensionContext(EXTENSION_ID, null);
if (!_context)
_log("ERROR", "Extension context is null. Please check if extension.xml is setup correctly.");
else
_context.addEventListener(StatusEvent.STATUS, _onStatus);
}
/**
*
* @param type
* @param eventData
*/
private function _dispatchEvent(type:String, eventData:String):void {
this.dispatchEvent(new InAppPurchaseEvent(type, eventData))
}
/**
*
* @param event
*/
private function _onStatus(event:StatusEvent):void {
if (event.code == InAppPurchaseEvent.PURCHASE_SUCCESSFUL && _isIOSOrMacOS())
_iosPendingPurchases.push(event.level);
else if(event.code == "DEBUG")
_log("DEBUG", event.level);
else if(event.code == "log")
trace(event.level);
_dispatchEvent(event.code, event.level);
}
/**
*
* @param strings
*/
private function _log(...strings):void {
if (logEnabled) {
strings.unshift(EXTENSION_ID);
trace.apply(null, strings);
}
}
/**
*
* @return
*/
private static function _isIOSOrMacOS():Boolean {
return Capabilities.os.indexOf("Mac OS") > -1 || (Capabilities.manufacturer.indexOf("iOS") > -1 && Capabilities.os.indexOf("x86_64") < 0 && Capabilities.os.indexOf("i386") < 0);
}
/**
*
* @return
*/
private static function _isAndroid():Boolean {
return Capabilities.manufacturer.indexOf("Android") > -1;
}
}
}
|
remove old subscription token param
|
remove old subscription token param
|
ActionScript
|
apache-2.0
|
freshplanet/ANE-In-App-Purchase,freshplanet/ANE-In-App-Purchase,freshplanet/ANE-In-App-Purchase
|
1913069224dd2c21b0044eef9765c3ee4ee6939c
|
fullscreen-ane-android/src/com/mesmotronic/ane/AndroidFullScreen.as
|
fullscreen-ane-android/src/com/mesmotronic/ane/AndroidFullScreen.as
|
/*
Copyright (c) 2014, Mesmotronic Limited
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
* Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.mesmotronic.ane
{
import flash.external.ExtensionContext;
public class AndroidFullScreen
{
// Static initializer
{
init();
}
static private function init():void
{
context = ExtensionContext.createExtensionContext('com.mesmotronic.ane.fullscreen', '');
}
static private var context:ExtensionContext;
static public function get isSupported():Boolean
{
return !!context;
}
/**
* Hides the system status and navigation bars
* @return Boolean false if unsuccessful or not supported, otherwise true
*/
static public function hideSystemUI():Boolean
{
if (!context) return false;
return context.call("hideSystemUI");
}
/**
* Puts your app into full screen immersive mode, hiding the system and
* navigation bars. Users can show them by swiping from the top of the screen.
*
* @return Boolean false if unsuccessful or not supported, otherwise true
*/
static public function immersiveMode(sticky:Boolean=true):Boolean
{
if (!context) return false;
return context.call("immersiveMode", sticky);
}
/**
* Is immersive mode supported on this device?
*
* @return Boolean false if unsuccessful or not supported, otherwise true
*/
static public function get isImmersiveModeSupported():Boolean
{
if (!context) return false;
return context.call("immersiveModeSupported");
}
/**
* Show the system status and navigation bars
* @return Boolean false if unsuccessful or not supported, otherwise true
*/
static public function showSystemUI():Boolean
{
if (!context) return false;
return context.call("showSystemUI");
}
/**
* Extends your app underneath the status and navigation bar
* @return Boolean false if unsuccessful or not supported, otherwise true
*/
static public function showUnderSystemUI():Boolean
{
if (!context) return false;
return context.call("showUnderSystemUI");
}
}
}
|
/*
Copyright (c) 2014, Mesmotronic Limited
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
* Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.mesmotronic.ane
{
import flash.external.ExtensionContext;
public class AndroidFullScreen
{
// Static initializer
{
init();
}
static private function init():void
{
context = ExtensionContext.createExtensionContext('com.mesmotronic.ane.fullscreen', '');
}
static private var context:ExtensionContext;
static public function get isSupported():Boolean
{
return !!context;
}
/**
* Hides the system status and navigation bars
* @return Boolean false if unsuccessful or not supported, otherwise true
*/
static public function hideSystemUI():Boolean
{
if (!context) return false;
return context.call("hideSystemUI");
}
/**
* Puts your app into full screen immersive mode, hiding the system and
* navigation bars. Users can show them by swiping from the top of the screen.
*
* @return Boolean false if unsuccessful or not supported, otherwise true
*/
static public function immersiveMode(sticky:Boolean=true):Boolean
{
if (!context) return false;
return context.call("immersiveMode", sticky);
}
/**
* Is immersive mode supported on this device?
*
* @return Boolean false if unsuccessful or not supported, otherwise true
*/
static public function get isImmersiveModeSupported():Boolean
{
if (!context) return false;
return context.call("isImmersiveModeSupported");
}
/**
* Show the system status and navigation bars
* @return Boolean false if unsuccessful or not supported, otherwise true
*/
static public function showSystemUI():Boolean
{
if (!context) return false;
return context.call("showSystemUI");
}
/**
* Extends your app underneath the status and navigation bar
* @return Boolean false if unsuccessful or not supported, otherwise true
*/
static public function showUnderSystemUI():Boolean
{
if (!context) return false;
return context.call("showUnderSystemUI");
}
}
}
|
Update AndroidFullScreen.as
|
Update AndroidFullScreen.as
A little mistake. In FullScreenContext.java function name is isImmersiveModeSupported.
|
ActionScript
|
bsd-3-clause
|
mesmotronic/air-fullscreen-ane,mesmotronic/air-ane-fullscreen
|
d2090a3a0d1fdbea21c7d0061a25aba3a11028be
|
plugins/comscorePlugin/src/com/kaltura/kdpfl/view/ComscoreMediator.as
|
plugins/comscorePlugin/src/com/kaltura/kdpfl/view/ComscoreMediator.as
|
package com.kaltura.kdpfl.view
{
import com.kaltura.kdpfl.model.ConfigProxy;
import com.kaltura.kdpfl.model.MediaProxy;
import com.kaltura.kdpfl.model.SequenceProxy;
import com.kaltura.kdpfl.model.type.AdsNotificationTypes;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.model.type.SequenceContextType;
import com.kaltura.types.KalturaAdType;
import com.kaltura.vo.KalturaAdCuePoint;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.external.ExternalInterface;
import flash.net.URLLoader;
import flash.net.URLRequest;
import org.puremvc.as3.interfaces.INotification;
import org.puremvc.as3.patterns.mediator.Mediator;
public class ComscoreMediator extends Mediator
{
public static const NAME : String = "comscoreMediator";
public static const VIDEO_TYPE : String = "1";
public static const PREROLL_AD_CONTENT_TYPE : String = "09";
public static const POSTROLL_AD_CONTENT_TYPE : String = "10";
public static const MIDROLL_AD_CONTENT_TYPE : String = "11";
public static const IN_BANNER_VIDEO_AD : String = "12";
protected var _playerPlayedFired : Boolean = false;
protected var cParams : Object = new Object();
protected var _flashvars : Object;
protected var view:ComscorePluginCode;
//total number of segments, determined by number of ad cue points
private var _numOfSegments:int = 1;
//current playing segment
private var _currentSegment:int = 1;
//array containing all ad cue points start time, to calculate current segment
private var _startTimeArray:Array = new Array();
private var _shoudSendBeacon:Boolean = false;
private var _sendOnSequnceEnd:Boolean = false;
private static const CPARAMS_LENGTH:int = 6;
private var _sequenceProxy:SequenceProxy;
public function ComscoreMediator(mediatorName:String=null, viewComponent:Object=null)
{
super(NAME, viewComponent);
view = viewComponent as ComscorePluginCode;
}
override public function onRegister():void
{
_sequenceProxy = (facade.retrieveProxy(SequenceProxy.NAME) as SequenceProxy);
super.onRegister();
}
override public function listNotificationInterests():Array
{
var arr : Array = [
NotificationType.PLAYER_PLAYED,
AdsNotificationTypes.AD_START,
NotificationType.ENTRY_READY,
NotificationType.LAYOUT_READY,
NotificationType.CUE_POINTS_RECEIVED,
NotificationType.AD_OPPORTUNITY,
NotificationType.PLAYER_UPDATE_PLAYHEAD,
NotificationType.MID_SEQUENCE_COMPLETE]
return arr;
}
override public function handleNotification(notification:INotification):void
{
switch (notification.getName() )
{
case NotificationType.LAYOUT_READY:
_flashvars = (facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy).vo.flashvars;
break;
case NotificationType.ENTRY_READY:
createCParams();
_playerPlayedFired = false;
break;
case NotificationType.PLAYER_PLAYED:
if (!_playerPlayedFired)
{
if (!_sequenceProxy.vo.isInSequence)
{
cParams["c5"] = view.c5;
comscoreBeacon();
_playerPlayedFired = true;
}
}
break;
case AdsNotificationTypes.AD_START:
switch (_sequenceProxy.sequenceContext)
{
case SequenceContextType.PRE:
cParams["c5"] = PREROLL_AD_CONTENT_TYPE;
break;
case SequenceContextType.POST:
cParams["c5"] = POSTROLL_AD_CONTENT_TYPE;
break;
case SequenceContextType.MID:
cParams["c5"] = MIDROLL_AD_CONTENT_TYPE ;
_sendOnSequnceEnd = true;
break;
}
comscoreBeacon();
_shoudSendBeacon = false;
break;
case NotificationType.CUE_POINTS_RECEIVED:
var cuePointsMap:Object = notification.getBody();
_startTimeArray = new Array();
var entryMSDuration:int = (facade.retrieveProxy(MediaProxy.NAME) as MediaProxy).vo.entry.msDuration;
for (var inTime:String in cuePointsMap) {
if (parseInt(inTime)!=0 && parseInt(inTime)!=entryMSDuration) {
var cpArray:Array = cuePointsMap[inTime];
//whether this start time was already saved to _startTimeArray
var startTimeSaved:Boolean = false;
for (var i:int = 0; i<cpArray.length; i++) {
if (cpArray[i] is KalturaAdCuePoint) {
var curCp:KalturaAdCuePoint = cpArray[i] as KalturaAdCuePoint;
if (curCp.adType == KalturaAdType.VIDEO && !startTimeSaved) {
_startTimeArray.push(inTime);
startTimeSaved = true;
_numOfSegments++;
}
}
}
}
}
_startTimeArray.sort(Array.NUMERIC);
break;
case NotificationType.AD_OPPORTUNITY:
var msDuration:int = (facade.retrieveProxy(MediaProxy.NAME) as MediaProxy).vo.entry.msDuration;
var cp:KalturaAdCuePoint = notification.getBody().cuePoint as KalturaAdCuePoint;
if (cp.startTime!=0 && cp.startTime!=msDuration && cp.adType == KalturaAdType.VIDEO) {
for (var j:int =0 ; j<_startTimeArray.length; j++) {
if (_startTimeArray[j]==cp.startTime) {
//add 1 since array is zero based and segment is 1 based,
//add another one because we passed the cue point
_currentSegment = j + 2;
break;
}
}
_shoudSendBeacon = true;
}
break;
case NotificationType.PLAYER_UPDATE_PLAYHEAD:
if (_shoudSendBeacon) {
cParams["c5"] = view.c5;
comscoreBeacon();
_shoudSendBeacon = false;
}
break;
case NotificationType.MID_SEQUENCE_COMPLETE:
if (_sendOnSequnceEnd) {
cParams["c5"] = view.c5;
comscoreBeacon();
_sendOnSequnceEnd = false;
}
break;
}
}
protected function comscoreBeacon () : void
{
var loadUrl : String;
var referrer : String = "";
var page : String = "";
var title : String = "";
try {
if(_flashvars.referer)
{
referrer = ExternalInterface.call( "function() { return document.referrer; }").toString();
}
} catch (e : Error)
{
referrer = _flashvars.referer;
}
try {
if(_flashvars.referer)
{
page = ExternalInterface.call( "function () { return document.location.href; } ").toString();
}
} catch (e : Error)
{
page = _flashvars.referer;
}
try {
if(_flashvars.referer)
{
title = ExternalInterface.call( "function () { return document.title; } ").toString();
}
} catch (e : Error)
{
title = _flashvars.referer;
}
if (page.indexOf("https") != -1 ) {
loadUrl = "https://sb.";
} else {
loadUrl = "http://b."
}
loadUrl += "scorecardresearch.com/p?";
createCParams();
//concat cParams, by their order
for (var i:int = 0; i < CPARAMS_LENGTH; i++)
{
var curC:String = "c" + (i + 1);
if (cParams[curC] && cParams[curC]!='')
{
loadUrl += curC+"="+cParams[curC]+"&";
}
}
if (page && page != "") {
loadUrl += "c7=" + page +"&";
}
if (title && title != "") {
loadUrl += "c8=" + title +"&";
}
if (referrer && referrer != "") {
loadUrl += "c9=" + referrer +"&";
}
loadUrl += "c10=" + _currentSegment + "-" + _numOfSegments + "&";
loadUrl += "rn=" + Math.random().toString() + "&";
loadUrl +="cv=" + view.comscoreVersion + "&";
if (view.cs_eidr)
loadUrl +="cs_eidr="+view.cs_eidr + "&";
if (_sequenceProxy.vo.isInSequence && view.cs_adid)
loadUrl += "cs_adid="+view.cs_adid;
var loader : URLLoader = new URLLoader();
var urlRequest : URLRequest = new URLRequest(loadUrl);
loader.addEventListener(Event.COMPLETE, onComscoreBeaconSuccess);
loader.addEventListener(IOErrorEvent.IO_ERROR, onComscoreBeaconFailed);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onComscoreBeaconFailed);
loader.load(urlRequest);
}
protected function onComscoreBeaconSuccess (e : Event) : void
{
}
protected function onComscoreBeaconFailed (e : Event) : void
{
}
protected function createCParams() : void
{
cParams["c1"] = view.c1 ? view.c1 : VIDEO_TYPE;
cParams["c2"] = view.c2;
cParams["c3"] = view.c3;
cParams["c4"] = view.c4;
cParams["c6"] = view.c6;
}
}
}
|
package com.kaltura.kdpfl.view
{
import com.kaltura.kdpfl.model.ConfigProxy;
import com.kaltura.kdpfl.model.MediaProxy;
import com.kaltura.kdpfl.model.SequenceProxy;
import com.kaltura.kdpfl.model.type.AdsNotificationTypes;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.model.type.SequenceContextType;
import com.kaltura.types.KalturaAdType;
import com.kaltura.vo.KalturaAdCuePoint;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.external.ExternalInterface;
import flash.net.URLLoader;
import flash.net.URLRequest;
import org.puremvc.as3.interfaces.INotification;
import org.puremvc.as3.patterns.mediator.Mediator;
public class ComscoreMediator extends Mediator
{
public static const NAME : String = "comscoreMediator";
public static const VIDEO_TYPE : String = "1";
public static const PREROLL_AD_CONTENT_TYPE : String = "09";
public static const POSTROLL_AD_CONTENT_TYPE : String = "10";
public static const MIDROLL_AD_CONTENT_TYPE : String = "11";
public static const IN_BANNER_VIDEO_AD : String = "12";
protected var _playerPlayedFired : Boolean = false;
protected var cParams : Object = new Object();
protected var _flashvars : Object;
protected var view:ComscorePluginCode;
//total number of segments, determined by number of ad cue points
private var _numOfSegments:int = 1;
//current playing segment
private var _currentSegment:int = 1;
//array containing all ad cue points start time, to calculate current segment
private var _startTimeArray:Array = new Array();
private var _shoudSendBeacon:Boolean = false;
private var _sendOnSequnceEnd:Boolean = false;
private static const CPARAMS_LENGTH:int = 6;
private var _sequenceProxy:SequenceProxy;
public function ComscoreMediator(mediatorName:String=null, viewComponent:Object=null)
{
super(NAME, viewComponent);
view = viewComponent as ComscorePluginCode;
}
override public function onRegister():void
{
_sequenceProxy = (facade.retrieveProxy(SequenceProxy.NAME) as SequenceProxy);
super.onRegister();
}
override public function listNotificationInterests():Array
{
var arr : Array = [
NotificationType.PLAYER_PLAYED,
AdsNotificationTypes.AD_START,
NotificationType.ENTRY_READY,
NotificationType.LAYOUT_READY,
NotificationType.CUE_POINTS_RECEIVED,
NotificationType.AD_OPPORTUNITY,
NotificationType.PLAYER_UPDATE_PLAYHEAD,
NotificationType.MID_SEQUENCE_COMPLETE,
NotificationType.CHANGE_MEDIA]
return arr;
}
override public function handleNotification(notification:INotification):void
{
switch (notification.getName() )
{
case NotificationType.LAYOUT_READY:
_flashvars = (facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy).vo.flashvars;
break;
case NotificationType.ENTRY_READY:
createCParams();
_playerPlayedFired = false;
break;
case NotificationType.PLAYER_PLAYED:
if (!_playerPlayedFired)
{
if (!_sequenceProxy.vo.isInSequence)
{
cParams["c5"] = view.c5;
comscoreBeacon();
_playerPlayedFired = true;
}
}
break;
case AdsNotificationTypes.AD_START:
switch (_sequenceProxy.sequenceContext)
{
case SequenceContextType.PRE:
cParams["c5"] = PREROLL_AD_CONTENT_TYPE;
break;
case SequenceContextType.POST:
cParams["c5"] = POSTROLL_AD_CONTENT_TYPE;
break;
case SequenceContextType.MID:
cParams["c5"] = MIDROLL_AD_CONTENT_TYPE ;
_sendOnSequnceEnd = true;
break;
}
comscoreBeacon();
_shoudSendBeacon = false;
break;
case NotificationType.CUE_POINTS_RECEIVED:
var cuePointsMap:Object = notification.getBody();
_startTimeArray = new Array();
var entryMSDuration:int = (facade.retrieveProxy(MediaProxy.NAME) as MediaProxy).vo.entry.msDuration;
for (var inTime:String in cuePointsMap) {
if (parseInt(inTime)!=0 && parseInt(inTime)!=entryMSDuration) {
var cpArray:Array = cuePointsMap[inTime];
//whether this start time was already saved to _startTimeArray
var startTimeSaved:Boolean = false;
for (var i:int = 0; i<cpArray.length; i++) {
if (cpArray[i] is KalturaAdCuePoint) {
var curCp:KalturaAdCuePoint = cpArray[i] as KalturaAdCuePoint;
if (curCp.adType == KalturaAdType.VIDEO && !startTimeSaved) {
_startTimeArray.push(inTime);
startTimeSaved = true;
_numOfSegments++;
}
}
}
}
}
_startTimeArray.sort(Array.NUMERIC);
break;
case NotificationType.AD_OPPORTUNITY:
var msDuration:int = (facade.retrieveProxy(MediaProxy.NAME) as MediaProxy).vo.entry.msDuration;
var cp:KalturaAdCuePoint = notification.getBody().cuePoint as KalturaAdCuePoint;
if (cp.startTime!=0 && cp.startTime!=msDuration && cp.adType == KalturaAdType.VIDEO) {
for (var j:int =0 ; j<_startTimeArray.length; j++) {
if (_startTimeArray[j]==cp.startTime) {
//add 1 since array is zero based and segment is 1 based,
//add another one because we passed the cue point
_currentSegment = j + 2;
break;
}
}
_shoudSendBeacon = true;
}
break;
case NotificationType.PLAYER_UPDATE_PLAYHEAD:
if (_shoudSendBeacon) {
cParams["c5"] = view.c5;
comscoreBeacon();
_shoudSendBeacon = false;
}
break;
case NotificationType.MID_SEQUENCE_COMPLETE:
if (_sendOnSequnceEnd) {
cParams["c5"] = view.c5;
comscoreBeacon();
_sendOnSequnceEnd = false;
}
break;
case NotificationType.CHANGE_MEDIA:
_numOfSegments = 1;
}
}
protected function comscoreBeacon () : void
{
var loadUrl : String;
var referrer : String = "";
var page : String = "";
var title : String = "";
try {
if(_flashvars.referer)
{
referrer = ExternalInterface.call( "function() { return document.referrer; }").toString();
}
} catch (e : Error)
{
referrer = _flashvars.referer;
}
try {
if(_flashvars.referer)
{
page = ExternalInterface.call( "function () { return document.location.href; } ").toString();
}
} catch (e : Error)
{
page = _flashvars.referer;
}
try {
if(_flashvars.referer)
{
title = ExternalInterface.call( "function () { return document.title; } ").toString();
}
} catch (e : Error)
{
title = _flashvars.referer;
}
if (page.indexOf("https") != -1 ) {
loadUrl = "https://sb.";
} else {
loadUrl = "http://b."
}
loadUrl += "scorecardresearch.com/p?";
createCParams();
//concat cParams, by their order
for (var i:int = 0; i < CPARAMS_LENGTH; i++)
{
var curC:String = "c" + (i + 1);
if (cParams[curC] && cParams[curC]!='')
{
loadUrl += curC+"="+cParams[curC]+"&";
}
}
if (page && page != "") {
loadUrl += "c7=" + page +"&";
}
if (title && title != "") {
loadUrl += "c8=" + title +"&";
}
if (referrer && referrer != "") {
loadUrl += "c9=" + referrer +"&";
}
loadUrl += "c10=" + _currentSegment + "-" + _numOfSegments + "&";
loadUrl += "rn=" + Math.random().toString() + "&";
loadUrl +="cv=" + view.comscoreVersion + "&";
if (view.cs_eidr)
loadUrl +="cs_eidr="+view.cs_eidr + "&";
if (_sequenceProxy.vo.isInSequence && view.cs_adid)
loadUrl += "cs_adid="+view.cs_adid;
var loader : URLLoader = new URLLoader();
var urlRequest : URLRequest = new URLRequest(loadUrl);
loader.addEventListener(Event.COMPLETE, onComscoreBeaconSuccess);
loader.addEventListener(IOErrorEvent.IO_ERROR, onComscoreBeaconFailed);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onComscoreBeaconFailed);
loader.load(urlRequest);
}
protected function onComscoreBeaconSuccess (e : Event) : void
{
}
protected function onComscoreBeaconFailed (e : Event) : void
{
}
protected function createCParams() : void
{
cParams["c1"] = view.c1 ? view.c1 : VIDEO_TYPE;
cParams["c2"] = view.c2;
cParams["c3"] = view.c3;
cParams["c4"] = view.c4;
cParams["c6"] = view.c6;
}
}
}
|
reset segments count on change media
|
qnd: reset segments count on change media
git-svn-id: 3f608e5a9a704dd448217c0a64c508e7f145cfa1@92241 6b8eccd3-e8c5-4e7d-8186-e12b5326b719
|
ActionScript
|
agpl-3.0
|
shvyrev/kdp,shvyrev/kdp,kaltura/kdp,shvyrev/kdp,kaltura/kdp,kaltura/kdp
|
f4ff1dbfd42b1504c8179beb736897ade0ee5d5a
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/CSSTextField.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/CSSTextField.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.core
{
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import org.apache.flex.core.ValuesManager;
/**
* The CSSTextField class implements CSS text styles in a TextField.
* Not every CSS text style is currently supported.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class CSSTextField extends TextField
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function CSSTextField()
{
super();
}
/**
* @private
* The styleParent property is set if the CSSTextField
* is used in a SimpleButton-based instance because
* the parent property is null, defeating CSS lookup.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var styleParent:Object;
/**
* @private
*/
override public function set text(value:String):void
{
var sp:Object = parent;
if (!sp)
sp = styleParent;
var tf: TextFormat = new TextFormat();
tf.font = ValuesManager.valuesImpl.getValue(sp, "fontFamily") as String;
tf.size = ValuesManager.valuesImpl.getValue(sp, "fontSize");
tf.bold = ValuesManager.valuesImpl.getValue(sp, "fontWeight") == "bold";
tf.color = ValuesManager.valuesImpl.getValue(sp, "color");
var padding:Object = ValuesManager.valuesImpl.getValue(sp, "padding");
if (padding == null) padding = 0;
var paddingLeft:Object = ValuesManager.valuesImpl.getValue(sp,"padding-left");
if (paddingLeft == null) paddingLeft = padding;
var paddingRight:Object = ValuesManager.valuesImpl.getValue(sp,"padding-right");
if (paddingRight == null) paddingRight = padding;
tf.leftMargin = paddingLeft;
tf.rightMargin = paddingRight;
var align:Object = ValuesManager.valuesImpl.getValue(sp, "text-align");
if (align == "center")
{
autoSize = TextFieldAutoSize.NONE;
tf.align = "center";
}
else if (align == "right")
{
tf.align = "right";
autoSize = TextFieldAutoSize.NONE;
}
var backgroundColor:Object = ValuesManager.valuesImpl.getValue(sp, "background-color");
if (backgroundColor != null)
{
this.background = true;
if (backgroundColor is String)
{
backgroundColor = backgroundColor.replace("#", "0x");
backgroundColor = uint(backgroundColor);
}
this.backgroundColor = backgroundColor as uint;
}
defaultTextFormat = tf;
super.text = value;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.core
{
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
/**
* The CSSTextField class implements CSS text styles in a TextField.
* Not every CSS text style is currently supported.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class CSSTextField extends TextField
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function CSSTextField()
{
super();
}
/**
* @private
* The styleParent property is set if the CSSTextField
* is used in a SimpleButton-based instance because
* the parent property is null, defeating CSS lookup.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var styleParent:Object;
/**
* @private
*/
override public function set text(value:String):void
{
var sp:Object = parent;
if (!sp)
sp = styleParent;
sp.addEventListener("classNameChanged", updateStyles);
var tf: TextFormat = new TextFormat();
tf.font = ValuesManager.valuesImpl.getValue(sp, "fontFamily") as String;
tf.size = ValuesManager.valuesImpl.getValue(sp, "fontSize");
tf.bold = ValuesManager.valuesImpl.getValue(sp, "fontWeight") == "bold";
tf.color = ValuesManager.valuesImpl.getValue(sp, "color");
var padding:Object = ValuesManager.valuesImpl.getValue(sp, "padding");
if (padding == null) padding = 0;
var paddingLeft:Object = ValuesManager.valuesImpl.getValue(sp,"padding-left");
if (paddingLeft == null) paddingLeft = padding;
var paddingRight:Object = ValuesManager.valuesImpl.getValue(sp,"padding-right");
if (paddingRight == null) paddingRight = padding;
tf.leftMargin = paddingLeft;
tf.rightMargin = paddingRight;
var align:Object = ValuesManager.valuesImpl.getValue(sp, "text-align");
if (align == "center")
{
autoSize = TextFieldAutoSize.NONE;
tf.align = "center";
}
else if (align == "right")
{
tf.align = "right";
autoSize = TextFieldAutoSize.NONE;
}
var backgroundColor:Object = ValuesManager.valuesImpl.getValue(sp, "background-color");
if (backgroundColor != null)
{
this.background = true;
if (backgroundColor is String)
{
backgroundColor = backgroundColor.replace("#", "0x");
backgroundColor = uint(backgroundColor);
}
this.backgroundColor = backgroundColor as uint;
}
defaultTextFormat = tf;
super.text = value;
}
private function updateStyles(event:Event):void
{
// force styles to be re-calculated
this.text = text;
}
}
}
|
handle classname changes
|
handle classname changes
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
77e52edc9ca75b1f39bde14e1db1d7d52b9c6e63
|
src/aerys/minko/scene/controller/mesh/MeshVisibilityController.as
|
src/aerys/minko/scene/controller/mesh/MeshVisibilityController.as
|
package aerys.minko.scene.controller.mesh
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
import aerys.minko.scene.node.camera.AbstractCamera;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.enum.FrustumCulling;
import aerys.minko.type.math.BoundingBox;
import aerys.minko.type.math.BoundingSphere;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
/**
* The MeshVisibilityController watches the Mesh and the active Camera of a Scene
* to determine whether the object is actually inside the view frustum or not.
*
* @author Jean-Marc Le Roux
*
*/
public final class MeshVisibilityController extends AbstractController
{
use namespace minko_math;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
private static const STATE_UNDEFINED : uint = 0;
private static const STATE_INSIDE : uint = 1;
private static const STATE_OUTSIDE : uint = 2;
private var _mesh : Mesh;
private var _state : uint;
private var _lastTest : int;
private var _boundingBox : BoundingBox;
private var _boundingSphere : BoundingSphere;
private var _data : DataProvider;
private var _frustumCulling : uint;
private var _insideFrustum : Boolean;
public function get frustumCulling() : uint
{
return _frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
if (value != _frustumCulling)
{
_frustumCulling = value;
if (value == FrustumCulling.DISABLED)
{
_data.computedVisibility = true;
if (_mesh.localToWorldTransformChanged.hasCallback(meshLocalToWorldChangedHandler))
{
_mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler);
}
}
else if (_mesh && _mesh.scene)
{
_mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler);
testCulling();
}
}
}
public function get insideFrustum() : Boolean
{
return _insideFrustum;
}
public function get computedVisibility() : Boolean
{
return _data.computedVisibility;
}
public function MeshVisibilityController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
_data = new DataProvider(
{ computedVisibility : true },
'MeshVisibilityDataProvider',
DataProviderUsage.EXCLUSIVE
);
_boundingBox = new BoundingBox(Vector4.ZERO, Vector4.ONE);
_boundingSphere = new BoundingSphere(Vector4.ZERO, 0.);
_state = STATE_UNDEFINED;
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
if (_mesh != null)
throw new Error();
_mesh = target;
target.added.add(addedHandler);
target.removed.add(removedHandler);
if (target.root is Scene)
addedHandler(target, target.root as Scene);
if (_frustumCulling)
testCulling();
}
private function targetRemovedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
_mesh = null;
target.added.remove(addedHandler);
target.removed.remove(removedHandler);
if (target.root is Scene)
removedHandler(target, target.root as Scene);
}
private function addedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = mesh.scene;
if (!scene)
return ;
scene.bindings.addCallback('worldToScreen', worldToScreenChangedHandler);
if (_frustumCulling)
{
meshLocalToWorldChangedHandler(mesh, mesh.getLocalToWorldTransform());
mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler);
}
mesh.computedVisibilityChanged.add(computedVisiblityChangedHandler);
mesh.bindings.addProvider(_data);
}
private function removedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = ancestor.scene;
if (!scene)
return ;
scene.bindings.removeCallback('worldToScreen', worldToScreenChangedHandler);
if (_frustumCulling)
mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler);
mesh.computedVisibilityChanged.remove(computedVisiblityChangedHandler);
mesh.bindings.removeProvider(_data);
}
private function computedVisiblityChangedHandler(node : ISceneNode,
computedVisibility : Boolean) : void
{
_data.computedVisibility = computedVisibility;
}
private function worldToScreenChangedHandler(bindings : DataBindings,
bindingName : String,
oldValue : Matrix4x4,
value : Matrix4x4) : void
{
testCulling();
}
private function meshLocalToWorldChangedHandler(mesh : Mesh, transform : Matrix4x4) : void
{
var geom : Geometry = _mesh.geometry;
var culling : uint = _frustumCulling;
if (!geom.boundingBox || !geom.boundingSphere || culling == FrustumCulling.DISABLED)
return ;
if (culling & FrustumCulling.BOX)
transform.transformRawVectors(geom.boundingBox._vertices, _boundingBox._vertices);
if (culling & FrustumCulling.SPHERE)
{
var center : Vector4 = transform.transformVector(geom.boundingSphere.center);
var scale : Vector4 = transform.deltaTransformVector(Vector4.ONE);
var radius : Number = geom.boundingSphere.radius * Math.max(
Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z)
);
_boundingSphere.update(center, radius);
}
testCulling();
}
private function testCulling() : void
{
var culling : uint = _frustumCulling;
if (_mesh && _mesh.geometry && _mesh.geometry.boundingBox && _mesh.visible)
{
var camera : AbstractCamera = (_mesh.root as Scene).activeCamera;
if (!camera)
return ;
_lastTest = camera.frustum.testBoundingVolume(
_boundingSphere,
_boundingBox,
null,
culling,
_lastTest
);
var inside : Boolean = _lastTest == -1;
if (inside && _state != STATE_INSIDE)
{
_insideFrustum = true;
_data.computedVisibility = _mesh.parent.computedVisibility && _mesh.visible;
_mesh.computedVisibilityChanged.execute(_mesh, computedVisibility);
_state = STATE_INSIDE;
}
else if (!inside && _state != STATE_OUTSIDE)
{
_insideFrustum = false;
_data.computedVisibility = false;
_mesh.computedVisibilityChanged.execute(_mesh, false);
_state = STATE_OUTSIDE;
}
}
}
override public function clone() : AbstractController
{
return new MeshVisibilityController();
}
}
}
|
package aerys.minko.scene.controller.mesh
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
import aerys.minko.scene.node.camera.AbstractCamera;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.enum.FrustumCulling;
import aerys.minko.type.math.BoundingBox;
import aerys.minko.type.math.BoundingSphere;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
/**
* The MeshVisibilityController watches the Mesh and the active Camera of a Scene
* to determine whether the object is actually inside the view frustum or not.
*
* @author Jean-Marc Le Roux
*
*/
public final class MeshVisibilityController extends AbstractController
{
use namespace minko_math;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
private static const STATE_UNDEFINED : uint = 0;
private static const STATE_INSIDE : uint = 1;
private static const STATE_OUTSIDE : uint = 2;
private var _mesh : Mesh;
private var _state : uint;
private var _lastTest : int;
private var _boundingBox : BoundingBox;
private var _boundingSphere : BoundingSphere;
private var _data : DataProvider;
private var _frustumCulling : uint;
private var _insideFrustum : Boolean;
public function get frustumCulling() : uint
{
return _frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
if (value != _frustumCulling)
{
_frustumCulling = value;
if (value == FrustumCulling.DISABLED)
{
_data.computedVisibility = true;
if (_mesh.localToWorldTransformChanged.hasCallback(meshLocalToWorldChangedHandler))
_mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler);
}
else if (_mesh && _mesh.scene)
{
_mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler);
testCulling();
}
}
}
public function get insideFrustum() : Boolean
{
return _insideFrustum;
}
public function get computedVisibility() : Boolean
{
return _data.computedVisibility;
}
public function MeshVisibilityController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
_data = new DataProvider(
{ computedVisibility : true },
'MeshVisibilityDataProvider',
DataProviderUsage.EXCLUSIVE
);
_boundingBox = new BoundingBox(Vector4.ZERO, Vector4.ONE);
_boundingSphere = new BoundingSphere(Vector4.ZERO, 0.);
_state = STATE_UNDEFINED;
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
if (_mesh != null)
throw new Error();
_mesh = target;
target.added.add(addedHandler);
target.removed.add(removedHandler);
if (target.root is Scene)
addedHandler(target, target.root as Scene);
if (_frustumCulling)
testCulling();
}
private function targetRemovedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
_mesh = null;
target.added.remove(addedHandler);
target.removed.remove(removedHandler);
if (target.root is Scene)
removedHandler(target, target.root as Scene);
}
private function addedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = mesh.scene;
if (!scene)
return ;
scene.bindings.addCallback('worldToScreen', worldToScreenChangedHandler);
if (_frustumCulling)
{
meshLocalToWorldChangedHandler(mesh, mesh.getLocalToWorldTransform());
mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler);
}
mesh.computedVisibilityChanged.add(computedVisiblityChangedHandler);
mesh.bindings.addProvider(_data);
}
private function removedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = ancestor.scene;
if (!scene)
return ;
scene.bindings.removeCallback('worldToScreen', worldToScreenChangedHandler);
if (_frustumCulling)
mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler);
mesh.computedVisibilityChanged.remove(computedVisiblityChangedHandler);
mesh.bindings.removeProvider(_data);
}
private function computedVisiblityChangedHandler(node : ISceneNode,
computedVisibility : Boolean) : void
{
_data.computedVisibility = computedVisibility;
}
private function worldToScreenChangedHandler(bindings : DataBindings,
bindingName : String,
oldValue : Matrix4x4,
value : Matrix4x4) : void
{
testCulling();
}
private function meshLocalToWorldChangedHandler(mesh : Mesh, transform : Matrix4x4) : void
{
var geom : Geometry = _mesh.geometry;
var culling : uint = _frustumCulling;
if (!geom.boundingBox || !geom.boundingSphere || culling == FrustumCulling.DISABLED)
return ;
if (culling & FrustumCulling.BOX)
transform.transformRawVectors(geom.boundingBox._vertices, _boundingBox._vertices);
if (culling & FrustumCulling.SPHERE)
{
var center : Vector4 = transform.transformVector(geom.boundingSphere.center);
var scale : Vector4 = transform.deltaTransformVector(Vector4.ONE);
var radius : Number = geom.boundingSphere.radius * Math.max(
Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z)
);
_boundingSphere.update(center, radius);
}
testCulling();
}
private function testCulling() : void
{
var culling : uint = _frustumCulling;
if (_mesh && _mesh.geometry && _mesh.geometry.boundingBox && _mesh.visible)
{
var camera : AbstractCamera = (_mesh.root as Scene).activeCamera;
if (!camera)
return ;
_lastTest = camera.frustum.testBoundingVolume(
_boundingSphere,
_boundingBox,
null,
culling,
_lastTest
);
var inside : Boolean = _lastTest == -1;
if (inside && _state != STATE_INSIDE)
{
_insideFrustum = true;
_data.computedVisibility = _mesh.parent.computedVisibility && _mesh.visible;
_mesh.computedVisibilityChanged.execute(_mesh, computedVisibility);
_state = STATE_INSIDE;
}
else if (!inside && _state != STATE_OUTSIDE)
{
_insideFrustum = false;
_data.computedVisibility = false;
_mesh.computedVisibilityChanged.execute(_mesh, false);
_state = STATE_OUTSIDE;
}
}
}
override public function clone() : AbstractController
{
return new MeshVisibilityController();
}
}
}
|
remove useless brackets
|
remove useless brackets
|
ActionScript
|
mit
|
aerys/minko-as3
|
4845965208ec25f47aa53179d8c00e3659c12af1
|
src/as/com/threerings/flash/FilterUtil.as
|
src/as/com/threerings/flash/FilterUtil.as
|
//
// $Id$
//
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/nenya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.flash {
import flash.display.DisplayObject;
import flash.filters.BevelFilter;
import flash.filters.BitmapFilter;
import flash.filters.BlurFilter;
import flash.filters.ColorMatrixFilter;
import flash.filters.ConvolutionFilter;
import flash.filters.DisplacementMapFilter;
import flash.filters.DropShadowFilter;
import flash.filters.GlowFilter;
import flash.filters.GradientBevelFilter;
import flash.filters.GradientGlowFilter;
import com.threerings.util.ArrayUtil;
import com.threerings.util.ClassUtil;
/**
* Useful utility methods that wouldn't be needed if the flash API were not so retarded.
*/
public class FilterUtil
{
/**
* Add the specified filter to the DisplayObject.
*/
public static function addFilter (disp :DisplayObject, filter :BitmapFilter) :void
{
checkArgs(disp, filter);
var filts :Array = disp.filters;
if (filts == null) {
filts = [];
}
filts.push(filter);
disp.filters = filts;
}
/**
* Remove the specified filter from the DisplayObject.
* Note that the filter set in the DisplayObject is a clone, so the values
* of the specified filter are used to find a match.
*/
public static function removeFilter (disp :DisplayObject, filter :BitmapFilter) :void
{
checkArgs(disp, filter);
var filts :Array = disp.filters;
if (filts != null) {
for (var ii :int = filts.length - 1; ii >= 0; ii--) {
var oldFilter :BitmapFilter = (filts[ii] as BitmapFilter);
if (equals(oldFilter, filter)) {
filts.splice(ii, 1);
if (filts.length == 0) {
filts = null;
}
disp.filters = filts;
return; // SUCCESS
}
}
}
}
/**
* Are the two filters equals?
*/
public static function equals (f1 :BitmapFilter, f2 :BitmapFilter) :Boolean
{
if (f1 === f2) { // catch same instance, or both null
return true;
} else if (f1 == null || f2 == null) { // otherwise nulls are no good
return false;
}
var c1 :Class = ClassUtil.getClass(f1);
if (c1 !== ClassUtil.getClass(f2)) {
return false;
}
// when we have two filters of the same class, figure it out by hand...
switch (c1) {
case BevelFilter:
var bf1 :BevelFilter = (f1 as BevelFilter);
var bf2 :BevelFilter = (f2 as BevelFilter);
return (bf1.angle == bf2.angle) && (bf1.blurX == bf2.blurX) &&
(bf1.blurY == bf2.blurY) && (bf1.distance == bf2.distance) &&
(bf1.highlightAlpha == bf2.highlightAlpha) &&
(bf1.highlightColor == bf2.highlightColor) && (bf1.knockout == bf2.knockout) &&
(bf1.quality == bf2.quality) && (bf1.shadowAlpha == bf2.shadowAlpha) &&
(bf1.shadowColor == bf2.shadowColor) && (bf1.strength == bf2.strength) &&
(bf1.type == bf2.type);
case BlurFilter:
var blur1 :BlurFilter = (f1 as BlurFilter);
var blur2 :BlurFilter = (f2 as BlurFilter);
return (blur1.blurX == blur2.blurX) && (blur1.blurY == blur2.blurY) &&
(blur1.quality == blur2.quality);
case ColorMatrixFilter:
var cmf1 :ColorMatrixFilter = (f1 as ColorMatrixFilter);
var cmf2 :ColorMatrixFilter = (f2 as ColorMatrixFilter);
return ArrayUtil.equals(cmf1.matrix, cmf2.matrix);
case ConvolutionFilter:
var cf1 :ConvolutionFilter = (f1 as ConvolutionFilter);
var cf2 :ConvolutionFilter = (f2 as ConvolutionFilter);
return (cf1.alpha == cf2.alpha) && (cf1.bias == cf2.bias) && (cf1.clamp == cf2.clamp) &&
(cf1.color == cf2.color) && (cf1.divisor == cf2.divisor) &&
ArrayUtil.equals(cf1.matrix, cf2.matrix) && (cf1.matrixX == cf2.matrixX) &&
(cf1.matrixY == cf2.matrixY) && (cf1.preserveAlpha == cf2.preserveAlpha);
case DisplacementMapFilter:
var dmf1 :DisplacementMapFilter = (f1 as DisplacementMapFilter);
var dmf2 :DisplacementMapFilter = (f2 as DisplacementMapFilter);
return (dmf1.alpha == dmf2.alpha) && (dmf1.color == dmf2.color) &&
(dmf1.componentX == dmf2.componentX) && (dmf1.componentY == dmf2.componentY) &&
(dmf1.mapBitmap == dmf2.mapBitmap) && dmf1.mapPoint.equals(dmf2.mapPoint) &&
(dmf1.mode == dmf2.mode) && (dmf1.scaleX == dmf2.scaleX) &&
(dmf1.scaleY == dmf2.scaleY);
case DropShadowFilter:
var dsf1 :DropShadowFilter = (f1 as DropShadowFilter);
var dsf2 :DropShadowFilter = (f2 as DropShadowFilter);
return (dsf1.alpha == dsf2.alpha) && (dsf1.angle = dsf2.angle) &&
(dsf1.blurX = dsf2.blurX) && (dsf1.blurY = dsf2.blurY) &&
(dsf1.color = dsf2.color) && (dsf1.distance = dsf2.distance) &&
(dsf1.hideObject = dsf2.hideObject) && (dsf1.inner = dsf2.inner) &&
(dsf1.knockout = dsf2.knockout) && (dsf1.quality = dsf2.quality) &&
(dsf1.strength = dsf2.strength);
case GlowFilter:
var gf1 :GlowFilter = (f1 as GlowFilter);
var gf2 :GlowFilter = (f2 as GlowFilter);
return (gf1.alpha == gf2.alpha) && (gf1.blurX == gf2.blurX) &&
(gf1.blurY == gf2.blurY) && (gf1.color == gf2.color) && (gf1.inner == gf2.inner) &&
(gf1.knockout == gf2.knockout) && (gf1.quality == gf2.quality) &&
(gf1.strength == gf2.strength);
case GradientBevelFilter:
var gbf1 :GradientBevelFilter = (f1 as GradientBevelFilter);
var gbf2 :GradientBevelFilter = (f2 as GradientBevelFilter);
return ArrayUtil.equals(gbf1.alphas, gbf2.alphas) && (gbf1.angle == gbf2.angle) &&
(gbf1.blurX == gbf2.blurX) && (gbf1.blurY == gbf2.blurY) &&
ArrayUtil.equals(gbf1.colors, gbf2.colors) && (gbf1.distance == gbf2.distance) &&
(gbf1.knockout == gbf2.knockout) && (gbf1.quality == gbf2.quality) &&
ArrayUtil.equals(gbf1.ratios, gbf2.ratios) && (gbf1.strength == gbf2.strength) &&
(gbf1.type == gbf2.type);
case GradientGlowFilter:
var ggf1 :GradientGlowFilter = (f1 as GradientGlowFilter);
var ggf2 :GradientGlowFilter = (f2 as GradientGlowFilter);
return ArrayUtil.equals(ggf1.alphas, ggf2.alphas) && (ggf1.angle == ggf2.angle) &&
(ggf1.blurX == ggf2.blurX) && (ggf1.blurY == ggf2.blurY) &&
ArrayUtil.equals(ggf1.colors, ggf2.colors) && (ggf1.distance == ggf2.distance) &&
(ggf1.knockout == ggf2.knockout) && (ggf1.quality == ggf2.quality) &&
ArrayUtil.equals(ggf1.ratios, ggf2.ratios) && (ggf1.strength == ggf2.strength) &&
(ggf1.type == ggf2.type);
default:
throw new ArgumentError("OMG! Unknown filter type: " + c1);
}
}
/**
* Create a filter that, if applied to a DisplayObject, will shift the hue of that object
* by the given value.
*/
public static function createHueShift (hue :int) :ColorMatrixFilter
{
return shiftHueBy(null, hue);
}
/**
* Shift the color matrix filter by the given amount. This is adapted from the code found at
* http://www.kirupa.com/forum/showthread.php?t=230706
*/
public static function shiftHueBy (original :ColorMatrixFilter,
hueShift :int) :ColorMatrixFilter
{
var cosMatrix :Array = [ 0.787, -0.715, -0.072,
-0.212, 0.285, -0.072,
-0.213, -0.715, 0.928 ];
var sinMatrix :Array = [-0.213, -0.715, 0.928,
0.143, 0.140, -0.283,
-0.787, 0.715, 0.072 ];
var multiplier :Array = [];
var cos :Number = Math.cos(hueShift * Math.PI / 180);
var sin :Number = Math.sin(hueShift * Math.PI / 180);
for (var ii :int = 0; ii < 9; ii++) {
multiplier.push([ 0.213, 0.715, 0.072 ][ii%3] + cosMatrix[ii] * cos +
sinMatrix[ii] * sin);
}
var originalMatrix :Array;
if (original == null || original.matrix == null) {
// thats the identity matrix for this filter
originalMatrix = [ 1, 0, 0, 0, 0,
0, 1, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0 ];
} else {
originalMatrix = original.matrix;
}
// this loop compresses a massive, wacky concatination function that was used in the code
// from the site listed above
var matrix :Array = [];
for (ii = 0; ii < 20; ii++) {
if ((ii % 5) > 2) {
matrix.push(originalMatrix[ii]);
} else {
var base :int = Math.floor(ii / 5) * 5;
matrix.push((originalMatrix[base] * multiplier[ii%5]) +
(originalMatrix[base+1] * multiplier[(ii%5)+3]) +
(originalMatrix[base+2] * multiplier[(ii%5)+6]));
}
}
return new ColorMatrixFilter(matrix);
}
protected static function checkArgs (disp :DisplayObject, filter :BitmapFilter) :void
{
if (disp == null || filter == null) {
throw new ArgumentError("args may not be null");
}
}
}
}
|
//
// $Id$
//
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/nenya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.flash {
import flash.display.DisplayObject;
import flash.filters.BevelFilter;
import flash.filters.BitmapFilter;
import flash.filters.BlurFilter;
import flash.filters.ColorMatrixFilter;
import flash.filters.ConvolutionFilter;
import flash.filters.DisplacementMapFilter;
import flash.filters.DropShadowFilter;
import flash.filters.GlowFilter;
import flash.filters.GradientBevelFilter;
import flash.filters.GradientGlowFilter;
import com.threerings.util.ArrayUtil;
import com.threerings.util.ClassUtil;
/**
* Useful utility methods that wouldn't be needed if the flash API were not so retarded.
*/
public class FilterUtil
{
/**
* Add the specified filter to the DisplayObject.
*/
public static function addFilter (disp :DisplayObject, filter :BitmapFilter) :void
{
checkArgs(disp, filter);
var filts :Array = disp.filters;
if (filts == null) {
filts = [];
}
filts.push(filter);
disp.filters = filts;
}
/**
* Remove the specified filter from the DisplayObject.
* Note that the filter set in the DisplayObject is a clone, so the values
* of the specified filter are used to find a match.
*/
public static function removeFilter (disp :DisplayObject, filter :BitmapFilter) :void
{
checkArgs(disp, filter);
var filts :Array = disp.filters;
if (filts != null) {
for (var ii :int = filts.length - 1; ii >= 0; ii--) {
var oldFilter :BitmapFilter = (filts[ii] as BitmapFilter);
if (equals(oldFilter, filter)) {
filts.splice(ii, 1);
if (filts.length == 0) {
filts = null;
}
disp.filters = filts;
return; // SUCCESS
}
}
}
}
/**
* Are the two filters equals?
*/
public static function equals (f1 :BitmapFilter, f2 :BitmapFilter) :Boolean
{
if (f1 === f2) { // catch same instance, or both null
return true;
} else if (f1 == null || f2 == null) { // otherwise nulls are no good
return false;
}
var c1 :Class = ClassUtil.getClass(f1);
if (c1 !== ClassUtil.getClass(f2)) {
return false;
}
// when we have two filters of the same class, figure it out by hand...
switch (c1) {
case BevelFilter:
var bf1 :BevelFilter = (f1 as BevelFilter);
var bf2 :BevelFilter = (f2 as BevelFilter);
return (bf1.angle == bf2.angle) && (bf1.blurX == bf2.blurX) &&
(bf1.blurY == bf2.blurY) && (bf1.distance == bf2.distance) &&
(bf1.highlightAlpha == bf2.highlightAlpha) &&
(bf1.highlightColor == bf2.highlightColor) && (bf1.knockout == bf2.knockout) &&
(bf1.quality == bf2.quality) && (bf1.shadowAlpha == bf2.shadowAlpha) &&
(bf1.shadowColor == bf2.shadowColor) && (bf1.strength == bf2.strength) &&
(bf1.type == bf2.type);
case BlurFilter:
var blur1 :BlurFilter = (f1 as BlurFilter);
var blur2 :BlurFilter = (f2 as BlurFilter);
return (blur1.blurX == blur2.blurX) && (blur1.blurY == blur2.blurY) &&
(blur1.quality == blur2.quality);
case ColorMatrixFilter:
var cmf1 :ColorMatrixFilter = (f1 as ColorMatrixFilter);
var cmf2 :ColorMatrixFilter = (f2 as ColorMatrixFilter);
return ArrayUtil.equals(cmf1.matrix, cmf2.matrix);
case ConvolutionFilter:
var cf1 :ConvolutionFilter = (f1 as ConvolutionFilter);
var cf2 :ConvolutionFilter = (f2 as ConvolutionFilter);
return (cf1.alpha == cf2.alpha) && (cf1.bias == cf2.bias) && (cf1.clamp == cf2.clamp) &&
(cf1.color == cf2.color) && (cf1.divisor == cf2.divisor) &&
ArrayUtil.equals(cf1.matrix, cf2.matrix) && (cf1.matrixX == cf2.matrixX) &&
(cf1.matrixY == cf2.matrixY) && (cf1.preserveAlpha == cf2.preserveAlpha);
case DisplacementMapFilter:
var dmf1 :DisplacementMapFilter = (f1 as DisplacementMapFilter);
var dmf2 :DisplacementMapFilter = (f2 as DisplacementMapFilter);
return (dmf1.alpha == dmf2.alpha) && (dmf1.color == dmf2.color) &&
(dmf1.componentX == dmf2.componentX) && (dmf1.componentY == dmf2.componentY) &&
(dmf1.mapBitmap == dmf2.mapBitmap) && dmf1.mapPoint.equals(dmf2.mapPoint) &&
(dmf1.mode == dmf2.mode) && (dmf1.scaleX == dmf2.scaleX) &&
(dmf1.scaleY == dmf2.scaleY);
case DropShadowFilter:
var dsf1 :DropShadowFilter = (f1 as DropShadowFilter);
var dsf2 :DropShadowFilter = (f2 as DropShadowFilter);
return (dsf1.alpha == dsf2.alpha) && (dsf1.angle = dsf2.angle) &&
(dsf1.blurX = dsf2.blurX) && (dsf1.blurY = dsf2.blurY) &&
(dsf1.color = dsf2.color) && (dsf1.distance = dsf2.distance) &&
(dsf1.hideObject = dsf2.hideObject) && (dsf1.inner = dsf2.inner) &&
(dsf1.knockout = dsf2.knockout) && (dsf1.quality = dsf2.quality) &&
(dsf1.strength = dsf2.strength);
case GlowFilter:
var gf1 :GlowFilter = (f1 as GlowFilter);
var gf2 :GlowFilter = (f2 as GlowFilter);
return (gf1.alpha == gf2.alpha) && (gf1.blurX == gf2.blurX) &&
(gf1.blurY == gf2.blurY) && (gf1.color == gf2.color) && (gf1.inner == gf2.inner) &&
(gf1.knockout == gf2.knockout) && (gf1.quality == gf2.quality) &&
(gf1.strength == gf2.strength);
case GradientBevelFilter:
var gbf1 :GradientBevelFilter = (f1 as GradientBevelFilter);
var gbf2 :GradientBevelFilter = (f2 as GradientBevelFilter);
return ArrayUtil.equals(gbf1.alphas, gbf2.alphas) && (gbf1.angle == gbf2.angle) &&
(gbf1.blurX == gbf2.blurX) && (gbf1.blurY == gbf2.blurY) &&
ArrayUtil.equals(gbf1.colors, gbf2.colors) && (gbf1.distance == gbf2.distance) &&
(gbf1.knockout == gbf2.knockout) && (gbf1.quality == gbf2.quality) &&
ArrayUtil.equals(gbf1.ratios, gbf2.ratios) && (gbf1.strength == gbf2.strength) &&
(gbf1.type == gbf2.type);
case GradientGlowFilter:
var ggf1 :GradientGlowFilter = (f1 as GradientGlowFilter);
var ggf2 :GradientGlowFilter = (f2 as GradientGlowFilter);
return ArrayUtil.equals(ggf1.alphas, ggf2.alphas) && (ggf1.angle == ggf2.angle) &&
(ggf1.blurX == ggf2.blurX) && (ggf1.blurY == ggf2.blurY) &&
ArrayUtil.equals(ggf1.colors, ggf2.colors) && (ggf1.distance == ggf2.distance) &&
(ggf1.knockout == ggf2.knockout) && (ggf1.quality == ggf2.quality) &&
ArrayUtil.equals(ggf1.ratios, ggf2.ratios) && (ggf1.strength == ggf2.strength) &&
(ggf1.type == ggf2.type);
default:
throw new ArgumentError("OMG! Unknown filter type: " + c1);
}
}
/**
* Create a filter that, if applied to a DisplayObject, will shift the hue of that object
* by the given value.
*
* @param hueShift a value, in degrees, between -180 and 180.
*/
public static function createHueShift (hue :int) :ColorMatrixFilter
{
return shiftHueBy(null, hue);
}
/**
* Shift the color matrix filter by the given amount. This is adapted from the code found at
* http://www.kirupa.com/forum/showthread.php?t=230706
*
* @param hueShift a value, in degrees, between -180 and 180.
*/
public static function shiftHueBy (original :ColorMatrixFilter,
hueShift :int) :ColorMatrixFilter
{
var cosMatrix :Array = [ 0.787, -0.715, -0.072,
-0.212, 0.285, -0.072,
-0.213, -0.715, 0.928 ];
var sinMatrix :Array = [-0.213, -0.715, 0.928,
0.143, 0.140, -0.283,
-0.787, 0.715, 0.072 ];
var multiplier :Array = [];
var cos :Number = Math.cos(hueShift * Math.PI / 180);
var sin :Number = Math.sin(hueShift * Math.PI / 180);
for (var ii :int = 0; ii < 9; ii++) {
multiplier.push([ 0.213, 0.715, 0.072 ][ii%3] + cosMatrix[ii] * cos +
sinMatrix[ii] * sin);
}
var originalMatrix :Array;
if (original == null || original.matrix == null) {
// thats the identity matrix for this filter
originalMatrix = [ 1, 0, 0, 0, 0,
0, 1, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0 ];
} else {
originalMatrix = original.matrix;
}
// this loop compresses a massive, wacky concatination function that was used in the code
// from the site listed above
var matrix :Array = [];
for (ii = 0; ii < 20; ii++) {
if ((ii % 5) > 2) {
matrix.push(originalMatrix[ii]);
} else {
var base :int = Math.floor(ii / 5) * 5;
matrix.push((originalMatrix[base] * multiplier[ii%5]) +
(originalMatrix[base+1] * multiplier[(ii%5)+3]) +
(originalMatrix[base+2] * multiplier[(ii%5)+6]));
}
}
return new ColorMatrixFilter(matrix);
}
protected static function checkArgs (disp :DisplayObject, filter :BitmapFilter) :void
{
if (disp == null || filter == null) {
throw new ArgumentError("args may not be null");
}
}
}
}
|
Document the hueShift parameter.
|
Document the hueShift parameter.
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@365 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
c9d1fa7277ed2339ec713efb77182f4d5223bd30
|
HLSPlugin/src/org/denivip/osmf/elements/m3u8Classes/M3U8PlaylistParser.as
|
HLSPlugin/src/org/denivip/osmf/elements/m3u8Classes/M3U8PlaylistParser.as
|
package org.denivip.osmf.elements.m3u8Classes
{
import flash.events.EventDispatcher;
import org.denivip.osmf.net.HLSDynamicStreamingResource;
import org.osmf.events.ParseEvent;
import org.osmf.logging.Log;
import org.osmf.logging.Logger;
import org.osmf.media.MediaResourceBase;
import org.osmf.media.MediaType;
import org.osmf.media.URLResource;
import org.osmf.metadata.Metadata;
import org.osmf.metadata.MetadataNamespaces;
import org.osmf.net.DynamicStreamingItem;
import org.osmf.net.DynamicStreamingResource;
import org.osmf.net.StreamType;
import org.osmf.net.StreamingItem;
import org.osmf.net.StreamingURLResource;
[Event(name="parseComplete", type="org.osmf.events.ParseEvent")]
[Event(name="parseError", type="org.osmf.events.ParseEvent")]
/**
* You will not belive, but this class parses *.m3u8 playlist
*/
public class M3U8PlaylistParser extends EventDispatcher
{
public function M3U8PlaylistParser(){
// nothing todo here...
}
public function parse(value:String, baseResource:URLResource):void{
if(!value || value == ''){
throw new ArgumentError("Parsed value is missing =(");
}
var lines:Array = value.split(/\r?\n/);
if(lines[0] != '#EXTM3U'){
;
CONFIG::LOGGING
{
logger.warn('Incorrect header! {0}', lines[0]);
}
}
var result:MediaResourceBase;
var isLive:Boolean = true;
var streamItems:Vector.<DynamicStreamingItem>;
var tempStreamingRes:StreamingURLResource = null;
var tempDynamicRes:DynamicStreamingResource = null;
var alternateStreams:Vector.<StreamingItem> = null;
var initialStreamName:String = '';
for(var i:int = 1; i < lines.length; i++){
var line:String = String(lines[i]).replace(/^([\s|\t|\n]+)?(.*)([\s|\t|\n]+)?$/gm, "$2");
if(line.indexOf("#EXTINF:") == 0){
result = baseResource;
tempStreamingRes = result as StreamingURLResource;
if(tempStreamingRes && tempStreamingRes.streamType == StreamType.LIVE_OR_RECORDED){
for(var j:int = i+1; j < lines.length; j++){
if(String(lines[j]).indexOf('#EXT-X-ENDLIST') == 0){
isLive = false;
break;
}
}
if(isLive)
tempStreamingRes.streamType = StreamType.LIVE;
}
break;
}
if(line.indexOf("#EXT-X-STREAM-INF:") == 0){
if(!result){
result = new HLSDynamicStreamingResource(baseResource.url);
tempDynamicRes = result as DynamicStreamingResource;
tempStreamingRes = baseResource as StreamingURLResource;
if(tempStreamingRes){
tempDynamicRes.streamType = tempStreamingRes.streamType;
tempDynamicRes.clipStartTime = tempStreamingRes.clipStartTime;
tempDynamicRes.clipEndTime = tempStreamingRes.clipEndTime;
}
streamItems = new Vector.<DynamicStreamingItem>();
}
var bw:Number;
if(line.search(/BANDWIDTH=(\d+)/) > 0)
bw = parseFloat(line.match(/BANDWIDTH=(\d+)/)[1])/1000;
var width:int = -1;
var height:int = -1;
if(line.search(/RESOLUTION=(\d+)x(\d+)/) > 0){
width = parseInt(line.match(/RESOLUTION=(\d+)x(\d+)/)[1]);
height = parseInt(line.match(/RESOLUTION=(\d+)x(\d+)/)[2]);
}
var name:String = lines[i+1];
streamItems.push(new DynamicStreamingItem(name, bw, width, height));
// store stream name of first stream encountered
if(initialStreamName == ''){
initialStreamName = name;
}
DynamicStreamingResource(result).streamItems = streamItems;
}
if(line.indexOf("#EXT-X-MEDIA:") == 0){
if(line.search(/TYPE=(.*?)\W/) > 0 && line.match(/TYPE=(.*?)\W/)[1] == 'AUDIO'){
var stUrl:String;
var lang:String;
var stName:String;
if(line.search(/URI="(.*?)"/) > 0){
stUrl = line.match(/URI="(.*?)"/)[1];
if(stUrl.search(/(file|https?):\/\//) != 0){
stUrl = baseResource.url.substr(0, baseResource.url.lastIndexOf('/')+1) + stUrl;
}
}
if(line.search(/LANGUAGE="(.*?)"/) > 0){
lang = line.match(/LANGUAGE="(.*?)"/)[1]
}
if(line.search(/NAME="(.*?)"/) > 0){
stName = line.match(/NAME="(.*?)"/)[1];
}
if(!alternateStreams)
alternateStreams = new Vector.<StreamingItem>();
alternateStreams.push(
new StreamingItem(MediaType.AUDIO, stUrl, 0, {label:stName, language:lang})
);
}
}
}
if(tempDynamicRes && tempDynamicRes.streamItems){
if(tempDynamicRes.streamItems.length == 1){
tempStreamingRes = baseResource as StreamingURLResource;
if(tempStreamingRes){
// var url:String = (lines[i].search(/(ftp|file|https?):\/\//) == 0) ? lines[i] : rateItem.url.substr(0, rateItem.url.lastIndexOf('/')+1) + lines[i];
var url:String = (tempDynamicRes.streamItems[0].streamName.search(/(ftp|file|https?):\/\//) == 0)
? tempDynamicRes.streamItems[0].streamName
: tempDynamicRes.host.substr(0, tempDynamicRes.host.lastIndexOf('/')+1) + tempDynamicRes.streamItems[0].streamName;
result = new StreamingURLResource(
url,
tempStreamingRes.streamType,
tempStreamingRes.clipStartTime,
tempStreamingRes.clipEndTime,
tempStreamingRes.connectionArguments,
tempStreamingRes.urlIncludesFMSApplicationInstance,
tempStreamingRes.drmContentData
);
}
}else{
if(baseResource.getMetadataValue(MetadataNamespaces.RESOURCE_INITIAL_INDEX) != null){
var initialIndex:int = baseResource.getMetadataValue(MetadataNamespaces.RESOURCE_INITIAL_INDEX) as int;
tempDynamicRes.initialIndex = initialIndex < 0 ? 0 : (initialIndex >= tempDynamicRes.streamItems.length) ? (tempDynamicRes.streamItems.length-1) : initialIndex;
}else{
// set initialIndex to index of first stream name encountered
tempDynamicRes.initialIndex = tempDynamicRes.indexFromName(initialStreamName);
}
}
}
baseResource.addMetadataValue("HLS_METADATA", new Metadata()); // fix for multistreaming resources
result.addMetadataValue("HLS_METADATA", new Metadata());
var httpMetadata:Metadata = new Metadata();
result.addMetadataValue(MetadataNamespaces.HTTP_STREAMING_METADATA, httpMetadata);
if(alternateStreams && result is StreamingURLResource){
(result as StreamingURLResource).alternativeAudioStreamItems = alternateStreams;
}
if(result is StreamingURLResource && StreamingURLResource(result).streamType == StreamType.DVR){
var dvrMetadata:Metadata = new Metadata();
result.addMetadataValue(MetadataNamespaces.DVR_METADATA, dvrMetadata);
}
dispatchEvent(new ParseEvent(ParseEvent.PARSE_COMPLETE, false, false, result));
}
/*
private function addDVRInfo():void{
CONFIG::LOGGING
{
logger.info('DVR!!! \\o/'); // we happy!
}
// black magic...
var dvrInfo:DVRInfo = new DVRInfo();
dvrInfo.id = dvrInfo.url = '';
dvrInfo.isRecording = true; // if live then in process
//dvrInfo.startTime = 0.0;
// attach info into playlist
}
*/
CONFIG::LOGGING
{
private var logger:Logger = Log.getLogger("org.denivip.osmf.elements.m3u8Classes.M3U8PlaylistParser");
}
}
}
|
package org.denivip.osmf.elements.m3u8Classes
{
import flash.events.EventDispatcher;
import org.denivip.osmf.net.HLSDynamicStreamingResource;
import org.denivip.osmf.utility.Url;
import org.osmf.events.ParseEvent;
import org.osmf.logging.Log;
import org.osmf.logging.Logger;
import org.osmf.media.MediaResourceBase;
import org.osmf.media.MediaType;
import org.osmf.media.URLResource;
import org.osmf.metadata.Metadata;
import org.osmf.metadata.MetadataNamespaces;
import org.osmf.net.DynamicStreamingItem;
import org.osmf.net.DynamicStreamingResource;
import org.osmf.net.StreamType;
import org.osmf.net.StreamingItem;
import org.osmf.net.StreamingURLResource;
[Event(name="parseComplete", type="org.osmf.events.ParseEvent")]
[Event(name="parseError", type="org.osmf.events.ParseEvent")]
/**
* You will not belive, but this class parses *.m3u8 playlist
*/
public class M3U8PlaylistParser extends EventDispatcher
{
public function M3U8PlaylistParser(){
// nothing todo here...
}
public function parse(value:String, baseResource:URLResource):void{
if(!value || value == ''){
throw new ArgumentError("Parsed value is missing =(");
}
var lines:Array = value.split(/\r?\n/);
if(lines[0] != '#EXTM3U'){
;
CONFIG::LOGGING
{
logger.warn('Incorrect header! {0}', lines[0]);
}
}
var result:MediaResourceBase;
var isLive:Boolean = true;
var streamItems:Vector.<DynamicStreamingItem>;
var tempStreamingRes:StreamingURLResource = null;
var tempDynamicRes:DynamicStreamingResource = null;
var alternateStreams:Vector.<StreamingItem> = null;
var initialStreamName:String = '';
for(var i:int = 1; i < lines.length; i++){
var line:String = String(lines[i]).replace(/^([\s|\t|\n]+)?(.*)([\s|\t|\n]+)?$/gm, "$2");
if(line.indexOf("#EXTINF:") == 0){
result = baseResource;
tempStreamingRes = result as StreamingURLResource;
if(tempStreamingRes && tempStreamingRes.streamType == StreamType.LIVE_OR_RECORDED){
for(var j:int = i+1; j < lines.length; j++){
if(String(lines[j]).indexOf('#EXT-X-ENDLIST') == 0){
isLive = false;
break;
}
}
if(isLive)
tempStreamingRes.streamType = StreamType.LIVE;
}
break;
}
if(line.indexOf("#EXT-X-STREAM-INF:") == 0){
if(!result){
result = new HLSDynamicStreamingResource(baseResource.url);
tempDynamicRes = result as DynamicStreamingResource;
tempStreamingRes = baseResource as StreamingURLResource;
if(tempStreamingRes){
tempDynamicRes.streamType = tempStreamingRes.streamType;
tempDynamicRes.clipStartTime = tempStreamingRes.clipStartTime;
tempDynamicRes.clipEndTime = tempStreamingRes.clipEndTime;
}
streamItems = new Vector.<DynamicStreamingItem>();
}
var bw:Number;
if(line.search(/BANDWIDTH=(\d+)/) > 0)
bw = parseFloat(line.match(/BANDWIDTH=(\d+)/)[1])/1000;
var width:int = -1;
var height:int = -1;
if(line.search(/RESOLUTION=(\d+)x(\d+)/) > 0){
width = parseInt(line.match(/RESOLUTION=(\d+)x(\d+)/)[1]);
height = parseInt(line.match(/RESOLUTION=(\d+)x(\d+)/)[2]);
}
var name:String = lines[i+1];
streamItems.push(new DynamicStreamingItem(name, bw, width, height));
// store stream name of first stream encountered
if(initialStreamName == ''){
initialStreamName = name;
}
DynamicStreamingResource(result).streamItems = streamItems;
}
if(line.indexOf("#EXT-X-MEDIA:") == 0){
if(line.search(/TYPE=(.*?)\W/) > 0 && line.match(/TYPE=(.*?)\W/)[1] == 'AUDIO'){
var stUrl:String;
var lang:String;
var stName:String;
if(line.search(/URI="(.*?)"/) > 0){
stUrl = line.match(/URI="(.*?)"/)[1];
if(stUrl.search(/(file|https?):\/\//) != 0){
stUrl = baseResource.url.substr(0, baseResource.url.lastIndexOf('/')+1) + stUrl;
}
}
if(line.search(/LANGUAGE="(.*?)"/) > 0){
lang = line.match(/LANGUAGE="(.*?)"/)[1]
}
if(line.search(/NAME="(.*?)"/) > 0){
stName = line.match(/NAME="(.*?)"/)[1];
}
if(!alternateStreams)
alternateStreams = new Vector.<StreamingItem>();
alternateStreams.push(
new StreamingItem(MediaType.AUDIO, stUrl, 0, {label:stName, language:lang})
);
}
}
}
if(tempDynamicRes && tempDynamicRes.streamItems){
if(tempDynamicRes.streamItems.length == 1){
tempStreamingRes = baseResource as StreamingURLResource;
if(tempStreamingRes){
// var url:String = (lines[i].search(/(ftp|file|https?):\/\//) == 0) ? lines[i] : rateItem.url.substr(0, rateItem.url.lastIndexOf('/')+1) + lines[i];
/*
var url:String = (tempDynamicRes.streamItems[0].streamName.search(/(ftp|file|https?):\/\//) == 0)
? tempDynamicRes.streamItems[0].streamName
: tempDynamicRes.host.substr(0, tempDynamicRes.host.lastIndexOf('/')+1) + tempDynamicRes.streamItems[0].streamName;
*/
var url:String = Url.absolute(tempDynamicRes.host, tempDynamicRes.streamItems[0].streamName);
result = new StreamingURLResource(
url,
tempStreamingRes.streamType,
tempStreamingRes.clipStartTime,
tempStreamingRes.clipEndTime,
tempStreamingRes.connectionArguments,
tempStreamingRes.urlIncludesFMSApplicationInstance,
tempStreamingRes.drmContentData
);
}
}else{
if(baseResource.getMetadataValue(MetadataNamespaces.RESOURCE_INITIAL_INDEX) != null){
var initialIndex:int = baseResource.getMetadataValue(MetadataNamespaces.RESOURCE_INITIAL_INDEX) as int;
tempDynamicRes.initialIndex = initialIndex < 0 ? 0 : (initialIndex >= tempDynamicRes.streamItems.length) ? (tempDynamicRes.streamItems.length-1) : initialIndex;
}else{
// set initialIndex to index of first stream name encountered
tempDynamicRes.initialIndex = tempDynamicRes.indexFromName(initialStreamName);
}
}
}
baseResource.addMetadataValue("HLS_METADATA", new Metadata()); // fix for multistreaming resources
result.addMetadataValue("HLS_METADATA", new Metadata());
var httpMetadata:Metadata = new Metadata();
result.addMetadataValue(MetadataNamespaces.HTTP_STREAMING_METADATA, httpMetadata);
if(alternateStreams && result is StreamingURLResource){
(result as StreamingURLResource).alternativeAudioStreamItems = alternateStreams;
}
if(result is StreamingURLResource && StreamingURLResource(result).streamType == StreamType.DVR){
var dvrMetadata:Metadata = new Metadata();
result.addMetadataValue(MetadataNamespaces.DVR_METADATA, dvrMetadata);
}
dispatchEvent(new ParseEvent(ParseEvent.PARSE_COMPLETE, false, false, result));
}
/*
private function addDVRInfo():void{
CONFIG::LOGGING
{
logger.info('DVR!!! \\o/'); // we happy!
}
// black magic...
var dvrInfo:DVRInfo = new DVRInfo();
dvrInfo.id = dvrInfo.url = '';
dvrInfo.isRecording = true; // if live then in process
//dvrInfo.startTime = 0.0;
// attach info into playlist
}
*/
CONFIG::LOGGING
{
private var logger:Logger = Log.getLogger("org.denivip.osmf.elements.m3u8Classes.M3U8PlaylistParser");
}
}
}
|
Update M3U8PlaylistParser.as
|
Update M3U8PlaylistParser.as
Relative to absolute path - moved to org.denivip.osmf.utility.Url
|
ActionScript
|
isc
|
denivip/osmf-hls-plugin,denivip/osmf-hls-plugin,mruse/osmf-hls-plugin,mruse/osmf-hls-plugin
|
56cad035cad2b133985dec55ed55c5bc03706d58
|
src/aerys/minko/type/loader/SceneLoader.as
|
src/aerys/minko/type/loader/SceneLoader.as
|
package aerys.minko.type.loader
{
import flash.events.Event;
import flash.events.ProgressEvent;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.setTimeout;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.type.Signal;
import aerys.minko.type.loader.parser.IParser;
import aerys.minko.type.loader.parser.ParserOptions;
public class SceneLoader implements ILoader
{
private static const REGISTERED_PARSERS : Vector.<Class> = new <Class>[];
private static const STATE_IDLE : uint = 0;
private static const STATE_LOADING : uint = 1;
private static const STATE_PARSING : uint = 2;
private static const STATE_COMPLETE : uint = 3;
private var _currentState : int;
private var _progress : Signal;
private var _complete : Signal;
private var _error : Signal;
private var _data : ISceneNode;
private var _parser : IParser;
private var _numDependencies : uint;
private var _dependencies : Vector.<ILoader>;
private var _parserOptions : ParserOptions;
private var _currentProgress : Number;
private var _currentProgressChanged : Boolean;
private var _isComplete : Boolean;
public function get error() : Signal
{
return _error;
}
public function get progress() : Signal
{
return _progress;
}
public function get complete() : Signal
{
return _complete;
}
public function get isComplete() : Boolean
{
return _isComplete;
}
public function get data() : ISceneNode
{
return _data;
}
public static function registerParser(parserClass : Class) : void
{
if (REGISTERED_PARSERS.indexOf(parserClass) != -1)
return;
if (!(new parserClass(new ParserOptions()) is IParser))
throw new Error('Parsers must implement the IParser interface.');
REGISTERED_PARSERS.push(parserClass);
}
public function SceneLoader(parserOptions : ParserOptions = null)
{
_currentState = STATE_IDLE;
_error = new Signal('SceneLoader.error');
_progress = new Signal('SceneLoader.progress');
_complete = new Signal('SceneLoader.complete');
_data = null;
_isComplete = false;
_parserOptions = parserOptions || new ParserOptions();
}
public function load(urlRequest : URLRequest) : void
{
if (_currentState != STATE_IDLE)
throw new Error('This controller is already loading an asset.');
_currentState = STATE_LOADING;
var urlLoader : URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
urlLoader.addEventListener(ProgressEvent.PROGRESS, loadProgressHandler);
urlLoader.addEventListener(Event.COMPLETE, loadCompleteHandler);
urlLoader.load(urlRequest);
}
private function loadProgressHandler(e : ProgressEvent) : void
{
_progress.execute(this, 0.5 * e.bytesLoaded / e.bytesTotal);
}
private function loadCompleteHandler(e : Event) : void
{
_currentState = STATE_IDLE;
loadBytes(URLLoader(e.currentTarget).data);
}
public function loadClass(classObject : Class) : void
{
loadBytes(new classObject());
}
public function loadBytes(byteArray : ByteArray) : void
{
var startPosition : uint = byteArray.position;
if (_currentState != STATE_IDLE)
throw new Error('This loader is already loading an asset.');
_currentState = STATE_PARSING;
_progress.execute(this, 0.5);
if (_parserOptions != null && _parserOptions.parser != null)
{
_parser = new (_parserOptions.parser)(_parserOptions);
if (!_parser.isParsable(byteArray))
throw new Error('Invalid datatype for this parser.');
}
else
{
// search a parser by testing registered parsers.
var numRegisteredParser : uint = REGISTERED_PARSERS.length;
for (var parserId : uint = 0; parserId < numRegisteredParser; ++parserId)
{
_parser = new REGISTERED_PARSERS[parserId](_parserOptions);
byteArray.position = startPosition;
if (_parser.isParsable(byteArray))
break;
}
if (parserId == numRegisteredParser)
throw new Error('No parser could be found for this datatype.');
}
byteArray.position = startPosition;
_dependencies = _parser.getDependencies(byteArray);
_numDependencies = 0;
if (_dependencies != null)
for each (var dependency : ILoader in _dependencies)
if (!dependency.isComplete)
{
dependency.error.add(decrementDependencyCounter);
dependency.complete.add(decrementDependencyCounter);
_numDependencies++;
}
if (_numDependencies == 0)
parse();
}
private function decrementDependencyCounter(...args) : void
{
--_numDependencies;
if (_numDependencies == 0)
parse();
}
private function parse() : void
{
_parser.error.add(parseErrorHandler);
_parser.progress.add(parseProgressHandler);
_parser.complete.add(parseCompleteHandler);
_parser.parse();
}
private function parseErrorHandler(parser : IParser) : void
{
_isComplete = true;
_parser = null;
}
private function parseProgressHandler(parser : IParser, progress : Number) : void
{
_progress.execute(this, 0.5 * (1 + progress));
}
private function parseCompleteHandler(parser : IParser, loadedData : ISceneNode) : void
{
_isComplete = true;
_data = loadedData;
_parser = null;
// call later to make sure the loading is always seen as asynchronous
setTimeout(callLaterComplete, 0, loadedData);
}
private function callLaterComplete(loadedData : ISceneNode) : void
{
_complete.execute(this, loadedData);
}
}
}
|
package aerys.minko.type.loader
{
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.setTimeout;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.type.Signal;
import aerys.minko.type.loader.parser.IParser;
import aerys.minko.type.loader.parser.ParserOptions;
public class SceneLoader implements ILoader
{
private static const REGISTERED_PARSERS : Vector.<Class> = new <Class>[];
private static const STATE_IDLE : uint = 0;
private static const STATE_LOADING : uint = 1;
private static const STATE_PARSING : uint = 2;
private static const STATE_COMPLETE : uint = 3;
private var _currentState : int;
private var _progress : Signal;
private var _complete : Signal;
private var _error : Signal;
private var _data : ISceneNode;
private var _parser : IParser;
private var _numDependencies : uint;
private var _dependencies : Vector.<ILoader>;
private var _parserOptions : ParserOptions;
private var _currentProgress : Number;
private var _currentProgressChanged : Boolean;
private var _isComplete : Boolean;
public function get error() : Signal
{
return _error;
}
public function get progress() : Signal
{
return _progress;
}
public function get complete() : Signal
{
return _complete;
}
public function get isComplete() : Boolean
{
return _isComplete;
}
public function get data() : ISceneNode
{
return _data;
}
public static function registerParser(parserClass : Class) : void
{
if (REGISTERED_PARSERS.indexOf(parserClass) != -1)
return;
if (!(new parserClass(new ParserOptions()) is IParser))
throw new Error('Parsers must implement the IParser interface.');
REGISTERED_PARSERS.push(parserClass);
}
public function SceneLoader(parserOptions : ParserOptions = null)
{
_currentState = STATE_IDLE;
_error = new Signal('SceneLoader.error');
_progress = new Signal('SceneLoader.progress');
_complete = new Signal('SceneLoader.complete');
_data = null;
_isComplete = false;
_parserOptions = parserOptions || new ParserOptions();
}
public function load(urlRequest : URLRequest) : void
{
if (_currentState != STATE_IDLE)
throw new Error('This controller is already loading an asset.');
_currentState = STATE_LOADING;
var urlLoader : URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
urlLoader.addEventListener(ProgressEvent.PROGRESS, loadProgressHandler);
urlLoader.addEventListener(Event.COMPLETE, loadCompleteHandler);
urlLoader.addEventListener(IOErrorEvent.IO_ERROR, loadErrorHandler);
urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, loadSecurityErrorHandler);
try
{
urlLoader.load(urlRequest);
}
catch (e : Error)
{
_error.execute(this, e.errorID, e.message);
}
}
private function loadErrorHandler(e : IOErrorEvent) : void
{
_error.execute(this, e.errorID, e.text);
}
private function loadSecurityErrorHandler(e : SecurityErrorEvent) : void
{
_error.execute(this, e.errorID, e.text);
}
private function loadProgressHandler(e : ProgressEvent) : void
{
_progress.execute(this, 0.5 * e.bytesLoaded / e.bytesTotal);
}
private function loadCompleteHandler(e : Event) : void
{
_currentState = STATE_IDLE;
loadBytes(URLLoader(e.currentTarget).data);
}
public function loadClass(classObject : Class) : void
{
loadBytes(new classObject());
}
public function loadBytes(byteArray : ByteArray) : void
{
var startPosition : uint = byteArray.position;
if (_currentState != STATE_IDLE)
throw new Error('This loader is already loading an asset.');
_currentState = STATE_PARSING;
_progress.execute(this, 0.5);
if (_parserOptions != null && _parserOptions.parser != null)
{
_parser = new (_parserOptions.parser)(_parserOptions);
if (!_parser.isParsable(byteArray))
throw new Error('Invalid datatype for this parser.');
}
else
{
// search a parser by testing registered parsers.
var numRegisteredParser : uint = REGISTERED_PARSERS.length;
for (var parserId : uint = 0; parserId < numRegisteredParser; ++parserId)
{
_parser = new REGISTERED_PARSERS[parserId](_parserOptions);
byteArray.position = startPosition;
if (_parser.isParsable(byteArray))
break;
}
if (parserId == numRegisteredParser)
throw new Error('No parser could be found for this datatype.');
}
byteArray.position = startPosition;
_dependencies = _parser.getDependencies(byteArray);
_numDependencies = 0;
if (_dependencies != null)
for each (var dependency : ILoader in _dependencies)
if (!dependency.isComplete)
{
dependency.error.add(decrementDependencyCounter);
dependency.complete.add(decrementDependencyCounter);
_numDependencies++;
}
if (_numDependencies == 0)
parse();
}
private function decrementDependencyCounter(...args) : void
{
--_numDependencies;
if (_numDependencies == 0)
parse();
}
private function parse() : void
{
_parser.error.add(parseErrorHandler);
_parser.progress.add(parseProgressHandler);
_parser.complete.add(parseCompleteHandler);
_parser.parse();
}
private function parseErrorHandler(parser : IParser) : void
{
_isComplete = true;
_parser = null;
}
private function parseProgressHandler(parser : IParser, progress : Number) : void
{
_progress.execute(this, 0.5 * (1 + progress));
}
private function parseCompleteHandler(parser : IParser, loadedData : ISceneNode) : void
{
_isComplete = true;
_data = loadedData;
_parser = null;
// call later to make sure the loading is always seen as asynchronous
setTimeout(callLaterComplete, 0, loadedData);
}
private function callLaterComplete(loadedData : ISceneNode) : void
{
_complete.execute(this, loadedData);
}
}
}
|
Fix error handling in SceneLoader.
|
Fix error handling in SceneLoader.
|
ActionScript
|
mit
|
aerys/minko-as3
|
90083e5f239dfc87bc03d37cdcc276076a8166eb
|
astyle_config.as
|
astyle_config.as
|
# detached brackets
--style=allman
# 4 spaces, no tabs
--indent=spaces=4
# for C++ files only
--indent-classes
# Indent 'switch' blocks so that the 'case X:' statements are indented in the switch block.
# The entire case block is indented.
--indent-switches
# Add extra indentation to namespace blocks. This option has no effect on Java files.
--indent-namespaces
# Converts tabs into spaces in the non-indentation part of the line.
--convert-tabs
# requires --convert-tabs to work properly
--indent-preprocessor
--indent-col1-comments
--min-conditional-indent=2
--max-instatement-indent=40
# Pad empty lines around header blocks (e.g. 'if', 'for', 'while'...).
--break-blocks
# Insert space padding around operators.
--pad-oper
# Insert space padding after paren headers only (e.g. 'if', 'for', 'while'...).
--pad-header
# Add brackets to unbracketed one line conditional statements (e.g. 'if', 'for', 'while'...).
--add-brackets
--align-pointer=name
# Do not retain a backup of the original file. The original file is purged after it is formatted.
--suffix=none
# For each directory in the command line, process all subdirectories recursively.
--recursive
# Preserve the original file's date and time modified.
--preserve-date
# Formatted files display mode. Display only the files that have been formatted.
# Do not display files that are unchanged.
--formatted
--lineend=linux
|
# detached brackets
--style=allman
# 4 spaces, no tabs
--indent=spaces=4
# for C++ files only
--indent-classes
# Indent 'switch' blocks so that the 'case X:' statements are indented in the switch block.
# The entire case block is indented.
--indent-switches
# Add extra indentation to namespace blocks. This option has no effect on Java files.
--indent-namespaces
# Converts tabs into spaces in the non-indentation part of the line.
--convert-tabs
# requires --convert-tabs to work properly
--indent-preprocessor
--indent-col1-comments
--min-conditional-indent=2
--max-instatement-indent=40
# Insert space padding around operators.
--pad-oper
# Insert space padding after paren headers only (e.g. 'if', 'for', 'while'...).
--pad-header
# Add brackets to unbracketed one line conditional statements (e.g. 'if', 'for', 'while'...).
--add-brackets
--align-pointer=name
# Do not retain a backup of the original file. The original file is purged after it is formatted.
--suffix=none
# For each directory in the command line, process all subdirectories recursively.
--recursive
# Preserve the original file's date and time modified.
--preserve-date
# Formatted files display mode. Display only the files that have been formatted.
# Do not display files that are unchanged.
--formatted
--lineend=linux
|
Remove --break-blocks option, it doesn't match the existing code style
|
Remove --break-blocks option, it doesn't match the existing code style
Strip trailing newlines.
|
ActionScript
|
apache-2.0
|
metalefty/xrdp,PKRoma/xrdp,ubuntu-xrdp/xrdp,proski/xrdp,proski/xrdp,jsorg71/xrdp,moobyfr/xrdp,neutrinolabs/xrdp,moobyfr/xrdp,jsorg71/xrdp,jsorg71/xrdp,cocoon/xrdp,neutrinolabs/xrdp,cocoon/xrdp,ubuntu-xrdp/xrdp,proski/xrdp,PKRoma/xrdp,cocoon/xrdp,ubuntu-xrdp/xrdp,metalefty/xrdp,neutrinolabs/xrdp,PKRoma/xrdp,metalefty/xrdp,moobyfr/xrdp
|
4dab1b36159935f4e0037a2f93ad4f26f56be7ac
|
src/aerys/minko/scene/visitor/rendering/RenderingVisitor.as
|
src/aerys/minko/scene/visitor/rendering/RenderingVisitor.as
|
package aerys.minko.scene.visitor.rendering
{
import aerys.minko.ns.minko;
import aerys.minko.render.effect.IEffect;
import aerys.minko.render.effect.IEffectPass;
import aerys.minko.render.effect.IEffectTarget;
import aerys.minko.render.renderer.IRenderer;
import aerys.minko.render.ressource.IRessource;
import aerys.minko.render.renderer.state.RenderState;
import aerys.minko.scene.node.*;
import aerys.minko.scene.node.group.*;
import aerys.minko.scene.node.mesh.*;
import aerys.minko.scene.node.texture.*;
import aerys.minko.scene.visitor.*;
import aerys.minko.scene.action.IAction;
import aerys.minko.scene.action.IActionTarget;
import aerys.minko.scene.visitor.data.*;
import aerys.minko.type.stream.IndexStream;
import aerys.minko.type.stream.VertexStreamList;
import flash.display.ActionScriptVersion;
import flash.utils.Dictionary;
public class RenderingVisitor implements ISceneVisitor
{
use namespace minko;
protected var _renderer : IRenderer;
protected var _numNodes : uint;
protected var _localData : LocalData;
protected var _worldData : Dictionary;
protected var _renderingData : RenderingData;
public function get localData() : LocalData { return _localData; }
public function get worldData() : Dictionary { return _worldData; }
public function get renderingData() : RenderingData { return _renderingData; }
public function get numNodes() : uint
{
return _numNodes;
}
public function RenderingVisitor(renderer : IRenderer)
{
_renderer = renderer;
_localData = new LocalData();
_worldData = new Dictionary();
_renderingData = new RenderingData();
}
public function reset(defaultEffect : IEffect, color : int = 0) : void
{
_renderer.clear(((color >> 16) & 0xff) / 255.,
((color >> 8) & 0xff) / 255.,
(color & 0xff) / 255.);
_worldData = null;
_numNodes = 0;
_renderingData.clear(defaultEffect);
}
public function updateWorldData(worldData : Dictionary) : void
{
_worldData = worldData;
for each (var worldObject : IWorldData in worldData)
worldObject.setLocalDataProvider(_renderingData.styleStack, _localData);
// update our transformManager if there is a camera, or
// set it to null to render to screenspace otherwise
var cameraData : CameraData = worldData[CameraData] as CameraData;
if (cameraData)
{
_localData.view = cameraData.view;
_localData.projection = cameraData.projection;
}
}
public function visit(scene : IScene) : void
{
var actions : Vector.<IAction> = scene.actions;
var numActions : int = actions.length;
var i : int = 0;
for (i = 0; i < numActions; ++i)
if (!actions[i].prefix(scene, this, _renderer))
break ;
for (i = 0; i < numActions; ++i)
if (!actions[i].infix(scene, this, _renderer))
break ;
for (i = 0; i < numActions; ++i)
if (!actions[i].postfix(scene, this, _renderer))
break ;
// update statistical data
++_numNodes;
}
}
}
|
package aerys.minko.scene.visitor.rendering
{
import aerys.minko.render.effect.IEffect;
import aerys.minko.render.renderer.IRenderer;
import aerys.minko.scene.action.IAction;
import aerys.minko.scene.node.IScene;
import aerys.minko.scene.visitor.ISceneVisitor;
import aerys.minko.scene.visitor.data.CameraData;
import aerys.minko.scene.visitor.data.IWorldData;
import aerys.minko.scene.visitor.data.LocalData;
import aerys.minko.scene.visitor.data.RenderingData;
import flash.utils.Dictionary;
public class RenderingVisitor implements ISceneVisitor
{
protected var _renderer : IRenderer;
protected var _numNodes : uint;
protected var _localData : LocalData;
protected var _worldData : Dictionary;
protected var _renderingData : RenderingData;
public function get localData() : LocalData { return _localData; }
public function get worldData() : Dictionary { return _worldData; }
public function get renderingData() : RenderingData { return _renderingData; }
public function get numNodes() : uint
{
return _numNodes;
}
public function RenderingVisitor(renderer : IRenderer)
{
_renderer = renderer;
_localData = new LocalData();
_worldData = new Dictionary();
_renderingData = new RenderingData();
}
public function reset(defaultEffect : IEffect, color : int = 0) : void
{
_renderer.clear(((color >> 16) & 0xff) / 255.,
((color >> 8) & 0xff) / 255.,
(color & 0xff) / 255.);
_worldData = null;
_numNodes = 0;
_renderingData.clear(defaultEffect);
}
public function updateWorldData(worldData : Dictionary) : void
{
_worldData = worldData;
for each (var worldObject : IWorldData in worldData)
worldObject.setLocalDataProvider(_renderingData.styleStack, _localData);
// update our transformManager if there is a camera, or
// set it to null to render to screenspace otherwise
var cameraData : CameraData = worldData[CameraData] as CameraData;
if (cameraData)
{
_localData.view = cameraData.view;
_localData.projection = cameraData.projection;
}
}
public function visit(scene : IScene) : void
{
var actions : Vector.<IAction> = scene.actions;
var numActions : int = actions.length;
var i : int = 0;
for (i = 0; i < numActions; ++i)
if (!actions[i].prefix(scene, this, _renderer))
break ;
for (i = 0; i < numActions; ++i)
if (!actions[i].infix(scene, this, _renderer))
break ;
for (i = 0; i < numActions; ++i)
if (!actions[i].postfix(scene, this, _renderer))
break ;
// update statistical data
++_numNodes;
}
}
}
|
Reorganize imports
|
Reorganize imports
|
ActionScript
|
mit
|
aerys/minko-as3
|
2200d1cff3e5b71326b65a99bede138bd724f403
|
collect-client/src/main/flex/org/openforis/collect/presenter/DetailPresenter.as
|
collect-client/src/main/flex/org/openforis/collect/presenter/DetailPresenter.as
|
package org.openforis.collect.presenter {
/**
*
* @author S. Ricci
* */
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.ui.Keyboard;
import mx.binding.utils.ChangeWatcher;
import mx.collections.IList;
import mx.managers.PopUpManager;
import mx.rpc.AsyncResponder;
import mx.rpc.events.ResultEvent;
import org.openforis.collect.Application;
import org.openforis.collect.client.ClientFactory;
import org.openforis.collect.client.DataClient;
import org.openforis.collect.event.ApplicationEvent;
import org.openforis.collect.event.UIEvent;
import org.openforis.collect.i18n.Message;
import org.openforis.collect.metamodel.proxy.EntityDefinitionProxy;
import org.openforis.collect.metamodel.proxy.ModelVersionProxy;
import org.openforis.collect.model.CollectRecord$Step;
import org.openforis.collect.model.proxy.EntityProxy;
import org.openforis.collect.model.proxy.RecordProxy;
import org.openforis.collect.model.proxy.UserProxy;
import org.openforis.collect.remoting.service.UpdateResponse;
import org.openforis.collect.ui.UIBuilder;
import org.openforis.collect.ui.component.ErrorListPopUp;
import org.openforis.collect.ui.component.detail.FormContainer;
import org.openforis.collect.ui.view.DetailView;
import org.openforis.collect.util.AlertUtil;
import org.openforis.collect.util.PopUpUtil;
import org.openforis.collect.util.StringUtil;
public class DetailPresenter extends AbstractPresenter {
private var _dataClient:DataClient;
private var _view:DetailView;
private var _errorsListPopUp:ErrorListPopUp;
private var _rootEntityKeyTextChangeWatcher:ChangeWatcher;
public function DetailPresenter(view:DetailView) {
this._view = view;
this._dataClient = ClientFactory.dataClient;
super();
}
override internal function initEventListeners():void {
_view.backToListButton.addEventListener(MouseEvent.CLICK, backToListButtonClickHandler);
_view.saveButton.addEventListener(MouseEvent.CLICK, saveButtonClickHandler);
_view.autoSaveCheckBox.addEventListener(MouseEvent.CLICK, autoSaveCheckBoxClickHandler);
_view.submitButton.addEventListener(MouseEvent.CLICK, submitButtonClickHandler);
_view.rejectButton.addEventListener(MouseEvent.CLICK, rejectButtonClickHandler);
eventDispatcher.addEventListener(ApplicationEvent.UPDATE_RESPONSE_RECEIVED, updateResponseReceivedHandler);
eventDispatcher.addEventListener(ApplicationEvent.RECORD_SAVED, recordSavedHandler);
eventDispatcher.addEventListener(UIEvent.ACTIVE_RECORD_CHANGED, activeRecordChangedListener);
_view.stage.addEventListener(KeyboardEvent.KEY_DOWN, stageKeyDownHandler);
}
/**
* Active record changed
* */
internal function activeRecordChangedListener(event:UIEvent):void {
var preview:Boolean = Application.preview;
var activeRecord:RecordProxy = Application.activeRecord;
var version:ModelVersionProxy = activeRecord.version;
var rootEntity:EntityProxy = activeRecord.rootEntity;
rootEntity.updateKeyText();
updateRecordKeyLabel();
if ( _rootEntityKeyTextChangeWatcher == null ) {
_rootEntityKeyTextChangeWatcher = ChangeWatcher.watch(rootEntity, "keyText", updateRecordKeyLabel);
} else {
_rootEntityKeyTextChangeWatcher.reset(rootEntity);
}
_view.formVersionContainer.visible = version != null;
if ( version != null ) {
_view.formVersionText.text = version.getLabelText();
}
var step:CollectRecord$Step = activeRecord.step;
_view.currentPhaseText.text = getStepLabel(step);
var user:UserProxy = Application.user;
var canSubmit:Boolean = !preview && user.canSubmit(activeRecord);
var canReject:Boolean = !preview && user.canReject(activeRecord);
var canSave:Boolean = !preview && Application.activeRecordEditable;
_view.header.visible = _view.header.includeInLayout = !preview;
_view.submitButton.visible = _view.submitButton.includeInLayout = canSubmit;
_view.rejectButton.visible = _view.rejectButton.includeInLayout = canReject;
if ( canReject ) {
_view.rejectButton.label = step == CollectRecord$Step.ANALYSIS ? Message.get("edit.unlock"): Message.get("edit.reject");
}
_view.saveButton.visible = canSave;
_view.updateStatusLabel.text = null;
_view.autoSaveCheckBox.visible = canSave;
_view.updateStatusLabel.visible = canSave;
var rootEntityDefn:EntityDefinitionProxy = Application.activeRootEntity;
var form:FormContainer = null;
if (_view.formsContainer.contatinsForm(version,rootEntityDefn)){
_view.currentState = DetailView.EDIT_STATE;
form = _view.formsContainer.getForm(version, rootEntityDefn);
} else {
//build form
_view.currentState = DetailView.LOADING_STATE;
form = UIBuilder.buildForm(rootEntityDefn, version);
_view.formsContainer.addForm(form, version, rootEntityDefn);
_view.currentState = DetailView.EDIT_STATE;
}
form = _view.formsContainer.setActiveForm(version, rootEntityDefn);
form.record = activeRecord;
}
protected function recordSavedHandler(event:ApplicationEvent):void {
var rootEntityLabel:String = Application.activeRootEntity.getInstanceOrHeadingLabelText();
_view.messageDisplay.show(Message.get("edit.recordSaved", [rootEntityLabel]));
}
protected function autoSaveCheckBoxClickHandler(event:MouseEvent):void {
Application.autoSave = _view.autoSaveCheckBox.selected;
}
protected function updateRecordKeyLabel(event:Event = null):void {
var result:String;
var rootEntityLabel:String = Application.activeRootEntity.getInstanceOrHeadingLabelText();
var keyText:String = Application.activeRecord.rootEntity.keyText;
if(StringUtil.isBlank(keyText) && isNaN(Application.activeRecord.id)) {
result = Message.get('edit.newRecordKeyLabel', [rootEntityLabel]);
} else {
result = StringUtil.concat(" ", rootEntityLabel, keyText);
}
_view.recordKeyLabel.text = result;
}
/**
* Back to list
* */
protected function backToListButtonClickHandler(event:Event):void {
if(Application.activeRecord.updated) {
AlertUtil.showConfirm("edit.confirmBackToList", null, null, performClearActiveRecord);
} else {
performClearActiveRecord();
}
}
protected function performClearActiveRecord():void {
//reset immediately activeRecord to avoid concurrency problems
//when keepAlive message is sent and record is being unlocked
ClientFactory.sessionClient.cancelLastKeepAliveOperation();
Application.activeRecord = null;
_dataClient.clearActiveRecord(new AsyncResponder(clearActiveRecordHandler, faultHandler));
}
protected function saveButtonClickHandler(event:MouseEvent):void {
performSaveActiveRecord();
}
protected function performSaveActiveRecord():void {
_dataClient.saveActiveRecord(saveActiveRecordResultHandler, faultHandler, Application.autoSave);
}
protected function submitButtonClickHandler(event:MouseEvent):void {
var r:RecordProxy = Application.activeRecord;
r.showErrors();
var applicationEvent:ApplicationEvent = new ApplicationEvent(ApplicationEvent.ASK_FOR_SUBMIT);
eventDispatcher.dispatchEvent(applicationEvent);
var totalErrors:int = r.errors + r.missingErrors + r.skipped;
if ( totalErrors > 0 ) {
openErrorsListPopUp();
} else {
var messageResource:String;
if(r.step == CollectRecord$Step.ENTRY) {
messageResource = "edit.confirmSubmitDataCleansing";
AlertUtil.showConfirm(messageResource, null, null, performSubmitToClenasing);
} else if(r.step == CollectRecord$Step.CLEANSING) {
messageResource = "edit.confirmSubmitDataAnalysis";
AlertUtil.showConfirm(messageResource, null, null, performSubmitToAnalysis);
}
}
}
protected function openErrorsListPopUp():void {
if ( _errorsListPopUp != null ) {
PopUpManager.removePopUp(_errorsListPopUp);
_errorsListPopUp = null;
}
_errorsListPopUp = ErrorListPopUp(PopUpUtil.createPopUp(ErrorListPopUp, false));
}
protected function rejectButtonClickHandler(event:MouseEvent):void {
var messageResource:String;
var r:RecordProxy = Application.activeRecord;
if(r.step == CollectRecord$Step.CLEANSING) {
messageResource = "edit.confirmRejectDataCleansing";
AlertUtil.showConfirm(messageResource, null, null, performRejectToEntry);
} else if(r.step == CollectRecord$Step.ANALYSIS) {
messageResource = "edit.confirmRejectDataAnalysis";
AlertUtil.showConfirm(messageResource, null, null, performRejectToCleansing);
}
}
protected function performSubmitToClenasing():void {
var responder:AsyncResponder = new AsyncResponder(promoteRecordResultHandler, faultHandler);
_dataClient.promoteToCleansing(responder);
}
protected function performSubmitToAnalysis():void {
var responder:AsyncResponder = new AsyncResponder(promoteRecordResultHandler, faultHandler);
_dataClient.promoteToAnalysis(responder);
}
protected function performRejectToCleansing():void {
var responder:AsyncResponder = new AsyncResponder(rejectRecordResultHandler, faultHandler);
_dataClient.demoteToCleansing(responder);
}
protected function performRejectToEntry():void {
var responder:AsyncResponder = new AsyncResponder(rejectRecordResultHandler, faultHandler);
_dataClient.demoteToEntry(responder);
}
internal function clearActiveRecordHandler(event:ResultEvent, token:Object = null):void {
var uiEvent:UIEvent = new UIEvent(UIEvent.BACK_TO_LIST);
eventDispatcher.dispatchEvent(uiEvent);
}
internal function saveActiveRecordResultHandler(event:ResultEvent, token:Object = null):void {
Application.activeRecord.showErrors();
Application.activeRecord.updated = false;
var applicationEvent:ApplicationEvent = new ApplicationEvent(ApplicationEvent.RECORD_SAVED);
eventDispatcher.dispatchEvent(applicationEvent);
}
internal function promoteRecordResultHandler(event:ResultEvent, token:Object = null):void {
var rootEntity:EntityDefinitionProxy = Application.activeRootEntity;
var rootEntityLabel:String = rootEntity.getInstanceOrHeadingLabelText();
var r:RecordProxy = Application.activeRecord;
var keyLabel:String = r.rootEntity.keyText;
var actualStep:CollectRecord$Step = getNextStep(r.step);
var stepLabel:String = getStepLabel(actualStep).toLowerCase();
AlertUtil.showMessage("edit.recordSubmitted", [rootEntityLabel, keyLabel, stepLabel], "edit.recordSubmittedTitle", [rootEntityLabel]);
Application.activeRecord = null;
var uiEvent:UIEvent = new UIEvent(UIEvent.BACK_TO_LIST);
eventDispatcher.dispatchEvent(uiEvent);
}
internal function rejectRecordResultHandler(event:ResultEvent, token:Object = null):void {
var rootEntity:EntityDefinitionProxy = Application.activeRootEntity;
var rootEntityLabel:String = rootEntity.getInstanceOrHeadingLabelText();
var r:RecordProxy = Application.activeRecord;
var keyLabel:String = r.rootEntity.keyText;
var actualStep:CollectRecord$Step = getPreviousStep(r.step);
var stepLabel:String = getStepLabel(actualStep).toLowerCase();
AlertUtil.showMessage("edit.recordRejected", [rootEntityLabel, keyLabel, stepLabel], "edit.recordRejectedTitle", [rootEntityLabel]);
Application.activeRecord = null;
var uiEvent:UIEvent = new UIEvent(UIEvent.BACK_TO_LIST);
eventDispatcher.dispatchEvent(uiEvent);
}
protected function updateResponseReceivedHandler(event:ApplicationEvent):void {
var updateMessageKey:String;
if ( Application.activeRecord.updated ) {
updateMessageKey = "edit.changes_not_saved";
} else {
updateMessageKey = "edit.all_changes_saved";
}
_view.updateStatusLabel.text = Message.get(updateMessageKey);
}
protected function stageKeyDownHandler(event:KeyboardEvent):void {
//save record pressing CTRL + s
if ( !Application.preview && Application.activeRecordEditable &&
event.ctrlKey && event.keyCode == Keyboard.S ) {
performSaveActiveRecord();
}
}
public static function getNextStep(step:CollectRecord$Step):CollectRecord$Step {
switch ( step ) {
case CollectRecord$Step.ENTRY:
return CollectRecord$Step.CLEANSING;
case CollectRecord$Step.CLEANSING:
return CollectRecord$Step.ANALYSIS;
default:
return null;
}
}
public static function getPreviousStep(step:CollectRecord$Step):CollectRecord$Step {
switch ( step ) {
case CollectRecord$Step.CLEANSING:
return CollectRecord$Step.ENTRY;
case CollectRecord$Step.ANALYSIS:
return CollectRecord$Step.CLEANSING;
default:
return null;
}
}
public static function getStepLabel(step:CollectRecord$Step):String {
switch ( step ) {
case CollectRecord$Step.ENTRY:
return Message.get("edit.dataEntry");
case CollectRecord$Step.CLEANSING:
return Message.get("edit.dataCleansing");
case CollectRecord$Step.ANALYSIS:
return Message.get("edit.dataAnalysis");
default:
return null;
}
}
}
}
|
package org.openforis.collect.presenter {
/**
*
* @author S. Ricci
* */
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.ui.Keyboard;
import mx.binding.utils.ChangeWatcher;
import mx.collections.IList;
import mx.managers.PopUpManager;
import mx.rpc.AsyncResponder;
import mx.rpc.events.ResultEvent;
import org.openforis.collect.Application;
import org.openforis.collect.client.ClientFactory;
import org.openforis.collect.client.DataClient;
import org.openforis.collect.event.ApplicationEvent;
import org.openforis.collect.event.UIEvent;
import org.openforis.collect.i18n.Message;
import org.openforis.collect.metamodel.proxy.EntityDefinitionProxy;
import org.openforis.collect.metamodel.proxy.ModelVersionProxy;
import org.openforis.collect.model.CollectRecord$Step;
import org.openforis.collect.model.proxy.EntityProxy;
import org.openforis.collect.model.proxy.RecordProxy;
import org.openforis.collect.model.proxy.UserProxy;
import org.openforis.collect.remoting.service.UpdateResponse;
import org.openforis.collect.ui.UIBuilder;
import org.openforis.collect.ui.component.ErrorListPopUp;
import org.openforis.collect.ui.component.detail.FormContainer;
import org.openforis.collect.ui.view.DetailView;
import org.openforis.collect.util.AlertUtil;
import org.openforis.collect.util.PopUpUtil;
import org.openforis.collect.util.StringUtil;
public class DetailPresenter extends AbstractPresenter {
private var _dataClient:DataClient;
private var _view:DetailView;
private var _errorsListPopUp:ErrorListPopUp;
private var _rootEntityKeyTextChangeWatcher:ChangeWatcher;
public function DetailPresenter(view:DetailView) {
this._view = view;
this._dataClient = ClientFactory.dataClient;
super();
}
override internal function initEventListeners():void {
_view.backToListButton.addEventListener(MouseEvent.CLICK, backToListButtonClickHandler);
_view.saveButton.addEventListener(MouseEvent.CLICK, saveButtonClickHandler);
_view.autoSaveCheckBox.addEventListener(MouseEvent.CLICK, autoSaveCheckBoxClickHandler);
_view.submitButton.addEventListener(MouseEvent.CLICK, submitButtonClickHandler);
_view.rejectButton.addEventListener(MouseEvent.CLICK, rejectButtonClickHandler);
eventDispatcher.addEventListener(ApplicationEvent.UPDATE_RESPONSE_RECEIVED, updateResponseReceivedHandler);
eventDispatcher.addEventListener(ApplicationEvent.RECORD_SAVED, recordSavedHandler);
eventDispatcher.addEventListener(UIEvent.ACTIVE_RECORD_CHANGED, activeRecordChangedListener);
_view.stage.addEventListener(KeyboardEvent.KEY_DOWN, stageKeyDownHandler);
}
/**
* Active record changed
* */
internal function activeRecordChangedListener(event:UIEvent):void {
var preview:Boolean = Application.preview;
var activeRecord:RecordProxy = Application.activeRecord;
var version:ModelVersionProxy = activeRecord.version;
var rootEntity:EntityProxy = activeRecord.rootEntity;
rootEntity.updateKeyText();
updateRecordKeyLabel();
if ( _rootEntityKeyTextChangeWatcher == null ) {
_rootEntityKeyTextChangeWatcher = ChangeWatcher.watch(rootEntity, "keyText", updateRecordKeyLabel);
} else {
_rootEntityKeyTextChangeWatcher.reset(rootEntity);
}
_view.formVersionContainer.visible = version != null;
if ( version != null ) {
_view.formVersionText.text = version.getLabelText();
}
var step:CollectRecord$Step = activeRecord.step;
_view.currentPhaseText.text = getStepLabel(step);
var user:UserProxy = Application.user;
var canSubmit:Boolean = !preview && user.canSubmit(activeRecord);
var canReject:Boolean = !preview && user.canReject(activeRecord);
var canSave:Boolean = !preview && Application.activeRecordEditable;
_view.header.visible = _view.header.includeInLayout = !preview;
_view.submitButton.visible = _view.submitButton.includeInLayout = canSubmit;
_view.rejectButton.visible = _view.rejectButton.includeInLayout = canReject;
if ( canReject ) {
_view.rejectButton.label = step == CollectRecord$Step.ANALYSIS ? Message.get("edit.unlock"): Message.get("edit.reject");
}
_view.saveButton.visible = canSave;
_view.updateStatusLabel.text = null;
_view.autoSaveCheckBox.visible = canSave;
_view.updateStatusLabel.visible = canSave;
var rootEntityDefn:EntityDefinitionProxy = Application.activeRootEntity;
var form:FormContainer = null;
if (_view.formsContainer.contatinsForm(version,rootEntityDefn)){
_view.currentState = DetailView.EDIT_STATE;
form = _view.formsContainer.getForm(version, rootEntityDefn);
} else {
//build form
_view.currentState = DetailView.LOADING_STATE;
form = UIBuilder.buildForm(rootEntityDefn, version);
_view.formsContainer.addForm(form, version, rootEntityDefn);
_view.currentState = DetailView.EDIT_STATE;
}
form = _view.formsContainer.setActiveForm(version, rootEntityDefn);
form.record = activeRecord;
}
protected function recordSavedHandler(event:ApplicationEvent):void {
var rootEntityLabel:String = Application.activeRootEntity.getInstanceOrHeadingLabelText();
_view.messageDisplay.show(Message.get("edit.recordSaved", [rootEntityLabel]));
}
protected function autoSaveCheckBoxClickHandler(event:MouseEvent):void {
Application.autoSave = _view.autoSaveCheckBox.selected;
}
protected function updateRecordKeyLabel(event:Event = null):void {
var result:String;
var rootEntityLabel:String = Application.activeRootEntity.getInstanceOrHeadingLabelText();
var keyText:String = Application.activeRecord.rootEntity.keyText;
if(StringUtil.isBlank(keyText) && isNaN(Application.activeRecord.id)) {
result = Message.get('edit.newRecordKeyLabel', [rootEntityLabel]);
} else {
result = StringUtil.concat(" ", rootEntityLabel, keyText);
}
_view.recordKeyLabel.text = result;
}
/**
* Back to list
* */
protected function backToListButtonClickHandler(event:Event):void {
if(Application.activeRecord.updated) {
AlertUtil.showConfirm("edit.confirmBackToList", null, null, performClearActiveRecord);
} else {
performClearActiveRecord();
}
}
protected function performClearActiveRecord():void {
//reset immediately activeRecord to avoid concurrency problems
//when keepAlive message is sent and record is being unlocked
ClientFactory.sessionClient.cancelLastKeepAliveOperation();
Application.activeRecord = null;
_dataClient.clearActiveRecord(new AsyncResponder(clearActiveRecordHandler, faultHandler));
}
protected function saveButtonClickHandler(event:MouseEvent):void {
performSaveActiveRecord();
}
protected function performSaveActiveRecord():void {
_dataClient.saveActiveRecord(saveActiveRecordResultHandler, faultHandler, Application.autoSave);
}
protected function submitButtonClickHandler(event:MouseEvent):void {
var r:RecordProxy = Application.activeRecord;
r.showErrors();
var applicationEvent:ApplicationEvent = new ApplicationEvent(ApplicationEvent.ASK_FOR_SUBMIT);
eventDispatcher.dispatchEvent(applicationEvent);
var totalErrors:int = r.errors + r.missingErrors + r.skipped;
if ( totalErrors > 0 ) {
openErrorsListPopUp();
} else {
var messageResource:String;
if(r.step == CollectRecord$Step.ENTRY) {
messageResource = "edit.confirmSubmitDataCleansing";
AlertUtil.showConfirm(messageResource, null, null, performSubmitToClenasing);
} else if(r.step == CollectRecord$Step.CLEANSING) {
messageResource = "edit.confirmSubmitDataAnalysis";
AlertUtil.showConfirm(messageResource, null, null, performSubmitToAnalysis);
}
}
}
protected function openErrorsListPopUp():void {
if ( _errorsListPopUp != null ) {
PopUpManager.removePopUp(_errorsListPopUp);
_errorsListPopUp = null;
}
_errorsListPopUp = ErrorListPopUp(PopUpUtil.createPopUp(ErrorListPopUp, false));
}
protected function rejectButtonClickHandler(event:MouseEvent):void {
var messageResource:String;
var r:RecordProxy = Application.activeRecord;
if(r.step == CollectRecord$Step.CLEANSING) {
messageResource = "edit.confirmRejectDataCleansing";
AlertUtil.showConfirm(messageResource, null, null, performRejectToEntry);
} else if(r.step == CollectRecord$Step.ANALYSIS) {
messageResource = "edit.confirmRejectDataAnalysis";
AlertUtil.showConfirm(messageResource, null, null, performRejectToCleansing);
}
}
protected function performSubmitToClenasing():void {
var responder:AsyncResponder = new AsyncResponder(promoteRecordResultHandler, faultHandler);
_dataClient.promoteToCleansing(responder);
}
protected function performSubmitToAnalysis():void {
var responder:AsyncResponder = new AsyncResponder(promoteRecordResultHandler, faultHandler);
_dataClient.promoteToAnalysis(responder);
}
protected function performRejectToCleansing():void {
var responder:AsyncResponder = new AsyncResponder(rejectRecordResultHandler, faultHandler);
_dataClient.demoteToCleansing(responder);
}
protected function performRejectToEntry():void {
var responder:AsyncResponder = new AsyncResponder(rejectRecordResultHandler, faultHandler);
_dataClient.demoteToEntry(responder);
}
internal function clearActiveRecordHandler(event:ResultEvent, token:Object = null):void {
var uiEvent:UIEvent = new UIEvent(UIEvent.BACK_TO_LIST);
eventDispatcher.dispatchEvent(uiEvent);
}
internal function saveActiveRecordResultHandler(event:ResultEvent, token:Object = null):void {
Application.activeRecord.showErrors();
Application.activeRecord.updated = false;
updateStatusLabel();
var applicationEvent:ApplicationEvent = new ApplicationEvent(ApplicationEvent.RECORD_SAVED);
eventDispatcher.dispatchEvent(applicationEvent);
}
internal function promoteRecordResultHandler(event:ResultEvent, token:Object = null):void {
var rootEntity:EntityDefinitionProxy = Application.activeRootEntity;
var rootEntityLabel:String = rootEntity.getInstanceOrHeadingLabelText();
var r:RecordProxy = Application.activeRecord;
var keyLabel:String = r.rootEntity.keyText;
var actualStep:CollectRecord$Step = getNextStep(r.step);
var stepLabel:String = getStepLabel(actualStep).toLowerCase();
AlertUtil.showMessage("edit.recordSubmitted", [rootEntityLabel, keyLabel, stepLabel], "edit.recordSubmittedTitle", [rootEntityLabel]);
Application.activeRecord = null;
var uiEvent:UIEvent = new UIEvent(UIEvent.BACK_TO_LIST);
eventDispatcher.dispatchEvent(uiEvent);
}
internal function rejectRecordResultHandler(event:ResultEvent, token:Object = null):void {
var rootEntity:EntityDefinitionProxy = Application.activeRootEntity;
var rootEntityLabel:String = rootEntity.getInstanceOrHeadingLabelText();
var r:RecordProxy = Application.activeRecord;
var keyLabel:String = r.rootEntity.keyText;
var actualStep:CollectRecord$Step = getPreviousStep(r.step);
var stepLabel:String = getStepLabel(actualStep).toLowerCase();
AlertUtil.showMessage("edit.recordRejected", [rootEntityLabel, keyLabel, stepLabel], "edit.recordRejectedTitle", [rootEntityLabel]);
Application.activeRecord = null;
var uiEvent:UIEvent = new UIEvent(UIEvent.BACK_TO_LIST);
eventDispatcher.dispatchEvent(uiEvent);
}
protected function updateResponseReceivedHandler(event:ApplicationEvent):void {
updateStatusLabel();
}
protected function updateStatusLabel():void {
var updateMessageKey:String;
if ( Application.activeRecord.updated ) {
updateMessageKey = "edit.changes_not_saved";
} else {
updateMessageKey = "edit.all_changes_saved";
}
_view.updateStatusLabel.text = Message.get(updateMessageKey);
}
protected function stageKeyDownHandler(event:KeyboardEvent):void {
//save record pressing CTRL + s
if ( !Application.preview && Application.activeRecordEditable &&
event.ctrlKey && event.keyCode == Keyboard.S ) {
performSaveActiveRecord();
}
}
public static function getNextStep(step:CollectRecord$Step):CollectRecord$Step {
switch ( step ) {
case CollectRecord$Step.ENTRY:
return CollectRecord$Step.CLEANSING;
case CollectRecord$Step.CLEANSING:
return CollectRecord$Step.ANALYSIS;
default:
return null;
}
}
public static function getPreviousStep(step:CollectRecord$Step):CollectRecord$Step {
switch ( step ) {
case CollectRecord$Step.CLEANSING:
return CollectRecord$Step.ENTRY;
case CollectRecord$Step.ANALYSIS:
return CollectRecord$Step.CLEANSING;
default:
return null;
}
}
public static function getStepLabel(step:CollectRecord$Step):String {
switch ( step ) {
case CollectRecord$Step.ENTRY:
return Message.get("edit.dataEntry");
case CollectRecord$Step.CLEANSING:
return Message.get("edit.dataCleansing");
case CollectRecord$Step.ANALYSIS:
return Message.get("edit.dataAnalysis");
default:
return null;
}
}
}
}
|
Update record status label when record is saved
|
Update record status label when record is saved
|
ActionScript
|
mit
|
openforis/collect,openforis/collect,openforis/collect,openforis/collect
|
cbf0e4b1b32bae72e91e0a09074c2f17443e73c4
|
software/sasFlex/src/gov/nih/nci/cbiit/casas/components/FormulaPanel.as
|
software/sasFlex/src/gov/nih/nci/cbiit/casas/components/FormulaPanel.as
|
package gov.nih.nci.cbiit.casas.components
{
import flash.display.MovieClip;
import learnmath.windows.apps.EditorApp;
import mx.controls.Alert;
public class FormulaPanel extends EditorApp
{
public function FormulaPanel(arg0:MovieClip, arg1:int, arg2:int, arg3:int, arg4:int, arg5:Function)
{
super(arg0, arg1, arg2, arg3, arg4, arg5);
name= "<a href=\'http://ncicb.nci.nih.gov/\'>NCI Center for Bioinformatics & Information Technology - Scientific Algorithm Service</a>";
return;
}
override public function openAction()
{
// var _loc_1:* = String(ExternalInterface.call("getMathMLFromJavascript"));
// if (_loc_1 != null)
// {
// }
// if (_loc_1.length != 0)
// {
// }
// if (_loc_1 == "null")
// {
// return;
// }
// this.editor.newFormula();
// this.editor.insert(_loc_1, this.lastStyle);
Alert.show("open is cliked...","Scientific Algorithm Service:openAction()");
super.openAction();
return;
}// end function
override public function saveAction()
{
// var _loc_1:* = this.convToMathML(this.editor.getMathMLString());
// ExternalInterface.call("saveMathMLToJavascript", _loc_1);
// this.isSaved = true;
Alert.show("save is cliked...","Scientific Algorithm Service:saveAction()");
super.saveAction();
return;
}// end function
}
}
|
package gov.nih.nci.cbiit.casas.components
{
import flash.display.MovieClip;
import flash.net.FileReference;
import learnmath.windows.apps.EditorApp;
import mx.controls.Alert;
public class FormulaPanel extends EditorApp
{
public function FormulaPanel(arg0:MovieClip, arg1:int, arg2:int, arg3:int, arg4:int, arg5:Function)
{
super(arg0, arg1, arg2, arg3, arg4, arg5);
name= "<a href=\'http://ncicb.nci.nih.gov/\'>NCI Center for Bioinformatics & Information Technology - Scientific Algorithm Service</a>";
return;
}
override public function openAction():*
{
// var _loc_1:* = String(ExternalInterface.call("getMathMLFromJavascript"));
// if (_loc_1 != null)
// {
// }
// if (_loc_1.length != 0)
// {
// }
// if (_loc_1 == "null")
// {
// return;
// }
// this.editor.newFormula();
// this.editor.insert(_loc_1, this.lastStyle);
var myFileReference:FileReference = new FileReference();
myFileReference.browse();
super.openAction();
return;
}// end function
override public function saveAction():*
{
// var _loc_1:* = this.convToMathML(this.editor.getMathMLString());
// ExternalInterface.call("saveMathMLToJavascript", _loc_1);
// this.isSaved = true;
Alert.show("save is cliked...","Scientific Algorithm Service:saveAction()");
super.saveAction();
return;
}// end function
}
}
|
set return type for functions
|
set return type for functions
SVN-Revision: 3134
|
ActionScript
|
bsd-3-clause
|
NCIP/caadapter,NCIP/caadapter,NCIP/caadapter
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.