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
|
---|---|---|---|---|---|---|---|---|---|
999d788916e8857d4335f6fecc9c242828f8c06a
|
actionscript/src/com/freshplanet/nativeExtensions/PushNotification.as
|
actionscript/src/com/freshplanet/nativeExtensions/PushNotification.as
|
package com.freshplanet.nativeExtensions
{
import flash.display.BitmapData;
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.system.Capabilities;
import mx.graphics.shaderClasses.ExclusionShader;
public class PushNotification extends EventDispatcher
{
public static const RECURRENCE_NONE:int = 0;
public static const RECURRENCE_DAILY:int = 1;
public static const RECURRENCE_WEEK:int = 2;
public static const RECURRENCE_MONTH:int = 3;
public static const RECURRENCE_YEAR:int = 4;
private static var extCtx:ExtensionContext = null;
private static var _instance:PushNotification;
public function PushNotification()
{
if (!_instance)
{
if (this.isPushNotificationSupported)
{
extCtx = ExtensionContext.createExtensionContext("com.freshplanet.AirPushNotification", null);
if (extCtx != null)
{
extCtx.addEventListener(StatusEvent.STATUS, onStatus);
} else
{
trace('extCtx is null.');
}
}
_instance = this;
}
else
{
throw Error( 'This is a singleton, use getInstance, do not call the constructor directly');
}
}
public function get isPushNotificationSupported():Boolean
{
var result:Boolean = (Capabilities.manufacturer.search('iOS') > -1 || Capabilities.manufacturer.search('Android') > -1);
return result;
}
public static function getInstance() : PushNotification
{
return _instance ? _instance : new PushNotification();
}
/**
* Needs Project id for Android Notifications.
* The project id is the one the developer used to register to gcm.
* @param projectId: project id to use
*/
public function registerForPushNotification(projectId:String = null) : void
{
if (this.isPushNotificationSupported)
{
extCtx.call("registerPush", projectId);
}
}
public function setBadgeNumberValue(value:int):void
{
if (this.isPushNotificationSupported)
{
extCtx.call("setBadgeNb", value);
}
}
/**
* Sends a local notification to the device.
* @param message the local notification text displayed
* @param timestamp when the local notification should appear (in sec)
* @param title (Android Only) Title of the local notification
* @param recurrenceType
*
*/
public function sendLocalNotification(message:String, timestamp:int, title:String, recurrenceType:int = RECURRENCE_NONE):void
{
trace("[Push Notification]","sendLocalNotification");
if (this.isPushNotificationSupported)
{
extCtx.call("sendLocalNotification", message, timestamp, title, recurrenceType);
}
}
public function setIsAppInForeground(value:Boolean):void
{
if (this.isPushNotificationSupported)
{
extCtx.call("setIsAppInForeground", value);
}
}
public function addListenerForStarterNotifications(listener:Function):void
{
if (this.isPushNotificationSupported)
{
this.addEventListener(PushNotificationEvent.APP_STARTING_FROM_NOTIFICATION_EVENT, listener);
extCtx.call("fetchStarterNotification");
}
}
// onStatus()
// Event handler for the event that the native implementation dispatches.
//
private function onStatus(e:StatusEvent):void
{
if (this.isPushNotificationSupported)
{
var event : PushNotificationEvent;
var data:String = e.level;
switch (e.code)
{
case "TOKEN_SUCCESS":
event = new PushNotificationEvent( PushNotificationEvent.PERMISSION_GIVEN_WITH_TOKEN_EVENT );
event.token = e.level;
break;
case "TOKEN_FAIL":
event = new PushNotificationEvent( PushNotificationEvent.PERMISSION_REFUSED_EVENT );
event.errorCode = "NativeCodeError";
event.errorMessage = e.level;
break;
case "COMING_FROM_NOTIFICATION":
event = new PushNotificationEvent( PushNotificationEvent.COMING_FROM_NOTIFICATION_EVENT );
if (data != null)
{
try
{
event.parameters = JSON.parse(data);
} catch (error:Error)
{
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "APP_STARTING_FROM_NOTIFICATION":
event = new PushNotificationEvent( PushNotificationEvent.APP_STARTING_FROM_NOTIFICATION_EVENT );
if (data != null)
{
try
{
event.parameters = JSON.parse(data);
} catch (error:Error)
{
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "APP_BROUGHT_TO_FOREGROUND_FROM_NOTIFICATION":
event = new PushNotificationEvent( PushNotificationEvent.APP_BROUGHT_TO_FOREGROUND_FROM_NOTIFICATION_EVENT );
if (data != null)
{
try
{
event.parameters = JSON.parse(data);
} catch (error:Error)
{
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "NOTIFICATION_RECEIVED_WHEN_IN_FOREGROUND":
event = new PushNotificationEvent( PushNotificationEvent.NOTIFICATION_RECEIVED_WHEN_IN_FOREGROUND_EVENT );
if (data != null)
{
try
{
event.parameters = JSON.parse(data);
} catch (error:Error)
{
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "LOGGING":
trace(e, e.level);
break;
}
if (event != null)
{
this.dispatchEvent( event );
}
}
}
}
}
|
package com.freshplanet.nativeExtensions
{
import flash.display.BitmapData;
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.system.Capabilities;
public class PushNotification extends EventDispatcher
{
public static const RECURRENCE_NONE:int = 0;
public static const RECURRENCE_DAILY:int = 1;
public static const RECURRENCE_WEEK:int = 2;
public static const RECURRENCE_MONTH:int = 3;
public static const RECURRENCE_YEAR:int = 4;
private static var extCtx:ExtensionContext = null;
private static var _instance:PushNotification;
public function PushNotification()
{
if (!_instance)
{
if (this.isPushNotificationSupported)
{
extCtx = ExtensionContext.createExtensionContext("com.freshplanet.AirPushNotification", null);
if (extCtx != null)
{
extCtx.addEventListener(StatusEvent.STATUS, onStatus);
} else
{
trace('extCtx is null.');
}
}
_instance = this;
}
else
{
throw Error( 'This is a singleton, use getInstance, do not call the constructor directly');
}
}
public function get isPushNotificationSupported():Boolean
{
var result:Boolean = (Capabilities.manufacturer.search('iOS') > -1 || Capabilities.manufacturer.search('Android') > -1);
return result;
}
public static function getInstance() : PushNotification
{
return _instance ? _instance : new PushNotification();
}
/**
* Needs Project id for Android Notifications.
* The project id is the one the developer used to register to gcm.
* @param projectId: project id to use
*/
public function registerForPushNotification(projectId:String = null) : void
{
if (this.isPushNotificationSupported)
{
extCtx.call("registerPush", projectId);
}
}
public function setBadgeNumberValue(value:int):void
{
if (this.isPushNotificationSupported)
{
extCtx.call("setBadgeNb", value);
}
}
/**
* Sends a local notification to the device.
* @param message the local notification text displayed
* @param timestamp when the local notification should appear (in sec)
* @param title (Android Only) Title of the local notification
* @param recurrenceType
*
*/
public function sendLocalNotification(message:String, timestamp:int, title:String, recurrenceType:int = RECURRENCE_NONE):void
{
trace("[Push Notification]","sendLocalNotification");
if (this.isPushNotificationSupported)
{
extCtx.call("sendLocalNotification", message, timestamp, title, recurrenceType);
}
}
public function setIsAppInForeground(value:Boolean):void
{
if (this.isPushNotificationSupported)
{
extCtx.call("setIsAppInForeground", value);
}
}
public function addListenerForStarterNotifications(listener:Function):void
{
if (this.isPushNotificationSupported)
{
this.addEventListener(PushNotificationEvent.APP_STARTING_FROM_NOTIFICATION_EVENT, listener);
extCtx.call("fetchStarterNotification");
}
}
// onStatus()
// Event handler for the event that the native implementation dispatches.
//
private function onStatus(e:StatusEvent):void
{
if (this.isPushNotificationSupported)
{
var event : PushNotificationEvent;
var data:String = e.level;
switch (e.code)
{
case "TOKEN_SUCCESS":
event = new PushNotificationEvent( PushNotificationEvent.PERMISSION_GIVEN_WITH_TOKEN_EVENT );
event.token = e.level;
break;
case "TOKEN_FAIL":
event = new PushNotificationEvent( PushNotificationEvent.PERMISSION_REFUSED_EVENT );
event.errorCode = "NativeCodeError";
event.errorMessage = e.level;
break;
case "COMING_FROM_NOTIFICATION":
event = new PushNotificationEvent( PushNotificationEvent.COMING_FROM_NOTIFICATION_EVENT );
if (data != null)
{
try
{
event.parameters = JSON.parse(data);
} catch (error:Error)
{
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "APP_STARTING_FROM_NOTIFICATION":
event = new PushNotificationEvent( PushNotificationEvent.APP_STARTING_FROM_NOTIFICATION_EVENT );
if (data != null)
{
try
{
event.parameters = JSON.parse(data);
} catch (error:Error)
{
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "APP_BROUGHT_TO_FOREGROUND_FROM_NOTIFICATION":
event = new PushNotificationEvent( PushNotificationEvent.APP_BROUGHT_TO_FOREGROUND_FROM_NOTIFICATION_EVENT );
if (data != null)
{
try
{
event.parameters = JSON.parse(data);
} catch (error:Error)
{
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "NOTIFICATION_RECEIVED_WHEN_IN_FOREGROUND":
event = new PushNotificationEvent( PushNotificationEvent.NOTIFICATION_RECEIVED_WHEN_IN_FOREGROUND_EVENT );
if (data != null)
{
try
{
event.parameters = JSON.parse(data);
} catch (error:Error)
{
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "LOGGING":
trace(e, e.level);
break;
}
if (event != null)
{
this.dispatchEvent( event );
}
}
}
}
}
|
Remove useless import.
|
Remove useless import.
|
ActionScript
|
apache-2.0
|
freshplanet/ANE-Push-Notification,freshplanet/ANE-Push-Notification,iamyuiwong/ANE-Push-Notification,StarIslandGames/ANE-Push-Notification,rozdonmobile/ANE-Push-Notification,nicechap/ANE-Push-Notification,marcorei/ANE-Push-Notification,freshplanet/ANE-Push-Notification,marcorei/ANE-Push-Notification,StarIslandGames/ANE-Push-Notification,rozdonmobile/ANE-Push-Notification,iamyuiwong/ANE-Push-Notification,nicechap/ANE-Push-Notification
|
39fea0632ab5877d0901803405198a27d75a8baa
|
src/main/as/flump/Flump.as
|
src/main/as/flump/Flump.as
|
package flump {
import flash.display.MovieClip;
import flash.filesystem.FileMode;
import flash.filesystem.File;
import flash.filesystem.FileStream;
import flash.utils.ByteArray;
import com.adobe.images.PNGEncoder;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.geom.Rectangle;
import com.threerings.flashbang.resource.SwfResource;
import com.threerings.flashbang.resource.ResourceManager;
import com.threerings.util.F;
import flash.display.LoaderInfo;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.sampler.Sample;
import flash.sampler.StackFrame;
import flash.sampler.getSamples;
import flash.sampler.pauseSampling;
import flash.sampler.clearSamples;
import flash.sampler.startSampling;
import flash.sampler.stopSampling;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.ui.Keyboard;
public class Flump extends Sprite
{
public function Flump ()
{
_rsrc.registerDefaultResourceTypes();
addEventListener(Event.ADDED_TO_STAGE, F.callbackOnce(addedToStage));
}
protected function addedToStage () :void
{
_rsrc.queueResourceLoad("swf", "pant", { embeddedClass: PANT});
_rsrc.queueResourceLoad("swf", "hat", { embeddedClass: HAT});
_rsrc.queueResourceLoad("swf", "top", { embeddedClass: TOP});
_rsrc.queueResourceLoad("swf", "hed", { embeddedClass: HED});
_rsrc.queueResourceLoad("swf", "sho", { embeddedClass: SHO});
_rsrc.queueResourceLoad("swf", "base", { embeddedClass: BASE});
_rsrc.loadQueuedResources(resourcesLoaded);
}
protected function resourcesLoaded () :void
{
F.forEach(layers, export);
trace("{\n " + _offsets.join(",\n ") + "\n}");
}
protected function export (layer :String) :void
{
var theClass :Class;
for each (var resource :String in resources) {
theClass= SwfResource.getSwf(_rsrc, resource).getClass(layer + "_class");
if (theClass != null) break;
}
if (theClass == null) { trace("skipping " + layer); return; }
const holder :Sprite = new Sprite();
const child :Sprite = Sprite(new theClass());
holder.addChild(child);
const bounds :Rectangle = child.getBounds(holder);
if (bounds.width == 0 || bounds.height == 0) { trace("invisible " + layer); return; }
if (_renames.hasOwnProperty(layer)) layer = _renames[layer];
child.x = -bounds.x;
child.y = -bounds.y;
_offsets.push(layer + ": [" + bounds.x + ', ' + bounds.y + "]");
const bd :BitmapData = new BitmapData(bounds.width, bounds.height, true);
// Clear bitmapdata's default white background with a transparent one
bd.fillRect(new Rectangle(0, 0, bounds.width, bounds.height), 0);
bd.draw(holder);
var fs :FileStream = new FileStream();
fs.open(new File("/Users/charlie/dev/flump/" + layer + ".png"), FileMode.WRITE);
fs.writeBytes(PNGEncoder.encode(bd));
fs.close();
}
protected const _offsets :Array = [];
protected const _rsrc :ResourceManager = new ResourceManager();
protected const _renames :Object = {"container_device_a": "device", "container_head_a": "head"};
protected const layers :Array = ["forearmL", "handL", "head", "neck", "bicepL", "scarfB",
"chest", "belly", "skirtL", "skirtM", "skirtR", "thighL", "pelvis", "calfL", "footL",
"thighR", "calfR", "footR", "forearmR", "handR", "device", "bicepR", "tails", "hairB",
"container_head_a", "container_device_a", "shadow"];
protected const resources :Array = ["pant", "hat", "top", "hed", "sho", "base"];
[Embed(source="/../swfresources/avatar/HAT_001.swf", mimeType="application/octet-stream")]
protected const HAT :Class;
[Embed(source="/../swfresources/avatar/PNT_001.swf", mimeType="application/octet-stream")]
protected const PANT :Class;
[Embed(source="/../swfresources/avatar/TOP_001.swf", mimeType="application/octet-stream")]
protected const TOP :Class;
[Embed(source="/../swfresources/avatar/HED_001.swf", mimeType="application/octet-stream")]
protected const HED :Class;
[Embed(source="/../swfresources/avatar/SHO_001.swf", mimeType="application/octet-stream")]
protected const SHO :Class;
[Embed(source="/../swfresources/avatar/male_player_base.swf", mimeType="application/octet-stream")]
protected const BASE :Class;
}
}
|
//
// Flump - Copyright 2012 Three Rings Design
package flump {
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.geom.Point;
import flash.geom.Rectangle;
import com.adobe.images.PNGEncoder;
import com.threerings.util.F;
public class Flump extends Sprite
{
protected function exportToPng (dest :String, toExport :Sprite) :Point {
const holder :Sprite = new Sprite();
holder.addChild(toExport);
const bounds :Rectangle = toExport.getBounds(holder);
toExport.x = -bounds.x;
toExport.y = -bounds.y;
const bd :BitmapData = new BitmapData(bounds.width, bounds.height, true);
// Clear bitmapdata's default white background with a transparent one
bd.fillRect(new Rectangle(0, 0, bounds.width, bounds.height), 0);
bd.draw(holder);
var fs :FileStream = new FileStream();
fs.open(new File(dest), FileMode.WRITE);
fs.writeBytes(PNGEncoder.encode(bd));
fs.close();
return new Point(bounds.x, bounds.y);
}
}}
|
Clean out testing code, leave png export
|
Clean out testing code, leave png export
|
ActionScript
|
mit
|
tconkling/flump,mathieuanthoine/flump,funkypandagame/flump,mathieuanthoine/flump,funkypandagame/flump,tconkling/flump,mathieuanthoine/flump
|
56504b0a68b90769d6507c423b670494a1b2c450
|
dolly-framework/src/test/actionscript/dolly/CopyingOfCopyableCloneableClassTest.as
|
dolly-framework/src/test/actionscript/dolly/CopyingOfCopyableCloneableClassTest.as
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.CopyableCloneableClass;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertNotNull;
use namespace dolly_internal;
public class CopyingOfCopyableCloneableClassTest {
private var copyableCloneableClass:CopyableCloneableClass;
private var copyableCloneableClassType:Type;
[Before]
public function before():void {
copyableCloneableClass = new CopyableCloneableClass();
copyableCloneableClass.property1 = "property1 value";
copyableCloneableClass.writableField1 = "writableField1 value";
copyableCloneableClassType = Type.forInstance(copyableCloneableClass);
}
[After]
public function after():void {
copyableCloneableClass = null;
copyableCloneableClassType = null;
}
[Test]
public function findingAllWritableFieldsForType():void {
const writableFields:Vector.<Field> = Copier.findCopyableFieldsForType(copyableCloneableClassType);
assertNotNull(writableFields);
assertEquals(2, writableFields.length);
}
[Test]
public function cloningByCloner():void {
const clone:CopyableCloneableClass = Copier.copy(copyableCloneableClass);
assertNotNull(clone);
assertNotNull(clone.property1);
assertEquals(clone.property1, copyableCloneableClass.property1);
assertNotNull(clone.writableField1);
assertEquals(clone.writableField1, copyableCloneableClass.writableField1);
}
[Test]
public function cloningByCloneFunction():void {
const cloneInstance:CopyableCloneableClass = copy(copyableCloneableClass);
assertNotNull(cloneInstance);
assertNotNull(cloneInstance.property1);
assertEquals(cloneInstance.property1, copyableCloneableClass.property1);
assertNotNull(cloneInstance.writableField1);
assertEquals(cloneInstance.writableField1, copyableCloneableClass.writableField1);
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.CopyableCloneableClass;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertNotNull;
use namespace dolly_internal;
public class CopyingOfCopyableCloneableClassTest {
private var copyableCloneableClass:CopyableCloneableClass;
private var copyableCloneableClassType:Type;
[Before]
public function before():void {
copyableCloneableClass = new CopyableCloneableClass();
copyableCloneableClass.property1 = "property1 value";
copyableCloneableClass.writableField1 = "writableField1 value";
copyableCloneableClassType = Type.forInstance(copyableCloneableClass);
}
[After]
public function after():void {
copyableCloneableClass = null;
copyableCloneableClassType = null;
}
[Test]
public function findingAllCopyableFieldsForType():void {
const copyableFields:Vector.<Field> = Copier.findCopyableFieldsForType(copyableCloneableClassType);
assertNotNull(copyableFields);
assertEquals(2, copyableFields.length);
assertNotNull(copyableFields[0]);
assertNotNull(copyableFields[1]);
}
[Test]
public function cloningByCloner():void {
const clone:CopyableCloneableClass = Copier.copy(copyableCloneableClass);
assertNotNull(clone);
assertNotNull(clone.property1);
assertEquals(clone.property1, copyableCloneableClass.property1);
assertNotNull(clone.writableField1);
assertEquals(clone.writableField1, copyableCloneableClass.writableField1);
}
[Test]
public function cloningByCloneFunction():void {
const cloneInstance:CopyableCloneableClass = copy(copyableCloneableClass);
assertNotNull(cloneInstance);
assertNotNull(cloneInstance.property1);
assertEquals(cloneInstance.property1, copyableCloneableClass.property1);
assertNotNull(cloneInstance.writableField1);
assertEquals(cloneInstance.writableField1, copyableCloneableClass.writableField1);
}
}
}
|
Fix variable and methods names.
|
Fix variable and methods names.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
891fc0b09fcfe84d53a7abb1bd5088d8f48427a4
|
src/com/esri/builder/controllers/RemoveCustomWidgetController.as
|
src/com/esri/builder/controllers/RemoveCustomWidgetController.as
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////////
package com.esri.builder.controllers
{
import com.esri.builder.controllers.supportClasses.processes.CleanUpProcess;
import com.esri.builder.controllers.supportClasses.processes.ProcessArbiter;
import com.esri.builder.controllers.supportClasses.processes.ProcessArbiterEvent;
import com.esri.builder.controllers.supportClasses.WellKnownDirectories;
import com.esri.builder.eventbus.AppEvent;
import com.esri.builder.model.WidgetType;
import com.esri.builder.model.WidgetTypeRegistryModel;
import com.esri.builder.views.BuilderAlert;
import flash.filesystem.File;
import mx.resources.ResourceManager;
public class RemoveCustomWidgetController
{
private var removeWidgetArbiter:ProcessArbiter;
private var widgetTypeToRemove:WidgetType;
public function RemoveCustomWidgetController()
{
AppEvent.addListener(AppEvent.REMOVE_CUSTOM_WIDGET, removeCustomWidgetHandler);
}
private function removeCustomWidgetHandler(importCustomWidget:AppEvent):void
{
widgetTypeToRemove = importCustomWidget.data as WidgetType;
removeWidget(widgetTypeToRemove);
}
private function removeWidget(widgetType:WidgetType):void
{
removeWidgetArbiter = new ProcessArbiter();
removeWidgetArbiter.addEventListener(ProcessArbiterEvent.COMPLETE, importArbiter_completeHandler);
removeWidgetArbiter.addEventListener(ProcessArbiterEvent.FAILURE, importArbiter_failureHandler);
var customWidgetConfig:File = WellKnownDirectories.getInstance().customModules.resolvePath(widgetTypeToRemove.name + "Module.xml");
var customWidgetFolder:File = WellKnownDirectories.getInstance().customFlexViewer.resolvePath("widgets/" + widgetType.name);
removeWidgetArbiter.addProcess(new CleanUpProcess(customWidgetConfig));
removeWidgetArbiter.addProcess(new CleanUpProcess(customWidgetFolder));
removeWidgetArbiter.executeProcs();
}
protected function importArbiter_completeHandler(event:ProcessArbiterEvent):void
{
removeWidgetArbiter.removeEventListener(ProcessArbiterEvent.COMPLETE, importArbiter_completeHandler);
removeWidgetArbiter.removeEventListener(ProcessArbiterEvent.FAILURE, importArbiter_failureHandler);
WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.removeWidgetType(widgetTypeToRemove);
AppEvent.dispatch(AppEvent.REMOVE_CUSTOM_WIDGET_SUCCESS);
}
protected function importArbiter_failureHandler(event:ProcessArbiterEvent):void
{
removeWidgetArbiter.removeEventListener(ProcessArbiterEvent.COMPLETE, importArbiter_completeHandler);
removeWidgetArbiter.removeEventListener(ProcessArbiterEvent.FAILURE, importArbiter_failureHandler);
var removeCustomWidgetFailureMessage:String = ResourceManager.getInstance().getString("BuilderStrings",
"removeCustomWidgetProcess.failure",
[ event.message ]);
var removeCustomWidgetFailureTitle:String = ResourceManager.getInstance().getString("BuilderStrings",
"widgetManager.removeCustomWidget");
BuilderAlert.show(removeCustomWidgetFailureMessage, removeCustomWidgetFailureTitle);
AppEvent.dispatch(AppEvent.REMOVE_CUSTOM_WIDGET_FAILURE);
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////////
package com.esri.builder.controllers
{
import com.esri.builder.controllers.supportClasses.processes.CleanUpProcess;
import com.esri.builder.controllers.supportClasses.processes.ProcessArbiter;
import com.esri.builder.controllers.supportClasses.processes.ProcessArbiterEvent;
import com.esri.builder.controllers.supportClasses.WellKnownDirectories;
import com.esri.builder.eventbus.AppEvent;
import com.esri.builder.model.WidgetType;
import com.esri.builder.model.WidgetTypeRegistryModel;
import com.esri.builder.views.BuilderAlert;
import flash.filesystem.File;
import mx.resources.ResourceManager;
public class RemoveCustomWidgetController
{
private var removeWidgetArbiter:ProcessArbiter;
private var widgetTypeToRemove:WidgetType;
public function RemoveCustomWidgetController()
{
AppEvent.addListener(AppEvent.REMOVE_CUSTOM_WIDGET, removeCustomWidgetHandler);
}
private function removeCustomWidgetHandler(importCustomWidget:AppEvent):void
{
widgetTypeToRemove = importCustomWidget.data as WidgetType;
removeWidget(widgetTypeToRemove);
}
private function removeWidget(widgetType:WidgetType):void
{
removeWidgetArbiter = new ProcessArbiter();
removeWidgetArbiter.addEventListener(ProcessArbiterEvent.COMPLETE, importArbiter_completeHandler);
removeWidgetArbiter.addEventListener(ProcessArbiterEvent.FAILURE, importArbiter_failureHandler);
var customWidgetModule:File = WellKnownDirectories.getInstance().customModules.resolvePath(widgetTypeToRemove.name + "Module.swf");
var customWidgetConfig:File = WellKnownDirectories.getInstance().customModules.resolvePath(widgetTypeToRemove.name + "Module.xml");
var customWidgetFolder:File = WellKnownDirectories.getInstance().customFlexViewer.resolvePath("widgets/" + widgetType.name);
removeWidgetArbiter.addProcess(new CleanUpProcess(customWidgetModule));
removeWidgetArbiter.addProcess(new CleanUpProcess(customWidgetConfig));
removeWidgetArbiter.addProcess(new CleanUpProcess(customWidgetFolder));
removeWidgetArbiter.executeProcs();
}
protected function importArbiter_completeHandler(event:ProcessArbiterEvent):void
{
removeWidgetArbiter.removeEventListener(ProcessArbiterEvent.COMPLETE, importArbiter_completeHandler);
removeWidgetArbiter.removeEventListener(ProcessArbiterEvent.FAILURE, importArbiter_failureHandler);
WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.removeWidgetType(widgetTypeToRemove);
AppEvent.dispatch(AppEvent.REMOVE_CUSTOM_WIDGET_SUCCESS);
}
protected function importArbiter_failureHandler(event:ProcessArbiterEvent):void
{
removeWidgetArbiter.removeEventListener(ProcessArbiterEvent.COMPLETE, importArbiter_completeHandler);
removeWidgetArbiter.removeEventListener(ProcessArbiterEvent.FAILURE, importArbiter_failureHandler);
var removeCustomWidgetFailureMessage:String = ResourceManager.getInstance().getString("BuilderStrings",
"removeCustomWidgetProcess.failure",
[ event.message ]);
var removeCustomWidgetFailureTitle:String = ResourceManager.getInstance().getString("BuilderStrings",
"widgetManager.removeCustomWidget");
BuilderAlert.show(removeCustomWidgetFailureMessage, removeCustomWidgetFailureTitle);
AppEvent.dispatch(AppEvent.REMOVE_CUSTOM_WIDGET_FAILURE);
}
}
}
|
Update RemoveCustomWidgetController to remove imported modules.
|
Update RemoveCustomWidgetController to remove imported modules.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
75519a19779fb68468ec50b9752a1288357a42f8
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/ILayoutParent.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/ILayoutParent.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
{
/**
* The ILayoutParent interface is the basic interface for the
* container that have an IBeadLayout. The layout implementation
* often needs to know certain things about other objects in
* the component.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public interface ILayoutParent
{
/**
* The container that parents all of the content.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
function get contentView():IParentIUIBase;
/**
* The container whose size changes
* imply the need for another layout pass. This
* is normally the host component.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
function get resizableView():IUIBase;
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.core
{
/**
* The ILayoutParent interface is the basic interface for the
* container views that have an IBeadLayout. The layout implementation
* often needs to know certain things about other objects in
* the view.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public interface ILayoutParent
{
/**
* The container that parents all of the content.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
function get contentView():IParentIUIBase;
/**
* The container whose size changes
* imply the need for another layout pass. This
* is normally the host component.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
function get resizableView():IUIBase;
}
}
|
clean up a comment
|
clean up a comment
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
74c026ef5856b2c97e96b776a3deef05fcd41f45
|
src/aerys/minko/scene/controller/camera/FirstPersonCameraController.as
|
src/aerys/minko/scene/controller/camera/FirstPersonCameraController.as
|
package aerys.minko.scene.controller.camera
{
import aerys.minko.render.Viewport;
import aerys.minko.scene.controller.AbstractScriptController;
import aerys.minko.scene.controller.EnterFrameController;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
import flash.display.BitmapData;
import flash.events.IEventDispatcher;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.ui.Keyboard;
public class FirstPersonCameraController extends AbstractScriptController
{
private static const TMP_MATRIX : Matrix4x4 = new Matrix4x4();
private var _ghostMode : Boolean = true;
private var _rotation : Vector4 = new Vector4();
private var _enabled : Boolean = true;
private var _update : Boolean = false;
private var _step : Number = 1;
private var _mousePosition : Point = new Point();
private var _position : Vector4 = new Vector4(0, 0, 0, 1);
private var _lookAt : Vector4 = new Vector4(0, 0, 0, 1);
private var _up : Vector4 = new Vector4(0, 1, 0, 1);
public function get enabled() : Boolean
{
return _enabled;
}
public function set enabled(value : Boolean) : void
{
_enabled = value;
}
public function get ghostMode() : Boolean
{
return _ghostMode;
}
public function set ghostMode(value : Boolean) : void
{
_ghostMode = value;
}
public function get step() : Number
{
return _step;
}
public function set step(value : Number) : void
{
_step = value;
}
public function FirstPersonCameraController()
{
super ();
}
public function bindDefaultControls(dispatcher : IEventDispatcher) : FirstPersonCameraController
{
dispatcher.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
return this;
}
public function unbindDefaultControls(dispatcher : IEventDispatcher) : FirstPersonCameraController
{
dispatcher.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
return this;
}
override protected function sceneEnterFrameHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
super.sceneEnterFrameHandler(scene, viewport, destination, time);
if (_update && _enabled)
{
_lookAt.x = _position.x + Math.sin(_rotation.y) * Math.cos(_rotation.x);
_lookAt.y = _position.y + Math.sin(_rotation.x);
_lookAt.z = _position.z + Math.cos(_rotation.y) * Math.cos(_rotation.x);
TMP_MATRIX.lookAt(_lookAt, _position, _up);
var numTargets : uint = this.numTargets;
for (var targetId : uint = 0; targetId < numTargets; ++targetId)
getTarget(targetId).transform.copyFrom(TMP_MATRIX);
_update = false;
}
}
public function walk(distance : Number) : void
{
if (_ghostMode)
{
_position.y += Math.sin(_rotation.x) * distance;
_position.x += Math.sin(_rotation.y) * Math.cos(-_rotation.x) * distance;
_position.z += Math.cos(_rotation.y) * Math.cos(-_rotation.x) * distance;
}
else
{
_position.x += Math.sin(_rotation.y) * distance;
_position.z += Math.cos(_rotation.y) * distance;
}
_update = true;
}
public function strafe(distance : Number) : void
{
_position.x += Math.sin(_rotation.y + Math.PI / 2) * distance;
_position.z += Math.cos(_rotation.y + Math.PI / 2) * distance;
_update = true;
}
override protected function update(target : ISceneNode) : void
{
if (keyboard.keyIsDown(Keyboard.RIGHT))
strafe(_step);
if (keyboard.keyIsDown(Keyboard.LEFT))
strafe(-_step);
if (keyboard.keyIsDown(Keyboard.UP))
walk(_step);
if (keyboard.keyIsDown(Keyboard.DOWN))
walk(-_step);
}
override protected function targetAddedHandler(ctrl : EnterFrameController,
target : ISceneNode) : void
{
super.targetAddedHandler(ctrl, target);
_update = true;
}
private function mouseMoveHandler(event : MouseEvent) : void
{
if (event.buttonDown)
{
_rotation.y += -(_mousePosition.x - event.stageX) * .005;
_rotation.x += (_mousePosition.y - event.stageY) * .005;
_update = true;
}
_mousePosition.setTo(event.stageX, event.stageY);
}
}
}
|
package aerys.minko.scene.controller.camera
{
import aerys.minko.render.Viewport;
import aerys.minko.scene.controller.AbstractScriptController;
import aerys.minko.scene.controller.EnterFrameController;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
import flash.display.BitmapData;
import flash.display.Stage;
import flash.events.IEventDispatcher;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.ui.Keyboard;
public class FirstPersonCameraController extends AbstractScriptController
{
private static const TMP_MATRIX : Matrix4x4 = new Matrix4x4();
private var _stage : Stage = null;
private var _ghostMode : Boolean = true;
private var _rotation : Vector4 = new Vector4();
private var _enabled : Boolean = true;
private var _update : Boolean = false;
private var _step : Number = 1;
private var _mousePosition : Point = new Point();
private var _position : Vector4 = new Vector4(0, 0, 0, 1);
private var _lookAt : Vector4 = new Vector4(0, 0, 0, 1);
private var _up : Vector4 = new Vector4(0, 1, 0, 1);
public function get enabled() : Boolean
{
return _enabled;
}
public function set enabled(value : Boolean) : void
{
_enabled = value;
}
public function get ghostMode() : Boolean
{
return _ghostMode;
}
public function set ghostMode(value : Boolean) : void
{
_ghostMode = value;
}
public function get step() : Number
{
return _step;
}
public function set step(value : Number) : void
{
_step = value;
}
public function FirstPersonCameraController(stage : Stage)
{
_stage = stage;
}
public function bindDefaultControls(dispatcher : IEventDispatcher) : FirstPersonCameraController
{
dispatcher.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
return this;
}
public function unbindDefaultControls(dispatcher : IEventDispatcher) : FirstPersonCameraController
{
dispatcher.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
return this;
}
override protected function sceneEnterFrameHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
super.sceneEnterFrameHandler(scene, viewport, destination, time);
if (_update && _enabled)
{
_lookAt.x = _position.x + Math.sin(_rotation.y) * Math.cos(_rotation.x);
_lookAt.y = _position.y + Math.sin(_rotation.x);
_lookAt.z = _position.z + Math.cos(_rotation.y) * Math.cos(_rotation.x);
TMP_MATRIX.lookAt(_lookAt, _position, _up);
var numTargets : uint = this.numTargets;
for (var targetId : uint = 0; targetId < numTargets; ++targetId)
getTarget(targetId).transform.copyFrom(TMP_MATRIX);
_update = false;
}
}
public function walk(distance : Number) : void
{
if (_ghostMode)
{
_position.y += Math.sin(_rotation.x) * distance;
_position.x += Math.sin(_rotation.y) * Math.cos(-_rotation.x) * distance;
_position.z += Math.cos(_rotation.y) * Math.cos(-_rotation.x) * distance;
}
else
{
_position.x += Math.sin(_rotation.y) * distance;
_position.z += Math.cos(_rotation.y) * distance;
}
_update = true;
}
public function strafe(distance : Number) : void
{
_position.x += Math.sin(_rotation.y + Math.PI / 2) * distance;
_position.z += Math.cos(_rotation.y + Math.PI / 2) * distance;
_update = true;
}
override protected function update(target : ISceneNode) : void
{
if (keyboard.keyIsDown(Keyboard.RIGHT))
strafe(_step);
if (keyboard.keyIsDown(Keyboard.LEFT))
strafe(-_step);
if (keyboard.keyIsDown(Keyboard.UP))
walk(_step);
if (keyboard.keyIsDown(Keyboard.DOWN))
walk(-_step);
}
override protected function targetAddedHandler(ctrl : EnterFrameController,
target : ISceneNode) : void
{
super.targetAddedHandler(ctrl, target);
_update = true;
}
private function mouseMoveHandler(event : MouseEvent) : void
{
if (event.buttonDown)
{
if (_stage && _stage.mouseLock)
{
_rotation.y += event.movementX * .005;
_rotation.x += -event.movementY * .005;
}
else
{
_rotation.y += -(_mousePosition.x - event.stageX) * .005;
_rotation.x += (_mousePosition.y - event.stageY) * .005;
}
_update = true;
}
_mousePosition.setTo(event.stageX, event.stageY);
}
}
}
|
Enable Mouse Lock API when available in the FPS camera.
|
Enable Mouse Lock API when available in the FPS camera.
|
ActionScript
|
mit
|
aerys/minko-as3
|
527fa197af5e01c5e770838abfe68e2cec08a59a
|
build-aux/base.as
|
build-aux/base.as
|
## -*- shell-script -*-
## base.as: This file is part of build-aux.
## Copyright (C) Gostai S.A.S., 2006-2008.
##
## This software is provided "as is" without warranty of any kind,
## either expressed or implied, including but not limited to the
## implied warranties of fitness for a particular purpose.
##
## See the LICENSE file for more information.
## For comments, bug reports and feedback: http://www.urbiforge.com
##
m4_pattern_forbid([^_?URBI_])dnl
# m4_define([_m4_divert(M4SH-INIT)], 5)
m4_define([_m4_divert(URBI-INIT)], 10)
m4_defun([_URBI_ABSOLUTE_PREPARE],
[
# is_absolute PATH
# ----------------
is_absolute ()
{
case $[1] in
([[\\/]]* | ?:[[\\/]]*) return 0;;
( *) return 1;;
esac
}
# absolute NAME -> ABS-NAME
# -------------------------
# Return an absolute path to NAME.
absolute ()
{
local res
AS_IF([is_absolute "$[1]"],
[# Absolute paths do not need to be expanded.
res=$[1]],
[local dir=$(pwd)/$(dirname "$[1]")
if test -d "$dir"; then
res=$(cd "$dir" 2>/dev/null && pwd)/$(basename "$[1]")
else
fatal "absolute: not a directory: $dir"
fi])
# On Windows, we must make sure we have a Windows-like UNIX-friendly path (of
# the form C:/cygwin/path/to/somewhere instead of /path/to/somewhere, notice
# the use of forward slashes in the Windows path. Windows *does* understand
# paths with forward slashes).
case $(uname -s) in
(CYGWIN*) res=$(cygpath "$res")
esac
echo "$res"
}
])
m4_defun([_URBI_FIND_PROG_PREPARE],
[# find_file FILE PATH
# -------------------
# Return full path to FILE in PATH ($PATH_SEPARATOR separated),
# nothing if not found.
find_prog ()
{
_AS_PATH_WALK([$[2]],
[AS_IF([test -f $as_dir/$[1]],
[echo "$as_dir/$[1]"; break])])
}
# xfind_file PROG PATH
# --------------------
# Same as xfind_prog, but don't take "no" for an answer.
xfind_file ()
{
local res
res=$(find_prog "$[1]" "$[2]")
test -n "$res" ||
error OSFILE "cannot find $[1] in $[2]"
echo "$res"
}
# find_prog PROG [PATH=$PATH]
# ---------------------------
# Return full path to PROG in PATH ($PATH_SEPARATOR separated),
# nothing if not found.
find_prog ()
{
local path=$PATH
test -z "$[2]" || path=$[2]
_AS_PATH_WALK([$path],
[AS_IF([AS_TEST_X([$as_dir/$[1]])],
[echo "$as_dir/$[1]"; break])])
}
# xfind_prog PROG [PATH=$PATH]
# ----------------------------
# Same as xfind_prog, but don't take "no" for an answer.
xfind_prog ()
{
local path=$PATH
test -z "$[2]" || path=$[2]
local res
res=$(find_prog "$[1]" "$path")
test -n "$res" ||
error OSFILE "cannot find executable $[1] in $path"
echo "$res"
}
# require_thing TEST-FLAG ERROR_MESSAGE THING [HINT]
# --------------------------------------------------
require_thing ()
{
local flag=$[1]
local error="$[2]: $[3]"
local thing=$[3]
shift 3
test $flag "$thing" ||
error OSFILE "$error" "$[@]"
}
# require_dir DIR [HINT]
# ----------------------
require_dir ()
{
require_thing -d "no such directory" "$[@]"
}
# require_file FILE [HINT]
# ------------------------
require_file ()
{
require_thing -f "no such file" "$[@]"
}
])
m4_defun([_URBI_STDERR_PREPARE],
[
# stderr LINES
# ------------
stderr ()
{
local i
for i
do
echo >&2 "$as_me: $i"
done
# This line is a nuisance in usual output, yet it makes sense in debug
# output in RST files. But the problem should be solved there
# instead.
#
# echo >&2
}
# verbose LINES
# -------------
verbose ()
{
case $verbose:" $VERBOSE " in
(*true:*|*" $me "*) stderr "$@";;
esac
}
# error EXIT MESSAGES
# -------------------
error ()
{
local exit=$[1]
shift
stderr "$[@]"
ex_exit $exit
}
# fatal MESSAGES
# --------------
fatal ()
{
# To help the user, just make sure that she is not confused between
# the prototypes of fatal and error: the first argument is unlikely
# to be integer.
case $[1] in
(*[[!0-9]]*|'') ;;
(*) stderr "warning: possible confusion between fatal and error" \
"fatal $[*]";;
esac
error 1 "$[@]"
}
# ex_to_string EXIT
# -----------------
# Return a decoding of EXIT status if available, nothing otherwise.
ex_to_string ()
{
case $[1] in
( 0) echo ' (EX_OK: successful termination)';;
( 64) echo ' (EX_USAGE: command line usage error)';;
( 65) echo ' (EX_DATAERR: data format error)';;
( 66) echo ' (EX_NOINPUT: cannot open input)';;
( 67) echo ' (EX_NOUSER: addressee unknown)';;
( 68) echo ' (EX_NOHOST: host name unknown)';;
( 69) echo ' (EX_UNAVAILABLE: service unavailable)';;
( 70) echo ' (EX_SOFTWARE: internal software error)';;
( 71) echo ' (EX_OSERR: system error (e.g., cannot fork))';;
( 72) echo ' (EX_OSFILE: critical OS file missing)';;
( 73) echo ' (EX_CANTCREAT: cannot create (user) output file)';;
( 74) echo ' (EX_IOERR: input/output error)';;
( 75) echo ' (EX_TEMPFAIL: temp failure; user is invited to retry)';;
( 76) echo ' (EX_PROTOCOL: remote error in protocol)';;
( 77) echo ' (EX_NOPERM: permission denied)';;
( 78) echo ' (EX_CONFIG: configuration error)';;
(176) echo ' (EX_SKIP: skip this test with unmet dependencies)';;
(177) echo ' (EX_HARD: hard error that cannot be saved)';;
(242) echo ' (killed by Valgrind)';;
( *) if test 127 -lt $[1]; then
echo " (SIG$(kill -l $[1] || true))"
fi;;
esac
}
# ex_to_int CODE
# --------------
# Decode the CODE and return the corresponding int.
ex_to_int ()
{
case $[1] in
(OK |EX_OK) echo 0;;
(USAGE |EX_USAGE) echo 64;;
(DATAERR |EX_DATAERR) echo 65;;
(NOINPUT |EX_NOINPUT) echo 66;;
(NOUSER |EX_NOUSER) echo 67;;
(NOHOST |EX_NOHOST) echo 68;;
(UNAVAILABLE|EX_UNAVAILABLE) echo 69;;
(SOFTWARE |EX_SOFTWARE) echo 70;;
(OSERR |EX_OSERR) echo 71;;
(OSFILE |EX_OSFILE) echo 72;;
(CANTCREAT |EX_CANTCREAT) echo 73;;
(IOERR |EX_IOERR) echo 74;;
(TEMPFAIL |EX_TEMPFAIL) echo 75;;
(PROTOCOL |EX_PROTOCOL) echo 76;;
(NOPERM |EX_NOPERM) echo 77;;
(CONFIG |EX_CONFIG) echo 78;;
(SKIP |EX_SKIP) echo 176;;
(HARD |EX_HARD) echo 177;;
(*) echo $[1];;
esac
}
ex_exit ()
{
exit $(ex_to_int $[1])
}
])
# URBI_GET_OPTIONS
# ----------------
# Generate get_options().
m4_define([URBI_GET_OPTIONS],
[# Parse command line options
get_options ()
{
while test $[#] -ne 0; do
case $[1] in
(--*=*)
opt=$(echo "$[1]" | sed -e 's/=.*//')
val=$(echo "$[1]" | sed -e ['s/[^=]*=//'])
shift
set dummy "$opt" "$val" ${1+"$[@]"};
shift
;;
esac
case $[1] in
$@
esac
shift
done
}
])
m4_defun([_URBI_PREPARE],
[
# mkcd DIR
# --------
# Remove, create, and cd into DIR.
mkcd ()
{
local dir=$[1]
rm -rf "$dir"
mkdir -p "$dir"
cd "$dir"
}
# truth TEST-ARGUMENTS...
# -----------------------
# Run "test TEST-ARGUMENTS" and echo true/false depending on the result.
truth ()
{
if test "$[@]"; then
echo true
else
echo false
fi
}
_URBI_ABSOLUTE_PREPARE
_URBI_FIND_PROG_PREPARE
_URBI_STDERR_PREPARE
])
# URBI_PREPARE
# ------------
# Output all the M4sh possible initialization into the initialization
# diversion.
m4_defun([URBI_PREPARE],
[m4_divert_text([M4SH-INIT], [_URBI_PREPARE])dnl
URBI_RST_PREPARE()dnl
URBI_INSTRUMENT_PREPARE()dnl
URBI_CHILDREN_PREPARE()dnl
])
# URBI_INIT
# ---------
# Replaces the AS_INIT invocation.
# Must be defined via "m4_define", not "m4_defun" since it is AS_INIT
# which will set up the diversions used for "m4_defun".
m4_define([URBI_INIT],
[AS_INIT()dnl
URBI_PREPARE()
set -e
case $VERBOSE in
(x) set -x;;
esac
# We can only check absolute dirs, since we may be called from other
# directories than the ones we were created from.
: ${abs_builddir='@abs_builddir@'}
: ${abs_srcdir='@abs_srcdir@'}
: ${abs_top_builddir='@abs_top_builddir@'}
check_dir abs_top_builddir config.status
: ${abs_top_srcdir='@abs_top_srcdir@'}
check_dir abs_top_srcdir configure.ac
: ${builddir='@builddir@'}
: ${srcdir='@srcdir@'}
: ${top_builddir='@top_builddir@'}
: ${top_srcdir='@top_srcdir@'}
# Bounce the signals to trap 0, passing the signal as exit value.
for signal in 1 2 13 15; do
trap 'error $((128 + $signal)) \
"received signal $signal ($(kill -l $signal))"' $signal
done
])
|
## -*- shell-script -*-
## base.as: This file is part of build-aux.
## Copyright (C) Gostai S.A.S., 2006-2008.
##
## This software is provided "as is" without warranty of any kind,
## either expressed or implied, including but not limited to the
## implied warranties of fitness for a particular purpose.
##
## See the LICENSE file for more information.
## For comments, bug reports and feedback: http://www.urbiforge.com
##
m4_pattern_forbid([^_?URBI_])dnl
# m4_define([_m4_divert(M4SH-INIT)], 5)
m4_define([_m4_divert(URBI-INIT)], 10)
m4_defun([_URBI_ABSOLUTE_PREPARE],
[
# is_absolute PATH
# ----------------
is_absolute ()
{
case $[1] in
([[\\/]]* | ?:[[\\/]]*) return 0;;
( *) return 1;;
esac
}
# absolute NAME -> ABS-NAME
# -------------------------
# Return an absolute path to NAME.
absolute ()
{
local res
AS_IF([is_absolute "$[1]"],
[# Absolute paths do not need to be expanded.
res=$[1]],
[local dir=$(pwd)/$(dirname "$[1]")
if test -d "$dir"; then
res=$(cd "$dir" 2>/dev/null && pwd)/$(basename "$[1]")
else
fatal "absolute: not a directory: $dir"
fi])
# On Windows, we must make sure we have a Windows-like UNIX-friendly path (of
# the form C:/cygwin/path/to/somewhere instead of /path/to/somewhere, notice
# the use of forward slashes in the Windows path. Windows *does* understand
# paths with forward slashes).
case $(uname -s) in
(CYGWIN*) res=$(cygpath "$res")
esac
echo "$res"
}
])
m4_defun([_URBI_FIND_PROG_PREPARE],
[# find_file FILE PATH
# -------------------
# Return full path to FILE in PATH ($PATH_SEPARATOR separated),
# nothing if not found.
find_prog ()
{
_AS_PATH_WALK([$[2]],
[AS_IF([test -f $as_dir/$[1]],
[echo "$as_dir/$[1]"; break])])
}
# xfind_file PROG PATH
# --------------------
# Same as xfind_prog, but don't take "no" for an answer.
xfind_file ()
{
local res
res=$(find_prog "$[1]" "$[2]")
test -n "$res" ||
error OSFILE "cannot find $[1] in $[2]"
echo "$res"
}
# find_prog PROG [PATH=$PATH]
# ---------------------------
# Return full path to PROG in PATH ($PATH_SEPARATOR separated),
# nothing if not found.
find_prog ()
{
local path=$PATH
test -z "$[2]" || path=$[2]
_AS_PATH_WALK([$path],
[AS_IF([AS_TEST_X([$as_dir/$[1]])],
[echo "$as_dir/$[1]"; break])])
}
# xfind_prog PROG [PATH=$PATH]
# ----------------------------
# Same as xfind_prog, but don't take "no" for an answer.
xfind_prog ()
{
local path=$PATH
test -z "$[2]" || path=$[2]
local res
res=$(find_prog "$[1]" "$path")
test -n "$res" ||
error OSFILE "cannot find executable $[1] in $path"
echo "$res"
}
# require_thing TEST-FLAG ERROR_MESSAGE THING [HINT]
# --------------------------------------------------
require_thing ()
{
local flag=$[1]
local error="$[2]: $[3]"
local thing=$[3]
shift 3
test $flag "$thing" ||
error OSFILE "$error" "$[@]"
}
# require_dir DIR [HINT]
# ----------------------
require_dir ()
{
require_thing -d "no such directory" "$[@]"
}
# require_file FILE [HINT]
# ------------------------
require_file ()
{
require_thing -f "no such file" "$[@]"
}
])
m4_defun([_URBI_STDERR_PREPARE],
[
# stderr LINES
# ------------
stderr ()
{
local i
for i
do
echo >&2 "$as_me: $i"
done
# This line is a nuisance in usual output, yet it makes sense in debug
# output in RST files. But the problem should be solved there
# instead.
#
# echo >&2
}
# verbose LINES
# -------------
verbose ()
{
case $verbose:" $VERBOSE " in
(true:*|*" $me "*) stderr "$[@]";;
esac
}
# error EXIT MESSAGES
# -------------------
error ()
{
local exit=$[1]
shift
stderr "$[@]"
ex_exit $exit
}
# fatal MESSAGES
# --------------
fatal ()
{
# To help the user, just make sure that she is not confused between
# the prototypes of fatal and error: the first argument is unlikely
# to be integer.
case $[1] in
(*[[!0-9]]*|'') ;;
(*) stderr "warning: possible confusion between fatal and error" \
"fatal $[*]";;
esac
error 1 "$[@]"
}
# ex_to_string EXIT
# -----------------
# Return a decoding of EXIT status if available, nothing otherwise.
ex_to_string ()
{
case $[1] in
( 0) echo ' (EX_OK: successful termination)';;
( 64) echo ' (EX_USAGE: command line usage error)';;
( 65) echo ' (EX_DATAERR: data format error)';;
( 66) echo ' (EX_NOINPUT: cannot open input)';;
( 67) echo ' (EX_NOUSER: addressee unknown)';;
( 68) echo ' (EX_NOHOST: host name unknown)';;
( 69) echo ' (EX_UNAVAILABLE: service unavailable)';;
( 70) echo ' (EX_SOFTWARE: internal software error)';;
( 71) echo ' (EX_OSERR: system error (e.g., cannot fork))';;
( 72) echo ' (EX_OSFILE: critical OS file missing)';;
( 73) echo ' (EX_CANTCREAT: cannot create (user) output file)';;
( 74) echo ' (EX_IOERR: input/output error)';;
( 75) echo ' (EX_TEMPFAIL: temp failure; user is invited to retry)';;
( 76) echo ' (EX_PROTOCOL: remote error in protocol)';;
( 77) echo ' (EX_NOPERM: permission denied)';;
( 78) echo ' (EX_CONFIG: configuration error)';;
(176) echo ' (EX_SKIP: skip this test with unmet dependencies)';;
(177) echo ' (EX_HARD: hard error that cannot be saved)';;
(242) echo ' (killed by Valgrind)';;
( *) if test 127 -lt $[1]; then
echo " (SIG$(kill -l $[1] || true))"
fi;;
esac
}
# ex_to_int CODE
# --------------
# Decode the CODE and return the corresponding int.
ex_to_int ()
{
case $[1] in
(OK |EX_OK) echo 0;;
(USAGE |EX_USAGE) echo 64;;
(DATAERR |EX_DATAERR) echo 65;;
(NOINPUT |EX_NOINPUT) echo 66;;
(NOUSER |EX_NOUSER) echo 67;;
(NOHOST |EX_NOHOST) echo 68;;
(UNAVAILABLE|EX_UNAVAILABLE) echo 69;;
(SOFTWARE |EX_SOFTWARE) echo 70;;
(OSERR |EX_OSERR) echo 71;;
(OSFILE |EX_OSFILE) echo 72;;
(CANTCREAT |EX_CANTCREAT) echo 73;;
(IOERR |EX_IOERR) echo 74;;
(TEMPFAIL |EX_TEMPFAIL) echo 75;;
(PROTOCOL |EX_PROTOCOL) echo 76;;
(NOPERM |EX_NOPERM) echo 77;;
(CONFIG |EX_CONFIG) echo 78;;
(SKIP |EX_SKIP) echo 176;;
(HARD |EX_HARD) echo 177;;
(*) echo $[1];;
esac
}
ex_exit ()
{
exit $(ex_to_int $[1])
}
])
# URBI_GET_OPTIONS
# ----------------
# Generate get_options().
m4_define([URBI_GET_OPTIONS],
[# Parse command line options
get_options ()
{
while test $[#] -ne 0; do
case $[1] in
(--*=*)
opt=$(echo "$[1]" | sed -e 's/=.*//')
val=$(echo "$[1]" | sed -e ['s/[^=]*=//'])
shift
set dummy "$opt" "$val" ${1+"$[@]"};
shift
;;
esac
case $[1] in
$@
esac
shift
done
}
])
m4_defun([_URBI_PREPARE],
[
# mkcd DIR
# --------
# Remove, create, and cd into DIR.
mkcd ()
{
local dir=$[1]
rm -rf "$dir"
mkdir -p "$dir"
cd "$dir"
}
# truth TEST-ARGUMENTS...
# -----------------------
# Run "test TEST-ARGUMENTS" and echo true/false depending on the result.
truth ()
{
if test "$[@]"; then
echo true
else
echo false
fi
}
_URBI_ABSOLUTE_PREPARE
_URBI_FIND_PROG_PREPARE
_URBI_STDERR_PREPARE
])
# URBI_PREPARE
# ------------
# Output all the M4sh possible initialization into the initialization
# diversion.
m4_defun([URBI_PREPARE],
[m4_divert_text([M4SH-INIT], [_URBI_PREPARE])dnl
URBI_RST_PREPARE()dnl
URBI_INSTRUMENT_PREPARE()dnl
URBI_CHILDREN_PREPARE()dnl
])
# URBI_INIT
# ---------
# Replaces the AS_INIT invocation.
# Must be defined via "m4_define", not "m4_defun" since it is AS_INIT
# which will set up the diversions used for "m4_defun".
m4_define([URBI_INIT],
[AS_INIT()dnl
URBI_PREPARE()
set -e
case $VERBOSE in
(x) set -x;;
esac
# We can only check absolute dirs, since we may be called from other
# directories than the ones we were created from.
: ${abs_builddir='@abs_builddir@'}
: ${abs_srcdir='@abs_srcdir@'}
: ${abs_top_builddir='@abs_top_builddir@'}
check_dir abs_top_builddir config.status
: ${abs_top_srcdir='@abs_top_srcdir@'}
check_dir abs_top_srcdir configure.ac
: ${builddir='@builddir@'}
: ${srcdir='@srcdir@'}
: ${top_builddir='@top_builddir@'}
: ${top_srcdir='@top_srcdir@'}
# Bounce the signals to trap 0, passing the signal as exit value.
for signal in 1 2 13 15; do
trap 'error $((128 + $signal)) \
"received signal $signal ($(kill -l $signal))"' $signal
done
])
|
Fix m4 quotation issues.
|
Fix m4 quotation issues.
* build-aux/base.as (verbose): here.
|
ActionScript
|
bsd-3-clause
|
aldebaran/libport,aldebaran/libport,aldebaran/libport,aldebaran/libport,aldebaran/libport
|
90bcb30dcd249a0c477b82794a84fb12ad903cdb
|
src/avm2/tests/regress/correctness/pass/xml.as
|
src/avm2/tests/regress/correctness/pass/xml.as
|
print("XML statics");
(function () {
var tests = [
[XML.ignoreWhitespace = true, XML.ignoreWhitespace],
];
for (var i = 0; i < tests.length; i++) {
print(i + ": " + tests[i]);
}
})();
print("Testing Basic XML");
(function () {
var x = <foo a="aaa"><bar b="bbb">e=mc^2</bar></foo>;
x.cat = <cat c="ccc"/>;
x.@name = "x";
x.@type = "T";
var tests = [
[x.name() == "foo", x.name()],
[x.bar.name() == "bar", x.bar.name()],
[x.@a == "aaa", x.@a],
[x.@type == "T", x.@type],
[x..bar == "e=mc^2", x..bar],
];
for (var i = 0; i < tests.length; i++) {
print(i + ": " + tests[i]);
}
})();
print("Testing Any Name");
(function () {
var x = <foo a="aaa"><bar b="bbb"/><cat c="ccc"/></foo>;
var r1 = <><bar b="bbb"/><cat c="ccc"/></>;
var tests = [
[x.*.toXMLString() === r1.toXMLString(), x.*.toXMLString()],
[x.@*.toString() === "aaa", x.@*.toString()],
[x.*.@*.toString() === "bbbccc", x.*.@*.toString()],
];
for (var i = 0; i < tests.length; i++) {
print(i + ": " + tests[i]);
}
})();
print("Testing attribute() and attributes() methods");
(function () {
var x = <foo a="aaa"><bar b="bbb"/><cat c="ccc"/></foo>;
var r1 = <><bar b="bbb"/><cat c="ccc"/></>;
var tests = [
[x.attribute("*"), x.attribute("*")],
[x.attributes(), x.attributes()],
[x.*.attribute("*"), x.*.attribute("*")],
[x.*.attributes(), x.*.attributes()],
];
for (var i = 0; i < tests.length; i++) {
print(i + ": " + tests[i]);
}
})();
print("Testing enumeration");
(function () {
var x = <><foo a="aaa"/><bar b="bbb"/><cat c="ccc"/></>;
x.foo;
var a = []
for each (var v in x) {
a.push(v.@*);
}
var tests = [
[a]
];
for (var i = 0; i < tests.length; i++) {
print(i + ": " + tests[i]);
}
})();
print("Testing XMLList.prototype.setProperty() (aka [[PUT]])");
(function () {
var x = <foo a="aaa"><bar b="bbb"/><bar/><cat c="ccc"/></foo>;
var tests = [
[x.bar.toXMLString()],
// [x.bar = "barbarbar", x.bar.toXMLString()],
// [x.* = "***", x.toXMLString()]
];
for (var i = 0; i < tests.length; i++) {
print(i + ": " + tests[i]);
}
})();
print("Testing YouTube use of E4X");
class A {}
(function () {
var variable:*;
var type:XML;
var eventClass:Class;
var loc1:*;
variable = undefined;
eventClass = A;
type =
<type name="avmplus::A" base="Class" isDynamic="true" isFinal="true" isStatic="true">
<extendsClass type="Class"/>
<extendsClass type="Object"/>
<variable name="c" type="String"/>
<variable name="b" type="String"/>
<variable name="a" type="String"/>
<factory type="avmplus::A">
<extendsClass type="Object"/>
<variable name="x" type="*"/>
<variable name="z" type="*"/>
<variable name="y" type="*"/>
</factory>
</type>;
var loc2:*=0;
var loc5:*=0;
var loc6:*=type;
var loc4:*=new XMLList("");
for each (var loc7:* in loc6.*) {
var loc8:*;
with (loc8 = loc7) {
if (@type == "String") {
loc4[loc5++] = loc7;
}
}
}
var loc3:*=loc4;
for each (variable in loc3) {
eventClass[variable.@name] = type.@name + "." + variable.@name;
}
var keys = [];
for (var p in eventClass) {
keys.push(p);
}
keys.sort();
for (var i = 0; i < keys.length; i++) {
var p = keys[i];
print("eventClass[p]="+eventClass[p]);
}
})();
|
print("XML statics");
(function () {
var tests = [
[XML.ignoreWhitespace = true, XML.ignoreWhitespace],
];
for (var i = 0; i < tests.length; i++) {
print(i + ": " + tests[i]);
}
})();
print("Testing Basic XML");
(function () {
var x = <foo a="aaa"><bar b="bbb">e=mc^2</bar></foo>;
x.cat = <cat c="ccc"/>;
x.@name = "x";
x.@type = "T";
var tests = [
[x.name() == "foo", x.name()],
[x.bar.name() == "bar", x.bar.name()],
[x.@a == "aaa", x.@a],
[x.@type == "T", x.@type],
[x..bar == "e=mc^2", x..bar],
];
for (var i = 0; i < tests.length; i++) {
print(i + ": " + tests[i]);
}
})();
print("Testing Any Name");
(function () {
var x = <foo a="aaa"><bar b="bbb"/><cat c="ccc"/></foo>;
var r1 = <><bar b="bbb"/><cat c="ccc"/></>;
var tests = [
[x.*.toXMLString() === r1.toXMLString(), x.*.toXMLString()],
[x.@*.toString() === "aaa", x.@*.toString()],
[x.*.@*.toString() === "bbbccc", x.*.@*.toString()],
];
for (var i = 0; i < tests.length; i++) {
print(i + ": " + tests[i]);
}
})();
print("Testing attribute() and attributes() methods");
(function () {
var x = <foo a="aaa"><bar b="bbb"/><cat c="ccc"/></foo>;
var r1 = <><bar b="bbb"/><cat c="ccc"/></>;
var tests = [
[x.attribute("*"), x.attribute("*")],
[x.attributes(), x.attributes()],
[x.*.attribute("*"), x.*.attribute("*")],
[x.*.attributes(), x.*.attributes()],
];
for (var i = 0; i < tests.length; i++) {
print(i + ": " + tests[i]);
}
})();
print("Testing enumeration");
(function () {
var x = <><foo a="aaa"/><bar b="bbb"/><cat c="ccc"/></>;
x.foo;
var a = []
for each (var v in x) {
a.push(v.@*);
}
var tests = [
[a]
];
for (var i = 0; i < tests.length; i++) {
print(i + ": " + tests[i]);
}
})();
print("Testing XMLList.prototype.setProperty() (aka [[PUT]])");
(function () {
var x = <foo a="aaa"><bar b="bbb"/><bar/><cat c="ccc"/></foo>;
var tests = [
[x.bar.toXMLString()],
// [x.bar = "barbarbar", x.bar.toXMLString()],
// [x.* = "***", x.toXMLString()]
];
for (var i = 0; i < tests.length; i++) {
print(i + ": " + tests[i]);
}
})();
print("Testing YouTube use of E4X");
class A {}
(function () {
var variable:*;
var type:XML;
var eventClass:Class;
var loc1:*;
variable = undefined;
eventClass = A;
type =
<type name="avmplus::A" base="Class" isDynamic="true" isFinal="true" isStatic="true">
<extendsClass type="Class"/>
<extendsClass type="Object"/>
<variable name="c" type="String"/>
<variable name="b" type="String"/>
<variable name="a" type="String"/>
<factory type="avmplus::A">
<extendsClass type="Object"/>
<variable name="x" type="*"/>
<variable name="z" type="*"/>
<variable name="y" type="*"/>
</factory>
</type>;
var loc2:*=0;
var loc5:*=0;
var loc6:*=type;
var loc4:*=new XMLList("");
for each (var loc7:* in loc6.*) {
var loc8:*;
with (loc8 = loc7) {
if (@type == "String") {
loc4[loc5++] = loc7;
}
}
}
var loc3:*=loc4;
for each (variable in loc3) {
eventClass[variable.@name] = type.@name + "." + variable.@name;
}
var keys = [];
for (var p in eventClass) {
keys.push(p);
}
keys.sort();
for (var i = 0; i < keys.length; i++) {
var p = keys[i];
print("eventClass[p]="+eventClass[p]);
}
})();
print("Testing XML.prototype.child as used by Candy Crush");
(function () {
var x = new XML(
'<gamedata randomseed="1282661104" version="1">' +
'<musicOn>false</musicOn>' +
'<soundOn>true</soundOn>' +
'<isShortGame>false</isShortGame>' +
'<booster_1>0</booster_1>' +
'<booster_2>0</booster_2>' +
'<booster_3>0</booster_3>' +
'<booster_4>0</booster_4>' +
'<booster_5>0</booster_5>' +
'<bestScore>100</bestScore>' +
'<bestChain>2</bestChain>' +
'<bestLevel>1</bestLevel>' +
'<bestCrushed>5</bestCrushed>' +
'<bestMixed>2</bestMixed>' +
'<text id="intro.time">Le jeu commence dans {0} secondes</text>' +
'<text id="intro.title">Speel als volgt:</text>' +
'<text id="intro.info1">Sett sammen 3 godteri i samme farge for å knuse ...</text>' +
'<text id="intro.info2">You can also combine the power candy for additio ...</text>' +
'<text id="game.nomoves">No more moves!</text>' +
'<text id="outro.opengame">Please register to play the full game</text>' +
'<text id="outro.title">Game Over</text>' +
'<text id="outro.now">now</text>' +
'<text id="outro.bestever">best ever</text>' +
'<text id="outro.score">Score</text>' +
'<text id="outro.chain">Longest chain</text>' +
'<text id="outro.level">Level reached</text>' +
'<text id="outro.crushed">Candy crushed</text>' +
'<text id="outro.time">Game ends in {0} seconds</text>' +
'<text id="outro.trophy.one">crushed {0} candy in one game</text>' +
'<text id="outro.trophy.two">scored {0} in one game</text>' +
'<text id="outro.trophy.three">made {0} combined candy in one game</text>' +
'<text id="outro.combo_wrapper_line">combo wrapper line description</text>' +
'<text id="outro.combo_color_color">combo color color description</text>' +
'<text id="outro.combo_color_line">combo color line description</text>' +
'<text id="outro.combo_color_wrapper">combo color wrapper description. ...</text>' +
'</gamedata>');
var tests = [
[x.child("text").length()],
];
for (var i = 0; i < tests.length; i++) {
print(i + ": " + tests[i]);
}
})();
|
Add test for XML.prototype.child() as used by Candy Crush
|
Add test for XML.prototype.child() as used by Candy Crush
|
ActionScript
|
apache-2.0
|
tschneidereit/shumway,mozilla/shumway,tschneidereit/shumway,mbebenita/shumway,yurydelendik/shumway,mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway,mozilla/shumway,tschneidereit/shumway,tschneidereit/shumway,mbebenita/shumway,yurydelendik/shumway,mbebenita/shumway,mbebenita/shumway,yurydelendik/shumway,tschneidereit/shumway,yurydelendik/shumway,mbebenita/shumway,mozilla/shumway,tschneidereit/shumway,yurydelendik/shumway,yurydelendik/shumway,yurydelendik/shumway,mozilla/shumway,mozilla/shumway,mozilla/shumway,mbebenita/shumway,tschneidereit/shumway,mozilla/shumway,mbebenita/shumway,mozilla/shumway
|
fd4641355b0d5b5699b399fbf17e149dab62ac7a
|
src/com/axis/rtspclient/BitArray.as
|
src/com/axis/rtspclient/BitArray.as
|
package com.axis.rtspclient {
import com.axis.ErrorManager;
import flash.utils.ByteArray;
public class BitArray extends ByteArray {
private var src:ByteArray;
private var byte:uint;
private var bitpos:uint;
public function BitArray(src:ByteArray) {
this.src = src;
this.bitpos = 0;
this.byte = 0; /* This should really be undefined, uint wont allow it though */
}
public function readBits(length:uint):uint {
if (32 < length || 0 === length) {
/* To big for an uint */
ErrorManager.dispatchError(819, null, true);
}
var result:uint = 0;
for (var i:uint = 1; i <= length; ++i) {
if (0 === bitpos) {
/* Previous byte all read out. Get a new one. */
byte = src.readUnsignedByte();
}
/* Shift result one left to make room for another bit,
then add the next bit on the stream. */
result = (result << 1) | ((byte >> (8 - (++bitpos))) & 0x01);
bitpos %= 8;
}
return result;
}
public function readUnsignedExpGolomb():uint {
var bitsToRead:uint = 0;
while (readBits(1) !== 1) bitsToRead++;
if (bitsToRead == 0) return 0; /* Easy peasy, just a single 1. This is 0 in exp golomb */
if (bitsToRead >= 31) ErrorManager.dispatchError(820, null, true);
var n:uint = readBits(bitsToRead); /* Read all bits part of this number */
n |= (0x1 << (bitsToRead)); /* Move in the 1 read by while-statement above */
return n - 1; /* Because result in exp golomb is one larger */
}
private function readSignedExpGolomb(sps:BitArray):uint {
var r:uint = this.readUnsignedExpGolomb();
if (r & 0x01) {
r = (r+1) >> 1;
} else {
r = -(r >> 1);
}
return r;
}
}
}
|
package com.axis.rtspclient {
import com.axis.ErrorManager;
import flash.utils.ByteArray;
public class BitArray extends ByteArray {
private var src:ByteArray;
private var byte:uint;
private var bitpos:uint;
public function BitArray(src:ByteArray) {
this.src = src;
this.bitpos = 0;
this.byte = 0; /* This should really be undefined, uint wont allow it though */
}
public function readBits(length:uint):uint {
if (32 < length || 0 === length) {
/* To big for an uint */
ErrorManager.dispatchError(819, null, true);
}
var result:uint = 0;
for (var i:uint = 1; i <= length; ++i) {
if (0 === bitpos) {
/* Previous byte all read out. Get a new one. */
byte = src.readUnsignedByte();
}
/* Shift result one left to make room for another bit,
then add the next bit on the stream. */
result = (result << 1) | ((byte >> (8 - (++bitpos))) & 0x01);
bitpos %= 8;
}
return result;
}
public function readUnsignedExpGolomb():uint {
var bitsToRead:uint = 0;
while (readBits(1) !== 1) bitsToRead++;
if (bitsToRead == 0) return 0; /* Easy peasy, just a single 1. This is 0 in exp golomb */
if (bitsToRead >= 31) ErrorManager.dispatchError(820, null, true);
var n:uint = readBits(bitsToRead); /* Read all bits part of this number */
n |= (0x1 << (bitsToRead)); /* Move in the 1 read by while-statement above */
return n - 1; /* Because result in exp golomb is one larger */
}
public function readSignedExpGolomb(sps:BitArray):uint {
var r:uint = this.readUnsignedExpGolomb();
if (r & 0x01) {
r = (r+1) >> 1;
} else {
r = -(r >> 1);
}
return r;
}
}
}
|
make readSignedExpGolomb public
|
make readSignedExpGolomb public
|
ActionScript
|
bsd-3-clause
|
AxisCommunications/locomote-video-player,gaetancollaud/locomote-video-player
|
22dbc15ee0d9f7fa253d212805bc0e3c4de181db
|
src/battlecode/common/RobotType.as
|
src/battlecode/common/RobotType.as
|
package battlecode.common {
public class RobotType {
public static const ARCHON:String = "ARCHON";
public static const SCOUT:String = "SCOUT";
public static const SOLDIER:String = "SOLDIER";
public static const GUARD:String = "GUARD";
public static const VIPER:String = "VIPER";
public static const TURRET:String = "TURRET";
public static const TTM:String = "TTM";
public static const ZOMBIEDEN:String = "ZOMBIEDEN";
public static const STANDARDZOMBIE:String = "STANDARDZOMBIE";
public static const FASTZOMBIE:String = "FASTZOMBIE";
public static const RANGEDZOMBIE:String = "RANGEDZOMBIE";
public static const BIGZOMBIE:String = "BIGZOMBIE";
public function RobotType() {
}
public static function values():Array {
return [
ARCHON,
SCOUT,
SOLDIER,
GUARD,
VIPER,
TURRET,
TTM,
ZOMBIEDEN,
STANDARDZOMBIE,
FASTZOMBIE,
RANGEDZOMBIE,
BIGZOMBIE
];
}
public static function units():Array {
return [
SOLDIER,
GUARD,
VIPER,
SCOUT,
TURRET,
TTM
];
}
public static function zombies():Array {
return [
ZOMBIEDEN,
STANDARDZOMBIE,
FASTZOMBIE,
RANGEDZOMBIE,
BIGZOMBIE
]
}
public static function maxEnergon(type:String):Number {
switch (type) {
case ARCHON:
return 1000;
case SCOUT:
return 100;
case SOLDIER:
return 60;
case GUARD:
return 150;
case VIPER:
return 120;
case TURRET:
return 100;
case TTM:
return 100;
case ZOMBIEDEN:
return 2000;
case STANDARDZOMBIE:
return 60;
case RANGEDZOMBIE:
return 60;
case FASTZOMBIE:
return 80;
case BIGZOMBIE:
return 500;
}
throw new ArgumentError("Unknown type: " + type);
}
public static function movementDelay(type:String):Number {
switch (type) {
case ARCHON:
return 2;
case SCOUT:
return 1.4;
case SOLDIER:
return 2;
case GUARD:
return 2;
case VIPER:
return 2;
case TURRET:
return 0;
case TTM:
return 2;
case STANDARDZOMBIE:
return 3;
case RANGEDZOMBIE:
return 3;
case FASTZOMBIE:
return 1.4;
case BIGZOMBIE:
return 3;
}
return 1;
}
public static function movementDelayDiagonal(type:String):uint {
return movementDelay(type) * Math.SQRT2;
}
public static function attackDelay(type:String):Number {
switch (type) {
case ARCHON:
return 2;
case SCOUT:
return 1;
case SOLDIER:
return 2;
case GUARD:
return 2;
case VIPER:
return 2;
case TURRET:
return 0;
case TTM:
return 2;
case STANDARDZOMBIE:
return 2;
case RANGEDZOMBIE:
return 1;
case FASTZOMBIE:
return 1;
case BIGZOMBIE:
return 3;
}
return 0;
}
public static function partValue(type:String):Number {
switch (type) {
case ARCHON:
return 0;
case SCOUT:
return 40;
case SOLDIER:
return 30;
case GUARD:
return 30;
case VIPER:
return 100;
case TURRET:
return 125;
case TTM:
return 125;
default:
return 0;
}
}
public static function isZombie(type:String):Boolean {
switch (type) {
case ZOMBIEDEN:
case STANDARDZOMBIE:
case FASTZOMBIE:
case RANGEDZOMBIE:
case BIGZOMBIE:
return true;
}
return false;
}
}
}
|
package battlecode.common {
public class RobotType {
public static const ARCHON:String = "ARCHON";
public static const SCOUT:String = "SCOUT";
public static const SOLDIER:String = "SOLDIER";
public static const GUARD:String = "GUARD";
public static const VIPER:String = "VIPER";
public static const TURRET:String = "TURRET";
public static const TTM:String = "TTM";
public static const ZOMBIEDEN:String = "ZOMBIEDEN";
public static const STANDARDZOMBIE:String = "STANDARDZOMBIE";
public static const FASTZOMBIE:String = "FASTZOMBIE";
public static const RANGEDZOMBIE:String = "RANGEDZOMBIE";
public static const BIGZOMBIE:String = "BIGZOMBIE";
public function RobotType() {
}
public static function values():Array {
return [
ARCHON,
SCOUT,
SOLDIER,
GUARD,
VIPER,
TURRET,
TTM,
ZOMBIEDEN,
STANDARDZOMBIE,
FASTZOMBIE,
RANGEDZOMBIE,
BIGZOMBIE
];
}
public static function units():Array {
return [
SOLDIER,
GUARD,
VIPER,
SCOUT,
TURRET,
TTM
];
}
public static function zombies():Array {
return [
ZOMBIEDEN,
STANDARDZOMBIE,
FASTZOMBIE,
RANGEDZOMBIE,
BIGZOMBIE
]
}
public static function maxEnergon(type:String):Number {
switch (type) {
case ARCHON:
return 1000;
case SCOUT:
return 80;
case SOLDIER:
return 60;
case GUARD:
return 145;
case VIPER:
return 120;
case TURRET:
return 100;
case TTM:
return 100;
case ZOMBIEDEN:
return 2000;
case STANDARDZOMBIE:
return 60;
case RANGEDZOMBIE:
return 60;
case FASTZOMBIE:
return 80;
case BIGZOMBIE:
return 500;
}
throw new ArgumentError("Unknown type: " + type);
}
public static function movementDelay(type:String):Number {
switch (type) {
case ARCHON:
return 2;
case SCOUT:
return 1.4;
case SOLDIER:
return 2;
case GUARD:
return 2;
case VIPER:
return 2;
case TURRET:
return 0;
case TTM:
return 2;
case STANDARDZOMBIE:
return 3;
case RANGEDZOMBIE:
return 3;
case FASTZOMBIE:
return 1.4;
case BIGZOMBIE:
return 3;
}
return 1;
}
public static function movementDelayDiagonal(type:String):uint {
return movementDelay(type) * Math.SQRT2;
}
public static function attackDelay(type:String):Number {
switch (type) {
case ARCHON:
return 2;
case SCOUT:
return 1;
case SOLDIER:
return 2;
case GUARD:
return 2;
case VIPER:
return 2;
case TURRET:
return 0;
case TTM:
return 2;
case STANDARDZOMBIE:
return 2;
case RANGEDZOMBIE:
return 1;
case FASTZOMBIE:
return 1;
case BIGZOMBIE:
return 3;
}
return 0;
}
public static function partValue(type:String):Number {
switch (type) {
case ARCHON:
return 0;
case SCOUT:
return 25;
case SOLDIER:
return 30;
case GUARD:
return 30;
case VIPER:
return 120;
case TURRET:
return 130;
case TTM:
return 130;
default:
return 0;
}
}
public static function isZombie(type:String):Boolean {
switch (type) {
case ZOMBIEDEN:
case STANDARDZOMBIE:
case FASTZOMBIE:
case RANGEDZOMBIE:
case BIGZOMBIE:
return true;
}
return false;
}
}
}
|
update robot type constants
|
update robot type constants
|
ActionScript
|
mit
|
trun/battlecode-webclient
|
b75123478d47fa39a8956153bb581c05e281c1a0
|
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;
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));
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 = 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;
}
}
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.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 = 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");
}
}
}
|
Set initial stream to be played to first entry in M3U8 playlist
|
Set initial stream to be played to first entry in M3U8 playlist
According to HLS especficiation we should play initially the first item
in the m3u8 playlist:
"The first entry in the variant playlist is played when a user joins
the stream and is used as part of a test to determine which stream is
most appropriate. The order of the other entries is irrelevant."
from:
https://developer.apple.com/library/mac/documentation/networkinginternet
/conceptual/streamingmediaguide/UsingHTTPLiveStreaming/UsingHTTPLiveStre
aming.html#//apple_ref/doc/uid/TP40008332-CH102-SW18
|
ActionScript
|
isc
|
mruse/osmf-hls-plugin,denivip/osmf-hls-plugin,denivip/osmf-hls-plugin,mruse/osmf-hls-plugin
|
d335d2b85e1d8d21ac3b5d1963ac3a7ab16dfe95
|
Game/Resources/elevatorScene/Scripts/elevator_frontDoorCon.as
|
Game/Resources/elevatorScene/Scripts/elevator_frontDoorCon.as
|
class elevator_frontDoorCon {
Hub @hub;
Entity @doorWithX;
Entity @doorWithService;
Entity @puzzleBoard;
bool openDoor;
vec3 tempPosWithX;
vec3 tempPosWithService;
float boardPitch;
float speed;
float uniformScale;
elevator_frontDoorCon(Entity @entity){
@hub = Managers();
@doorWithX = GetEntityByGUID(1511870049);
@doorWithService = GetEntityByGUID(1511870278);
@puzzleBoard = GetEntityByGUID(1512029307);
openDoor = false;
speed = 0.5f;
uniformScale = 0;
// Remove this if updates are not desired.
RegisterUpdate();
}
// Called by the engine for each frame.
void Update(float deltaTime) {
if(openDoor == true) {
if(tempPosWithX.z < 2.0f) {
tempPosWithX = doorWithX.GetWorldPosition();
tempPosWithService = doorWithService.GetWorldPosition();
tempPosWithX.z -= speed * deltaTime;
tempPosWithService.z += speed * deltaTime;
doorWithX.SetWorldPosition(tempPosWithX);
doorWithService.SetWorldPosition(tempPosWithService);
}
uniformScale += (1.0f / 3.5f) * deltaTime;
if (uniformScale > 1.0f) {
uniformScale = 1.0f;
}
puzzleBoard.scale = vec3(uniformScale, uniformScale, uniformScale);
}
if(openDoor == false) {
if(tempPosWithX.z > 0.0f) {
tempPosWithX = doorWithX.GetWorldPosition();
tempPosWithService = doorWithService.GetWorldPosition();
tempPosWithX.z += speed * deltaTime;
tempPosWithService.z -= speed * deltaTime;
doorWithX.SetWorldPosition(tempPosWithX);
doorWithService.SetWorldPosition(tempPosWithService);
}
}
}
void OpenDoor() {
openDoor = true;
doorWithX.GetSoundSource().Play();
doorWithService.GetSoundSource().Play();
}
void CloseDoor() {
openDoor = false;
}
}
|
class elevator_frontDoorCon {
Hub @hub;
Entity @doorWithX;
Entity @doorWithService;
Entity @puzzleBoard;
bool openDoor;
vec3 tempPosWithX;
vec3 tempPosWithService;
float boardPitch;
float speed;
float uniformScale;
elevator_frontDoorCon(Entity @entity){
@hub = Managers();
@doorWithX = GetEntityByGUID(1511870049);
@doorWithService = GetEntityByGUID(1511870278);
@puzzleBoard = GetEntityByGUID(1512029307);
openDoor = false;
speed = 0.5f;
uniformScale = 0;
// Remove this if updates are not desired.
RegisterUpdate();
}
// Called by the engine for each frame.
void Update(float deltaTime) {
if(openDoor == true) {
if(tempPosWithX.z < 2.0f) {
tempPosWithX = doorWithX.GetWorldPosition();
tempPosWithService = doorWithService.GetWorldPosition();
tempPosWithX.z -= speed * deltaTime;
tempPosWithService.z += speed * deltaTime;
doorWithX.SetWorldPosition(tempPosWithX);
doorWithService.SetWorldPosition(tempPosWithService);
}
uniformScale += (1.0f / 3.5f) * deltaTime;
if (uniformScale > 1.0f) {
uniformScale = 1.0f;
}
puzzleBoard.scale = vec3(uniformScale, uniformScale, uniformScale);
}
if(openDoor == false) {
if(tempPosWithX.z > 0.0f) {
tempPosWithX = doorWithX.GetWorldPosition();
tempPosWithService = doorWithService.GetWorldPosition();
tempPosWithX.z += speed * deltaTime;
tempPosWithService.z -= speed * deltaTime;
doorWithX.SetWorldPosition(tempPosWithX);
doorWithService.SetWorldPosition(tempPosWithService);
}
}
}
void OpenDoor() {
openDoor = true;
doorWithX.GetSoundSource().Play();
doorWithService.GetSoundSource().Play();
}
void CloseDoor() {
openDoor = false;
}
}
|
Replace tabs with spaces.
|
Replace tabs with spaces.
|
ActionScript
|
mit
|
Chainsawkitten/LargeGameProjectEngine,Chainsawkitten/LargeGameProjectEngine
|
3b57e7ff76159ae7c799707131f6aea0980c0b45
|
src/aerys/minko/render/shader/part/phong/attenuation/PCFShadowMapAttenuationShaderPart.as
|
src/aerys/minko/render/shader/part/phong/attenuation/PCFShadowMapAttenuationShaderPart.as
|
package aerys.minko.render.shader.part.phong.attenuation
{
import aerys.minko.render.material.phong.PhongProperties;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.part.phong.LightAwareShaderPart;
import aerys.minko.render.shader.part.phong.depth.LinearDepthFromLightShaderPart;
import aerys.minko.scene.node.light.PointLight;
import aerys.minko.type.enum.SamplerDimension;
import aerys.minko.type.enum.SamplerFiltering;
import aerys.minko.type.enum.SamplerMipMapping;
import aerys.minko.type.enum.SamplerWrapping;
import aerys.minko.type.enum.ShadowMappingQuality;
/**
* Fixme, bias should be:Total bias is m*SLOPESCALE + DEPTHBIAS
* Where m = max( | ∂z/∂x | , | ∂z/∂y | )
* ftp://download.nvidia.com/developer/presentations/2004/GPU_Jackpot/Shadow_Mapping.pdf
*
* @author Romain Gilliotte
*/
public class PCFShadowMapAttenuationShaderPart extends LightAwareShaderPart implements IAttenuationShaderPart
{
private var _depthShaderPart : LinearDepthFromLightShaderPart;
public function PCFShadowMapAttenuationShaderPart(main : Shader)
{
super(main);
_depthShaderPart = new LinearDepthFromLightShaderPart(main);
}
public function getAttenuation(lightId : uint) : SFloat
{
// retrieve shadow bias
var shadowBias : SFloat;
if (meshBindings.propertyExists(PhongProperties.SHADOW_BIAS))
shadowBias = meshBindings.getParameter(PhongProperties.SHADOW_BIAS, 1);
else
shadowBias = getLightParameter(lightId, PhongProperties.SHADOW_BIAS, 1);
// retrieve depthmap matrix
var lightType : uint = getLightProperty(lightId, 'type');
var depthMap : SFloat = getLightTextureParameter(
lightId,
'shadowMap',
SamplerFiltering.NEAREST,
SamplerMipMapping.DISABLE,
SamplerWrapping.CLAMP,
lightType == PointLight.LIGHT_TYPE ? SamplerDimension.CUBE : SamplerDimension.FLAT
);
var fsWorldPosition : SFloat = interpolate(vsWorldPosition);
var uv : SFloat = _depthShaderPart.getUV(lightId, fsWorldPosition);
var currentDepth : SFloat = _depthShaderPart.getDepthForAttenuation(lightId, fsWorldPosition);
var precomputedDepth : SFloat = unpack(sampleTexture(depthMap, uv));
var curDepthSubBias : SFloat = min(subtract(1, shadowBias), currentDepth);
var noShadows : SFloat = lessEqual(curDepthSubBias, add(shadowBias, precomputedDepth));
if (lightType == PointLight.LIGHT_TYPE)
return noShadows;
var quality : uint = getLightProperty(lightId, 'shadowQuality');
if (quality != ShadowMappingQuality.HARD)
{
var invertSize : SFloat = divide(
getLightParameter(lightId, 'shadowSpread', 1),
getLightParameter(lightId, 'shadowMapSize', 1)
);
var uvs : Vector.<SFloat> = new <SFloat>[];
var uvDelta : SFloat;
if (quality > ShadowMappingQuality.LOW)
{
uvDelta = multiply(float3(-1, 0, 1), invertSize);
uvs.push(
add(uv.xyxy, uvDelta.xxxy), // (-1, -1), (-1, 0)
add(uv.xyxy, uvDelta.xzyx), // (-1, 1), ( 0, -1)
add(uv.xyxy, uvDelta.yzzx), // ( 0, 1), ( 1, -1)
add(uv.xyxy, uvDelta.zyzz) // ( 1, 0), ( 1, 1)
);
}
if (quality > ShadowMappingQuality.MEDIUM)
{
uvDelta = multiply(float3(-2, 0, 2), invertSize);
uvs.push(
add(uv.xyxy, uvDelta.xyyx), // (-2, 0), (0, -2)
add(uv.xyxy, uvDelta.yzzy) // ( 0, 2), (2, 0)
);
}
if (quality > ShadowMappingQuality.HARD)
{
uvDelta = multiply(float4(-2, -1, 1, 2), invertSize);
uvs.push(
add(uv.xyxy, uvDelta.xzyw), // (-2, 1), (-1, 2)
add(uv.xyxy, uvDelta.zwwz), // ( 1, 2), ( 2, 1)
add(uv.xyxy, uvDelta.wyzx), // ( 2, -1), ( 1, -2)
add(uv.xyxy, uvDelta.xyyx) // (-2, -1), (-1, -2)
);
}
var numSamples : uint = uvs.length;
for (var sampleId : uint = 0; sampleId < numSamples; sampleId += 2)
{
precomputedDepth = float4(
unpack(sampleTexture(depthMap, uvs[sampleId].xy)),
unpack(sampleTexture(depthMap, uvs[sampleId].zw)),
unpack(sampleTexture(depthMap, uvs[sampleId + 1].xy)),
unpack(sampleTexture(depthMap, uvs[sampleId + 1].zw))
);
var localNoShadows : SFloat = lessEqual(curDepthSubBias, add(shadowBias, precomputedDepth));
noShadows.incrementBy(dotProduct4(localNoShadows, float4(1, 1, 1, 1)));
}
noShadows.scaleBy(1 / (2 * numSamples + 1));
}
//return noShadows.x;
var insideShadow : SFloat = multiply(multiply(lessThan(uv.x, 1), greaterThan(uv.x, 0)), multiply(lessThan(uv.y, 1), greaterThan(uv.y, 0)));
var outsideShadow : SFloat = subtract(1, insideShadow);
return add(multiply(noShadows.x, insideShadow), outsideShadow);
}
}
}
|
package aerys.minko.render.shader.part.phong.attenuation
{
import aerys.minko.render.material.phong.PhongProperties;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.part.phong.LightAwareShaderPart;
import aerys.minko.render.shader.part.phong.depth.LinearDepthFromLightShaderPart;
import aerys.minko.scene.node.light.PointLight;
import aerys.minko.type.enum.SamplerDimension;
import aerys.minko.type.enum.SamplerFiltering;
import aerys.minko.type.enum.SamplerMipMapping;
import aerys.minko.type.enum.SamplerWrapping;
import aerys.minko.type.enum.ShadowMappingQuality;
/**
* Fixme, bias should be:Total bias is m*SLOPESCALE + DEPTHBIAS
* Where m = max( | ∂z/∂x | , | ∂z/∂y | )
* ftp://download.nvidia.com/developer/presentations/2004/GPU_Jackpot/Shadow_Mapping.pdf
*
* @author Romain Gilliotte
*/
public class PCFShadowMapAttenuationShaderPart extends LightAwareShaderPart implements IAttenuationShaderPart
{
private var _depthShaderPart : LinearDepthFromLightShaderPart;
public function PCFShadowMapAttenuationShaderPart(main : Shader)
{
super(main);
_depthShaderPart = new LinearDepthFromLightShaderPart(main);
}
public function getAttenuation(lightId : uint) : SFloat
{
// retrieve shadow bias
var shadowBias : SFloat;
if (meshBindings.propertyExists(PhongProperties.SHADOW_BIAS))
shadowBias = meshBindings.getParameter(PhongProperties.SHADOW_BIAS, 1);
else
shadowBias = getLightParameter(lightId, PhongProperties.SHADOW_BIAS, 1);
// retrieve depthmap matrix
var lightType : uint = getLightProperty(lightId, 'type');
var depthMap : SFloat = getLightTextureParameter(
lightId,
'shadowMap',
SamplerFiltering.NEAREST,
SamplerMipMapping.DISABLE,
SamplerWrapping.CLAMP,
lightType == PointLight.LIGHT_TYPE ? SamplerDimension.CUBE : SamplerDimension.FLAT
);
var fsWorldPosition : SFloat = interpolate(vsWorldPosition);
var uv : SFloat = _depthShaderPart.getUV(lightId, fsWorldPosition);
var currentDepth : SFloat = _depthShaderPart.getDepthForAttenuation(lightId, fsWorldPosition);
var precomputedDepth : SFloat = unpack(sampleTexture(depthMap, uv));
var curDepthSubBias : SFloat = min(subtract(1, shadowBias), currentDepth);
var noShadows : SFloat = lessEqual(curDepthSubBias, add(shadowBias, precomputedDepth));
if (lightType == PointLight.LIGHT_TYPE)
return noShadows;
var quality : uint = getLightProperty(lightId, 'shadowQuality');
if (quality != ShadowMappingQuality.HARD)
{
var invertSize : SFloat = divide(
getLightParameter(lightId, 'shadowSpread', 1),
getLightParameter(lightId, 'shadowMapSize', 1)
);
var uvs : Vector.<SFloat> = new <SFloat>[];
var uvDelta : SFloat;
if (quality > ShadowMappingQuality.LOW)
{
uvDelta = multiply(float3(-1, 0, 1), invertSize);
uvs.push(
add(uv.xyxy, uvDelta.xxxy), // (-1, -1), (-1, 0)
add(uv.xyxy, uvDelta.xzyx), // (-1, 1), ( 0, -1)
add(uv.xyxy, uvDelta.yzzx), // ( 0, 1), ( 1, -1)
add(uv.xyxy, uvDelta.zyzz) // ( 1, 0), ( 1, 1)
);
}
if (quality > ShadowMappingQuality.MEDIUM)
{
uvDelta = multiply(float3(-2, 0, 2), invertSize);
uvs.push(
add(uv.xyxy, uvDelta.xyyx), // (-2, 0), (0, -2)
add(uv.xyxy, uvDelta.yzzy) // ( 0, 2), (2, 0)
);
}
if (quality > ShadowMappingQuality.HARD)
{
uvDelta = multiply(float4(-2, -1, 1, 2), invertSize);
uvs.push(
add(uv.xyxy, uvDelta.xzyw), // (-2, 1), (-1, 2)
add(uv.xyxy, uvDelta.zwwz), // ( 1, 2), ( 2, 1)
add(uv.xyxy, uvDelta.wyzx), // ( 2, -1), ( 1, -2)
add(uv.xyxy, uvDelta.xyyx) // (-2, -1), (-1, -2)
);
}
var numSamples : uint = uvs.length;
for (var sampleId : uint = 0; sampleId < numSamples; sampleId += 2)
{
precomputedDepth = float4(
unpack(sampleTexture(depthMap, uvs[sampleId].xy)),
unpack(sampleTexture(depthMap, uvs[sampleId].zw)),
unpack(sampleTexture(depthMap, uvs[sampleId + 1].xy)),
unpack(sampleTexture(depthMap, uvs[sampleId + 1].zw))
);
var localNoShadows : SFloat = lessEqual(curDepthSubBias, add(shadowBias, precomputedDepth));
noShadows.incrementBy(dotProduct4(localNoShadows, float4(1, 1, 1, 1)));
}
noShadows.scaleBy(1 / (2 * numSamples + 1));
}
var insideShadow : SFloat = multiply(multiply(lessThan(uv.x, 1), greaterThan(uv.x, 0)), multiply(lessThan(uv.y, 1), greaterThan(uv.y, 0)));
var outsideShadow : SFloat = subtract(1, insideShadow);
return add(multiply(noShadows.x, insideShadow), outsideShadow);
}
}
}
|
Remove comments
|
Remove comments
|
ActionScript
|
mit
|
aerys/minko-as3
|
e9436b6920aa99d4c433f2ecf02a0b07d691c22f
|
as/form/frame2.as
|
as/form/frame2.as
|
#include "includes/idiomes.as"
//Segonquart Studio 2007. Steal it with respect , honey ;-)
//-------------------------------
//Imports
//-------------------------------
import System.Objects.*;
import flash.filters.GlowFilter;
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
//Thanks Moses...and respect ;-)
//-------------------------------
ZigoEngine.simpleSetup (Shortcuts, PennerEasing);
ZigoEngine.register (PennerEasing, Shortcuts, FuseFMP, FuseItem);
Stage.scaleMode = "noScale";
//-------------------------------
//Variables
//-------------------------------
var m03:MovieClip;
var o3:MovieClip;
var cp:TextField;
/*Form */
var formulari_mc:MovieClip;
/*Inputs Fields */
var cp:MovieClip;
/*Button */
var ok_mc:MovieClip;
var gf:GlowFilter = new GlowFilter (0xBEE47E, 100, 3, 3, 5, 3, false, false);
function initialState ():Void
{
this.m03.alphaTo (100, 2.2, "easeOutBounce");
this.m03._brightOffset = 100;
this.m03.brightOffsetTo (0, 1, 'easeInBack', .2);
this.m03.o3.tw.alphaTo (100, 2, "easeOutQuad", 2.3);
this.m03.o3.tw._scale = 40;
this.m03.o3.tw.scaleTo (100, 1, 'easeOutElastic');
this.ok_mc._visible = true;
this.ok_mc.filters = [gf];
this.ok_mc._alphaTo (100, 1, "linear");
this.ok_mc._scale = 20;
this.ok_mc.scaleTo (25, 1, "easeInOutBounce");
}
function transformElementsUI ():Void{
this.onRollOver = this.pOver;
this.onRollOut = this.pOut;
this.onPress =this.pPress;
}
function pPress():Void{
ok_mc.fadeOut ();
_parent.formulari_mc.slideTo (600, '0', "easeInOutBack");
_parent.contact_txt._visible = false;
_parent.mail_txt._visible = false;
};
function pOver():Void{
addEventListener (this, "onPress");
ok_mc.scaleTo (60, 2, 'easeOutBounce');
ok_mc.onEnterFrame = function ():Void
{
if (gf.blurX < 20)
{
gf.blurX++;
gf.blurY++;
}
else
{
delete this.onEnterFrame;
}
this.filters = [gf];
};
};
function pOut():Void{
ok_mc.onEnterFrame = function ()
{
this.filters = [gf];
if (gf.blurX > 3)
{
gf.blurX--;
gf.blurY--;
}
else
{
delete this.onEnterFrame;
}
};
};
initialState();
transformElementsUI();
stop();
|
#include "includes/idiomes.as"
//Segonquart Studio 2007. Steal it with respect , honey ;-)
//-------------------------------
//Imports
//-------------------------------
import System.Objects.*;
import flash.filters.GlowFilter;
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
//Thanks Moses...and respect ;-)
//-------------------------------
ZigoEngine.simpleSetup (Shortcuts, PennerEasing);
ZigoEngine.register (PennerEasing, Shortcuts, FuseFMP, FuseItem);
Stage.scaleMode = "noScale";
//-------------------------------
//Variables
//-------------------------------
var m03:MovieClip;
var o3:MovieClip;
var cp:TextField;
/*Form */
var formulari_mc:MovieClip;
/*Inputs Fields */
var cp:MovieClip;
/*Button */
var ok_mc:MovieClip;
var gf:GlowFilter = new GlowFilter (0xBEE47E, 100, 3, 3, 5, 3, false, false);
function initialState ():Void
{
this.m03.alphaTo (100, 2.2, "easeOutBounce");
this.m03._brightOffset = 100;
this.m03.brightOffsetTo (0, 1, 'easeInBack', .2);
this.m03.o3.tw.alphaTo (100, 2, "easeOutQuad", 2.3);
this.m03.o3.tw._scale = 40;
this.m03.o3.tw.scaleTo (100, 1, 'easeOutElastic');
this.ok_mc._visible = true;
this.ok_mc.filters = [gf];
this.ok_mc._alphaTo (100, 1, "linear");
this.ok_mc._scale = 20;
this.ok_mc.scaleTo (25, 1, "easeInOutBounce");
}
function transformElementsUI ():Void{
this.onRollOver = this.pOver;
this.onRollOut = this.pOut;
this.onPress =this.pPress;
}
function pPress():Void{
ok_mc.fadeOut ();
_parent.formulari_mc.slideTo (600, '0', "easeInOutBack");
_parent.contact_txt._visible = false;
_parent.mail_txt._visible = false;
};
function pOver():Void{
addEventListener (this, "onPress");
ok_mc.scaleTo (60, 2, 'easeOutBounce');
ok_mc.onEnterFrame = function ():Void
{
if (gf.blurX < 20)
{
gf.blurX++;
gf.blurY++;
}
else
{
delete this.onEnterFrame;
}
this.filters = [gf];
};
};
function pOut():Void{
ok_mc.onEnterFrame = function ()
{
this.filters = [gf];
if (gf.blurX > 3)
{
gf.blurX--;
gf.blurY--;
}
else
{
delete this.onEnterFrame;
}
};
};
initialState();
transformElementsUI();
stop();
|
Update frame2.as
|
Update frame2.as
|
ActionScript
|
bsd-3-clause
|
delfiramirez/web-talking-wear,delfiramirez/web-talking-wear,delfiramirez/web-talking-wear
|
1679fcbf2e861e8c90d51bab35293dd317e3ae04
|
src/com/google/analytics/core/DomainNameMode.as
|
src/com/google/analytics/core/DomainNameMode.as
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
* Marc Alcaraz <[email protected]>.
*/
package com.google.analytics.core
{
/**
* The domain name mode enumeration class.
*/
public class DomainNameMode
{
/**
* @private
*/
private var _value:int;
/**
* @private
*/
private var _name:String;
/**
* Creates a new DomainNameMode instance.
* @param value The enumeration value representation.
* @param name The enumeration name representation.
*/
public function DomainNameMode( value:int = 0, name:String = "" )
{
_value = value;
_name = name;
}
/**
* Returns the primitive value of the object.
* @return the primitive value of the object.
*/
public function valueOf():int
{
return _value;
}
/**
* Returns the String representation of the object.
* @return the String representation of the object.
*/
public function toString():String
{
return _name;
}
/**
* Determinates the "none" DomainNameMode value.
* <p>"none" is used in the following two situations :</p>
* <p>- You want to disable tracking across hosts.</p>
* <p>- You want to set up tracking across two separate domains.</p>
* <p>Cross- domain tracking requires configuration of the setAllowLinker() and link() methods.</p>
*/
public static const none:DomainNameMode = new DomainNameMode( 0, "none" );
/**
* Attempts to automaticaly resolve the domain name.
*/
public static const auto:DomainNameMode = new DomainNameMode( 1, "auto" );
/**
* Custom is used to set explicitly to your domain name if your website spans multiple hostnames,
* and you want to track visitor behavior across all hosts.
* <p>For example, if you have two hosts : <code>server1.example.com</code> and <code>server2.example.com</code>,
* you would set the domain name as follows :
* <pre class="prettyprint">
* pageTracker.setDomainName( new Domain( DomainName.custom, ".example.com" ) ) ;
* </p>
*/
public static const custom:DomainNameMode = new DomainNameMode( 2, "custom" );
}
}
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
* Marc Alcaraz <[email protected]>.
*/
package com.google.analytics.core
{
/**
* The domain name mode enumeration class.
*/
public class DomainNameMode
{
/**
* @private
*/
private var _value:int;
/**
* @private
*/
private var _name:String;
/**
* Creates a new DomainNameMode instance.
* @param value The enumeration value representation.
* @param name The enumeration name representation.
*/
public function DomainNameMode( value:int = 0, name:String = "" )
{
_value = value;
_name = name;
}
/**
* Returns the primitive value of the object.
* @return the primitive value of the object.
*/
public function valueOf():int
{
return _value;
}
/**
* Returns the String representation of the object.
* @return the String representation of the object.
*/
public function toString():String
{
return _name;
}
/**
* Determinates the "none" DomainNameMode value.
* <p>"none" is used in the following two situations :</p>
* <p>- You want to disable tracking across hosts.</p>
* <p>- You want to set up tracking across two separate domains.</p>
* <p>Cross- domain tracking requires configuration of the setAllowLinker() and link() methods.</p>
*/
public static const none:DomainNameMode = new DomainNameMode( 0, "none" );
/**
* Attempts to automaticaly resolve the domain name.
*/
public static const auto:DomainNameMode = new DomainNameMode( 1, "auto" );
/**
* Custom is used to set explicitly to your domain name if your website spans multiple hostnames,
* and you want to track visitor behavior across all hosts.
* <p>For example, if you have two hosts : <code>server1.example.com</code> and <code>server2.example.com</code>,
* you would set the domain name as follows : </p>
* <pre class="prettyprint">
* pageTracker.setDomainName( new Domain( DomainName.custom, ".example.com" ) ) ;
* </pre>
*/
public static const custom:DomainNameMode = new DomainNameMode( 2, "custom" );
}
}
|
fix asdoc comment again
|
fix asdoc comment again
|
ActionScript
|
apache-2.0
|
jisobkim/gaforflash,Vigmar/gaforflash,jeremy-wischusen/gaforflash,Vigmar/gaforflash,dli-iclinic/gaforflash,dli-iclinic/gaforflash,DimaBaliakin/gaforflash,soumavachakraborty/gaforflash,drflash/gaforflash,Miyaru/gaforflash,mrthuanvn/gaforflash,drflash/gaforflash,mrthuanvn/gaforflash,jeremy-wischusen/gaforflash,jisobkim/gaforflash,Miyaru/gaforflash,DimaBaliakin/gaforflash,soumavachakraborty/gaforflash
|
f2c4ad858192adcf4f60da8e65fb756531e7b437
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/controllers/DropMouseController.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/controllers/DropMouseController.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.controllers
{
import flash.display.DisplayObject;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IDragInitiator;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.UIBase;
import org.apache.flex.events.DragEvent;
import org.apache.flex.events.EventDispatcher;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.events.MouseEvent;
/**
* Indicates that the mouse has entered the component during
* a drag operatino.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="dragEnter", type="org.apache.flex.events.DragEvent")]
/**
* Indicates that the mouse is moving over a component during
* a drag/drop operation.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="dragOver", type="org.apache.flex.events.DragEvent")]
/**
* Indicates that a drop operation should be executed.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="dragDrop", type="org.apache.flex.events.DragEvent")]
/**
* The DropMouseController bead handles mouse events on the
* a component, looking for events from a drag/drop operation.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class DropMouseController extends EventDispatcher implements IBead
{
/**
* constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function DropMouseController()
{
}
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(_strand).addEventListener(DragEvent.DRAG_MOVE, dragMoveHandler);
}
public function get strand():IStrand
{
return _strand;
}
private var inside:Boolean;
private var dragSource:Object;
private var dragInitiator:IDragInitiator;
public function acceptDragDrop(target:IUIBase, type:String):void
{
// TODO: aharui: switch icons
}
/**
* @private
*/
private function dragMoveHandler(event:DragEvent):void
{
trace("dragMove");
var dragEvent:DragEvent;
if (!inside)
{
dragEvent = new DragEvent("dragEnter", true, true);
dragEvent.copyMouseEventProperties(event);
dragSource = dragEvent.dragSource = event.dragSource;
dragInitiator = dragEvent.dragInitiator = event.dragInitiator;
dispatchEvent(dragEvent);
inside = true;
DisplayObject(_strand).stage.addEventListener(DragEvent.DRAG_END, dragEndHandler);
DisplayObject(_strand).addEventListener(MouseEvent.ROLL_OUT, rollOutHandler);
}
else
{
dragEvent = new DragEvent("dragOver", true, true);
dragEvent.copyMouseEventProperties(event);
dragEvent.dragSource = event.dragSource;
dragEvent.dragInitiator = event.dragInitiator;
IEventDispatcher(_strand).dispatchEvent(dragEvent);
}
}
private function rollOutHandler(event:MouseEvent):void
{
var dragEvent:DragEvent;
if (inside)
{
dragEvent = new DragEvent("dragExit", true, true);
dragEvent.copyMouseEventProperties(event);
dragEvent.dragSource = dragSource;
dragEvent.dragInitiator = dragInitiator;
dragSource = null;
dragInitiator = null;
event.stopImmediatePropagation();
dispatchEvent(dragEvent);
inside = false;
}
DisplayObject(_strand).stage.removeEventListener(DragEvent.DRAG_END, dragEndHandler);
DisplayObject(_strand).removeEventListener(MouseEvent.ROLL_OUT, rollOutHandler);
}
private function dragEndHandler(event:DragEvent):void
{
trace("dragEnd");
var dragEvent:DragEvent;
dragEvent = new DragEvent("dragDrop", true, true);
dragEvent.copyMouseEventProperties(event);
dragEvent.dragSource = event.dragSource;
dragEvent.dragInitiator = event.dragInitiator;
dragSource = null;
dragInitiator = null;
event.stopImmediatePropagation();
dispatchEvent(dragEvent);
DisplayObject(_strand).stage.removeEventListener(DragEvent.DRAG_END, dragEndHandler);
DisplayObject(_strand).removeEventListener(MouseEvent.ROLL_OUT, rollOutHandler);
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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.controllers
{
import flash.display.DisplayObject;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IDragInitiator;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.UIBase;
import org.apache.flex.events.DragEvent;
import org.apache.flex.events.EventDispatcher;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.events.MouseEvent;
/**
* Indicates that the mouse has entered the component during
* a drag operatino.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="dragEnter", type="org.apache.flex.events.DragEvent")]
/**
* Indicates that the mouse is moving over a component during
* a drag/drop operation.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="dragOver", type="org.apache.flex.events.DragEvent")]
/**
* Indicates that a drop operation should be executed.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="dragDrop", type="org.apache.flex.events.DragEvent")]
/**
* The DropMouseController bead handles mouse events on the
* a component, looking for events from a drag/drop operation.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class DropMouseController extends EventDispatcher implements IBead
{
/**
* constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function DropMouseController()
{
}
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(_strand).addEventListener(DragEvent.DRAG_MOVE, dragMoveHandler);
}
public function get strand():IStrand
{
return _strand;
}
private var inside:Boolean;
private var dragSource:Object;
private var dragInitiator:IDragInitiator;
public function acceptDragDrop(target:IUIBase, type:String):void
{
// TODO: aharui: switch icons
}
/**
* @private
*/
private function dragMoveHandler(event:DragEvent):void
{
trace("dragMove");
var dragEvent:DragEvent;
if (!inside)
{
dragEvent = new DragEvent("dragEnter", true, true);
dragEvent.copyMouseEventProperties(event);
dragSource = dragEvent.dragSource = event.dragSource;
dragInitiator = dragEvent.dragInitiator = event.dragInitiator;
dispatchEvent(dragEvent);
inside = true;
DisplayObject(_strand).stage.addEventListener(DragEvent.DRAG_END, dragEndHandler);
DisplayObject(_strand).addEventListener(MouseEvent.ROLL_OUT, rollOutHandler);
}
else
{
dragEvent = new DragEvent("dragOver", true, true);
dragEvent.copyMouseEventProperties(event);
dragEvent.dragSource = event.dragSource;
dragEvent.dragInitiator = event.dragInitiator;
IEventDispatcher(_strand).dispatchEvent(dragEvent);
}
}
private function rollOutHandler(event:MouseEvent):void
{
var dragEvent:DragEvent;
if (inside)
{
dragEvent = new DragEvent("dragExit", true, true);
dragEvent.copyMouseEventProperties(event);
dragEvent.dragSource = dragSource;
dragEvent.dragInitiator = dragInitiator;
dragSource = null;
dragInitiator = null;
event.stopImmediatePropagation();
dispatchEvent(dragEvent);
inside = false;
}
DisplayObject(_strand).stage.removeEventListener(DragEvent.DRAG_END, dragEndHandler);
DisplayObject(_strand).removeEventListener(MouseEvent.ROLL_OUT, rollOutHandler);
}
private function dragEndHandler(event:DragEvent):void
{
trace("dragEnd");
var dragEvent:DragEvent;
dragEvent = new DragEvent("dragDrop", true, true);
dragEvent.copyMouseEventProperties(event);
dragEvent.dragSource = event.dragSource;
dragEvent.dragInitiator = event.dragInitiator;
dragSource = null;
dragInitiator = null;
event.stopImmediatePropagation();
dispatchEvent(dragEvent);
inside = false;
DisplayObject(_strand).stage.removeEventListener(DragEvent.DRAG_END, dragEndHandler);
DisplayObject(_strand).removeEventListener(MouseEvent.ROLL_OUT, rollOutHandler);
}
}
}
|
reset vars after drop
|
reset vars after drop
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
88d0994cf9b4341dd7cc9cb6796cf29fa97eed68
|
src/org/mangui/HLS/utils/AES.as
|
src/org/mangui/HLS/utils/AES.as
|
package org.mangui.HLS.utils {
import com.hurlant.crypto.symmetric.CBCMode;
import com.hurlant.crypto.symmetric.ICipher;
import com.hurlant.crypto.symmetric.IPad;
import com.hurlant.crypto.symmetric.IVMode;
import com.hurlant.crypto.symmetric.NullPad;
import com.hurlant.crypto.symmetric.PKCS5;
import flash.utils.ByteArray;
import flash.utils.Timer;
import flash.events.Event;
import flash.events.TimerEvent;
/**
* Contains Utility functions for Decryption
*/
public class AES
{
private var _key:FastAESKey;
private var _mode:ICipher;
private var _iv:ByteArray;
/* callback function upon read complete */
private var _callback:Function;
/** Timer for decrypting packets **/
private var _timer:Timer;
/** Byte data to be decrypt **/
private var _data:ByteArray;
/** Byte data to be decrypt **/
private var _decrypteddata:ByteArray;
/** read position **/
private var _read_position:Number;
/** chunk size to avoid blocking **/
private static const CHUNK_SIZE:uint = 2048;
/** is bytearray full ? **/
private var _data_complete:Boolean;
public function AES(key:ByteArray,iv:ByteArray) {
var pad:IPad = new PKCS5;
_key = new FastAESKey(key);
_mode = new CBCMode(_key, pad);
pad.setBlockSize(_mode.getBlockSize());
_iv = iv;
if (_mode is IVMode) {
var ivmode:IVMode = _mode as IVMode;
ivmode.IV = iv;
}
}
public function decrypt(data:ByteArray,callback:Function):void {
Log.debug("AES:async decrypt starting");
_data = data;
_data_complete = false;
_callback = callback;
_decrypteddata = new ByteArray();
_read_position = 0;
_timer = new Timer(0,0);
_timer.addEventListener(TimerEvent.TIMER, _decryptTimer);
_timer.start();
}
public function notifyappend():void {
//Log.info("notify append");
_timer.start();
}
public function notifycomplete():void {
//Log.info("notify complete");
_data_complete = true;
_timer.start();
}
public function cancel():void {
if(_timer) {
_timer.stop();
_timer = null;
}
}
private function _decryptTimer(e:Event):void {
var start_time:Number = new Date().getTime();
do {
_decryptData();
// dont spend more than 20 ms in the decrypt timer to avoid blocking/freezing video
} while (_timer.running && new Date().getTime() - start_time < 20);
}
/** decrypt a small chunk of packets each time to avoid blocking **/
private function _decryptData():void {
_data.position = _read_position;
if(_data.bytesAvailable) {
var dumpByteArray:ByteArray = new ByteArray();
var newIv:ByteArray;
var pad:IPad;
if(_data.bytesAvailable <= CHUNK_SIZE) {
if (_data_complete) {
//Log.info("data complete, last chunk");
pad = new PKCS5;
_read_position+=_data.bytesAvailable;
_data.readBytes(dumpByteArray,0,_data.bytesAvailable);
} else {
//Log.info("data not complete, stop timer");
// data not complete, and available data less than chunk size, stop timer and return
_timer.stop();
return;
}
} else { // bytesAvailable > CHUNK_SIZE
//Log.info("process chunk");
pad = new NullPad;
_read_position+=CHUNK_SIZE;
_data.readBytes(dumpByteArray,0,CHUNK_SIZE);
// Save new IV from ciphertext
newIv = new ByteArray();
dumpByteArray.position = (CHUNK_SIZE-16);
dumpByteArray.readBytes(newIv, 0, 16);
}
dumpByteArray.position = 0;
//Log.info("before decrypt");
_mode = new CBCMode(_key, pad);
pad.setBlockSize(_mode.getBlockSize());
(_mode as IVMode).IV = _iv;
_mode.decrypt(dumpByteArray);
//Log.info("after decrypt");
_decrypteddata.writeBytes(dumpByteArray);
// switch IV to new one in case more bytes are available
if(newIv) {
_iv = newIv;
}
} else {
//Log.info("no bytes available, stop timer");
_timer.stop();
if (_data_complete) {
Log.debug("AES:data+decrypt completed, callback");
// callback
_decrypteddata.position=0;
_callback(_decrypteddata);
}
}
}
public function destroy():void {
_key.dispose();
//_key = null;
_mode = null;
}
}
}
|
package org.mangui.HLS.utils {
import com.hurlant.crypto.symmetric.CBCMode;
import com.hurlant.crypto.symmetric.ICipher;
import com.hurlant.crypto.symmetric.IPad;
import com.hurlant.crypto.symmetric.IVMode;
import com.hurlant.crypto.symmetric.NullPad;
import com.hurlant.crypto.symmetric.PKCS5;
import flash.utils.ByteArray;
import flash.utils.Timer;
import flash.events.Event;
import flash.events.TimerEvent;
/**
* Contains Utility functions for Decryption
*/
public class AES
{
private var _key:FastAESKey;
private var _mode:ICipher;
private var _iv:ByteArray;
/* callback function upon read complete */
private var _callback:Function;
/** Timer for decrypting packets **/
private var _timer:Timer;
/** Byte data to be decrypt **/
private var _data:ByteArray;
/** Byte data to be decrypt **/
private var _decrypteddata:ByteArray;
/** read position **/
private var _read_position:uint;
/** chunk size to avoid blocking **/
private static const CHUNK_SIZE:uint = 2048;
/** is bytearray full ? **/
private var _data_complete:Boolean;
public function AES(key:ByteArray,iv:ByteArray) {
var pad:IPad = new PKCS5;
_key = new FastAESKey(key);
_mode = new CBCMode(_key, pad);
pad.setBlockSize(_mode.getBlockSize());
_iv = iv;
if (_mode is IVMode) {
var ivmode:IVMode = _mode as IVMode;
ivmode.IV = iv;
}
}
public function decrypt(data:ByteArray,callback:Function):void {
Log.debug("AES:async decrypt starting");
_data = data;
_data_complete = false;
_callback = callback;
_decrypteddata = new ByteArray();
_read_position = 0;
_timer = new Timer(0,0);
_timer.addEventListener(TimerEvent.TIMER, _decryptTimer);
_timer.start();
}
public function notifyappend():void {
//Log.info("notify append");
_timer.start();
}
public function notifycomplete():void {
//Log.info("notify complete");
_data_complete = true;
_timer.start();
}
public function cancel():void {
if(_timer) {
_timer.stop();
_timer = null;
}
}
private function _decryptTimer(e:Event):void {
var start_time:Number = new Date().getTime();
do {
_decryptData();
// dont spend more than 20 ms in the decrypt timer to avoid blocking/freezing video
} while (_timer.running && new Date().getTime() - start_time < 20);
}
/** decrypt a small chunk of packets each time to avoid blocking **/
private function _decryptData():void {
_data.position = _read_position;
if(_data.bytesAvailable) {
var dumpByteArray:ByteArray = new ByteArray();
var newIv:ByteArray;
var pad:IPad;
if(_data.bytesAvailable <= CHUNK_SIZE) {
if (_data_complete) {
//Log.info("data complete, last chunk");
pad = new PKCS5;
_read_position+=_data.bytesAvailable;
_data.readBytes(dumpByteArray,0,_data.bytesAvailable);
} else {
//Log.info("data not complete, stop timer");
// data not complete, and available data less than chunk size, stop timer and return
_timer.stop();
return;
}
} else { // bytesAvailable > CHUNK_SIZE
//Log.info("process chunk");
pad = new NullPad;
_read_position+=CHUNK_SIZE;
_data.readBytes(dumpByteArray,0,CHUNK_SIZE);
// Save new IV from ciphertext
newIv = new ByteArray();
dumpByteArray.position = (CHUNK_SIZE-16);
dumpByteArray.readBytes(newIv, 0, 16);
}
dumpByteArray.position = 0;
//Log.info("before decrypt");
_mode = new CBCMode(_key, pad);
pad.setBlockSize(_mode.getBlockSize());
(_mode as IVMode).IV = _iv;
_mode.decrypt(dumpByteArray);
//Log.info("after decrypt");
_decrypteddata.writeBytes(dumpByteArray);
// switch IV to new one in case more bytes are available
if(newIv) {
_iv = newIv;
}
} else {
//Log.info("no bytes available, stop timer");
_timer.stop();
if (_data_complete) {
Log.debug("AES:data+decrypt completed, callback");
// callback
_decrypteddata.position=0;
_callback(_decrypteddata);
}
}
}
public function destroy():void {
_key.dispose();
//_key = null;
_mode = null;
}
}
}
|
switch to uint
|
switch to uint
|
ActionScript
|
mpl-2.0
|
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
|
d46602fc8d3ead5c9bd54cbb4fa8bef621de8787
|
src/TestRunner.as
|
src/TestRunner.as
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
*/
package
{
import library.ASTUce.Runner;
import com.google.analytics.AllTests;
import flash.display.Sprite;
/* note:
Run the Google Analytics unit tests
*/
[SWF(width="400", height="400", backgroundColor='0xffffff', frameRate='24', pageTitle='testrunner', scriptRecursionLimit='1000', scriptTimeLimit='60')]
[ExcludeClass]
public class TestRunner extends Sprite
{
public function TestRunner()
{
Runner.main( com.google.analytics.AllTests.suite( ) );
}
}
}
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
*/
package
{
import library.ASTUce.Runner;
import com.google.analytics.AllTests;
import flash.display.Sprite;
/* note:
Run the Google Analytics unit tests
*/
[SWF(width="400", height="400", backgroundColor='0xffffff', frameRate='24', pageTitle='testrunner', scriptRecursionLimit='1000', scriptTimeLimit='60')]
[ExcludeClass]
public class TestRunner extends Sprite
{
public function TestRunner()
{
Runner.main( com.google.analytics.AllTests.suite( ) );
}
}
}
|
update comment
|
update comment
|
ActionScript
|
apache-2.0
|
nsdevaraj/gaforflash,minimedj/gaforflash,minimedj/gaforflash,nsdevaraj/gaforflash
|
38509245f7e08564f913f81f8776cdbe1291661e
|
tests/flashtest.as
|
tests/flashtest.as
|
package{
import flash.display.Sprite;
import flash.text.TextField;
import flash.utils.ByteArray;
[SWF(width="400", height="400")]
public class flashtest extends Sprite {
private var tf:TextField;
public function flashtest() {
tf = new TextField();
tf.width = tf.height = 400;
tf.wordWrap = true;
addChild(tf);
var b:ByteArray = new ByteArray();
var v:Vector.<int> = new Vector.<int>();
for(var z:int = 0; z < 3; ++z)
v.push(z);
b.writeObject(v);
dumpByteArray(b);
var data:Array = [
0x0d, 0x07, 0x00,
0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x02,
0x00, 0x00, 0x00, 0x03
];
b = createByteArray(data);
var o:* = b.readObject();
tf.appendText(o + "\n");
var a:Vector.<int> = o as Vector.<int>;
if(a != null) {
tf.appendText("Vector with " + a.length + " elements\n");
for(var j:int = 0; j < a.length; ++j)
tf.appendText(j + ": " + a[j] + "\n");
} else {
tf.appendText("Vector is null\n");
}
}
private function dumpByteArray(b:ByteArray):void {
b.position = 0;
tf.appendText(b.bytesAvailable + "\n");
var cnt:int = 0;
while(b.bytesAvailable) {
var c:String = b.readUnsignedByte().toString(16);
if(c.length < 2) c = "0" + c;
tf.appendText("0x" + c);
if (b.bytesAvailable == 0) break;
if (++cnt == 12) {
cnt = 0;
tf.appendText(",\n");
} else {
tf.appendText(", ");
}
}
tf.appendText("\n");
}
private function createByteArray(data:Array):ByteArray {
var b:ByteArray = new ByteArray();
for(var i:int = 0; i < data.length; ++i)
b.writeByte(data[i]);
b.position = 0;
return b;
}
}
}
|
package{
import flash.display.Sprite;
import flash.net.registerClassAlias;
import flash.text.TextField;
import flash.utils.ByteArray;
[SWF(width="400", height="400")]
public class flashtest extends Sprite {
private var tf:TextField;
public function flashtest() {
tf = new TextField();
tf.width = tf.height = 400;
tf.wordWrap = true;
addChild(tf);
dumpValues();
}
private function dumpValues():void {
tf.text = "";
var b:ByteArray = new ByteArray();
var a:Array = [undefined, null, [], "foo"];
a.foo = "qux";
a.bar = [];
b.writeObject(a);
dumpByteArray(b);
}
private function readValues():void {
var data:Array = [
0x0d, 0x07, 0x00,
0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x02,
0x00, 0x00, 0x00, 0x03
];
var b:ByteArray = createByteArray(data);
var o:* = b.readObject();
tf.appendText(o + "\n");
var a:Vector.<int> = o as Vector.<int>;
if(a != null) {
tf.appendText("Vector with " + a.length + " elements\n");
for(var j:int = 0; j < a.length; ++j)
tf.appendText(j + ": " + a[j] + "\n");
} else {
tf.appendText("Vector is null\n");
}
}
private function testExternalizable():void {
tf.text = "";
registerClassAlias("Foo", Foo);
var b:ByteArray = new ByteArray();
var f:Foo = new Foo("asd");
var g:Foo = new Foo("bar");
var a:Array = [f, f, g];
b.writeObject(a);
dumpByteArray(b);
b.position = 0;
var a2:Array = b.readObject();
tf.appendText((a[0] as Foo).foo);
tf.appendText((a[1] as Foo).foo);
tf.appendText((a[2] as Foo).foo);
}
private function dumpByteArray(b:ByteArray):void {
b.position = 0;
tf.appendText(b.bytesAvailable + "\n");
var cnt:int = 0;
while(b.bytesAvailable) {
var c:String = b.readUnsignedByte().toString(16);
if(c.length < 2) c = "0" + c;
tf.appendText("0x" + c);
if (b.bytesAvailable == 0) break;
if (++cnt == 12) {
cnt = 0;
tf.appendText(",\n");
} else {
tf.appendText(", ");
}
}
tf.appendText("\n");
}
private function createByteArray(data:Array):ByteArray {
var b:ByteArray = new ByteArray();
for(var i:int = 0; i < data.length; ++i)
b.writeByte(data[i]);
b.position = 0;
return b;
}
}
}
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import flash.utils.IExternalizable;
class Foo implements IExternalizable {
public var foo:String;
public function Foo(s:String = "default") {
foo = s;
}
public function writeExternal(output:IDataOutput):void {
output.writeUTF(foo);
}
public function readExternal(input:IDataInput):void {
foo = input.readUTF();
}
}
|
Add externalizable object to Flash test.
|
Add externalizable object to Flash test.
|
ActionScript
|
mit
|
adir-/amf-cpp,Ventero/amf-cpp
|
6814731c6a5531202bf168aa3b874f5307d3435e
|
actionscript/src/com/freshplanet/ane/AirCapabilities/AirCapabilities.as
|
actionscript/src/com/freshplanet/ane/AirCapabilities/AirCapabilities.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.AirCapabilities {
import com.freshplanet.ane.AirCapabilities.events.AirCapabilitiesLowMemoryEvent;
import com.freshplanet.ane.AirCapabilities.events.AirCapabilitiesOpenURLEvent;
import flash.display.BitmapData;
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.system.Capabilities;
public class AirCapabilities extends EventDispatcher {
// --------------------------------------------------------------------------------------//
// //
// PUBLIC API //
// //
// --------------------------------------------------------------------------------------//
/**
* Is the ANE supported on the current platform
*/
static public function get isSupported():Boolean {
return (Capabilities.manufacturer.indexOf("iOS") > -1 && Capabilities.os.indexOf("x86_64") < 0 && Capabilities.os.indexOf("i386") < 0) || Capabilities.manufacturer.indexOf("Android") > -1;
}
/**
* If <code>true</code>, logs will be displayed at the ActionScript and native level.
*/
public function setLogging(value:Boolean):void {
_doLogging = value;
if (isSupported)
_extContext.call("setLogging", value);
}
public function get nativeLogger():ILogger {
return _logger;
}
/**
* AirCapabilities instance
*/
static public function get instance():AirCapabilities {
return _instance != null ? _instance : new AirCapabilities()
}
/**
* Is SMS available
* @return
*/
public function hasSmsEnabled():Boolean {
if (isSupported)
return _extContext.call("hasSMS");
return false;
}
/**
* Is Twitter available
* @return
*/
public function hasTwitterEnabled():Boolean {
if (isSupported)
return _extContext.call("hasTwitter");
return false;
}
/**
* Sends an SMS message
* @param message to send
* @param recipient phonenumber
*/
public function sendMsgWithSms(message:String, recipient:String = null):void {
if (isSupported)
_extContext.call("sendWithSms", message, recipient);
}
/**
* Sends a Twitter message
* @param message
*/
public function sendMsgWithTwitter(message:String):void {
if (isSupported)
_extContext.call("sendWithTwitter", message);
}
/**
* Redirect user to Rating page
* @param appId
* @param appName
*/
public function redirecToRating(appId:String, appName:String):void {
if (isSupported)
_extContext.call("redirectToRating", appId, appName);
}
/**
* Model of the device
* @return
*/
public function getDeviceModel():String {
if (isSupported)
return _extContext.call("getDeviceModel") as String;
return "";
}
/**
* Name of the machine
* @return
*/
public function getMachineName():String {
if (isSupported)
return _extContext.call("getMachineName") as String;
return "";
}
/**
* Opens the referral link URL
* @param url
*/
public function processReferralLink(url:String):void {
if (isSupported)
_extContext.call("processReferralLink", url);
}
/**
* Opens Facebook page
* @param pageId id of the facebook page
*/
public function redirectToPageId(pageId:String):void {
if (isSupported)
_extContext.call("redirectToPageId", pageId);
}
/**
* Opens Twitter account
* @param twitterAccount
*/
public function redirectToTwitterAccount(twitterAccount:String):void {
if (isSupported)
_extContext.call("redirectToTwitterAccount", twitterAccount);
}
/**
* Is posting pictures on Twitter enabled
* @return
*/
public function canPostPictureOnTwitter():Boolean {
if (isSupported)
return _extContext.call("canPostPictureOnTwitter");
return false;
}
/**
* Post new picture on Twitter
* @param message
* @param bitmapData
*/
public function postPictureOnTwitter(message:String, bitmapData:BitmapData):void {
if (isSupported)
_extContext.call("postPictureOnTwitter", message, bitmapData);
}
/**
* Is Instagram enabled
* @return
*/
public function hasInstagramEnabled():Boolean {
if (isSupported)
return _extContext.call("hasInstagramEnabled");
return false;
}
/**
* Post new picture on Instagram
* @param message
* @param bitmapData
* @param x
* @param y
* @param width
* @param height
*/
public function postPictureOnInstagram(message:String, bitmapData:BitmapData,
x:int, y:int, width:int, height:int):void {
if (isSupported)
_extContext.call("postPictureOnInstagram", message, bitmapData, x, y, width, height);
}
/**
* Open an application (if installed on the Device) or send the player to the appstore. iOS Only
* @param schemes List of schemes (String) that the application accepts. Examples : @"sms://", @"twit://". You can find schemes in http://handleopenurl.com/
* @param appStoreURL (optional) Link to the AppStore page for the Application for the player to download. URL can be generated via Apple's linkmaker (itunes.apple.com/linkmaker?)
*/
public function openExternalApplication(schemes:Array, appStoreURL:String = null):void {
if (isSupported && Capabilities.manufacturer.indexOf("Android") == -1)
_extContext.call("openExternalApplication", schemes, appStoreURL);
}
/**
* Is opening URLs available
* @param url
* @return
*/
public function canOpenURL(url:String):Boolean {
return isSupported ? _extContext.call("canOpenURL", url) as Boolean : false;
}
/**
* Open URL
* @param url
*/
public function openURL(url:String):void {
if (canOpenURL(url))
_extContext.call("openURL", url);
}
/**
* Opens modal app store. Available on iOS only
* @param appStoreId id of the app to open a modal view to (do not include the "id" at the beginning of the number)
*/
public function openModalAppStoreIOS(appStoreId:String):void {
if (Capabilities.manufacturer.indexOf("iOS") > -1)
_extContext.call("openModalAppStore", appStoreId);
}
/**
* Version of the operating system
* @return
*/
public function getOSVersion():String {
if (isSupported)
return _extContext.call("getOSVersion") as String;
return "";
}
/**
* @return current amount of RAM being used in bytes
*/
public function getCurrentMem():Number {
if (!isSupported)
return -1;
var ret:Object = _extContext.call("getCurrentMem");
if (ret is Error)
throw ret;
else
return ret ? ret as Number : 0;
}
/**
* @return amount of RAM used by the VM
*/
public function getCurrentVirtualMem():Number {
if(!isSupported)
return -1;
if (Capabilities.manufacturer.indexOf("iOS") == -1)
return -1;
var ret:Object = _extContext.call("getCurrentVirtualMem");
if (ret is Error)
throw ret;
else
return ret ? ret as Number : 0;
}
/**
* @return is requesting review available. Available on iOS only
*/
public function canRequestReview():Boolean {
if (!isSupported)
return false;
if (Capabilities.manufacturer.indexOf("iOS") == -1)
return false;
return _extContext.call("canRequestReview");
}
/**
* Request AppStore review. Available on iOS only
*/
public function requestReview():void {
if (!canRequestReview())
return;
_extContext.call("requestReview");
}
/**
* Generate haptic feedback - iOS only
*/
public function generateHapticFeedback(feedbackType:AirCapabilitiesHapticFeedbackType):void {
if (Capabilities.manufacturer.indexOf("iOS") < 0)
return;
if(!feedbackType)
return
_extContext.call("generateHapticFeedback", feedbackType.value);
}
public function getNativeScale():Number
{
if (Capabilities.manufacturer.indexOf("iOS") < 0)
return 1;
return _extContext.call("getNativeScale") as Number;
}
public function openAdSettings():void
{
if (Capabilities.manufacturer.indexOf("Android") < 0)
return;
_extContext.call("openAdSettings");
}
public function getTopInset():Number
{
if (Capabilities.manufacturer.indexOf("iOS") < 0)
return 0;
return _extContext.call("getTopInset") as Number;
}
public function getBottomInset():Number
{
if (Capabilities.manufacturer.indexOf("iOS") < 0)
return 0;
return _extContext.call("getBottomInset") as Number;
}
public function get iOSAppOnMac():Boolean
{
if(Capabilities.os.toLowerCase().indexOf("mac os") < 0 && Capabilities.manufacturer.indexOf("iOS") < 0)
return false;
return _extContext.call("iOSAppOnMac") as Boolean;
}
// --------------------------------------------------------------------------------------//
// //
// PRIVATE API //
// //
// --------------------------------------------------------------------------------------//
static private const EXTENSION_ID:String = "com.freshplanet.ane.AirCapabilities";
static private var _instance:AirCapabilities = null;
private var _extContext:ExtensionContext = null;
private var _doLogging:Boolean = false;
private var _logger:ILogger;
/**
* "private" singleton constructor
*/
public function AirCapabilities() {
super();
if (_instance)
throw new Error("singleton class, use .instance");
_extContext = ExtensionContext.createExtensionContext(EXTENSION_ID, null);
_extContext.addEventListener(StatusEvent.STATUS, _handleStatusEvent);
if (isSupported)
_logger = new NativeLogger(_extContext);
else
_logger = new DefaultLogger();
_instance = this;
}
private function _handleStatusEvent(event:StatusEvent):void {
if (event.code == "log")
_doLogging && trace("[AirCapabilities] " + event.level);
else if (event.code == "OPEN_URL")
this.dispatchEvent(new AirCapabilitiesOpenURLEvent(AirCapabilitiesOpenURLEvent.OPEN_URL_SUCCESS, event.level));
else if (event.code == AirCapabilitiesLowMemoryEvent.LOW_MEMORY_WARNING) {
var memory:Number = Number(event.level);
this.dispatchEvent(new AirCapabilitiesLowMemoryEvent(event.code, memory));
}
else
this.dispatchEvent(event);
}
}
}
|
/*
* Copyright 2017 FreshPlanet
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.freshplanet.ane.AirCapabilities {
import com.freshplanet.ane.AirCapabilities.events.AirCapabilitiesLowMemoryEvent;
import com.freshplanet.ane.AirCapabilities.events.AirCapabilitiesOpenURLEvent;
import flash.display.BitmapData;
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.system.Capabilities;
public class AirCapabilities extends EventDispatcher {
// --------------------------------------------------------------------------------------//
// //
// PUBLIC API //
// //
// --------------------------------------------------------------------------------------//
/**
* Is the ANE supported on the current platform
*/
static public function get isSupported():Boolean {
return (Capabilities.manufacturer.indexOf("iOS") > -1 && Capabilities.os.indexOf("x86_64") < 0 && Capabilities.os.indexOf("i386") < 0) || Capabilities.manufacturer.indexOf("Android") > -1;
}
/**
* If <code>true</code>, logs will be displayed at the ActionScript and native level.
*/
public function setLogging(value:Boolean):void {
_doLogging = value;
if (isSupported)
_extContext.call("setLogging", value);
}
public function get nativeLogger():ILogger {
return _logger;
}
/**
* AirCapabilities instance
*/
static public function get instance():AirCapabilities {
return _instance != null ? _instance : new AirCapabilities()
}
/**
* Is SMS available
* @return
*/
public function hasSmsEnabled():Boolean {
if (isSupported)
return _extContext.call("hasSMS");
return false;
}
/**
* Is Twitter available
* @return
*/
public function hasTwitterEnabled():Boolean {
if (isSupported)
return _extContext.call("hasTwitter");
return false;
}
/**
* Sends an SMS message
* @param message to send
* @param recipient phonenumber
*/
public function sendMsgWithSms(message:String, recipient:String = null):void {
if (isSupported)
_extContext.call("sendWithSms", message, recipient);
}
/**
* Sends a Twitter message
* @param message
*/
public function sendMsgWithTwitter(message:String):void {
if (isSupported)
_extContext.call("sendWithTwitter", message);
}
/**
* Redirect user to Rating page
* @param appId
* @param appName
*/
public function redirecToRating(appId:String, appName:String):void {
if (isSupported)
_extContext.call("redirectToRating", appId, appName);
}
/**
* Model of the device
* @return
*/
public function getDeviceModel():String {
if (isSupported)
return _extContext.call("getDeviceModel") as String;
return "";
}
/**
* Name of the machine
* @return
*/
public function getMachineName():String {
if (isSupported)
return _extContext.call("getMachineName") as String;
return "";
}
/**
* Opens the referral link URL
* @param url
*/
public function processReferralLink(url:String):void {
if (isSupported)
_extContext.call("processReferralLink", url);
}
/**
* Opens Facebook page
* @param pageId id of the facebook page
*/
public function redirectToPageId(pageId:String):void {
if (isSupported)
_extContext.call("redirectToPageId", pageId);
}
/**
* Opens Twitter account
* @param twitterAccount
*/
public function redirectToTwitterAccount(twitterAccount:String):void {
if (isSupported)
_extContext.call("redirectToTwitterAccount", twitterAccount);
}
/**
* Is posting pictures on Twitter enabled
* @return
*/
public function canPostPictureOnTwitter():Boolean {
if (isSupported)
return _extContext.call("canPostPictureOnTwitter");
return false;
}
/**
* Post new picture on Twitter
* @param message
* @param bitmapData
*/
public function postPictureOnTwitter(message:String, bitmapData:BitmapData):void {
if (isSupported)
_extContext.call("postPictureOnTwitter", message, bitmapData);
}
/**
* Is Instagram enabled
* @return
*/
public function hasInstagramEnabled():Boolean {
if (isSupported)
return _extContext.call("hasInstagramEnabled");
return false;
}
/**
* Post new picture on Instagram
* @param message
* @param bitmapData
* @param x
* @param y
* @param width
* @param height
*/
public function postPictureOnInstagram(message:String, bitmapData:BitmapData,
x:int, y:int, width:int, height:int):void {
if (isSupported)
_extContext.call("postPictureOnInstagram", message, bitmapData, x, y, width, height);
}
/**
* Open an application (if installed on the Device) or send the player to the appstore. iOS Only
* @param schemes List of schemes (String) that the application accepts. Examples : @"sms://", @"twit://". You can find schemes in http://handleopenurl.com/
* @param appStoreURL (optional) Link to the AppStore page for the Application for the player to download. URL can be generated via Apple's linkmaker (itunes.apple.com/linkmaker?)
*/
public function openExternalApplication(schemes:Array, appStoreURL:String = null):void {
if (isSupported && Capabilities.manufacturer.indexOf("Android") == -1)
_extContext.call("openExternalApplication", schemes, appStoreURL);
}
/**
* Is opening URLs available
* @param url
* @return
*/
public function canOpenURL(url:String):Boolean {
return isSupported ? _extContext.call("canOpenURL", url) as Boolean : false;
}
/**
* Open URL
* @param url
*/
public function openURL(url:String):void {
if (canOpenURL(url))
_extContext.call("openURL", url);
}
/**
* Opens modal app store. Available on iOS only
* @param appStoreId id of the app to open a modal view to (do not include the "id" at the beginning of the number)
*/
public function openModalAppStoreIOS(appStoreId:String):void {
if (Capabilities.manufacturer.indexOf("iOS") > -1)
_extContext.call("openModalAppStore", appStoreId);
}
/**
* Version of the operating system
* @return
*/
public function getOSVersion():String {
if (isSupported)
return _extContext.call("getOSVersion") as String;
return "";
}
/**
* @return current amount of RAM being used in bytes
*/
public function getCurrentMem():Number {
if (!isSupported)
return -1;
var ret:Object = _extContext.call("getCurrentMem");
if (ret is Error)
throw ret;
else
return ret ? ret as Number : 0;
}
/**
* @return amount of RAM used by the VM
*/
public function getCurrentVirtualMem():Number {
if(!isSupported)
return -1;
if (Capabilities.manufacturer.indexOf("iOS") == -1)
return -1;
var ret:Object = _extContext.call("getCurrentVirtualMem");
if (ret is Error)
throw ret;
else
return ret ? ret as Number : 0;
}
/**
* @return is requesting review available. Available on iOS only
*/
public function canRequestReview():Boolean {
if (!isSupported)
return false;
if (Capabilities.manufacturer.indexOf("iOS") == -1)
return false;
return _extContext.call("canRequestReview");
}
/**
* Request AppStore review. Available on iOS only
*/
public function requestReview():void {
if (!canRequestReview())
return;
_extContext.call("requestReview");
}
/**
* Generate haptic feedback - iOS only
*/
public function generateHapticFeedback(feedbackType:AirCapabilitiesHapticFeedbackType):void {
if (Capabilities.manufacturer.indexOf("iOS") < 0)
return;
if(!feedbackType)
return
_extContext.call("generateHapticFeedback", feedbackType.value);
}
public function getNativeScale():Number
{
if (Capabilities.manufacturer.indexOf("iOS") < 0)
return 1;
return _extContext.call("getNativeScale") as Number;
}
public function openAdSettings():void
{
if (Capabilities.manufacturer.indexOf("Android") < 0)
return;
_extContext.call("openAdSettings");
}
public function getTopInset():Number
{
if (Capabilities.manufacturer.indexOf("iOS") < 0)
return 0;
return _extContext.call("getTopInset") as Number;
}
public function getBottomInset():Number
{
if (Capabilities.manufacturer.indexOf("iOS") < 0)
return 0;
return _extContext.call("getBottomInset") as Number;
}
public function get iOSAppOnMac():Boolean
{
if(Capabilities.manufacturer.indexOf("iOS") < 0)
return false;
return _extContext.call("iOSAppOnMac") as Boolean;
}
// --------------------------------------------------------------------------------------//
// //
// PRIVATE API //
// //
// --------------------------------------------------------------------------------------//
static private const EXTENSION_ID:String = "com.freshplanet.ane.AirCapabilities";
static private var _instance:AirCapabilities = null;
private var _extContext:ExtensionContext = null;
private var _doLogging:Boolean = false;
private var _logger:ILogger;
/**
* "private" singleton constructor
*/
public function AirCapabilities() {
super();
if (_instance)
throw new Error("singleton class, use .instance");
_extContext = ExtensionContext.createExtensionContext(EXTENSION_ID, null);
_extContext.addEventListener(StatusEvent.STATUS, _handleStatusEvent);
if (isSupported)
_logger = new NativeLogger(_extContext);
else
_logger = new DefaultLogger();
_instance = this;
}
private function _handleStatusEvent(event:StatusEvent):void {
if (event.code == "log")
_doLogging && trace("[AirCapabilities] " + event.level);
else if (event.code == "OPEN_URL")
this.dispatchEvent(new AirCapabilitiesOpenURLEvent(AirCapabilitiesOpenURLEvent.OPEN_URL_SUCCESS, event.level));
else if (event.code == AirCapabilitiesLowMemoryEvent.LOW_MEMORY_WARNING) {
var memory:Number = Number(event.level);
this.dispatchEvent(new AirCapabilitiesLowMemoryEvent(event.code, memory));
}
else
this.dispatchEvent(event);
}
}
}
|
check just for iOS
|
check just for iOS
|
ActionScript
|
apache-2.0
|
freshplanet/ANE-AirCapabilities,freshplanet/ANE-AirCapabilities,freshplanet/ANE-AirCapabilities
|
4f9c1ddcb0b07fc159c13b24ff567a1aa793c4a2
|
frameworks/as/src/org/apache/flex/html/staticControls/beads/ListBead.as
|
frameworks/as/src/org/apache/flex/html/staticControls/beads/ListBead.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.events.Event;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IInitSkin;
import org.apache.flex.core.IItemRenderer;
import org.apache.flex.core.IItemRendererParent;
import org.apache.flex.core.ISelectionModel;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.UIBase;
import org.apache.flex.html.staticControls.beads.controllers.VScrollBarMouseController;
import org.apache.flex.html.staticControls.beads.layouts.VScrollBarLayout;
import org.apache.flex.html.staticControls.beads.models.ScrollBarModel;
import org.apache.flex.html.staticControls.beads.models.SingleLineBorderModel;
import org.apache.flex.html.staticControls.supportClasses.Border;
import org.apache.flex.html.staticControls.supportClasses.NonVirtualDataGroup;
import org.apache.flex.html.staticControls.supportClasses.ScrollBar;
public class ListBead implements IBead, IInitSkin, IStrand, IListBead
{
public function ListBead()
{
}
private var listModel:ISelectionModel;
private var _border:Border;
public function get border():Border
{
return _border;
}
private var _dataGroup:IItemRendererParent;
public function get dataGroup():IItemRendererParent
{
return _dataGroup;
}
private var _vScrollBar:ScrollBar;
public function get vScrollBar():ScrollBar
{
if (!_vScrollBar)
_vScrollBar = createScrollBar();
return _vScrollBar;
}
private var _strand:IStrand;
public function get strand():IStrand
{
return _strand;
}
public function set strand(value:IStrand):void
{
_strand = value;
_border = new Border();
border.addToParent(UIBase(_strand));
_border.model = new SingleLineBorderModel();
_border.addBead(new SingleLineBorderBead());
_dataGroup = new NonVirtualDataGroup();
UIBase(_dataGroup).addToParent(UIBase(_strand));
listModel = value.getBeadByType(ISelectionModel) as ISelectionModel;
listModel.addEventListener("selectedIndexChanged", selectionChangeHandler);
}
private var lastSelectedIndex:int = -1;
private function selectionChangeHandler(event:Event):void
{
if (lastSelectedIndex != -1)
{
var ir:IItemRenderer = dataGroup.getItemRendererForIndex(lastSelectedIndex) as IItemRenderer;
ir.selected = false;
}
ir = dataGroup.getItemRendererForIndex(listModel.selectedIndex);
ir.selected = true;
lastSelectedIndex = listModel.selectedIndex;
}
public function initSkin():void
{
}
private function createScrollBar():ScrollBar
{
var vsb:ScrollBar;
vsb = new ScrollBar();
vsb.addToParent(UIBase(_strand));
var vsbm:ScrollBarModel = new ScrollBarModel();
vsbm.maximum = 100;
vsbm.minimum = 0;
vsbm.pageSize = 10;
vsbm.pageStepSize = 10;
vsbm.snapInterval = 1;
vsbm.stepSize = 1;
vsbm.value = 0;
vsb.model = vsbm;
vsb.initModel();
vsb.width = 16;
var vsbb:ScrollBarBead = new ScrollBarBead();
vsbb.initSkin();
vsb.addBead(vsbb);
var vsbl:VScrollBarLayout = new VScrollBarLayout();
vsbb.addBead(vsbl);
var vsbc:VScrollBarMouseController = new VScrollBarMouseController();
vsb.addBead(vsbc);
return vsb;
}
// beads declared in MXML are added to the strand.
// from AS, just call addBead()
public var beads:Array;
private var _beads:Vector.<IBead>;
public function addBead(bead:IBead):void
{
if (!_beads)
_beads = new Vector.<IBead>;
_beads.push(bead);
bead.strand = this;
}
public function getBeadByType(classOrInterface:Class):IBead
{
for each (var bead:IBead in _beads)
{
if (bead is classOrInterface)
return bead;
}
return null;
}
public function removeBead(value:IBead):IBead
{
var n:int = _beads.length;
for (var i:int = 0; i < n; i++)
{
var bead:IBead = _beads[i];
if (bead == value)
{
_beads.splice(i, 1);
return bead;
}
}
return null;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.staticControls.beads
{
import flash.events.Event;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IInitSkin;
import org.apache.flex.core.IItemRenderer;
import org.apache.flex.core.IItemRendererParent;
import org.apache.flex.core.ISelectionModel;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.UIBase;
import org.apache.flex.html.staticControls.beads.controllers.VScrollBarMouseController;
import org.apache.flex.html.staticControls.beads.layouts.VScrollBarLayout;
import org.apache.flex.html.staticControls.beads.models.ScrollBarModel;
import org.apache.flex.html.staticControls.beads.models.SingleLineBorderModel;
import org.apache.flex.html.staticControls.supportClasses.Border;
import org.apache.flex.html.staticControls.supportClasses.NonVirtualDataGroup;
import org.apache.flex.html.staticControls.supportClasses.ScrollBar;
public class ListBead implements IBead, IInitSkin, IStrand, IListBead
{
public function ListBead()
{
}
private var listModel:ISelectionModel;
private var _border:Border;
public function get border():Border
{
return _border;
}
private var _dataGroup:IItemRendererParent;
public function get dataGroup():IItemRendererParent
{
return _dataGroup;
}
private var _vScrollBar:ScrollBar;
public function get vScrollBar():ScrollBar
{
if (!_vScrollBar)
_vScrollBar = createScrollBar();
return _vScrollBar;
}
private var _strand:IStrand;
public function get strand():IStrand
{
return _strand;
}
public function set strand(value:IStrand):void
{
_strand = value;
_border = new Border();
border.addToParent(UIBase(_strand));
_border.model = new SingleLineBorderModel();
_border.addBead(new SingleLineBorderBead());
_dataGroup = new NonVirtualDataGroup();
UIBase(_dataGroup).addToParent(UIBase(_strand));
listModel = value.getBeadByType(ISelectionModel) as ISelectionModel;
listModel.addEventListener("selectedIndexChanged", selectionChangeHandler);
}
private var lastSelectedIndex:int = -1;
private function selectionChangeHandler(event:Event):void
{
if (lastSelectedIndex != -1)
{
var ir:IItemRenderer = dataGroup.getItemRendererForIndex(lastSelectedIndex) as IItemRenderer;
ir.selected = false;
}
if (listModel.selectedIndex != -1)
{
ir = dataGroup.getItemRendererForIndex(listModel.selectedIndex);
ir.selected = true;
}
lastSelectedIndex = listModel.selectedIndex;
}
public function initSkin():void
{
}
private function createScrollBar():ScrollBar
{
var vsb:ScrollBar;
vsb = new ScrollBar();
vsb.addToParent(UIBase(_strand));
var vsbm:ScrollBarModel = new ScrollBarModel();
vsbm.maximum = 100;
vsbm.minimum = 0;
vsbm.pageSize = 10;
vsbm.pageStepSize = 10;
vsbm.snapInterval = 1;
vsbm.stepSize = 1;
vsbm.value = 0;
vsb.model = vsbm;
vsb.initModel();
vsb.width = 16;
var vsbb:ScrollBarBead = new ScrollBarBead();
vsbb.initSkin();
vsb.addBead(vsbb);
var vsbl:VScrollBarLayout = new VScrollBarLayout();
vsbb.addBead(vsbl);
var vsbc:VScrollBarMouseController = new VScrollBarMouseController();
vsb.addBead(vsbc);
return vsb;
}
// beads declared in MXML are added to the strand.
// from AS, just call addBead()
public var beads:Array;
private var _beads:Vector.<IBead>;
public function addBead(bead:IBead):void
{
if (!_beads)
_beads = new Vector.<IBead>;
_beads.push(bead);
bead.strand = this;
}
public function getBeadByType(classOrInterface:Class):IBead
{
for each (var bead:IBead in _beads)
{
if (bead is classOrInterface)
return bead;
}
return null;
}
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;
}
}
}
|
fix bug when selectedIndex == -1
|
fix bug when selectedIndex == -1
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
6a8f4b4ca71fd4cbb03ac58794051a8a7869fedf
|
src/battlecode/serial/MatchLoader.as
|
src/battlecode/serial/MatchLoader.as
|
package battlecode.serial {
import battlecode.events.ParseEvent;
import battlecode.util.GZIP;
import flash.errors.MemoryError;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.events.TimerEvent;
import flash.net.URLRequest;
import flash.net.URLStream;
import flash.system.System;
import flash.utils.ByteArray;
import flash.utils.Timer;
import flash.utils.getTimer;
import mx.controls.Alert;
[Event(name="parseProgress", type="battlecode.events.ParseEvent")]
[Event(name="parseComplete", type="battlecode.events.ParseEvent")]
[Event(name="progress", type="flash.events.ProgressEvent")]
[Event(name="complete", type="flash.events.Event")]
public class MatchLoader extends EventDispatcher {
private var matchPath:String;
private var stream:URLStream;
private var matches:Vector.<Match>;
private var numMatches:uint = 0;
private var builder:MatchBuilder;
private var nameA:String, nameB:String;
private var gamesXML:XMLList;
private var currentIndex:uint = 0;
private var gameTimer:Timer;
public function MatchLoader() {
this.stream = new URLStream();
this.stream.addEventListener(ProgressEvent.PROGRESS, onDownloadProgress, false, 0, true);
this.stream.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
this.stream.addEventListener(IOErrorEvent.IO_ERROR, onIOError, false, 0, true);
this.stream.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError, false, 0, true);
}
public function load(file:String):void {
matchPath = file;
this.stream.load(new URLRequest(file));
}
public function loadData(matchBytes:ByteArray):void {
// decompress the bytes (they are GZIP'd)
try {
matchBytes = GZIP.decompress(matchBytes);
} catch (e:Error) {
}
trace("--- DECOMPRESSION ---");
trace("MEM USAGE: " + Math.round(System.totalMemory / 1024 / 1024) + "MB");
try {
// parse the xml from the decompressed byte stream
var xmlStr:String = matchBytes.readUTFBytes(matchBytes.bytesAvailable);
var xml:XML = new XML(xmlStr);
} catch (e:MemoryError) {
Alert.show("Memory allocation error: " + e.message);
return;
} catch (e:TypeError) {
trace("TypeError: " + e.message);
Alert.show("Unauthorized: " + e.message);
return;
}
// clear match bytes
matchBytes.clear();
// generate new matches
numMatches = parseInt(xml.child("ser.MatchHeader").length());
matches = new Vector.<Match>();
gamesXML = xml.children();
gameTimer = new Timer(30);
gameTimer.addEventListener(TimerEvent.TIMER, onTimerTick);
gameTimer.start();
trace("--- XML PARSE ---");
trace("MEM USAGE: " + Math.round(System.totalMemory / 1000 / 1000) + "MB");
dispatchEvent(new Event(Event.COMPLETE));
}
public function setTeamNames(nameA:String, nameB:String):void {
this.nameA = nameA;
this.nameB = nameB;
}
public function getMatches():Vector.<Match> {
return matches;
}
public function getNumMatches():uint {
return numMatches;
}
private function onDownloadProgress(e:ProgressEvent):void {
dispatchEvent(e);
}
private function onComplete(e:Event):void {
var matchBytes:ByteArray = new ByteArray();
stream.readBytes(matchBytes);
stream.close();
stream = null;
loadData(matchBytes);
}
private function onIOError(e:IOErrorEvent):void {
trace("match load failed: " + e.toString());
Alert.show("Could not load the specified match file: File " + matchPath + " not found");
}
private function onSecurityError(e:SecurityError):void {
trace("match load failed: " + e.toString());
Alert.show("Could not load the specified match file: Security error");
}
private function onTimerTick(e:TimerEvent):void {
var start:Number = getTimer();
while(getTimer() - start < 30 && currentIndex < gamesXML.length()) {
var node:XML = gamesXML[currentIndex++];
var nodeName:String = node.name().toString();
switch (nodeName) {
case "ser.StoredConstants":
StoredConstantsLoader.loadConstants(node);
break;
case "ser.MatchHeader":
builder = new MatchBuilder();
builder.setHeader(node);
builder.setTeamNames(nameA, nameB);
break;
case "ser.MatchFooter":
builder.setFooter(node);
matches.push(builder.build());
builder = null;
trace("--- MATCH "+matches.length+" ---");
trace("MEM USAGE: " + Math.round(System.totalMemory / 1024 / 1024) + "MB");
break;
case "ser.ExtensibleMetadata":
builder.setExtensibleMetadata(node);
break;
case "ser.GameStats":
builder.setGameStats(node);
break;
case "ser.RoundDelta":
builder.addRoundDelta(node);
break;
case "ser.RoundStats":
builder.addRoundStats(node);
break;
default:
trace("Unknown node: " + node.name());
break;
}
}
var progressEvent:ParseEvent;
if (matches.length == numMatches) {
progressEvent = new ParseEvent(ParseEvent.COMPLETE);
gameTimer.stop();
} else {
progressEvent = new ParseEvent(ParseEvent.PROGRESS);
}
progressEvent.rowsParsed = currentIndex;
progressEvent.rowsTotal = gamesXML.length();
progressEvent.matchesParsed = matches.length;
progressEvent.matchesTotal = numMatches;
dispatchEvent(progressEvent);
}
}
}
|
package battlecode.serial {
import battlecode.events.ParseEvent;
import battlecode.util.GZIP;
import flash.errors.MemoryError;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.events.TimerEvent;
import flash.net.URLRequest;
import flash.net.URLStream;
import flash.system.System;
import flash.utils.ByteArray;
import flash.utils.Timer;
import flash.utils.getTimer;
import mx.controls.Alert;
[Event(name="parseProgress", type="battlecode.events.ParseEvent")]
[Event(name="parseComplete", type="battlecode.events.ParseEvent")]
[Event(name="progress", type="flash.events.ProgressEvent")]
[Event(name="complete", type="flash.events.Event")]
public class MatchLoader extends EventDispatcher {
private var matchPath:String;
private var stream:URLStream;
private var matches:Vector.<Match>;
private var numMatches:uint = 0;
private var builder:MatchBuilder;
private var nameA:String, nameB:String;
private var gamesXML:XMLList;
private var currentIndex:uint = 0;
private var gameTimer:Timer;
public function MatchLoader() {
this.stream = new URLStream();
this.stream.addEventListener(ProgressEvent.PROGRESS, onDownloadProgress, false, 0, true);
this.stream.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
this.stream.addEventListener(IOErrorEvent.IO_ERROR, onIOError, false, 0, true);
this.stream.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError, false, 0, true);
}
public function load(file:String):void {
matchPath = file;
this.stream.load(new URLRequest(file));
}
public function loadData(matchBytes:ByteArray):void {
// decompress the bytes (they are GZIP'd)
try {
matchBytes = GZIP.decompress(matchBytes);
} catch (e:Error) {
}
trace("--- DECOMPRESSION ---");
trace("MEM USAGE: " + Math.round(System.totalMemory / 1024 / 1024) + "MB");
try {
// parse the xml from the decompressed byte stream
var xmlStr:String = matchBytes.readUTFBytes(matchBytes.bytesAvailable);
var xml:XML = new XML(xmlStr);
} catch (e:MemoryError) {
Alert.show("Memory allocation error: " + e.message);
return;
} catch (e:TypeError) {
trace("TypeError: " + e.message);
Alert.show("Unauthorized: " + e.message);
return;
}
// clear match bytes
matchBytes.clear();
// generate new matches
numMatches = parseInt(xml.child("ser.MatchHeader").length());
matches = new Vector.<Match>();
gamesXML = xml.children();
gameTimer = new Timer(30);
gameTimer.addEventListener(TimerEvent.TIMER, onTimerTick);
gameTimer.start();
trace("--- XML PARSE ---");
trace("MEM USAGE: " + Math.round(System.totalMemory / 1000 / 1000) + "MB");
dispatchEvent(new Event(Event.COMPLETE));
}
public function setTeamNames(nameA:String, nameB:String):void {
this.nameA = nameA;
this.nameB = nameB;
}
public function getMatches():Vector.<Match> {
return matches;
}
public function getNumMatches():uint {
return numMatches;
}
private function onDownloadProgress(e:ProgressEvent):void {
dispatchEvent(e);
}
private function onComplete(e:Event):void {
var matchBytes:ByteArray = new ByteArray();
stream.readBytes(matchBytes);
stream.close();
stream = null;
loadData(matchBytes);
}
private function onIOError(e:IOErrorEvent):void {
trace("match load failed: " + e.toString());
Alert.show("Could not load the specified match file: File " + matchPath + " not found");
}
private function onSecurityError(e:SecurityErrorEvent):void {
trace("match load failed: " + e.toString());
Alert.show("Could not load the specified match file: Security error");
}
private function onTimerTick(e:TimerEvent):void {
var start:Number = getTimer();
while(getTimer() - start < 30 && currentIndex < gamesXML.length()) {
var node:XML = gamesXML[currentIndex++];
var nodeName:String = node.name().toString();
switch (nodeName) {
case "ser.StoredConstants":
StoredConstantsLoader.loadConstants(node);
break;
case "ser.MatchHeader":
builder = new MatchBuilder();
builder.setHeader(node);
builder.setTeamNames(nameA, nameB);
break;
case "ser.MatchFooter":
builder.setFooter(node);
matches.push(builder.build());
builder = null;
trace("--- MATCH "+matches.length+" ---");
trace("MEM USAGE: " + Math.round(System.totalMemory / 1024 / 1024) + "MB");
break;
case "ser.ExtensibleMetadata":
builder.setExtensibleMetadata(node);
break;
case "ser.GameStats":
builder.setGameStats(node);
break;
case "ser.RoundDelta":
builder.addRoundDelta(node);
break;
case "ser.RoundStats":
builder.addRoundStats(node);
break;
default:
trace("Unknown node: " + node.name());
break;
}
}
var progressEvent:ParseEvent;
if (matches.length == numMatches) {
progressEvent = new ParseEvent(ParseEvent.COMPLETE);
gameTimer.stop();
} else {
progressEvent = new ParseEvent(ParseEvent.PROGRESS);
}
progressEvent.rowsParsed = currentIndex;
progressEvent.rowsTotal = gamesXML.length();
progressEvent.matchesParsed = matches.length;
progressEvent.matchesTotal = numMatches;
dispatchEvent(progressEvent);
}
}
}
|
fix event type
|
fix event type
|
ActionScript
|
mit
|
trun/battlecode-webclient
|
5b4010bed4cad240ad534450fba7870158e658e6
|
dolly-framework/src/test/actionscript/dolly/CloningOfCompositeCloneableClassTest.as
|
dolly-framework/src/test/actionscript/dolly/CloningOfCompositeCloneableClassTest.as
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.CompositeCloneableClass;
import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertFalse;
import org.flexunit.asserts.assertNotNull;
import org.hamcrest.assertThat;
import org.hamcrest.collection.array;
import org.hamcrest.collection.arrayWithSize;
import org.hamcrest.collection.everyItem;
import org.hamcrest.core.isA;
import org.hamcrest.object.equalTo;
use namespace dolly_internal;
public class CloningOfCompositeCloneableClassTest {
private var compositeCloneableClass:CompositeCloneableClass;
private var compositeCloneableClassType:Type;
[Before]
public function before():void {
compositeCloneableClass = new CompositeCloneableClass();
compositeCloneableClass.array = [1, 2, 3, 4, 5];
compositeCloneableClass.arrayList = new ArrayList([1, 2, 3, 4, 5]);
compositeCloneableClass.arrayCollection = new ArrayCollection([1, 2, 3, 4, 5]);
compositeCloneableClassType = Type.forInstance(compositeCloneableClass);
}
[After]
public function after():void {
compositeCloneableClass = null;
compositeCloneableClassType = null;
}
[Test]
public function findingAllWritableFieldsForType():void {
const writableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(compositeCloneableClassType);
assertNotNull(writableFields);
assertEquals(5, writableFields.length);
}
[Test]
public function cloningOfArray():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
assertNotNull(clone.array);
assertThat(clone.array, arrayWithSize(5));
assertThat(clone.array, compositeCloneableClass.array);
assertFalse(clone.array == compositeCloneableClass.array);
assertThat(clone.array, everyItem(isA(Number)));
assertThat(clone.array, array(equalTo(1), equalTo(2), equalTo(3), equalTo(4), equalTo(5)));
}
[Test]
public function cloningOfArrayList():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const arrayList:ArrayList = clone.arrayList;
assertNotNull(arrayList);
assertFalse(clone.arrayList == compositeCloneableClass.arrayList);
assertEquals(arrayList.length, 5);
assertEquals(arrayList.getItemAt(0), 1);
assertEquals(arrayList.getItemAt(1), 2);
assertEquals(arrayList.getItemAt(2), 3);
assertEquals(arrayList.getItemAt(3), 4);
assertEquals(arrayList.getItemAt(4), 5);
}
[Test]
public function cloningOfArrayCollection():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const arrayCollection:ArrayCollection = clone.arrayCollection;
assertNotNull(arrayCollection);
assertFalse(clone.arrayCollection == compositeCloneableClass.arrayCollection);
assertEquals(arrayCollection.length, 5);
assertEquals(arrayCollection.getItemAt(0), 1);
assertEquals(arrayCollection.getItemAt(1), 2);
assertEquals(arrayCollection.getItemAt(2), 3);
assertEquals(arrayCollection.getItemAt(3), 4);
assertEquals(arrayCollection.getItemAt(4), 5);
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.CloneableClass;
import dolly.data.CompositeCloneableClass;
import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertFalse;
import org.flexunit.asserts.assertNotNull;
import org.hamcrest.assertThat;
import org.hamcrest.collection.array;
import org.hamcrest.collection.arrayWithSize;
import org.hamcrest.collection.everyItem;
import org.hamcrest.core.isA;
import org.hamcrest.object.equalTo;
use namespace dolly_internal;
public class CloningOfCompositeCloneableClassTest {
private var compositeCloneableClass:CompositeCloneableClass;
private var compositeCloneableClassType:Type;
[Before]
public function before():void {
compositeCloneableClass = new CompositeCloneableClass();
const nestedCloneable:CloneableClass = new CloneableClass();
nestedCloneable.property1 = "property1 value";
nestedCloneable.writableField1 = "writableField1 value";
const nestedCompositeCloneable:CompositeCloneableClass = new CompositeCloneableClass();
nestedCompositeCloneable.compositeCloneable = compositeCloneableClass;
nestedCompositeCloneable.array = [1, 2, 3];
nestedCompositeCloneable.arrayList = new ArrayList([1, 2, 3]);
nestedCompositeCloneable.arrayCollection = new ArrayCollection([1, 2, 3]);
compositeCloneableClass.cloneable = nestedCloneable;
compositeCloneableClass.compositeCloneable = nestedCompositeCloneable;
compositeCloneableClass.array = [1, 2, 3, 4, 5];
compositeCloneableClass.arrayList = new ArrayList([1, 2, 3, 4, 5]);
compositeCloneableClass.arrayCollection = new ArrayCollection([1, 2, 3, 4, 5]);
compositeCloneableClassType = Type.forInstance(compositeCloneableClass);
}
[After]
public function after():void {
compositeCloneableClass.compositeCloneable =
compositeCloneableClass.compositeCloneable.compositeCloneable = null;
compositeCloneableClass.cloneable = null;
compositeCloneableClass = null;
compositeCloneableClassType = null;
}
[Test]
public function findingAllWritableFieldsForType():void {
const writableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(compositeCloneableClassType);
assertNotNull(writableFields);
assertEquals(5, writableFields.length);
}
[Test]
public function cloningOfArray():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
assertNotNull(clone.array);
assertThat(clone.array, arrayWithSize(5));
assertThat(clone.array, compositeCloneableClass.array);
assertFalse(clone.array == compositeCloneableClass.array);
assertThat(clone.array, everyItem(isA(Number)));
assertThat(clone.array, array(equalTo(1), equalTo(2), equalTo(3), equalTo(4), equalTo(5)));
}
[Test]
public function cloningOfArrayList():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const arrayList:ArrayList = clone.arrayList;
assertNotNull(arrayList);
assertFalse(clone.arrayList == compositeCloneableClass.arrayList);
assertEquals(arrayList.length, 5);
assertEquals(arrayList.getItemAt(0), 1);
assertEquals(arrayList.getItemAt(1), 2);
assertEquals(arrayList.getItemAt(2), 3);
assertEquals(arrayList.getItemAt(3), 4);
assertEquals(arrayList.getItemAt(4), 5);
}
[Test]
public function cloningOfArrayCollection():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const arrayCollection:ArrayCollection = clone.arrayCollection;
assertNotNull(arrayCollection);
assertFalse(clone.arrayCollection == compositeCloneableClass.arrayCollection);
assertEquals(arrayCollection.length, 5);
assertEquals(arrayCollection.getItemAt(0), 1);
assertEquals(arrayCollection.getItemAt(1), 2);
assertEquals(arrayCollection.getItemAt(2), 3);
assertEquals(arrayCollection.getItemAt(3), 4);
assertEquals(arrayCollection.getItemAt(4), 5);
}
}
}
|
Initialize props "cloneable" and "compositeCloneable" of CompositeCloneableClass in tests.
|
Initialize props "cloneable" and "compositeCloneable" of CompositeCloneableClass in tests.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
34d2140d708bc288343dedf2eefa53bd4a2864f7
|
plugins/bitrateDetectionPlugin/src/com/kaltura/kdpfl/plugin/component/BitrateDetectionMediator.as
|
plugins/bitrateDetectionPlugin/src/com/kaltura/kdpfl/plugin/component/BitrateDetectionMediator.as
|
package com.kaltura.kdpfl.plugin.component
{
import com.kaltura.kdpfl.model.ConfigProxy;
import com.kaltura.kdpfl.model.MediaProxy;
import com.kaltura.kdpfl.model.SequenceProxy;
import com.kaltura.kdpfl.model.type.EnableType;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.view.controls.KTrace;
import com.kaltura.types.KalturaMediaType;
import com.kaltura.vo.KalturaMediaEntry;
import flash.display.Loader;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.TimerEvent;
import flash.external.ExternalInterface;
import flash.net.SharedObject;
import flash.net.URLRequest;
import flash.utils.Timer;
import org.puremvc.as3.interfaces.INotification;
import org.puremvc.as3.patterns.mediator.Mediator;
public class BitrateDetectionMediator extends Mediator
{
public static var NAME:String = "bitrateDetectionMediator";
/**
* Flag indicating autoPlay flashvar was true
*/
private var _wasAutoPlay:Boolean = false;
/**
* Flag indicating singleAutoPlay was true
*/
private var _wasSingleAutoPlay:Boolean = false;
/**
* The url loader
*/
private var _loader:Loader;
/**
* average download speed
*/
private var _avgSpeed:Number = 0;
/**
* counter for progress events, will be used to calculate average speed
*/
private var _progressCount:int;
/**
* timer for the download process
*/
private var _downloadTimer:Timer;
/**
* startTime of the download process
*/
private var _startTime:Number;
/**
* Indicating if player has already played
*/
private var _playedPlayed:Boolean = false;
private var _prevTime:Number;
private var _prevBytesLoaded:int;
private var _forceBitrate:int;
public function BitrateDetectionMediator(viewComponentObject:Object = null , forceBitrate:int = 0)
{
_forceBitrate = forceBitrate;
super(NAME, viewComponentObject);
}
override public function listNotificationInterests():Array
{
return [
NotificationType.DO_SWITCH,
NotificationType.KDP_EMPTY,
NotificationType.KDP_READY,
NotificationType.PLAYER_PLAYED,
NotificationType.MEDIA_READY
];
}
private var _bandwidth:Number = 0;
private var _bandwidthByUser:Number = 0;
override public function handleNotification(notification:INotification):void
{
//check bitrate only before player played
/* if (_playedPlayed)
{
return;
}*/
switch (notification.getName())
{
//in case the user switched the flavor manually
case NotificationType.DO_SWITCH:
_bandwidthByUser = int(notification.getBody())
break;
case NotificationType.MEDIA_READY:
if(_bandwidthByUser)
{
sendNotification(NotificationType.CHANGE_PREFERRED_BITRATE, {bitrate: _bandwidthByUser});
return;
}
if(_bandwidth)
sendNotification(NotificationType.CHANGE_PREFERRED_BITRATE, {bitrate: _bandwidth});
break;
case NotificationType.KDP_EMPTY:
case NotificationType.KDP_READY:
var mediaProxy:MediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy;
if (!mediaProxy.vo.entry ||
((mediaProxy.vo.entry is KalturaMediaEntry) && (int(mediaProxy.vo.entry.mediaType)==KalturaMediaType.IMAGE)))
break;
trace("bitrate detection:", notification.getName());
var configProxy:ConfigProxy = facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy;
if ((viewComponent as bitrateDetectionPluginCode).useFlavorCookie)
{
var flavorCookie : SharedObject;
try
{
//Check to see if we have a cookie
flavorCookie = SharedObject.getLocal("kaltura");
}
catch (e: Error)
{
//if not just start download
trace ("no permissions to access partner's file system");
startDownload();
return;
}
if (flavorCookie && flavorCookie.data)
{
//If we are in Auto Switch or the first time we run it - do the download test
if(!flavorCookie.data.preferedFlavorBR || (flavorCookie.data.preferedFlavorBR == -1))
{
startDownload();
}
}
}
//disable bitrate cookie--> start detection
else
{
startDownload();
}
break;
case NotificationType.PLAYER_PLAYED:
if(_bandwidth)
return;
_playedPlayed = true;
break;
}
}
/**
* Start a download process to find the preferred bitrate
*
*/
public function startDownload() : void
{
trace ("bitrate detection: start download");
if (!(viewComponent as bitrateDetectionPluginCode).downloadUrl)
return;
var configProxy:ConfigProxy = facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy;
var mediaProxy:MediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy;
//disable autoPlay - will change it back once the bitrate detection will finish
if (configProxy.vo.flashvars.autoPlay == "true")
{
trace ("bitrate detection: was auto play");
configProxy.vo.flashvars.autoPlay = "false";
_wasAutoPlay = true;
}
if (mediaProxy.vo.singleAutoPlay)
{
mediaProxy.vo.singleAutoPlay = false;
_wasSingleAutoPlay = true;
}
_startTime = ( new Date( ) ).getTime( );
_progressCount = 0;
_prevTime = _startTime;
_prevBytesLoaded = 0;
_loader = new Loader( );
_loader.contentLoaderInfo.addEventListener( Event.COMPLETE, downloadComplete );
_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
_loader.contentLoaderInfo.addEventListener( IOErrorEvent.IO_ERROR, ioErrorHandler );
_downloadTimer = new Timer ((viewComponent as bitrateDetectionPluginCode).downloadTimeoutMS, 1);
_downloadTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
sendNotification(NotificationType.ENABLE_GUI, {guiEnabled: false, enableType: EnableType.FULL});
sendNotification( NotificationType.SWITCHING_CHANGE_STARTED, {newIndex: -2, newBitrate: null});
_loader.load( new URLRequest( (viewComponent as bitrateDetectionPluginCode).downloadUrl + "?" + ( Math.random( ) * 100000 )) );
_downloadTimer.start();
}
/**
* on download progress- calculate average speed
* @param event
*
*/
private function onProgress (event:ProgressEvent):void
{
var curTime:Number = ( new Date( ) ).getTime( );
_progressCount++;
if (event.bytesLoaded!=0)
{
var totalTime:Number =( curTime - _startTime ) / 1000;
var totalKB:Number = event.bytesLoaded / 1024;
_avgSpeed = totalKB / totalTime;
}
_prevTime = curTime;
_prevBytesLoaded = event.bytesLoaded;
}
/**
* download complete handler - set the preferred bitrate, enable GUI
*
*/
private function downloadComplete( e:Event = null):void
{
_downloadTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
_loader.contentLoaderInfo.removeEventListener( ProgressEvent.PROGRESS, onProgress );
var bitrateVal:int = _avgSpeed * 8;
trace("*** preferred bitrate for bitrate detection plugin:", bitrateVal);
//for debugging - force a bitrate value to override the calculated one
if(_forceBitrate > 0)
{
bitrateVal = _forceBitrate;
}
//for testing - expose the # via JS
try
{
ExternalInterface.call('bitrateValue' , bitrateVal);
}
catch(error:Error)
{
}
sendNotification(NotificationType.CHANGE_PREFERRED_BITRATE, {bitrate: bitrateVal});
_bandwidth = bitrateVal;
//write to cookie
var flavorCookie : SharedObject;
try
{
flavorCookie = SharedObject.getLocal("kaltura");
}
catch (e : Error)
{
trace("No access to user's file system");
}
if (flavorCookie && flavorCookie.data)
{
flavorCookie.data.preferedFlavorBR = bitrateVal;
flavorCookie.flush();
}
finishDownloadProcess();
}
/**
* default timer time has passed, stop listening to progress event and continue the flow
* @param event
*
*/
private function onTimerComplete (event:TimerEvent):void {
downloadComplete();
}
/**
* I/O error getting the sample file, release the UI
* @param event
*
*/
private function ioErrorHandler(event:IOErrorEvent) : void
{
//Bypass: ignore #2124 error (loaded file is an unknown type)
if (!event.text || event.text.indexOf("Error #2124")==-1)
{
trace ("bitrate detection i/o error:", event.text);
finishDownloadProcess();
}
}
/**
* enable back the GUI.
* call Do_Play if we were in auto play and set back relevant flashvars
*
*/
private function finishDownloadProcess():void {
//if we changed variables, set them back
if (_wasAutoPlay || _wasSingleAutoPlay) {
var mediaProxy:MediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy;
var sequenceProxy:SequenceProxy = facade.retrieveProxy(SequenceProxy.NAME) as SequenceProxy;
if (_wasAutoPlay)
{
var configProxy:ConfigProxy = facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy;
configProxy.vo.flashvars.autoPlay = "true";
}
else
{
mediaProxy.vo.singleAutoPlay = true;
}
//play if we should have played
if (!_playedPlayed && !mediaProxy.vo.isMediaDisabled && !sequenceProxy.vo.isInSequence)
{
sendNotification(NotificationType.DO_PLAY);
}
}
sendNotification(NotificationType.ENABLE_GUI, {guiEnabled: true, enableType: EnableType.FULL});
}
}
}
|
package com.kaltura.kdpfl.plugin.component
{
import com.kaltura.kdpfl.model.ConfigProxy;
import com.kaltura.kdpfl.model.MediaProxy;
import com.kaltura.kdpfl.model.SequenceProxy;
import com.kaltura.kdpfl.model.type.EnableType;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.view.controls.KTrace;
import com.kaltura.types.KalturaMediaType;
import com.kaltura.vo.KalturaMediaEntry;
import flash.display.Loader;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.TimerEvent;
import flash.external.ExternalInterface;
import flash.net.SharedObject;
import flash.net.URLRequest;
import flash.utils.Timer;
import org.puremvc.as3.interfaces.INotification;
import org.puremvc.as3.patterns.mediator.Mediator;
public class BitrateDetectionMediator extends Mediator
{
public static var NAME:String = "bitrateDetectionMediator";
/**
* Flag indicating autoPlay flashvar was true
*/
private var _wasAutoPlay:Boolean = false;
/**
* Flag indicating singleAutoPlay was true
*/
private var _wasSingleAutoPlay:Boolean = false;
/**
* The url loader
*/
private var _loader:Loader;
/**
* average download speed
*/
private var _avgSpeed:Number = 0;
/**
* counter for progress events, will be used to calculate average speed
*/
private var _progressCount:int;
/**
* timer for the download process
*/
private var _downloadTimer:Timer;
/**
* startTime of the download process
*/
private var _startTime:Number;
/**
* Indicating if player has already played
*/
private var _playedPlayed:Boolean = false;
private var _configProxy:ConfigProxy;
private var _prevTime:Number;
private var _prevBytesLoaded:int;
private var _forceBitrate:int;
public function BitrateDetectionMediator(viewComponentObject:Object = null , forceBitrate:int = 0)
{
_forceBitrate = forceBitrate;
super(NAME, viewComponentObject);
}
override public function listNotificationInterests():Array
{
return [
NotificationType.DO_SWITCH,
NotificationType.KDP_EMPTY,
NotificationType.KDP_READY,
NotificationType.PLAYER_PLAYED,
NotificationType.MEDIA_READY
];
}
private var _bandwidth:Number = 0;
private var _bandwidthByUser:Number = 0;
override public function handleNotification(notification:INotification):void
{
//check bitrate only before player played
/* if (_playedPlayed)
{
return;
}*/
switch (notification.getName())
{
//in case the user switched the flavor manually
case NotificationType.DO_SWITCH:
_bandwidthByUser = int(notification.getBody())
break;
case NotificationType.MEDIA_READY:
if(_bandwidthByUser)
{
sendNotification(NotificationType.CHANGE_PREFERRED_BITRATE, {bitrate: _bandwidthByUser});
return;
}
if(_bandwidth)
sendNotification(NotificationType.CHANGE_PREFERRED_BITRATE, {bitrate: _bandwidth});
break;
case NotificationType.KDP_EMPTY:
case NotificationType.KDP_READY:
var mediaProxy:MediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy;
if (!mediaProxy.vo.entry ||
((mediaProxy.vo.entry is KalturaMediaEntry) && (int(mediaProxy.vo.entry.mediaType)==KalturaMediaType.IMAGE)))
break;
trace("bitrate detection:", notification.getName());
_configProxy = facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy;
if ((viewComponent as bitrateDetectionPluginCode).useFlavorCookie)
{
var flavorCookie : SharedObject;
try
{
//Check to see if we have a cookie
flavorCookie = SharedObject.getLocal("kaltura");
}
catch (e: Error)
{
//if not just start download
trace ("no permissions to access partner's file system");
startDownload();
return;
}
if (flavorCookie && flavorCookie.data)
{
//If we are in Auto Switch or the first time we run it - do the download test
if(!flavorCookie.data.preferedFlavorBR || (flavorCookie.data.preferedFlavorBR == -1))
{
startDownload();
}
}
}
//disable bitrate cookie--> start detection
else
{
startDownload();
}
break;
case NotificationType.PLAYER_PLAYED:
if(_bandwidth)
return;
_playedPlayed = true;
break;
}
}
/**
* Start a download process to find the preferred bitrate
*
*/
public function startDownload() : void
{
trace ("bitrate detection: start download");
if (!(viewComponent as bitrateDetectionPluginCode).downloadUrl)
return;
var mediaProxy:MediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy;
//disable autoPlay - will change it back once the bitrate detection will finish
if (_configProxy.vo.flashvars.autoPlay == "true")
{
trace ("bitrate detection: was auto play");
_configProxy.vo.flashvars.autoPlay = "false";
_wasAutoPlay = true;
}
if (mediaProxy.vo.singleAutoPlay)
{
mediaProxy.vo.singleAutoPlay = false;
_wasSingleAutoPlay = true;
}
_startTime = ( new Date( ) ).getTime( );
_progressCount = 0;
_prevTime = _startTime;
_prevBytesLoaded = 0;
_loader = new Loader( );
_loader.contentLoaderInfo.addEventListener( Event.COMPLETE, downloadComplete );
_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
_loader.contentLoaderInfo.addEventListener( IOErrorEvent.IO_ERROR, ioErrorHandler );
_downloadTimer = new Timer ((viewComponent as bitrateDetectionPluginCode).downloadTimeoutMS, 1);
_downloadTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
sendNotification(NotificationType.ENABLE_GUI, {guiEnabled: false, enableType: EnableType.FULL});
sendNotification( NotificationType.SWITCHING_CHANGE_STARTED, {newIndex: -2, newBitrate: null});
_loader.load( new URLRequest( (viewComponent as bitrateDetectionPluginCode).downloadUrl + "?" + ( Math.random( ) * 100000 )) );
_downloadTimer.start();
}
/**
* on download progress- calculate average speed
* @param event
*
*/
private function onProgress (event:ProgressEvent):void
{
var curTime:Number = ( new Date( ) ).getTime( );
_progressCount++;
if (event.bytesLoaded!=0)
{
var totalTime:Number =( curTime - _startTime ) / 1000;
var totalKB:Number = event.bytesLoaded / 1024;
_avgSpeed = totalKB / totalTime;
}
_prevTime = curTime;
_prevBytesLoaded = event.bytesLoaded;
}
/**
* download complete handler - set the preferred bitrate, enable GUI
*
*/
private function downloadComplete( e:Event = null):void
{
_downloadTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
_loader.contentLoaderInfo.removeEventListener( ProgressEvent.PROGRESS, onProgress );
var bitrateVal:int = _avgSpeed * 8;
trace("*** preferred bitrate for bitrate detection plugin:", bitrateVal);
//for debugging - force a bitrate value to override the calculated one
if(_forceBitrate > 0)
{
bitrateVal = _forceBitrate;
}
//for testing - expose the # via JS
try
{
ExternalInterface.call('bitrateValue' , bitrateVal);
}
catch(error:Error)
{
}
sendNotification(NotificationType.CHANGE_PREFERRED_BITRATE, {bitrate: bitrateVal});
_bandwidth = bitrateVal;
//write to cookie
if (_configProxy.vo.flashvars.allowCookies=="true")
{
var flavorCookie : SharedObject;
try
{
flavorCookie = SharedObject.getLocal("kaltura");
}
catch (e : Error)
{
trace("No access to user's file system");
}
if (flavorCookie && flavorCookie.data)
{
flavorCookie.data.preferedFlavorBR = bitrateVal;
flavorCookie.flush();
}
}
finishDownloadProcess();
}
/**
* default timer time has passed, stop listening to progress event and continue the flow
* @param event
*
*/
private function onTimerComplete (event:TimerEvent):void {
downloadComplete();
}
/**
* I/O error getting the sample file, release the UI
* @param event
*
*/
private function ioErrorHandler(event:IOErrorEvent) : void
{
//Bypass: ignore #2124 error (loaded file is an unknown type)
if (!event.text || event.text.indexOf("Error #2124")==-1)
{
trace ("bitrate detection i/o error:", event.text);
finishDownloadProcess();
}
}
/**
* enable back the GUI.
* call Do_Play if we were in auto play and set back relevant flashvars
*
*/
private function finishDownloadProcess():void {
//if we changed variables, set them back
if (_wasAutoPlay || _wasSingleAutoPlay) {
var mediaProxy:MediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy;
var sequenceProxy:SequenceProxy = facade.retrieveProxy(SequenceProxy.NAME) as SequenceProxy;
if (_wasAutoPlay)
{
_configProxy.vo.flashvars.autoPlay = "true";
}
else
{
mediaProxy.vo.singleAutoPlay = true;
}
//play if we should have played
if (!_playedPlayed && !mediaProxy.vo.isMediaDisabled && !sequenceProxy.vo.isInSequence)
{
sendNotification(NotificationType.DO_PLAY);
}
}
sendNotification(NotificationType.ENABLE_GUI, {guiEnabled: true, enableType: EnableType.FULL});
}
}
}
|
support in "allowCookies" flashvar
|
qnd: support in "allowCookies" flashvar
git-svn-id: 3f608e5a9a704dd448217c0a64c508e7f145cfa1@85787 6b8eccd3-e8c5-4e7d-8186-e12b5326b719
|
ActionScript
|
agpl-3.0
|
kaltura/kdp,shvyrev/kdp,shvyrev/kdp,kaltura/kdp,kaltura/kdp,shvyrev/kdp
|
79283e416a659093b7b3cdd493e393a9d8c38f49
|
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;
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 (PortalModel.getInstance().hasSameOrigin(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 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
&& (serverInfo.authInfo.tokenServicesUrl || serverInfo.authInfo.tokenServiceUrl));
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();
const tokenServiceURL:String = serverInfo.authInfo.tokenServicesUrl || serverInfo.authInfo.tokenServiceUrl;
tokenServiceCrossDomainRequest.url = extractCrossDomainPolicyFileURL(tokenServiceURL);
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;
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 (PortalModel.getInstance().hasSameOrigin(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 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
&& (serverInfo.authInfo.tokenServicesUrl || serverInfo.authInfo.tokenServiceUrl));
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();
const tokenServiceURL:String = serverInfo.authInfo.tokenServicesUrl || serverInfo.authInfo.tokenServiceUrl;
tokenServiceCrossDomainRequest.url = extractCrossDomainPolicyFileURL(tokenServiceURL);
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);
}
}
}
|
Trim trailing characters when extracting the server info URL.
|
Trim trailing characters when extracting the server info URL.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
249ac6912541cdd6eff1d6ec04f86a1de1f6e597
|
FlexUnit4Test/src/org/flexunit/experimental/theories/internals/cases/ParameterizedAssertionErrorCase.as
|
FlexUnit4Test/src/org/flexunit/experimental/theories/internals/cases/ParameterizedAssertionErrorCase.as
|
package org.flexunit.experimental.theories.internals.cases
{
import org.flexunit.Assert;
import org.flexunit.experimental.theories.internals.ParameterizedAssertionError;
public class ParameterizedAssertionErrorCase
{
//TODO: Ensure that these tests and this test case are being implemented correctly.
//It is currently impossible to test the stringValueOf function.
[Test(description="Ensure that the ParameterizedAssertionError constructor is correctly assigning parameter values")]
public function constructorTest():void {
var targetException:Error = new Error();
var methodName:String = "methodName";
var params:Array = new Array("valueOne", "valueTwo");
var parameterizedAssertionError:ParameterizedAssertionError = new ParameterizedAssertionError(targetException, methodName, "valueOne", "valueTwo");
var message:String = methodName + " " + params.join( ", " );
Assert.assertEquals( message, parameterizedAssertionError.message);
Assert.assertEquals( targetException, parameterizedAssertionError.targetException );
}
[Test(description="Ensure that the join function is correctly joining the delimiter to the other parameters")]
public function joinTest():void {
var delimiter:String = ", ";
var params:Array = new Array("valueOne", "valueTwo", "valueThree");
var message:String = params.join( delimiter );
Assert.assertEquals( message, ParameterizedAssertionError.join(delimiter, "valueOne", "valueTwo", "valueThree") );
}
}
}
|
package org.flexunit.experimental.theories.internals.cases
{
import org.flexunit.Assert;
import org.flexunit.experimental.theories.internals.ParameterizedAssertionError;
public class ParameterizedAssertionErrorCase
{
//TODO: Ensure that these tests and this test case are being implemented correctly.
//It is currently impossible to test the stringValueOf function.
[Ignore("Currently Ignoring Test as this functionality is under investigation due to Max stack overflow issue")]
[Test(description="Ensure that the ParameterizedAssertionError constructor is correctly assigning parameter values")]
public function constructorTest():void {
var targetException:Error = new Error();
var methodName:String = "methodName";
var params:Array = new Array("valueOne", "valueTwo");
var parameterizedAssertionError:ParameterizedAssertionError = new ParameterizedAssertionError(targetException, methodName, "valueOne", "valueTwo");
var message:String = methodName + " " + params.join( ", " );
Assert.assertEquals( message, parameterizedAssertionError.message);
Assert.assertEquals( targetException, parameterizedAssertionError.targetException );
}
[Test(description="Ensure that the join function is correctly joining the delimiter to the other parameters")]
public function joinTest():void {
var delimiter:String = ", ";
var params:Array = new Array("valueOne", "valueTwo", "valueThree");
var message:String = params.join( delimiter );
Assert.assertEquals( message, ParameterizedAssertionError.join(delimiter, "valueOne", "valueTwo", "valueThree") );
}
}
}
|
Set test to ignore while stack trace is still under investigation
|
Set test to ignore while stack trace is still under investigation
|
ActionScript
|
apache-2.0
|
SlavaRa/flex-flexunit,SlavaRa/flex-flexunit,SlavaRa/flex-flexunit,apache/flex-flexunit,apache/flex-flexunit,apache/flex-flexunit,SlavaRa/flex-flexunit,apache/flex-flexunit
|
ca805a0b6c6223368926e7b332ad971cf936a2b7
|
frameworks/as/src/org/apache/flex/html/staticControls/beads/TextFieldBeadBase.as
|
frameworks/as/src/org/apache/flex/html/staticControls/beads/TextFieldBeadBase.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.display.DisplayObjectContainer;
import org.apache.flex.core.CSSTextField;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.ITextBead;
import org.apache.flex.core.ITextModel;
import org.apache.flex.events.Event;
public class TextFieldBeadBase implements IBead, ITextBead
{
public function TextFieldBeadBase()
{
_textField = new CSSTextField();
}
private var _textField:CSSTextField;
public function get textField() : CSSTextField
{
return _textField;
}
private var _textModel:ITextModel;
public function get textModel() : ITextModel
{
return _textModel;
}
private var _strand:IStrand;
public function set strand(value:IStrand):void
{
_strand = value;
_textModel = value.getBeadByType(ITextModel) as ITextModel;
textModel.addEventListener("textChange", textChangeHandler);
textModel.addEventListener("htmlChange", htmlChangeHandler);
textModel.addEventListener("widthChanged", sizeChangeHandler);
textModel.addEventListener("heightChanged", sizeChangeHandler);
DisplayObjectContainer(value).addChild(_textField);
sizeChangeHandler(null);
if (textModel.text !== null)
text = textModel.text;
if (textModel.html !== null)
html = textModel.html;
}
public function get strand() : IStrand
{
return _strand;
}
public function get text():String
{
return _textField.text;
}
public function set text(value:String):void
{
_textField.text = value;
}
public function get html():String
{
return _textField.htmlText;
}
public function set html(value:String):void
{
_textField.htmlText = value;
}
private function textChangeHandler(event:Event):void
{
text = textModel.text;
}
private function htmlChangeHandler(event:Event):void
{
html = textModel.html;
}
private function sizeChangeHandler(event:Event):void
{
textField.width = DisplayObject(_strand).width;
textField.height = DisplayObject(_strand).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.staticControls.beads
{
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import org.apache.flex.core.CSSTextField;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.ITextBead;
import org.apache.flex.core.ITextModel;
import org.apache.flex.events.Event;
public class TextFieldBeadBase implements IBead, ITextBead
{
public function TextFieldBeadBase()
{
_textField = new CSSTextField();
}
private var _textField:CSSTextField;
public function get textField() : CSSTextField
{
return _textField;
}
private var _textModel:ITextModel;
public function get textModel() : ITextModel
{
return _textModel;
}
private var _strand:IStrand;
public function set strand(value:IStrand):void
{
_strand = value;
_textModel = value.getBeadByType(ITextModel) as ITextModel;
textModel.addEventListener("textChange", textChangeHandler);
textModel.addEventListener("htmlChange", htmlChangeHandler);
textModel.addEventListener("widthChanged", sizeChangeHandler);
textModel.addEventListener("heightChanged", sizeChangeHandler);
DisplayObjectContainer(value).addChild(_textField);
sizeChangeHandler(null);
if (textModel.text !== null)
text = textModel.text;
if (textModel.html !== null)
html = textModel.html;
}
public function get strand() : IStrand
{
return _strand;
}
public function get text():String
{
return _textField.text;
}
public function set text(value:String):void
{
if (value == null)
value == "";
_textField.text = value;
}
public function get html():String
{
return _textField.htmlText;
}
public function set html(value:String):void
{
_textField.htmlText = value;
}
private function textChangeHandler(event:Event):void
{
text = textModel.text;
}
private function htmlChangeHandler(event:Event):void
{
html = textModel.html;
}
private function sizeChangeHandler(event:Event):void
{
textField.width = DisplayObject(_strand).width;
textField.height = DisplayObject(_strand).height;
}
}
}
|
handle null to prevent RTE
|
handle null to prevent RTE
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
00393ef22513587ea0794bea5571c589672bfdaa
|
src/asx/array/inject.as
|
src/asx/array/inject.as
|
package asx.array {
/**
* Injects the memo value into an iterator function that is applied to every item in the array.
*
* @param memo Initial value to pass to the iterator
* @param array Array of values to apply the iterator to
* @param iterator Function to be applied to each value. Function signature must match one of:
* <ul>
* <li>function(memo:Object, value:Object):Object;</li>
* <li>function(memo:Object, value:Object, i:int):Object;</li>
* <li>function(memo:Object, value:Object, i:int, a:Array):Object;</li>
* </ul>
* @return result of applying the memo and value of each array item to the iterator
* @example Summing an array of numbers can be implemented with inject.
* <listing version="3.0">
* var numbers:Array = [1, 2, 3, 4, 5];
* var sum:Number = inject(0, function(total:Number, n:Number):Number {
* return total + n;
* });
* </listing>
*/
public function inject(memo:Object, array:Array, iterator:Function):Object {
array.forEach(function(value:Object, i:int, a:Array):void {
memo = iterator.apply(null, [memo, value, i, a].slice(0, Math.max(2, iterator.length)));
});
return memo;
}
}
|
package asx.array {
/**
* Injects the memo value into an iterator function that is applied to every item in the array.
*
* @param memo Initial value to pass to the iterator
* @param array Array of values to apply the iterator to
* @param iterator Function to be applied to each value. Function signature must match one of:
* <ul>
* <li>function(memo:Object, value:Object):Object;</li>
* <li>function(memo:Object, value:Object, i:int):Object;</li>
* <li>function(memo:Object, value:Object, i:int, a:Array):Object;</li>
* </ul>
* @return result of applying the memo and value of each array item to the iterator
* @example Summing an array of numbers can be implemented with inject.
* <listing version="3.0">
* var numbers:Array = [1, 2, 3, 4, 5];
* var sum:Number = inject(0, numbers, function(total:Number, n:Number):Number {
* return total + n;
* });
* </listing>
*/
public function inject(memo:Object, array:Array, iterator:Function):Object {
array.forEach(function(value:Object, i:int, a:Array):void {
memo = iterator.apply(null, [memo, value, i, a].slice(0, Math.max(2, iterator.length)));
});
return memo;
}
}
|
correct example for asx.array.inject
|
correct example for asx.array.inject
|
ActionScript
|
mit
|
drewbourne/asx,drewbourne/asx
|
ba9e3f96eac2a1a78ed100fc47cb8ab9e6d0f5a9
|
dolly-framework/src/test/actionscript/dolly/CloningOfCloneableClassTest.as
|
dolly-framework/src/test/actionscript/dolly/CloningOfCloneableClassTest.as
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.CloneableClass;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertNotNull;
use namespace dolly_internal;
public class CloningOfCloneableClassTest {
private var cloneableClass:CloneableClass;
private var cloneableClassType:Type;
[Before]
public function before():void {
cloneableClass = new CloneableClass();
cloneableClass.property1 = "property1 value";
cloneableClass.writableField1 = "writableField1 value";
cloneableClassType = Type.forInstance(cloneableClass);
}
[After]
public function after():void {
cloneableClass = null;
cloneableClassType = null;
}
[Test]
public function findingAllWritableFieldsForType():void {
const writableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(cloneableClassType);
assertNotNull(writableFields);
assertEquals(4, writableFields.length);
}
[Test]
public function cloningByCloner():void {
const clone:CloneableClass = Cloner.clone(cloneableClass);
assertNotNull(clone);
assertNotNull(clone.property1);
assertEquals(clone.property1, cloneableClass.property1);
assertNotNull(clone.writableField1);
assertEquals(clone.writableField1, cloneableClass.writableField1);
}
[Test]
public function cloningByCloneFunction():void {
const classLevelClone:CloneableClass = clone(cloneableClass);
assertNotNull(classLevelClone);
assertNotNull(classLevelClone.property1);
assertEquals(classLevelClone.property1, cloneableClass.property1);
assertNotNull(classLevelClone.writableField1);
assertEquals(classLevelClone.writableField1, cloneableClass.writableField1);
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.CloneableClass;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertNotNull;
use namespace dolly_internal;
public class CloningOfCloneableClassTest {
private var cloneableClass:CloneableClass;
private var cloneableClassType:Type;
[Before]
public function before():void {
cloneableClass = new CloneableClass();
cloneableClass.property1 = "property1 value";
cloneableClass.writableField1 = "writableField1 value";
cloneableClassType = Type.forInstance(cloneableClass);
}
[After]
public function after():void {
cloneableClass = null;
cloneableClassType = null;
}
[Test]
public function findingAllWritableFieldsForType():void {
const writableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(cloneableClassType);
assertNotNull(writableFields);
assertEquals(2, writableFields.length);
}
[Test]
public function cloningByCloner():void {
const clone:CloneableClass = Cloner.clone(cloneableClass);
assertNotNull(clone);
assertNotNull(clone.property1);
assertEquals(clone.property1, cloneableClass.property1);
assertNotNull(clone.writableField1);
assertEquals(clone.writableField1, cloneableClass.writableField1);
}
[Test]
public function cloningByCloneFunction():void {
const classLevelClone:CloneableClass = clone(cloneableClass);
assertNotNull(classLevelClone);
assertNotNull(classLevelClone.property1);
assertEquals(classLevelClone.property1, cloneableClass.property1);
assertNotNull(classLevelClone.writableField1);
assertEquals(classLevelClone.writableField1, cloneableClass.writableField1);
}
}
}
|
Change expected value to 2 in test.
|
Change expected value to 2 in test.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
51400761671119fb9726de776b4db69a69dbbb9f
|
test/trace/trace_properties.as
|
test/trace/trace_properties.as
|
#if __SWF_VERSION__ == 5
// create a _global object, since it doesn't have one, these are ver 6 values
_global = new_empty_object ();
_global.ASSetNative = ASSetNative;
_global.ASSetNativeAccessor = ASSetNativeAccessor;
_global.ASSetPropFlags = ASSetPropFlags;
_global.ASconstructor = ASconstructor;
_global.ASnative = ASnative;
_global.Accessibility = Accessibility;
_global.Array = Array;
_global.AsBroadcaster = AsBroadcaster;
_global.AsSetupError = AsSetupError;
_global.Boolean = Boolean;
_global.Button = Button;
_global.Camera = Camera;
_global.Color = Color;
_global.ContextMenu = ContextMenu;
_global.ContextMenuItem = ContextMenuItem;
_global.Date = Date;
_global.Error = Error;
_global.Function = Function;
_global.Infinity = Infinity;
_global.Key = Key;
_global.LoadVars = LoadVars;
_global.LocalConnection = LocalConnection;
_global.Math = Math;
_global.Microphone = Microphone;
_global.Mouse = Mouse;
_global.MovieClip = MovieClip;
_global.MovieClipLoader = MovieClipLoader;
_global.NaN = NaN;
_global.NetConnection = NetConnection;
_global.NetStream = NetStream;
_global.Number = Number;
_global.Object = Object;
_global.PrintJob = PrintJob;
_global.RemoteLSOUsage = RemoteLSOUsage;
_global.Selection = Selection;
_global.SharedObject = SharedObject;
_global.Sound = Sound;
_global.Stage = Stage;
_global.String = String;
_global.System = System;
_global.TextField = TextField;
_global.TextFormat = TextFormat;
_global.TextSnapshot = TextSnapshot;
_global.Video = Video;
_global.XML = XML;
_global.XMLNode = XMLNode;
_global.XMLSocket = XMLSocket;
_global.clearInterval = clearInterval;
_global.clearTimeout = clearTimeout;
_global.enableDebugConsole = enableDebugConsole;
_global.escape = escape;
_global.flash = flash;
_global.isFinite = isFinite;
_global.isNaN = isNaN;
_global.o = o;
_global.parseFloat = parseFloat;
_global.parseInt = parseInt;
_global.setInterval = setInterval;
_global.setTimeout = setTimeout;
_global.showRedrawRegions = showRedrawRegions;
_global.textRenderer = textRenderer;
_global.trace = trace;
_global.unescape = unescape;
_global.updateAfterEvent = updateAfterEvent;
#endif
function new_empty_object () {
var hash = new Object ();
ASSetPropFlags (hash, null, 0, 7);
for (var prop in hash) {
hash[prop] = "to-be-deleted";
delete hash[prop];
}
return hash;
}
function hasOwnProperty_inner (o, prop)
{
if (o.hasOwnProperty != undefined)
return o.hasOwnProperty (prop);
o.hasOwnProperty = ASnative (101, 5);
var result = o.hasOwnProperty (prop);
delete o.hasOwnProperty;
return result;
}
function hasOwnProperty (o, prop)
{
var result = hasOwnProperty_inner (o, prop);
#if __SWF_VERSION__ != 6
if (result == false) {
ASSetPropFlags (o, prop, 0, 256);
result = hasOwnProperty_inner (o, prop);
if (result)
ASSetPropFlags (o, prop, 256);
}
#endif
return result;
}
function new_info () {
return new_empty_object ();
}
function set_info (info, prop, id, value) {
info[prop + "_-_" + id] = value;
}
function get_info (info, prop, id) {
return info[prop + "_-_" + id];
}
function is_blaclisted (o, prop)
{
if (prop == "mySecretId" || prop == "globalSecretId")
return true;
if (o == _global.Camera && prop == "names")
return true;
if (o == _global.Microphone && prop == "names")
return true;
#if __SWF_VERSION__ < 6
if (prop == "__proto__" && o[prop] == undefined)
return true;
#endif
return false;
}
function trace_properties_recurse (o, prefix, identifier, level)
{
// to collect info about different properties
var info = new_info ();
// calculate indentation
var indentation = "";
for (var j = 0; j < level; j++) {
indentation = indentation + " ";
}
// mark the ones that are not hidden
for (var prop in o)
{
// only get the ones that are not only in the __proto__
if (is_blaclisted (o, prop) == false) {
if (hasOwnProperty (o, prop) == true)
set_info (info, prop, "hidden", false);
}
}
// unhide everything
ASSetPropFlags (o, null, 0, 1);
var all = new Array ();
var hidden = new Array ();
for (var prop in o)
{
// only get the ones that are not only in the __proto__
if (is_blaclisted (o, prop) == false) {
if (hasOwnProperty (o, prop) == true) {
all.push (prop);
if (get_info (info, prop, "hidden") != false) {
set_info (info, prop, "hidden", true);
hidden.push (prop);
}
}
}
}
all.sort ();
// hide the ones that were already hidden
ASSetPropFlags (o, hidden, 1, 0);
if (all.length == 0) {
trace (indentation + "no children");
return nextSecretId;
}
#if __SWF_VERSION__ != 6
for (var i = 0; i < all.length; i++)
{
var prop = all[i];
// try changing value
if (!hasOwnProperty_inner(o, prop) && hasOwnProperty(o, prop))
{
set_info (info, prop, "not6", true);
}
else
{
set_info (info, prop, "not6", false);
}
}
#endif
for (var i = 0; i < all.length; i++)
{
var prop = all[i];
if (typeof (o[prop]) == "undefined") {
ASSetPropFlags (o, prop, 0, 5248);
if (typeof (o[prop]) != "undefined") {
set_info (info, prop, "newer", true);
// don't set the flags back
} else {
set_info (info, prop, "newer", false);
}
} else {
set_info (info, prop, "newer", false);
}
}
for (var i = 0; i < all.length; i++)
{
var prop = all[i];
// try changing value
var old = o[prop];
var val = "hello " + o[prop];
o[prop] = val;
if (o[prop] != val)
{
set_info (info, prop, "constant", true);
// try changing value after removing constant propflag
ASSetPropFlags (o, prop, 0, 4);
o[prop] = val;
if (o[prop] != val) {
set_info (info, prop, "superconstant", true);
} else {
set_info (info, prop, "superconstant", false);
o[prop] = old;
}
ASSetPropFlags (o, prop, 4);
}
else
{
set_info (info, prop, "constant", false);
set_info (info, prop, "superconstant", false);
o[prop] = old;
}
}
for (var i = 0; i < all.length; i++)
{
var prop = all[i];
// remove constant flag
ASSetPropFlags (o, prop, 0, 4);
// try deleting
var old = o[prop];
delete o[prop];
if (hasOwnProperty (o, prop))
{
set_info (info, prop, "permanent", true);
}
else
{
set_info (info, prop, "permanent", false);
o[prop] = old;
}
// put constant flag back, if it was set
if (get_info (info, prop, "constant") == true)
ASSetPropFlags (o, prop, 4);
}
for (var i = 0; i < all.length; i++) {
var prop = all[i];
// format propflags
var flags = "";
if (get_info (info, prop, "hidden") == true) {
flags += "h";
}
if (get_info (info, prop, "superpermanent") == true) {
flags += "P";
} else if (get_info (info, prop, "permanent") == true) {
flags += "p";
}
if (get_info (info, prop, "superconstant") == true) {
flags += "C";
} else if (get_info (info, prop, "constant") == true) {
flags += "c";
}
if (get_info (info, prop, "not6") == true) {
flags += "6";
}
if (get_info (info, prop, "newer") == true) {
flags += "n";
}
if (flags != "")
flags = " (" + flags + ")";
var value = "";
// add value depending on the type
if (typeof (o[prop]) == "number" || typeof (o[prop]) == "boolean") {
value += " : " + o[prop];
} else if (typeof (o[prop]) == "string") {
value += " : \"" + o[prop] + "\"";
}
// recurse if it's object or function and this is the place it has been
// named after
if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function")
{
if (prefix + (prefix != "" ? "." : "") + identifier + "." + prop ==
o[prop]["mySecretId"])
{
trace (indentation + prop + flags + " = " + typeof (o[prop]));
trace_properties_recurse (o[prop], prefix + (prefix != "" ? "." : "") +
identifier, prop, level + 1);
}
else
{
trace (indentation + prop + flags + " = " + o[prop]["mySecretId"]);
}
}
else
{
trace (indentation + prop + flags + " = " + typeof (o[prop]) + value);
}
}
}
function generate_names (o, prefix, identifier)
{
// mark the ones that are not hidden
var nothidden = new Array ();
for (var prop in o) {
nothidden.push (prop);
}
// unhide everything
ASSetPropFlags (o, null, 0, 1);
var all = new Array ();
for (var prop in o)
{
if (is_blaclisted (o, prop) == false) {
// only get the ones that are not only in the __proto__
if (hasOwnProperty (o, prop) == true) {
all.push (prop);
}
}
}
all.sort ();
// hide the ones that were already hidden
ASSetPropFlags (o, null, 1, 0);
ASSetPropFlags (o, nothidden, 0, 1);
for (var i = 0; i < all.length; i++) {
var newer = false;
var prop = all[i];
if (typeof (o[prop]) == "undefined") {
ASSetPropFlags (o, prop, 0, 5248);
if (typeof (o[prop]) != "undefined")
newer = true;
}
if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function") {
if (hasOwnProperty (o[prop], "mySecretId")) {
all[i] = null; // don't recurse to it again
} else {
o[prop]["mySecretId"] = prefix + (prefix != "" ? "." : "") +
identifier + "." + prop;
}
}
if (newer == true)
ASSetPropFlags (o, prop, 5248);
}
for (var i = 0; i < all.length; i++) {
var prop = all[i];
if (prop != null) {
var newer = false;
if (typeof (o[prop]) == "undefined") {
ASSetPropFlags (o, prop, 0, 5248);
if (typeof (o[prop]) != "undefined")
newer = true;
}
if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function")
generate_names (o[prop], prefix + (prefix != "" ? "." : "") +
identifier, prop);
if (newer == true)
ASSetPropFlags (o, prop, 5248);
}
}
}
function trace_properties (o, prefix, identifier)
{
_global["mySecretId"] = "_global";
_global.Object["mySecretId"] = "_global.Object";
_global.XMLNode["mySecretId"] = "_global.XMLNode";
generate_names (_global.Object, "_global", "Object");
generate_names (_global.XMLNode, "_global", "XMLNode");
generate_names (_global, "", "_global");
if (typeof (o) == "object" || typeof (o) == "function")
{
if (!o.hasOwnProperty ("mySecretId")) {
o["mySecretId"] = prefix + (prefix != "" ? "." : "") + identifier;
generate_names (o, prefix, identifier);
}
if (prefix + (prefix != "" ? "." : "") + identifier == o["mySecretId"])
{
trace (prefix + (prefix != "" ? "." : "") + identifier + " = " +
typeof (o));
}
else
{
trace (prefix + (prefix != "" ? "." : "") + identifier + " = " +
o["mySecretId"]);
}
trace_properties_recurse (o, prefix, identifier, 1);
}
else
{
var value = "";
if (typeof (o) == "number" || typeof (o) == "boolean") {
value += " : " + o;
} else if (typeof (o) == "string") {
value += " : \"" + o + "\"";
}
trace (prefix + (prefix != "" ? "." : "") + identifier + " = " +
typeof (o) + value);
}
}
|
#if __SWF_VERSION__ == 5
// create a _global object, since it doesn't have one, these are ver 6 values
_global = new_empty_object ();
_global.ASSetNative = ASSetNative;
_global.ASSetNativeAccessor = ASSetNativeAccessor;
_global.ASSetPropFlags = ASSetPropFlags;
_global.ASconstructor = ASconstructor;
_global.ASnative = ASnative;
_global.Accessibility = Accessibility;
_global.Array = Array;
_global.AsBroadcaster = AsBroadcaster;
_global.AsSetupError = AsSetupError;
_global.Boolean = Boolean;
_global.Button = Button;
_global.Camera = Camera;
_global.Color = Color;
_global.ContextMenu = ContextMenu;
_global.ContextMenuItem = ContextMenuItem;
_global.Date = Date;
_global.Error = Error;
_global.Function = Function;
_global.Infinity = Infinity;
_global.Key = Key;
_global.LoadVars = LoadVars;
_global.LocalConnection = LocalConnection;
_global.Math = Math;
_global.Microphone = Microphone;
_global.Mouse = Mouse;
_global.MovieClip = MovieClip;
_global.MovieClipLoader = MovieClipLoader;
_global.NaN = NaN;
_global.NetConnection = NetConnection;
_global.NetStream = NetStream;
_global.Number = Number;
_global.Object = Object;
_global.PrintJob = PrintJob;
_global.RemoteLSOUsage = RemoteLSOUsage;
_global.Selection = Selection;
_global.SharedObject = SharedObject;
_global.Sound = Sound;
_global.Stage = Stage;
_global.String = String;
_global.System = System;
_global.TextField = TextField;
_global.TextFormat = TextFormat;
_global.TextSnapshot = TextSnapshot;
_global.Video = Video;
_global.XML = XML;
_global.XMLNode = XMLNode;
_global.XMLSocket = XMLSocket;
_global.clearInterval = clearInterval;
_global.clearTimeout = clearTimeout;
_global.enableDebugConsole = enableDebugConsole;
_global.escape = escape;
_global.flash = flash;
_global.isFinite = isFinite;
_global.isNaN = isNaN;
_global.o = o;
_global.parseFloat = parseFloat;
_global.parseInt = parseInt;
_global.setInterval = setInterval;
_global.setTimeout = setTimeout;
_global.showRedrawRegions = showRedrawRegions;
_global.textRenderer = textRenderer;
_global.trace = trace;
_global.unescape = unescape;
_global.updateAfterEvent = updateAfterEvent;
#endif
function new_empty_object () {
var hash = new Object ();
ASSetPropFlags (hash, null, 0, 7);
for (var prop in hash) {
hash[prop] = "to-be-deleted";
delete hash[prop];
}
return hash;
}
function hasOwnProperty_inner (o, prop)
{
if (o.hasOwnProperty != undefined)
return o.hasOwnProperty (prop);
o.hasOwnProperty = ASnative (101, 5);
var result = o.hasOwnProperty (prop);
delete o.hasOwnProperty;
return result;
}
function hasOwnProperty (o, prop)
{
var result = hasOwnProperty_inner (o, prop);
#if __SWF_VERSION__ != 6
if (result == false) {
ASSetPropFlags (o, prop, 0, 256);
result = hasOwnProperty_inner (o, prop);
if (result)
ASSetPropFlags (o, prop, 256);
}
#endif
return result;
}
function new_info () {
return new_empty_object ();
}
function set_info (info, prop, id, value) {
info[prop + "_-_" + id] = value;
}
function get_info (info, prop, id) {
return info[prop + "_-_" + id];
}
function is_blaclisted (o, prop)
{
if (prop == "mySecretId" || prop == "globalSecretId")
return true;
if (o == _global.Camera && prop == "names")
return true;
if (o == _global.Microphone && prop == "names")
return true;
#if __SWF_VERSION__ < 6
if (prop == "__proto__" && o[prop] == undefined)
return true;
#endif
return false;
}
function trace_properties_recurse (o, prefix, identifier, level)
{
// to collect info about different properties
var info = new_info ();
// calculate indentation
var indentation = "";
for (var j = 0; j < level; j++) {
indentation = indentation + " ";
}
// mark the ones that are not hidden
for (var prop in o)
{
// only get the ones that are not only in the __proto__
if (is_blaclisted (o, prop) == false) {
if (hasOwnProperty (o, prop) == true)
set_info (info, prop, "hidden", false);
}
}
// unhide everything
ASSetPropFlags (o, null, 0, 1);
var all = new Array ();
var hidden = new Array ();
for (var prop in o)
{
// only get the ones that are not only in the __proto__
if (is_blaclisted (o, prop) == false) {
if (hasOwnProperty (o, prop) == true) {
all.push (prop);
if (get_info (info, prop, "hidden") != false) {
set_info (info, prop, "hidden", true);
hidden.push (prop);
}
}
}
}
all.sort ();
// hide the ones that were already hidden
ASSetPropFlags (o, hidden, 1, 0);
if (all.length == 0) {
trace (indentation + "no children");
return nextSecretId;
}
#if __SWF_VERSION__ != 6
for (var i = 0; i < all.length; i++)
{
var prop = all[i];
// try changing value
if (!hasOwnProperty_inner(o, prop) && hasOwnProperty(o, prop))
{
set_info (info, prop, "not6", true);
}
else
{
set_info (info, prop, "not6", false);
}
}
#endif
for (var i = 0; i < all.length; i++)
{
var prop = all[i];
if (typeof (o[prop]) == "undefined") {
ASSetPropFlags (o, prop, 0, 5248);
if (typeof (o[prop]) != "undefined") {
set_info (info, prop, "newer", true);
// don't set the flags back
} else {
set_info (info, prop, "newer", false);
}
} else {
set_info (info, prop, "newer", false);
}
}
for (var i = 0; i < all.length; i++)
{
var prop = all[i];
// try changing value
var old = o[prop];
var val = "hello " + o[prop];
o[prop] = val;
if (o[prop] != val)
{
set_info (info, prop, "constant", true);
// try changing value after removing constant propflag
ASSetPropFlags (o, prop, 0, 4);
o[prop] = val;
if (o[prop] != val) {
set_info (info, prop, "superconstant", true);
} else {
set_info (info, prop, "superconstant", false);
o[prop] = old;
}
ASSetPropFlags (o, prop, 4);
}
else
{
set_info (info, prop, "constant", false);
set_info (info, prop, "superconstant", false);
o[prop] = old;
}
}
for (var i = 0; i < all.length; i++)
{
var prop = all[i];
// remove constant flag
ASSetPropFlags (o, prop, 0, 4);
// try deleting
var old = o[prop];
delete o[prop];
if (hasOwnProperty (o, prop))
{
set_info (info, prop, "permanent", true);
}
else
{
set_info (info, prop, "permanent", false);
o[prop] = old;
}
// put constant flag back, if it was set
if (get_info (info, prop, "constant") == true)
ASSetPropFlags (o, prop, 4);
}
for (var i = 0; i < all.length; i++) {
var prop = all[i];
// format propflags
var flags = "";
if (get_info (info, prop, "hidden") == true) {
flags += "h";
}
if (get_info (info, prop, "superpermanent") == true) {
flags += "P";
} else if (get_info (info, prop, "permanent") == true) {
flags += "p";
}
if (get_info (info, prop, "superconstant") == true) {
flags += "C";
} else if (get_info (info, prop, "constant") == true) {
flags += "c";
}
if (get_info (info, prop, "not6") == true) {
flags += "6";
}
if (get_info (info, prop, "newer") == true) {
flags += "n";
}
if (flags != "")
flags = " (" + flags + ")";
var value = "";
// add value depending on the type
if (typeof (o[prop]) == "number" || typeof (o[prop]) == "boolean") {
value += " : " + o[prop];
} else if (typeof (o[prop]) == "string") {
value += " : \"" + o[prop] + "\"";
}
// recurse if it's object or function and this is the place it has been
// named after
if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function")
{
if (prefix + (prefix != "" ? "." : "") + identifier + "." + prop ==
o[prop]["mySecretId"])
{
trace (indentation + prop + flags + " = " + typeof (o[prop]));
trace_properties_recurse (o[prop], prefix + (prefix != "" ? "." : "") +
identifier, prop, level + 1);
}
else
{
trace (indentation + prop + flags + " = " + o[prop]["mySecretId"]);
}
}
else
{
trace (indentation + prop + flags + " = " + typeof (o[prop]) + value);
}
}
}
function generate_names (o, prefix, identifier)
{
// mark the ones that are not hidden
var nothidden = new Array ();
for (var prop in o) {
nothidden.push (prop);
}
// unhide everything
ASSetPropFlags (o, null, 0, 1);
var all = new Array ();
for (var prop in o)
{
if (is_blaclisted (o, prop) == false) {
// only get the ones that are not only in the __proto__
if (hasOwnProperty (o, prop) == true) {
all.push (prop);
}
}
}
all.sort ();
// hide the ones that were already hidden
ASSetPropFlags (o, null, 1, 0);
ASSetPropFlags (o, nothidden, 0, 1);
for (var i = 0; i < all.length; i++) {
var newer = false;
var prop = all[i];
if (typeof (o[prop]) == "undefined") {
ASSetPropFlags (o, prop, 0, 5248);
if (typeof (o[prop]) != "undefined")
newer = true;
}
if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function") {
if (hasOwnProperty (o[prop], "mySecretId")) {
all[i] = null; // don't recurse to it again
} else {
o[prop]["mySecretId"] = prefix + (prefix != "" ? "." : "") +
identifier + "." + prop;
}
}
if (newer == true)
ASSetPropFlags (o, prop, 5248);
}
for (var i = 0; i < all.length; i++) {
var prop = all[i];
if (prop != null) {
var newer = false;
if (typeof (o[prop]) == "undefined") {
ASSetPropFlags (o, prop, 0, 5248);
if (typeof (o[prop]) != "undefined")
newer = true;
}
if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function")
generate_names (o[prop], prefix + (prefix != "" ? "." : "") +
identifier, prop);
if (newer == true)
ASSetPropFlags (o, prop, 5248);
}
}
}
function trace_properties (o, prefix, identifier)
{
_global["mySecretId"] = "_global";
_global.Object["mySecretId"] = "_global.Object";
_global.Function["mySecretId"] = "_global.Function";
_global.Function.prototype["mySecretId"] = "_global.Function.prototype";
_global.XMLNode["mySecretId"] = "_global.XMLNode";
generate_names (_global.Object, "_global", "Object");
generate_names (_global.Function, "_global", "Function");
generate_names (_global.Function.prototype, "_global", "Function.prototype");
generate_names (_global.XMLNode, "_global", "XMLNode");
generate_names (_global, "", "_global");
if (typeof (o) == "object" || typeof (o) == "function")
{
if (!o.hasOwnProperty ("mySecretId")) {
o["mySecretId"] = prefix + (prefix != "" ? "." : "") + identifier;
generate_names (o, prefix, identifier);
}
if (prefix + (prefix != "" ? "." : "") + identifier == o["mySecretId"])
{
trace (prefix + (prefix != "" ? "." : "") + identifier + " = " +
typeof (o));
}
else
{
trace (prefix + (prefix != "" ? "." : "") + identifier + " = " +
o["mySecretId"]);
}
trace_properties_recurse (o, prefix, identifier, 1);
}
else
{
var value = "";
if (typeof (o) == "number" || typeof (o) == "boolean") {
value += " : " + o;
} else if (typeof (o) == "string") {
value += " : \"" + o + "\"";
}
trace (prefix + (prefix != "" ? "." : "") + identifier + " = " +
typeof (o) + value);
}
}
|
Fix trace_properties.as to name Function and Function.prototype properly
|
Fix trace_properties.as to name Function and Function.prototype properly
|
ActionScript
|
lgpl-2.1
|
freedesktop-unofficial-mirror/swfdec__swfdec,mltframework/swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,mltframework/swfdec,freedesktop-unofficial-mirror/swfdec__swfdec
|
1d78e735372163cc4eb0d8e67d6280e64665c6f8
|
src/aerys/minko/render/shader/part/phong/attenuation/MatrixShadowMapAttenuationShaderPart.as
|
src/aerys/minko/render/shader/part/phong/attenuation/MatrixShadowMapAttenuationShaderPart.as
|
package aerys.minko.render.shader.part.phong.attenuation
{
import aerys.minko.render.material.phong.PhongProperties;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.part.phong.LightAwareShaderPart;
import aerys.minko.type.enum.SamplerFiltering;
import aerys.minko.type.enum.SamplerMipMapping;
import aerys.minko.type.enum.SamplerWrapping;
import aerys.minko.type.enum.ShadowMappingQuality;
/**
* Fixme, bias should be:Total bias is m*SLOPESCALE + DEPTHBIAS
* Where m = max( | ∂z/∂x | , | ∂z/∂y | )
* ftp://download.nvidia.com/developer/presentations/2004/GPU_Jackpot/Shadow_Mapping.pdf
*
* @author Romain Gilliotte
*/
public class MatrixShadowMapAttenuationShaderPart extends LightAwareShaderPart implements IAttenuationShaderPart
{
private static const DEFAULT_BIAS : Number = 1 / 256 / 256;
public function MatrixShadowMapAttenuationShaderPart(main : Shader)
{
super(main);
}
public function getAttenuation(lightId : uint) : SFloat
{
var lightType : uint = getLightConstant(lightId, 'type');
var screenPos : SFloat = interpolate(localToScreen(fsLocalPosition));
// retrieve shadow bias
var shadowBias : SFloat;
if (meshBindings.propertyExists(PhongProperties.SHADOW_BIAS))
shadowBias = meshBindings.getParameter(PhongProperties.SHADOW_BIAS, 1);
else if (sceneBindings.propertyExists(PhongProperties.SHADOW_BIAS))
shadowBias = sceneBindings.getParameter(PhongProperties.SHADOW_BIAS, 1);
else
shadowBias = float(DEFAULT_BIAS);
// retrieve depthmap and projection matrix
var worldToUV : SFloat = getLightParameter(lightId, 'worldToUV', 16);
var depthMap : SFloat = getLightTextureParameter(
lightId,
'shadowMap',
SamplerFiltering.NEAREST,
SamplerMipMapping.DISABLE,
SamplerWrapping.CLAMP
);
// read expected depth from shadow map, and compute current depth
var uv : SFloat;
uv = multiply4x4(vsWorldPosition, worldToUV);
uv = interpolate(uv);
var currentDepth : SFloat = uv.z;
currentDepth = min(subtract(1, shadowBias), currentDepth);
uv = divide(uv, uv.w);
var outsideMap : SFloat = notEqual(
0,
dotProduct4(notEqual(uv, saturate(uv)), notEqual(uv, saturate(uv)))
);
var precomputedDepth : SFloat = unpack(sampleTexture(depthMap, uv.xyyy));
var curDepthSubBias : SFloat = subtract(currentDepth, shadowBias);
var noShadows : SFloat = lessEqual(curDepthSubBias, precomputedDepth);
var quality : uint = getLightConstant(lightId, 'shadowQuality');
if (quality != ShadowMappingQuality.HARD)
{
var invertSize : SFloat = divide(
getLightParameter(lightId, 'shadowSpread', 1),
getLightParameter(lightId, 'shadowMapSize', 1)
);
var uvs : Vector.<SFloat> = new <SFloat>[];
var uvDelta : SFloat;
if (quality > ShadowMappingQuality.LOW)
{
uvDelta = multiply(float3(-1, 0, 1), invertSize);
uvs.push(
add(uv.xyxy, uvDelta.xxxy), // (-1, -1), (-1, 0)
add(uv.xyxy, uvDelta.xzyx), // (-1, 1), ( 0, -1)
add(uv.xyxy, uvDelta.yzzx), // ( 0, 1), ( 1, -1)
add(uv.xyxy, uvDelta.zyzz) // ( 1, 0), ( 1, 1)
);
}
if (quality > ShadowMappingQuality.MEDIUM)
{
uvDelta = multiply(float3(-2, 0, 2), invertSize);
uvs.push(
add(uv.xyxy, uvDelta.xyyx), // (-2, 0), (0, -2)
add(uv.xyxy, uvDelta.yzzy) // ( 0, 2), (2, 0)
);
}
if (quality > ShadowMappingQuality.HARD)
{
uvDelta = multiply(float4(-2, -1, 1, 2), invertSize);
uvs.push(
add(uv.xyxy, uvDelta.xzyw), // (-2, 1), (-1, 2)
add(uv.xyxy, uvDelta.zwwz), // ( 1, 2), ( 2, 1)
add(uv.xyxy, uvDelta.wyzx), // ( 2, -1), ( 1, -2)
add(uv.xyxy, uvDelta.xyyx) // (-2, -1), (-1, -2)
);
}
var numSamples : uint = uvs.length;
for (var sampleId : uint = 0; sampleId < numSamples; sampleId += 2)
{
precomputedDepth = float4(
unpack(sampleTexture(depthMap, uvs[sampleId].xy)),
unpack(sampleTexture(depthMap, uvs[sampleId].zw)),
unpack(sampleTexture(depthMap, uvs[sampleId + 1].xy)),
unpack(sampleTexture(depthMap, uvs[sampleId + 1].zw))
);
var localNoShadows : SFloat = lessEqual(curDepthSubBias, precomputedDepth);
noShadows.incrementBy(dotProduct4(localNoShadows, float4(1, 1, 1, 1)));
}
noShadows.scaleBy(1 / (2 * numSamples + 1));
}
return noShadows;
}
}
}
|
package aerys.minko.render.shader.part.phong.attenuation
{
import aerys.minko.render.material.phong.PhongProperties;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.part.phong.LightAwareShaderPart;
import aerys.minko.type.enum.SamplerFiltering;
import aerys.minko.type.enum.SamplerMipMapping;
import aerys.minko.type.enum.SamplerWrapping;
import aerys.minko.type.enum.ShadowMappingQuality;
/**
* Fixme, bias should be:Total bias is m*SLOPESCALE + DEPTHBIAS
* Where m = max( | ∂z/∂x | , | ∂z/∂y | )
* ftp://download.nvidia.com/developer/presentations/2004/GPU_Jackpot/Shadow_Mapping.pdf
*
* @author Romain Gilliotte
*/
public class MatrixShadowMapAttenuationShaderPart extends LightAwareShaderPart implements IAttenuationShaderPart
{
public function MatrixShadowMapAttenuationShaderPart(main : Shader)
{
super(main);
}
public function getAttenuation(lightId : uint) : SFloat
{
var lightType : uint = getLightConstant(lightId, 'type');
var screenPos : SFloat = interpolate(localToScreen(fsLocalPosition));
// retrieve shadow bias
var shadowBias : SFloat;
if (meshBindings.propertyExists(PhongProperties.SHADOW_BIAS))
shadowBias = meshBindings.getParameter(PhongProperties.SHADOW_BIAS, 1);
else
shadowBias = getLightParameter(lightId, PhongProperties.SHADOW_BIAS, 1);
// retrieve depthmap and projection matrix
var worldToUV : SFloat = getLightParameter(lightId, 'worldToUV', 16);
var depthMap : SFloat = getLightTextureParameter(
lightId,
'shadowMap',
SamplerFiltering.NEAREST,
SamplerMipMapping.DISABLE,
SamplerWrapping.CLAMP
);
// read expected depth from shadow map, and compute current depth
var uv : SFloat;
uv = multiply4x4(vsWorldPosition, worldToUV);
uv = interpolate(uv);
var currentDepth : SFloat = uv.z;
currentDepth = min(subtract(1, shadowBias), currentDepth);
uv = divide(uv, uv.w);
var outsideMap : SFloat = notEqual(
0,
dotProduct4(notEqual(uv, saturate(uv)), notEqual(uv, saturate(uv)))
);
var precomputedDepth : SFloat = unpack(sampleTexture(depthMap, uv.xyyy));
var curDepthSubBias : SFloat = subtract(currentDepth, shadowBias);
var noShadows : SFloat = lessEqual(curDepthSubBias, precomputedDepth);
var quality : uint = getLightConstant(lightId, 'shadowQuality');
if (quality != ShadowMappingQuality.HARD)
{
var invertSize : SFloat = divide(
getLightParameter(lightId, 'shadowSpread', 1),
getLightParameter(lightId, 'shadowMapSize', 1)
);
var uvs : Vector.<SFloat> = new <SFloat>[];
var uvDelta : SFloat;
if (quality > ShadowMappingQuality.LOW)
{
uvDelta = multiply(float3(-1, 0, 1), invertSize);
uvs.push(
add(uv.xyxy, uvDelta.xxxy), // (-1, -1), (-1, 0)
add(uv.xyxy, uvDelta.xzyx), // (-1, 1), ( 0, -1)
add(uv.xyxy, uvDelta.yzzx), // ( 0, 1), ( 1, -1)
add(uv.xyxy, uvDelta.zyzz) // ( 1, 0), ( 1, 1)
);
}
if (quality > ShadowMappingQuality.MEDIUM)
{
uvDelta = multiply(float3(-2, 0, 2), invertSize);
uvs.push(
add(uv.xyxy, uvDelta.xyyx), // (-2, 0), (0, -2)
add(uv.xyxy, uvDelta.yzzy) // ( 0, 2), (2, 0)
);
}
if (quality > ShadowMappingQuality.HARD)
{
uvDelta = multiply(float4(-2, -1, 1, 2), invertSize);
uvs.push(
add(uv.xyxy, uvDelta.xzyw), // (-2, 1), (-1, 2)
add(uv.xyxy, uvDelta.zwwz), // ( 1, 2), ( 2, 1)
add(uv.xyxy, uvDelta.wyzx), // ( 2, -1), ( 1, -2)
add(uv.xyxy, uvDelta.xyyx) // (-2, -1), (-1, -2)
);
}
var numSamples : uint = uvs.length;
for (var sampleId : uint = 0; sampleId < numSamples; sampleId += 2)
{
precomputedDepth = float4(
unpack(sampleTexture(depthMap, uvs[sampleId].xy)),
unpack(sampleTexture(depthMap, uvs[sampleId].zw)),
unpack(sampleTexture(depthMap, uvs[sampleId + 1].xy)),
unpack(sampleTexture(depthMap, uvs[sampleId + 1].zw))
);
var localNoShadows : SFloat = lessEqual(curDepthSubBias, precomputedDepth);
noShadows.incrementBy(dotProduct4(localNoShadows, float4(1, 1, 1, 1)));
}
noShadows.scaleBy(1 / (2 * numSamples + 1));
}
return noShadows;
}
}
}
|
read the shadow bias from the light data provider
|
read the shadow bias from the light data provider
|
ActionScript
|
mit
|
aerys/minko-as3
|
7295fb307d3a5494899d9f61d66204cee3d07f49
|
runtime/src/main/as/flump/mold/KeyframeMold.as
|
runtime/src/main/as/flump/mold/KeyframeMold.as
|
//
// Flump - Copyright 2013 Flump Authors
package flump.mold {
/** @private */
public class KeyframeMold
{
public var index :int;
/** The length of this keyframe in frames. */
public var duration :int;
/**
* The symbol of the image or movie in this keyframe, or null if there is nothing in it.
* For flipbook frames, this will be a name constructed out of the movie and frame index.
*/
public var ref :String;
/** The label on this keyframe, or null if there isn't one */
public var label :String;
/** Exploded values from matrix */
public var x :Number = 0.0, y :Number = 0.0, scaleX :Number = 1.0, scaleY :Number = 1.0,
skewX :Number = 0.0, skewY :Number = 0.0;
/** Transformation point */
public var pivotX :Number = 0.0, pivotY :Number = 0.0;
public var alpha :Number = 1;
public var visible :Boolean = true;
/** Is this keyframe tweened? */
public var tweened :Boolean = true;
/** Tween easing. Only valid if tweened==true. */
public var ease :Number = 0;
public static function fromJSON (o :Object) :KeyframeMold {
const mold :KeyframeMold = new KeyframeMold();
mold.index = require(o, "index");
mold.duration = require(o, "duration");
extractField(o, mold, "ref");
extractFields(o, mold, "loc", "x", "y");
extractFields(o, mold, "scale", "scaleX", "scaleY");
extractFields(o, mold, "skew", "skewX", "skewY");
extractFields(o, mold, "pivot", "pivotX", "pivotY");
extractField(o, mold, "alpha");
extractField(o, mold, "visible");
extractField(o, mold, "ease");
extractField(o, mold, "tweened");
extractField(o, mold, "label");
return mold;
}
/** True if this keyframe does not display anything. */
public function get isEmpty () :Boolean { return this.ref == null; }
public function get rotation () :Number { return skewX; }
// public function set rotation (angle :Number) :void { skewX = skewY = angle; }
public function rotate (delta :Number) :void {
skewX += delta;
skewY += delta;
}
public function toJSON (_:*) :Object {
var json :Object = {
index: index,
duration: duration
};
if (ref != null) {
json.ref = ref;
if (x != 0 || y != 0) json.loc = [round(x), round(y)];
if (scaleX != 1 || scaleY != 1) json.scale = [round(scaleX), round(scaleY)];
if (skewX != 0 || skewY != 0) json.skew = [round(skewX), round(skewY)];
if (pivotX != 0 || pivotY != 0) json.pivot = [round(pivotX), round(pivotY)];
if (alpha != 1) json.alpha = round(alpha);
if (!visible) json.visible = visible;
if (!tweened) json.tweened = tweened;
if (ease != 0) json.ease = round(ease);
}
if (label != null) json.label = label;
return json;
}
public function toXML () :XML {
var xml :XML = <kf duration={duration}/>;
if (ref != null) {
xml.@ref = ref;
if (x != 0 || y != 0) xml.@loc = "" + round(x) + "," + round(y);
if (scaleX != 1 || scaleY != 1) xml.@scale = "" + round(scaleX) + "," + round(scaleY);
if (skewX != 0 || skewY != 0) xml.@skew = "" + round(skewX) + "," + round(skewY);
if (pivotX != 0 || pivotY != 0) xml.@pivot = "" + round(pivotX) + "," + round(pivotY);
if (alpha != 1) xml.@alpha = round(alpha);
if (!visible) xml.@visible = visible;
if (!tweened) xml.@tweened = tweened;
if (ease != 0) xml.@ease = round(ease);
}
if (label != null) xml.@label = label;
return xml;
}
protected static function extractFields(o :Object, destObj :Object, source :String,
dest1 :String, dest2 :String) :void {
const extracted :* = o[source];
if (extracted === undefined) return;
destObj[dest1] = extracted[0];
destObj[dest2] = extracted[1];
}
protected static function extractField(o :Object, destObj :Object, field :String) :void {
const extracted :* = o[field];
if (extracted === undefined) return;
destObj[field] = extracted;
}
protected static function round (n :Number, places :int = 4) :Number {
const shift :int = Math.pow(10, places);
return Math.round(n * shift) / shift;
}
}
}
|
//
// Flump - Copyright 2013 Flump Authors
package flump.mold {
/** @private */
public class KeyframeMold
{
/**
* The index of the first frame in the keyframe.
* (Equivalent to prevKeyframe.index + prevKeyframe.duration)
*/
public var index :int;
/** The length of this keyframe in frames. */
public var duration :int;
/**
* The symbol of the image or movie in this keyframe, or null if there is nothing in it.
* For flipbook frames, this will be a name constructed out of the movie and frame index.
*/
public var ref :String;
/** The label on this keyframe, or null if there isn't one */
public var label :String;
/** Exploded values from matrix */
public var x :Number = 0.0, y :Number = 0.0, scaleX :Number = 1.0, scaleY :Number = 1.0,
skewX :Number = 0.0, skewY :Number = 0.0;
/** Transformation point */
public var pivotX :Number = 0.0, pivotY :Number = 0.0;
public var alpha :Number = 1;
public var visible :Boolean = true;
/** Is this keyframe tweened? */
public var tweened :Boolean = true;
/** Tween easing. Only valid if tweened==true. */
public var ease :Number = 0;
public static function fromJSON (o :Object) :KeyframeMold {
const mold :KeyframeMold = new KeyframeMold();
mold.index = require(o, "index");
mold.duration = require(o, "duration");
extractField(o, mold, "ref");
extractFields(o, mold, "loc", "x", "y");
extractFields(o, mold, "scale", "scaleX", "scaleY");
extractFields(o, mold, "skew", "skewX", "skewY");
extractFields(o, mold, "pivot", "pivotX", "pivotY");
extractField(o, mold, "alpha");
extractField(o, mold, "visible");
extractField(o, mold, "ease");
extractField(o, mold, "tweened");
extractField(o, mold, "label");
return mold;
}
/** True if this keyframe does not display anything. */
public function get isEmpty () :Boolean { return this.ref == null; }
public function get rotation () :Number { return skewX; }
// public function set rotation (angle :Number) :void { skewX = skewY = angle; }
public function rotate (delta :Number) :void {
skewX += delta;
skewY += delta;
}
public function toJSON (_:*) :Object {
var json :Object = {
index: index,
duration: duration
};
if (ref != null) {
json.ref = ref;
if (x != 0 || y != 0) json.loc = [round(x), round(y)];
if (scaleX != 1 || scaleY != 1) json.scale = [round(scaleX), round(scaleY)];
if (skewX != 0 || skewY != 0) json.skew = [round(skewX), round(skewY)];
if (pivotX != 0 || pivotY != 0) json.pivot = [round(pivotX), round(pivotY)];
if (alpha != 1) json.alpha = round(alpha);
if (!visible) json.visible = visible;
if (!tweened) json.tweened = tweened;
if (ease != 0) json.ease = round(ease);
}
if (label != null) json.label = label;
return json;
}
public function toXML () :XML {
var xml :XML = <kf duration={duration}/>;
if (ref != null) {
xml.@ref = ref;
if (x != 0 || y != 0) xml.@loc = "" + round(x) + "," + round(y);
if (scaleX != 1 || scaleY != 1) xml.@scale = "" + round(scaleX) + "," + round(scaleY);
if (skewX != 0 || skewY != 0) xml.@skew = "" + round(skewX) + "," + round(skewY);
if (pivotX != 0 || pivotY != 0) xml.@pivot = "" + round(pivotX) + "," + round(pivotY);
if (alpha != 1) xml.@alpha = round(alpha);
if (!visible) xml.@visible = visible;
if (!tweened) xml.@tweened = tweened;
if (ease != 0) xml.@ease = round(ease);
}
if (label != null) xml.@label = label;
return xml;
}
protected static function extractFields(o :Object, destObj :Object, source :String,
dest1 :String, dest2 :String) :void {
const extracted :* = o[source];
if (extracted === undefined) return;
destObj[dest1] = extracted[0];
destObj[dest2] = extracted[1];
}
protected static function extractField(o :Object, destObj :Object, field :String) :void {
const extracted :* = o[field];
if (extracted === undefined) return;
destObj[field] = extracted;
}
protected static function round (n :Number, places :int = 4) :Number {
const shift :int = Math.pow(10, places);
return Math.round(n * shift) / shift;
}
}
}
|
Add documentation for KeyframeMold.index
|
Add documentation for KeyframeMold.index
|
ActionScript
|
mit
|
mathieuanthoine/flump,tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump,tconkling/flump
|
a5d74b31c34433282913c5980b470566d117753c
|
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")]
/**
* 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"));
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.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;
}
}
}
|
make application a little more tolerant so it can be used in flexunit tests
|
make application a little more tolerant so it can be used in flexunit tests
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
4aaaa7cceee8848e06d66906b4c360aafc4f0d67
|
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();
}
/** 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:
}
}
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;
}
}
/** 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();
}
}
}
|
support playback even after playbak finished
|
support playback even after playbak finished
|
ActionScript
|
mpl-2.0
|
loungelogic/flashls,NicolasSiver/flashls,mangui/flashls,tedconf/flashls,vidible/vdb-flashls,clappr/flashls,jlacivita/flashls,neilrackett/flashls,codex-corp/flashls,hola/flashls,tedconf/flashls,neilrackett/flashls,clappr/flashls,NicolasSiver/flashls,mangui/flashls,thdtjsdn/flashls,loungelogic/flashls,hola/flashls,jlacivita/flashls,fixedmachine/flashls,vidible/vdb-flashls,codex-corp/flashls,thdtjsdn/flashls,fixedmachine/flashls
|
03be86ad8aeb43b363e89deb2efebc75add3d958
|
src/Modules/And.as
|
src/Modules/And.as
|
package Modules {
import Components.Port;
import Values.Value;
import Values.BooleanValue;
/**
* ...
* @author Nicholas "PleasingFungus" Feinberg
*/
public class And extends Module {
private var width:int;
public function And(X:int, Y:int, Width:int = 2) {
super(X, Y, "And", Module.CAT_LOGIC, Width, 1, 0);
width = Width;
configuration = new Configuration(new Range(2, 8, Width));
configurableInPlace = false;
delay = Math.ceil(Math.log(Width) / Math.log(2));
}
protected function resetPorts():void {
outputs = new Vector.<Port>;
outputs.push(new Port(true, this));
}
override public function renderDetails():String {
var out:String = "And\n\n";
for each (var input:Port in inputs)
out += input.getValue() + ',';
return out.slice(0, out.length - 1);
}
override public function getDescription():String {
return "Outputs "+BooleanValue.FALSE+" if any input is "+BooleanValue.FALSE+", else "+BooleanValue.TRUE+"."
}
override protected function getSaveValues():Array {
var values:Array = super.getSaveValues();
values.push(width);
return values;
}
override public function drive(port:Port):Value {
for each (var inputPort:Port in inputs) {
var inputValue:Value = inputPort.getValue();
if (inputValue.unknown || inputValue.unpowered)
return inputValue;
if (!BooleanValue.fromValue(inputValue).boolValue)
return BooleanValue.FALSE;
}
return BooleanValue.TRUE;
}
}
}
|
package Modules {
import Components.Port;
import Layouts.PortLayout;
import Layouts.InternalLayout;
import Layouts.Nodes.TallNode;
import Values.Value;
import Values.BooleanValue;
import flash.geom.Point;
/**
* ...
* @author Nicholas "PleasingFungus" Feinberg
*/
public class And extends Module {
private var width:int;
public function And(X:int, Y:int, Width:int = 2) {
super(X, Y, "And", Module.CAT_LOGIC, Width, 1, 0);
width = Width;
configuration = new Configuration(new Range(2, 8, Width));
configurableInPlace = false;
delay = Math.ceil(Math.log(Width) / Math.log(2));
}
override protected function generateInternalLayout():InternalLayout {
var ports:Array = [];
for each (var portLayout:PortLayout in layout.ports)
ports.push(portLayout);
var outport:PortLayout = layout.ports[layout.ports.length - 1];
return new InternalLayout([new TallNode(this, new Point(outport.offset.x - layout.dim.x / 2 - 1 / 2, outport.offset.y),
ports, [], function getValue():Value { return drive(outputs[0]); }, "All" )]);
}
protected function resetPorts():void {
outputs = new Vector.<Port>;
outputs.push(new Port(true, this));
}
override public function renderDetails():String {
var out:String = "And\n\n";
for each (var input:Port in inputs)
out += input.getValue() + ',';
return out.slice(0, out.length - 1);
}
override public function getDescription():String {
return "Outputs "+BooleanValue.FALSE+" if any input is "+BooleanValue.FALSE+", else "+BooleanValue.TRUE+"."
}
override protected function getSaveValues():Array {
var values:Array = super.getSaveValues();
values.push(width);
return values;
}
override public function drive(port:Port):Value {
for each (var inputPort:Port in inputs) {
var inputValue:Value = inputPort.getValue();
if (inputValue.unknown || inputValue.unpowered)
return inputValue;
if (!BooleanValue.fromValue(inputValue).boolValue)
return BooleanValue.FALSE;
}
return BooleanValue.TRUE;
}
}
}
|
ADD internals
|
ADD internals
|
ActionScript
|
mit
|
PleasingFungus/mde2,PleasingFungus/mde2
|
86467cedcd655fb92ad49fe5d63985f0698d8f02
|
flash/org/windmill/WMBootstrap.as
|
flash/org/windmill/WMBootstrap.as
|
/*
Copyright 2009, Matthew Eernisse ([email protected]) and Slide, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.windmill {
import flash.display.Loader;
import flash.net.URLRequest;
import flash.events.Event;
import flash.system.ApplicationDomain;
import flash.system.LoaderContext;
public class WMBootstrap {
public static var windmillLibPath:String = '/flash/org/windmill/Windmill.swf';
public static function init(context:*):void {
var loader:Loader = new Loader();
var url:String = WMBootstrap.windmillLibPath;
var req:URLRequest = new URLRequest(url);
var con:LoaderContext = new LoaderContext(false,
ApplicationDomain.currentDomain);
loader.contentLoaderInfo.addEventListener(
Event.COMPLETE, function ():void {
var Windmill:*;
Windmill = ApplicationDomain.currentDomain.getDefinition(
"org.windmill.Windmill") as Class;
Windmill.init({ context: context });
});
loader.load(req, con);
}
}
}
|
/*
Copyright 2009, Matthew Eernisse ([email protected]) and Slide, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.windmill {
import flash.display.Loader;
import flash.net.URLRequest;
import flash.events.Event;
import flash.system.ApplicationDomain;
import flash.system.SecurityDomain;
import flash.system.LoaderContext;
public class WMBootstrap {
public static var windmillLibPath:String = '/flash/org/windmill/Windmill.swf';
public static var wm:*;
public static function init(context:*, domains:* = null):void {
var loader:Loader = new Loader();
var url:String = WMBootstrap.windmillLibPath;
var req:URLRequest = new URLRequest(url);
var con:LoaderContext = new LoaderContext(false,
ApplicationDomain.currentDomain,
SecurityDomain.currentDomain);
loader.contentLoaderInfo.addEventListener(
Event.COMPLETE, function ():void {
wm = ApplicationDomain.currentDomain.getDefinition(
"org.windmill.Windmill") as Class;
wm.init({ context: context, domains: domains });
});
loader.load(req, con);
}
}
}
|
Load Windmill.swf in the correct SecurityDomain, and pass script-access domains up to Windmill so it can give access to the API.
|
Load Windmill.swf in the correct SecurityDomain, and pass script-access domains up to Windmill so it can give access to the API.
|
ActionScript
|
apache-2.0
|
windmill/windmill,windmill/windmill,windmill/windmill,windmill/windmill,windmill/windmill,windmill/windmill
|
f1047bbedf756b78085ad2f99e62ffe567ef2b30
|
src/com/esri/builder/components/serviceBrowser/supportClasses/ServiceDirectoryNodeFetcher.as
|
src/com/esri/builder/components/serviceBrowser/supportClasses/ServiceDirectoryNodeFetcher.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.tasks.JSONTask;
import com.esri.builder.components.serviceBrowser.filters.INodeFilter;
import com.esri.builder.components.serviceBrowser.nodes.FolderNode;
import com.esri.builder.components.serviceBrowser.nodes.GPTaskNode;
import com.esri.builder.components.serviceBrowser.nodes.LayerNode;
import com.esri.builder.components.serviceBrowser.nodes.RouteLayerNode;
import com.esri.builder.components.serviceBrowser.nodes.ServerNode;
import com.esri.builder.components.serviceBrowser.nodes.ServiceDirectoryNode;
import com.esri.builder.components.serviceBrowser.nodes.TableNode;
import flash.events.EventDispatcher;
import flash.net.URLVariables;
import mx.rpc.AsyncResponder;
import mx.rpc.Fault;
import mx.rpc.events.FaultEvent;
public class ServiceDirectoryNodeFetcher extends EventDispatcher
{
private const DEFAULT_TIMEOUT_IN_SECONDS:int = 10;
public var token:String;
public var requestTimeout:int;
private var nodes:Array;
private var nodeFilter:INodeFilter;
private var totalLayerNodesToLoad:int;
private var layerNodesToLoad:Array;
private var totalTableNodesToLoad:int;
private var tableNodesToLoad:Array;
private var allLayersProcessed:Boolean = true;
private var allTablesProcessed:Boolean = true;
public function fetch(url:String, nodeFilter:INodeFilter, parent:ServiceDirectoryNode):void
{
this.nodeFilter = nodeFilter;
const urlVars:URLVariables = new URLVariables();
urlVars.f = "json";
const nodeInfoRequest:JSONTask = new JSONTask(url);
nodeInfoRequest.requestTimeout = getValidRequestTimeout();
nodeInfoRequest.token = token;
nodeInfoRequest.execute(urlVars,
new AsyncResponder(nodeInfoRequest_resultHandler,
nodeInfoRequest_faultHandler,
parent));
}
private function getValidRequestTimeout():int
{
const isRequestTimeoutValid:Boolean = !isNaN(requestTimeout) && requestTimeout > -1;
return isRequestTimeoutValid ? requestTimeout : DEFAULT_TIMEOUT_IN_SECONDS;
}
private function nodeInfoRequest_resultHandler(metadata:Object, parent:ServiceDirectoryNode):void
{
nodes = [];
for each (var folderName:String in metadata.folders)
{
const folderNode:FolderNode =
ServiceDirectoryNodeCreator.createFolderNode(parent, folderName);
if (nodeFilter.isApplicable(folderNode))
{
folderNode.token = token;
nodes.push(folderNode);
}
}
for each (var taskName:String in metadata.tasks)
{
const taskNode:GPTaskNode =
ServiceDirectoryNodeCreator.createGPTaskNode(parent, taskName);
if (nodeFilter.isApplicable(taskNode))
{
taskNode.token = token;
nodes.push(taskNode);
}
}
for each (var service:Object in metadata.services)
{
const serverNode:ServerNode =
ServiceDirectoryNodeCreator.createServerNode(parent, service);
if (nodeFilter.isApplicable(serverNode))
{
serverNode.isBranch = nodeFilter.serverChildrenAllowed;
serverNode.token = token;
nodes.push(serverNode);
}
}
for each (var routeLayerName:String in metadata.routeLayers)
{
const routeNode:RouteLayerNode =
ServiceDirectoryNodeCreator.createRouteNode(parent, routeLayerName);
if (nodeFilter.isApplicable(routeNode))
{
routeNode.token = token;
nodes.push(routeNode);
}
}
layerNodesToLoad = [];
for each (var layer:Object in metadata.layers)
{
const layerNode:LayerNode =
ServiceDirectoryNodeCreator.createLayerNode(parent, layer);
if (layerNode)
{
layerNode.token = token;
layerNodesToLoad.push(layerNode);
}
}
tableNodesToLoad = [];
for each (var table:Object in metadata.tables)
{
const tableNode:TableNode =
ServiceDirectoryNodeCreator.createTableNode(parent, table);
if (tableNode)
{
tableNode.token = token;
tableNodesToLoad.push(tableNode);
}
}
if (layerNodesToLoad.length > 0)
{
allLayersProcessed = false;
fetchLayerNodeInfo();
}
if (tableNodesToLoad.length > 0)
{
allTablesProcessed = false;
fetchTableNodeInfo();
}
if (layerNodesToLoad.length == 0 && tableNodesToLoad.length == 0)
{
dispatchNodeFetchComplete();
}
}
private function fetchLayerNodeInfo():void
{
totalLayerNodesToLoad = layerNodesToLoad.length;
var urlVars:URLVariables;
var layerInfoRequest:JSONTask;
for each (var layerNode:LayerNode in layerNodesToLoad)
{
urlVars = new URLVariables();
urlVars.f = "json";
layerInfoRequest = new JSONTask(layerNode.internalURL);
layerInfoRequest.requestTimeout = getValidRequestTimeout();
layerInfoRequest.token = token;
layerInfoRequest.execute(urlVars,
new AsyncResponder(layerInfoRequest_resultHandler,
layerNodeInfoRequest_faultHandler,
layerNode));
}
}
private function fetchTableNodeInfo():void
{
totalTableNodesToLoad = tableNodesToLoad.length;
var urlVars:URLVariables;
var tableInfoRequest:JSONTask;
for each (var tableNode:TableNode in tableNodesToLoad)
{
urlVars = new URLVariables();
urlVars.f = "json";
tableInfoRequest = new JSONTask(tableNode.internalURL);
tableInfoRequest.requestTimeout = getValidRequestTimeout();
tableInfoRequest.token = token;
tableInfoRequest.execute(urlVars,
new AsyncResponder(tableInfoRequest_resultHandler,
tableNodeInfoRequest_faultHandler,
tableNode));
}
}
private function layerNodeInfoRequest_faultHandler(fault:Fault, token:Object = null):void
{
layerProcessed();
}
private function tableNodeInfoRequest_faultHandler(fault:Fault, token:Object = null):void
{
tableProcessed();
}
private function layerProcessed():void
{
totalLayerNodesToLoad--;
if (totalLayerNodesToLoad == 0)
{
addProcessedLayerNodesAndDispatchFetchComplete();
}
}
private function tableProcessed():void
{
totalTableNodesToLoad--;
if (totalTableNodesToLoad == 0)
{
addProcessedTableNodesAndDispatchFetchComplete();
}
}
private function addProcessedLayerNodesAndDispatchFetchComplete():void
{
for each (var layerNode:LayerNode in layerNodesToLoad)
{
if (nodeFilter.isApplicable(layerNode))
{
nodes.push(layerNode);
}
}
allLayersProcessed = true;
if (allLayersProcessed && allTablesProcessed)
{
dispatchNodeFetchComplete();
}
}
private function addProcessedTableNodesAndDispatchFetchComplete():void
{
for each (var tableNode:TableNode in tableNodesToLoad)
{
if (nodeFilter.isApplicable(tableNode))
{
nodes.push(tableNode);
}
}
allTablesProcessed = true;
if (allLayersProcessed && allTablesProcessed)
{
dispatchNodeFetchComplete();
}
}
private function dispatchNodeFetchComplete():void
{
dispatchEvent(
new ServiceDirectoryNodeFetchEvent(ServiceDirectoryNodeFetchEvent.NODE_FETCH_COMPLETE,
nodes));
}
private function layerInfoRequest_resultHandler(metadata:Object, layerNode:LayerNode):void
{
layerNode.metadata = metadata;
layerProcessed();
}
private function tableInfoRequest_resultHandler(metadata:Object, tableNode:TableNode):void
{
tableNode.metadata = metadata;
tableProcessed();
}
private function nodeInfoRequest_faultHandler(fault:Fault, token:Object = null):void
{
dispatchEvent(new FaultEvent(FaultEvent.FAULT, false, false, fault));
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
// 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.tasks.JSONTask;
import com.esri.builder.components.serviceBrowser.filters.INodeFilter;
import com.esri.builder.components.serviceBrowser.nodes.FolderNode;
import com.esri.builder.components.serviceBrowser.nodes.GPTaskNode;
import com.esri.builder.components.serviceBrowser.nodes.LayerNode;
import com.esri.builder.components.serviceBrowser.nodes.QueryableNode;
import com.esri.builder.components.serviceBrowser.nodes.RouteLayerNode;
import com.esri.builder.components.serviceBrowser.nodes.ServerNode;
import com.esri.builder.components.serviceBrowser.nodes.ServiceDirectoryNode;
import com.esri.builder.components.serviceBrowser.nodes.TableNode;
import flash.events.EventDispatcher;
import flash.net.URLVariables;
import mx.rpc.AsyncResponder;
import mx.rpc.Fault;
import mx.rpc.events.FaultEvent;
public class ServiceDirectoryNodeFetcher extends EventDispatcher
{
private const DEFAULT_TIMEOUT_IN_SECONDS:int = 10;
public var token:String;
public var requestTimeout:int;
private var nodes:Array;
private var nodeFilter:INodeFilter;
private var totalNodesToLoad:int;
private var nodesToLoad:Array;
private var allNodesProcessed:Boolean = true;
public function fetch(url:String, nodeFilter:INodeFilter, parent:ServiceDirectoryNode):void
{
this.nodeFilter = nodeFilter;
const urlVars:URLVariables = new URLVariables();
urlVars.f = "json";
const nodeInfoRequest:JSONTask = new JSONTask(url);
nodeInfoRequest.requestTimeout = getValidRequestTimeout();
nodeInfoRequest.token = token;
nodeInfoRequest.execute(urlVars,
new AsyncResponder(nodeInfoRequest_resultHandler,
nodeInfoRequest_faultHandler,
parent));
}
private function getValidRequestTimeout():int
{
const isRequestTimeoutValid:Boolean = !isNaN(requestTimeout) && requestTimeout > -1;
return isRequestTimeoutValid ? requestTimeout : DEFAULT_TIMEOUT_IN_SECONDS;
}
private function nodeInfoRequest_resultHandler(metadata:Object, parent:ServiceDirectoryNode):void
{
nodes = [];
for each (var folderName:String in metadata.folders)
{
const folderNode:FolderNode =
ServiceDirectoryNodeCreator.createFolderNode(parent, folderName);
if (nodeFilter.isApplicable(folderNode))
{
folderNode.token = token;
nodes.push(folderNode);
}
}
for each (var taskName:String in metadata.tasks)
{
const taskNode:GPTaskNode =
ServiceDirectoryNodeCreator.createGPTaskNode(parent, taskName);
if (nodeFilter.isApplicable(taskNode))
{
taskNode.token = token;
nodes.push(taskNode);
}
}
for each (var service:Object in metadata.services)
{
const serverNode:ServerNode =
ServiceDirectoryNodeCreator.createServerNode(parent, service);
if (nodeFilter.isApplicable(serverNode))
{
serverNode.isBranch = nodeFilter.serverChildrenAllowed;
serverNode.token = token;
nodes.push(serverNode);
}
}
for each (var routeLayerName:String in metadata.routeLayers)
{
const routeNode:RouteLayerNode =
ServiceDirectoryNodeCreator.createRouteNode(parent, routeLayerName);
if (nodeFilter.isApplicable(routeNode))
{
routeNode.token = token;
nodes.push(routeNode);
}
}
nodesToLoad = [];
for each (var layer:Object in metadata.layers)
{
const layerNode:LayerNode =
ServiceDirectoryNodeCreator.createLayerNode(parent, layer);
if (layerNode)
{
layerNode.token = token;
nodesToLoad.push(layerNode);
}
}
for each (var table:Object in metadata.tables)
{
const tableNode:TableNode =
ServiceDirectoryNodeCreator.createTableNode(parent, table);
if (tableNode)
{
tableNode.token = token;
nodesToLoad.push(tableNode);
}
}
if (nodesToLoad.length > 0)
{
allNodesProcessed = false;
fetchQueryableNodeInfo();
}
if (nodesToLoad.length == 0)
{
dispatchNodeFetchComplete();
}
}
private function fetchQueryableNodeInfo():void
{
totalNodesToLoad = nodesToLoad.length;
var urlVars:URLVariables;
var layerInfoRequest:JSONTask;
for each (var queryableNode:QueryableNode in nodesToLoad)
{
urlVars = new URLVariables();
urlVars.f = "json";
layerInfoRequest = new JSONTask(queryableNode.internalURL);
layerInfoRequest.requestTimeout = getValidRequestTimeout();
layerInfoRequest.token = token;
layerInfoRequest.execute(urlVars,
new AsyncResponder(queryableNodeInfoRequest_resultHandler,
queryableNodeInfoRequest_faultHandler,
queryableNode));
}
}
private function queryableNodeInfoRequest_faultHandler(fault:Fault, token:Object = null):void
{
nodeProcessed();
}
private function nodeProcessed():void
{
totalNodesToLoad--;
if (totalNodesToLoad == 0)
{
addProcessedNodesAndDispatchFetchComplete();
}
}
private function addProcessedNodesAndDispatchFetchComplete():void
{
for each (var queryableNode:QueryableNode in nodesToLoad)
{
if (nodeFilter.isApplicable(queryableNode))
{
nodes.push(queryableNode);
}
}
allNodesProcessed = true;
if (allNodesProcessed)
{
dispatchNodeFetchComplete();
}
}
private function dispatchNodeFetchComplete():void
{
dispatchEvent(
new ServiceDirectoryNodeFetchEvent(ServiceDirectoryNodeFetchEvent.NODE_FETCH_COMPLETE,
nodes));
}
private function queryableNodeInfoRequest_resultHandler(metadata:Object, queryableNode:QueryableNode):void
{
queryableNode.metadata = metadata;
nodeProcessed();
}
private function nodeInfoRequest_faultHandler(fault:Fault, token:Object = null):void
{
dispatchEvent(new FaultEvent(FaultEvent.FAULT, false, false, fault));
}
}
}
|
Simplify layer/table node info fetching.
|
Simplify layer/table node info fetching.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
490e872b013d42836841a6a1670aef1625d669db
|
src/com/google/analytics/API.as
|
src/com/google/analytics/API.as
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
*/
package com.google.analytics
{
import com.google.analytics.utils.Version;
public class API
{
/**
* version of Google Analytics AS3 API
*
* note:
* each components share the same code base and so the same version
*/
public static var version:Version = new Version();
include "version.properties"
version.revision = "$Rev$ ".split( " " )[1];
}
}
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
*/
package com.google.analytics
{
import core.version;
public class API
{
/**
* version of Google Analytics AS3 API
*
* note:
* each components share the same code base and so the same version
*/
public static var version:core.version = new core.version();
include "version.properties"
version.revision = "$Rev$ ".split( " " )[1];
}
}
|
replace utils Version class by uri.version class
|
replace utils Version class by uri.version class
|
ActionScript
|
apache-2.0
|
jisobkim/gaforflash,Miyaru/gaforflash,DimaBaliakin/gaforflash,mrthuanvn/gaforflash,jeremy-wischusen/gaforflash,mrthuanvn/gaforflash,Vigmar/gaforflash,soumavachakraborty/gaforflash,DimaBaliakin/gaforflash,drflash/gaforflash,jisobkim/gaforflash,soumavachakraborty/gaforflash,drflash/gaforflash,dli-iclinic/gaforflash,dli-iclinic/gaforflash,Miyaru/gaforflash,Vigmar/gaforflash,jeremy-wischusen/gaforflash
|
e392ade133a45418dac54540ddbb59f47005454d
|
actionscript/src/com/freshplanet/ane/AirPushNotification/PushNotification.as
|
actionscript/src/com/freshplanet/ane/AirPushNotification/PushNotification.as
|
/**
* Copyright 2017 FreshPlanet
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.freshplanet.ane.AirPushNotification {
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.system.Capabilities;
/**
*
*/
public class PushNotification extends EventDispatcher {
// --------------------------------------------------------------------------------------//
// //
// PUBLIC API //
// //
// --------------------------------------------------------------------------------------//
public static const RECURRENCE_NONE:int = 0;
public static const RECURRENCE_DAILY:int = 1;
public static const RECURRENCE_WEEK:int = 2;
public static const RECURRENCE_MONTH:int = 3;
public static const RECURRENCE_YEAR:int = 4;
public static const DEFAULT_LOCAL_NOTIFICATION_ID:int = 0;
/**
* If <code>true</code>, logs will be displayed at the ActionScript level.
*/
public static var logEnabled:Boolean = false;
/**
*
*/
public static function get isSupported():Boolean {
return _isIOS() || _isAndroid();
}
/**
*
*/
public static function get instance():PushNotification {
return _instance ? _instance : new PushNotification();
}
private function callContext(...args):*
{
var context: ExtensionContext = getContext();
if(!context) {
_log("ERROR", "Extension context is null. Please check if extension.xml is setup correctly.")
return null;
}
try {
return context.call.apply(context, args);
} catch (e: Error) {
_log("ERROR", "Error calling extension context: " + e.message + " : " + e.getStackTrace());
}
return null;
}
/**
* return true if notifs are enabled for this app in device settings
* If iOS < 8 or android < 4.1 this isn't available, so will always return true.
*/
public function getNotificationsEnabled():void {
if (!isSupported)
return;
callContext("getNotificationsEnabled");
}
/**
* Check if notificationChannel is enabled in Android notification settings
* @param channelId
* @return
*/
public function isNotificationChannelEnabled(channelId:String):Boolean {
if (!isSupported)
return false;
if(_isIOS())
return true;
return callContext("checkNotificationChannelEnabled", channelId);
}
/**
* return true if OS permits sending user to settings (iOS 8, Android
*/
public function get canSendUserToSettings():Boolean {
if (!isSupported)
return false;
return callContext("getCanSendUserToSettings");
}
/**
*
*/
public function openDeviceNotificationSettings(channelId:String = null):void {
if(!channelId)
channelId = "";
if (isSupported)
callContext("openDeviceNotificationSettings", channelId);
}
/**
* Needs Project id for Android Notifications.
* The project id is the one the developer used to register to gcm.
* @param projectId: project id to use
* @param iOSNotificationCategories: notification categories used on iOS (PushNotificationCategoryiOS)
*/
public function registerForPushNotification(projectId:String = null, iOSNotificationCategories:Array = null):void {
if(!isSupported)
return;
if (_isAndroid())
callContext("registerPush", projectId);
else if(_isIOS())
callContext("registerPush", iOSNotificationCategories != null ? JSON.stringify(iOSNotificationCategories) : null);
}
/**
*
* @param value
*/
public function setBadgeNumberValue(value:int):void {
if (isSupported)
callContext("setBadgeNb", value);
}
/**
* Sends a local notification to the device.
* @param message the local notification text displayed
* @param timestamp when the local notification should appear (in sec)
* @param title (Android Only) Title of the local notification
* @param recurrenceType
* @param notificationId
* @param deepLinkPath
* @param iconPath
* @param groupId used to group notifications together
* @param categoryId used to display custom summaries on iOS
* @param makeSquare used to display square icons on Android, will default to round
*/
public function sendLocalNotification(message:String,
timestamp:int,
title:String,
recurrenceType:int = RECURRENCE_NONE,
notificationId:int = DEFAULT_LOCAL_NOTIFICATION_ID,
deepLinkPath:String = null,
iconPath:String = null,
groupId:String = null,
categoryId:String = null,
makeSquare:Boolean = false
):void {
if (!isSupported)
return;
if(!iconPath)
iconPath = "";
if(!deepLinkPath)
deepLinkPath = "";
if(!groupId)
groupId = "";
if(!categoryId)
categoryId = "";
callContext("sendLocalNotification", message, timestamp, title, recurrenceType, notificationId, deepLinkPath, iconPath, groupId, categoryId, makeSquare);
}
/**
* Not implemented on Android for now.
* @param notificationId
*/
public function cancelLocalNotification(notificationId:int = DEFAULT_LOCAL_NOTIFICATION_ID):void {
if (isSupported) {
if (notificationId == DEFAULT_LOCAL_NOTIFICATION_ID)
callContext("cancelLocalNotification");
else
callContext("cancelLocalNotification", notificationId);
}
}
/**
*
*/
public function cancelAllLocalNotifications():void {
if (isSupported)
callContext("cancelAllLocalNotifications");
}
/**
*
* @param value
*/
public function setIsAppInForeground(value:Boolean, appGroupId:String):void {
if (isSupported)
callContext("setIsAppInForeground", value, appGroupId);
}
/**
*
* @param listener
*/
public function addListenerForStarterNotifications(listener:Function):void {
if (isSupported) {
this.addEventListener(PushNotificationEvent.APP_STARTING_FROM_NOTIFICATION_EVENT, listener);
callContext("fetchStarterNotification");
}
}
public function checkAppNotificationSettingsRequest():void {
if (_isIOS()) {
callContext("checkAppNotificationSettingsRequest");
}
}
public function storeTrackingNotifUrl(url:String, appGroupId:String):void {
if (isSupported)
callContext("storeNotifTrackingInfo", url, appGroupId);
}
/**
* Create Android notification channel
* @param channelId
* @param channelName
* @param importance
* @param enableLights
* @param enableVibration
*/
public function createAndroidNotificationChannel(channelId:String, channelName:String, importance:int, enableLights:Boolean, enableVibration:Boolean):void {
if (_isAndroid())
callContext("createNotificationChannel", channelId, channelName, importance, enableLights, enableVibration);
}
// --------------------------------------------------------------------------------------//
// //
// PRIVATE API //
// //
// --------------------------------------------------------------------------------------//
private static const EXTENSION_ID:String = "com.freshplanet.ane.AirPushNotification";
private static var _instance:PushNotification = null;
/**
* "private" singleton constructor
*/
public function PushNotification() {
super();
if (_instance)
throw Error("This is a singleton, use getInstance(), do not call the constructor directly.");
_instance = this;
}
private var __context:ExtensionContext;
private function getContext():ExtensionContext
{
if (!__context) {
__context = ExtensionContext.createExtensionContext(EXTENSION_ID, null);
if (!__context) {
_log("ERROR", "Extension context is null. Please check if extension.xml is setup correctly.");
} else {
__context.addEventListener(StatusEvent.STATUS, _onStatus);
}
}
return __context;
}
/**
*
* @param strings
*/
private function _log(...strings):void {
if (logEnabled) {
strings.unshift(EXTENSION_ID);
trace.apply(null, strings);
}
}
/**
*
* @return true if iOS
*/
private static function _isIOS():Boolean {
return Capabilities.manufacturer.indexOf("iOS") > -1 && Capabilities.os.indexOf("x86_64") < 0 && Capabilities.os.indexOf("i386") < 0;
}
/**
*
* @return true if Android
*/
private static function _isAndroid():Boolean {
return Capabilities.manufacturer.indexOf("Android") > -1;
}
/**
*
* @param e
*/
private function _onStatus(e:StatusEvent):void {
var event:PushNotificationEvent = null;
var data:String = e.level;
switch (e.code) {
case "TOKEN_SUCCESS":
event = new PushNotificationEvent(PushNotificationEvent.PERMISSION_GIVEN_WITH_TOKEN_EVENT);
event.token = e.level;
break;
case "TOKEN_FAIL":
event = new PushNotificationEvent(PushNotificationEvent.PERMISSION_REFUSED_EVENT);
event.errorCode = "NativeCodeError";
event.errorMessage = e.level;
break;
case "COMING_FROM_NOTIFICATION":
event = new PushNotificationEvent(PushNotificationEvent.COMING_FROM_NOTIFICATION_EVENT);
if (data != null) {
try {
event.parameters = JSON.parse(data);
}
catch (error:Error) {
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "APP_STARTING_FROM_NOTIFICATION":
event = new PushNotificationEvent(PushNotificationEvent.APP_STARTING_FROM_NOTIFICATION_EVENT);
if (data != null) {
try {
event.parameters = JSON.parse(data);
}
catch (error:Error) {
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "APP_BROUGHT_TO_FOREGROUND_FROM_NOTIFICATION":
event = new PushNotificationEvent(PushNotificationEvent.APP_BROUGHT_TO_FOREGROUND_FROM_NOTIFICATION_EVENT);
if (data != null) {
try {
event.parameters = JSON.parse(data);
}
catch (error:Error) {
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "APP_STARTED_IN_BACKGROUND_FROM_NOTIFICATION":
event = new PushNotificationEvent(PushNotificationEvent.APP_STARTED_IN_BACKGROUND_FROM_NOTIFICATION_EVENT);
if (data != null) {
try {
event.parameters = JSON.parse(data);
}
catch (error:Error) {
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "NOTIFICATION_RECEIVED_WHEN_IN_FOREGROUND":
event = new PushNotificationEvent(PushNotificationEvent.NOTIFICATION_RECEIVED_WHEN_IN_FOREGROUND_EVENT);
if (data != null) {
try {
event.parameters = JSON.parse(data);
}
catch (error:Error) {
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "NOTIFICATION_SETTINGS_ENABLED":
event = new PushNotificationEvent(PushNotificationEvent.NOTIFICATION_SETTINGS_ENABLED);
break;
case "NOTIFICATION_SETTINGS_DISABLED":
event = new PushNotificationEvent(PushNotificationEvent.NOTIFICATION_SETTINGS_DISABLED);
break;
case "GET_NOTIFICATIONS_ENABLED_RESULT":
event = new PushNotificationEvent(PushNotificationEvent.GET_NOTIFICATIONS_ENABLED_RESULT, e.level == "true");
break;
case "OPEN_APP_NOTIFICATION_SETTINGS":
event = new PushNotificationEvent(PushNotificationEvent.OPEN_APP_NOTIFICATION_SETTINGS);
break;
case "LOG_ISSUE":
event = new PushNotificationEvent(PushNotificationEvent.LOG_ISSUE, data);
break;
case "LOGGING":
trace(e, e.level);
break;
}
if (event != null)
this.dispatchEvent(event);
}
}
}
|
/**
* Copyright 2017 FreshPlanet
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.freshplanet.ane.AirPushNotification {
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.system.Capabilities;
/**
*
*/
public class PushNotification extends EventDispatcher {
// --------------------------------------------------------------------------------------//
// //
// PUBLIC API //
// //
// --------------------------------------------------------------------------------------//
public static const RECURRENCE_NONE:int = 0;
public static const RECURRENCE_DAILY:int = 1;
public static const RECURRENCE_WEEK:int = 2;
public static const RECURRENCE_MONTH:int = 3;
public static const RECURRENCE_YEAR:int = 4;
public static const DEFAULT_LOCAL_NOTIFICATION_ID:int = 0;
/**
* If <code>true</code>, logs will be displayed at the ActionScript level.
*/
public static var logEnabled:Boolean = false;
/**
*
*/
public static function get isSupported():Boolean {
return _isIOS() || _isAndroid();
}
/**
*
*/
public static function get instance():PushNotification {
return _instance ? _instance : new PushNotification();
}
private function callContext(...args):*
{
var context: ExtensionContext = getContext();
if(!context) {
_log("ERROR", "Extension context is null. Please check if extension.xml is setup correctly.")
return null;
}
try {
return context.call.apply(context, args);
} catch (e: Error) {
_log("ERROR", "Error calling extension context: " + e.message + " : " + e.getStackTrace());
}
return null;
}
/**
* return true if notifs are enabled for this app in device settings
* If iOS < 8 or android < 4.1 this isn't available, so will always return true.
*/
public function getNotificationsEnabled():void {
if (!isSupported)
return;
callContext("getNotificationsEnabled");
}
/**
* Check if notificationChannel is enabled in Android notification settings
* @param channelId
* @return
*/
public function isNotificationChannelEnabled(channelId:String):Boolean {
if (!isSupported)
return false;
if(_isIOS())
return true;
return callContext("checkNotificationChannelEnabled", channelId);
}
/**
* return true if OS permits sending user to settings (iOS 8, Android
*/
public function get canSendUserToSettings():Boolean {
if (!isSupported)
return false;
return callContext("getCanSendUserToSettings");
}
/**
*
*/
public function openDeviceNotificationSettings(channelId:String = null):void {
if(!channelId)
channelId = "";
if (isSupported)
callContext("openDeviceNotificationSettings", channelId);
}
/**
* Needs Project id for Android Notifications.
* The project id is the one the developer used to register to gcm.
* @param projectId: project id to use
* @param iOSNotificationCategories: notification categories used on iOS (PushNotificationCategoryiOS)
*/
public function registerForPushNotification(projectId:String = null, iOSNotificationCategories:Array = null):void {
if(!isSupported)
return;
if (_isAndroid())
callContext("registerPush", projectId);
else if(_isIOS())
callContext("registerPush", iOSNotificationCategories != null ? JSON.stringify(iOSNotificationCategories) : null);
}
/**
*
* @param value
*/
public function setBadgeNumberValue(value:int):void {
if (isSupported)
callContext("setBadgeNb", value);
}
/**
* Sends a local notification to the device.
* @param message the local notification text displayed
* @param timestamp when the local notification should appear (in sec)
* @param title (Android Only) Title of the local notification
* @param recurrenceType
* @param notificationId
* @param deepLinkPath
* @param iconPath
* @param groupId used to group notifications together
* @param categoryId used to display custom summaries on iOS
* @param makeSquare used to display square icons on Android, will default to round
*/
public function sendLocalNotification(message:String,
timestamp:int,
title:String,
recurrenceType:int = RECURRENCE_NONE,
notificationId:int = DEFAULT_LOCAL_NOTIFICATION_ID,
deepLinkPath:String = null,
iconPath:String = null,
groupId:String = null,
categoryId:String = null,
makeSquare:Boolean = false
):void {
if (!isSupported)
return;
if(!iconPath)
iconPath = "";
if(!deepLinkPath)
deepLinkPath = "";
if(!groupId)
groupId = "";
if(!categoryId)
categoryId = "";
callContext("sendLocalNotification", message, timestamp, title, recurrenceType, notificationId, deepLinkPath, iconPath, groupId, categoryId, makeSquare);
}
/**
* Not implemented on Android for now.
* @param notificationId
*/
public function cancelLocalNotification(notificationId:int = DEFAULT_LOCAL_NOTIFICATION_ID):void {
if (isSupported) {
if (notificationId == DEFAULT_LOCAL_NOTIFICATION_ID)
callContext("cancelLocalNotification");
else
callContext("cancelLocalNotification", notificationId);
}
}
/**
*
*/
public function cancelAllLocalNotifications():void {
if (isSupported)
callContext("cancelAllLocalNotifications");
}
/**
*
* @param value
*/
public function setIsAppInForeground(value:Boolean, appGroupId:String):void {
if (isSupported)
callContext("setIsAppInForeground", value, appGroupId);
}
/**
*
* @param listener
*/
public function addListenerForStarterNotifications(listener:Function):void {
if (isSupported) {
this.addEventListener(PushNotificationEvent.APP_STARTING_FROM_NOTIFICATION_EVENT, listener);
callContext("fetchStarterNotification");
}
}
public function checkAppNotificationSettingsRequest():void {
if (_isIOS()) {
callContext("checkAppNotificationSettingsRequest");
}
}
public function storeTrackingNotifUrl(url:String, appGroupId:String):void {
if (isSupported)
callContext("storeNotifTrackingInfo", url, appGroupId);
}
/**
* Create Android notification channel
* @param channelId
* @param channelName
* @param importance
* @param enableLights
* @param enableVibration
*/
public function createAndroidNotificationChannel(channelId:String, channelName:String, importance:int, enableLights:Boolean, enableVibration:Boolean):void {
if (_isAndroid())
callContext("createNotificationChannel", channelId, channelName, importance, enableLights, enableVibration);
}
// --------------------------------------------------------------------------------------//
// //
// PRIVATE API //
// //
// --------------------------------------------------------------------------------------//
private static const EXTENSION_ID:String = "com.freshplanet.ane.AirPushNotification";
private static var _instance:PushNotification = null;
/**
* "private" singleton constructor
*/
public function PushNotification() {
super();
if (_instance)
throw Error("This is a singleton, use getInstance(), do not call the constructor directly.");
_instance = this;
}
private var __context:ExtensionContext;
private function getContext():ExtensionContext
{
if (!__context) {
__context = ExtensionContext.createExtensionContext(EXTENSION_ID, null);
if (!__context) {
_log("ERROR", "Extension context is null. Please check if extension.xml is setup correctly.");
} else {
__context.addEventListener(StatusEvent.STATUS, _onStatus);
}
}
return __context;
}
/**
*
* @param strings
*/
private function _log(...strings):void {
if (logEnabled) {
strings.unshift(EXTENSION_ID);
trace.apply(null, strings);
}
}
/**
*
* @return true if iOS
*/
private static function _isIOS():Boolean {
return Capabilities.manufacturer.indexOf("iOS") > -1 && Capabilities.os.indexOf("x86_64") < 0 && Capabilities.os.indexOf("i386") < 0;
}
/**
*
* @return true if Android
*/
private static function _isAndroid():Boolean {
return Capabilities.manufacturer.indexOf("Android") > -1;
}
/**
*
* @param e
*/
private function _onStatus(e:StatusEvent):void {
var event:PushNotificationEvent = null;
var data:String = e.level;
switch (e.code) {
case "TOKEN_SUCCESS":
event = new PushNotificationEvent(PushNotificationEvent.PERMISSION_GIVEN_WITH_TOKEN_EVENT);
event.token = e.level;
break;
case "TOKEN_FAIL":
event = new PushNotificationEvent(PushNotificationEvent.PERMISSION_REFUSED_EVENT);
event.errorCode = "NativeCodeError";
event.errorMessage = e.level;
break;
case "COMING_FROM_NOTIFICATION":
event = new PushNotificationEvent(PushNotificationEvent.COMING_FROM_NOTIFICATION_EVENT);
if (data != null) {
try {
event.parameters = JSON.parse(data);
}
catch (error:Error) {
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "APP_STARTING_FROM_NOTIFICATION":
event = new PushNotificationEvent(PushNotificationEvent.APP_STARTING_FROM_NOTIFICATION_EVENT);
if (data != null) {
try {
event.parameters = JSON.parse(data);
}
catch (error:Error) {
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "APP_BROUGHT_TO_FOREGROUND_FROM_NOTIFICATION":
event = new PushNotificationEvent(PushNotificationEvent.APP_BROUGHT_TO_FOREGROUND_FROM_NOTIFICATION_EVENT);
if (data != null) {
try {
event.parameters = JSON.parse(data);
}
catch (error:Error) {
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "APP_STARTED_IN_BACKGROUND_FROM_NOTIFICATION":
event = new PushNotificationEvent(PushNotificationEvent.APP_STARTED_IN_BACKGROUND_FROM_NOTIFICATION_EVENT);
if (data != null) {
try {
event.parameters = JSON.parse(data);
}
catch (error:Error) {
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "NOTIFICATION_RECEIVED_WHEN_IN_FOREGROUND":
event = new PushNotificationEvent(PushNotificationEvent.NOTIFICATION_RECEIVED_WHEN_IN_FOREGROUND_EVENT);
if (data != null) {
try {
event.parameters = JSON.parse(data);
}
catch (error:Error) {
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "NOTIFICATION_SETTINGS_ENABLED":
event = new PushNotificationEvent(PushNotificationEvent.NOTIFICATION_SETTINGS_ENABLED);
break;
case "NOTIFICATION_SETTINGS_DISABLED":
event = new PushNotificationEvent(PushNotificationEvent.NOTIFICATION_SETTINGS_DISABLED);
break;
case "GET_NOTIFICATIONS_ENABLED_RESULT":
event = new PushNotificationEvent(PushNotificationEvent.GET_NOTIFICATIONS_ENABLED_RESULT, e.level == "true");
break;
case "OPEN_APP_NOTIFICATION_SETTINGS":
event = new PushNotificationEvent(PushNotificationEvent.OPEN_APP_NOTIFICATION_SETTINGS);
break;
case "LOG_ISSUE":
event = new PushNotificationEvent(PushNotificationEvent.LOG_ISSUE);
event.errorMessage = data;
break;
case "LOGGING":
trace(e, e.level);
break;
}
if (event != null)
this.dispatchEvent(event);
}
}
}
|
store error in errorMessage
|
store error in errorMessage
|
ActionScript
|
apache-2.0
|
freshplanet/ANE-Push-Notification,freshplanet/ANE-Push-Notification,freshplanet/ANE-Push-Notification
|
89bbc547f4aaed550c6c7e05b81bf9f47c615caa
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/TitleBarView.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/TitleBarView.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.Shape;
import org.apache.flex.core.IBeadView;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.UIBase;
import org.apache.flex.events.Event;
import org.apache.flex.html.Button;
import org.apache.flex.html.Label;
import org.apache.flex.html.TitleBar;
public class TitleBarView extends ContainerView implements IBeadView
{
public function TitleBarView()
{
super();
}
/**
* @private
*/
private var _titleLabel:Label;
public function get titleLabel():Label
{
return _titleLabel;
}
/**
* @private
*/
private var _closeButton:Button;
public function get closeButton():Button
{
return closeButton;
}
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
*/
override public function set strand(value:IStrand):void
{
super.strand = value;
_strand = value;
// add the label for the title and the button for the close
_titleLabel = createTitle();
_titleLabel.className = UIBase(_strand).className;
_titleLabel.id = "title";
UIBase(_strand).addElement(_titleLabel);
_closeButton = createCloseButton();
_closeButton.className = UIBase(_strand).className;
_closeButton.id = "closeButton";
UIBase(_strand).addElement(_closeButton);
TitleBar(_strand).childrenAdded();
UIBase(_strand).model.addEventListener('titleChange',handlePropertyChange);
UIBase(_strand).model.addEventListener('htmlTitleChange',handlePropertyChange);
UIBase(_strand).model.addEventListener('showCloseButtonChange',handlePropertyChange);
// dispatch this event to force any beads to update
UIBase(_strand).dispatchEvent(new Event("widthChanged"));
}
/**
* @private
*/
private function handlePropertyChange(event:Event):void
{
if( event.type == "showCloseButtonChange" ) {
if( closeButton ) closeButton.visible = TitleBar(_strand).showCloseButton;
}
else if( event.type == "titleChange" ) {
if( titleLabel ) {
titleLabel.text = TitleBar(_strand).title;
}
}
else if( event.type == "htmlTitleChange" ) {
if( titleLabel ) {
titleLabel.html = TitleBar(_strand).htmlTitle;
}
}
UIBase(_strand).dispatchEvent(new Event("widthChanged"));
}
/**
* @private
*/
protected function createTitle() : Label
{
var label:Label = new Label();
label.text = TitleBar(_strand).title;
return label;
}
/**
* @private
*/
protected function createCloseButton() : Button
{
var upState:Shape = new Shape();
upState.graphics.clear();
upState.graphics.beginFill(0xCCCCCC);
upState.graphics.drawRect(0,0,11,11);
upState.graphics.endFill();
var overState:Shape = new Shape();
overState.graphics.clear();
overState.graphics.beginFill(0x999999);
overState.graphics.drawRect(0,0,11,11);
overState.graphics.endFill();
var downState:Shape = new Shape();
downState.graphics.clear();
downState.graphics.beginFill(0x666666);
downState.graphics.drawRect(0, 0, 11, 11);
downState.graphics.endFill();
var hitArea:Shape = new Shape();
hitArea.graphics.clear();
hitArea.graphics.beginFill(0x000000);
hitArea.graphics.drawRect(0, 0, 11, 11);
hitArea.graphics.endFill();
var button:Button = new Button();
button.upState = upState;
button.overState = overState;
button.downState = downState;
button.hitTestState = hitArea;
button.visible = TitleBar(_strand).showCloseButton;
button.addEventListener('click',closeButtonHandler);
return button;
}
/**
* @private
*/
private function closeButtonHandler(event:org.apache.flex.events.Event) : void
{
var newEvent:Event = new Event('close',true);
UIBase(_strand).dispatchEvent(newEvent);
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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.Shape;
import org.apache.flex.core.IBeadView;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.UIBase;
import org.apache.flex.events.Event;
import org.apache.flex.html.Button;
import org.apache.flex.html.Label;
import org.apache.flex.html.TitleBar;
public class TitleBarView extends ContainerView implements IBeadView
{
public function TitleBarView()
{
super();
}
/**
* @private
*/
private var _titleLabel:Label;
public function get titleLabel():Label
{
return _titleLabel;
}
/**
* @private
*/
private var _closeButton:Button;
public function get closeButton():Button
{
return closeButton;
}
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
override public function set strand(value:IStrand):void
{
super.strand = value;
// add the label for the title and the button for the close
_titleLabel = createTitle();
_titleLabel.className = UIBase(_strand).className;
_titleLabel.id = "title";
UIBase(_strand).addElement(_titleLabel);
_closeButton = createCloseButton();
_closeButton.className = UIBase(_strand).className;
_closeButton.id = "closeButton";
UIBase(_strand).addElement(_closeButton);
TitleBar(_strand).childrenAdded();
UIBase(_strand).model.addEventListener('titleChange',handlePropertyChange);
UIBase(_strand).model.addEventListener('htmlTitleChange',handlePropertyChange);
UIBase(_strand).model.addEventListener('showCloseButtonChange',handlePropertyChange);
// dispatch this event to force any beads to update
UIBase(_strand).dispatchEvent(new Event("widthChanged"));
}
/**
* @private
*/
private function handlePropertyChange(event:Event):void
{
if( event.type == "showCloseButtonChange" ) {
if( closeButton ) closeButton.visible = TitleBar(_strand).showCloseButton;
}
else if( event.type == "titleChange" ) {
if( titleLabel ) {
titleLabel.text = TitleBar(_strand).title;
}
}
else if( event.type == "htmlTitleChange" ) {
if( titleLabel ) {
titleLabel.html = TitleBar(_strand).htmlTitle;
}
}
UIBase(_strand).dispatchEvent(new Event("widthChanged"));
}
/**
* @private
*/
protected function createTitle() : Label
{
var label:Label = new Label();
label.text = TitleBar(_strand).title;
return label;
}
/**
* @private
*/
protected function createCloseButton() : Button
{
var upState:Shape = new Shape();
upState.graphics.clear();
upState.graphics.beginFill(0xCCCCCC);
upState.graphics.drawRect(0,0,11,11);
upState.graphics.endFill();
var overState:Shape = new Shape();
overState.graphics.clear();
overState.graphics.beginFill(0x999999);
overState.graphics.drawRect(0,0,11,11);
overState.graphics.endFill();
var downState:Shape = new Shape();
downState.graphics.clear();
downState.graphics.beginFill(0x666666);
downState.graphics.drawRect(0, 0, 11, 11);
downState.graphics.endFill();
var hitArea:Shape = new Shape();
hitArea.graphics.clear();
hitArea.graphics.beginFill(0x000000);
hitArea.graphics.drawRect(0, 0, 11, 11);
hitArea.graphics.endFill();
var button:Button = new Button();
button.upState = upState;
button.overState = overState;
button.downState = downState;
button.hitTestState = hitArea;
button.visible = TitleBar(_strand).showCloseButton;
button.addEventListener('click',closeButtonHandler);
return button;
}
/**
* @private
*/
private function closeButtonHandler(event:org.apache.flex.events.Event) : void
{
var newEvent:Event = new Event('close',true);
UIBase(_strand).dispatchEvent(newEvent);
}
}
}
|
fix asdoc issue
|
fix asdoc issue
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
1f3429aa39821c95249a7873c1a306b3e2a15a31
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/ContainerView.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/ContainerView.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.beads
{
import org.apache.flex.core.BeadViewBase;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IBeadLayout;
import org.apache.flex.core.IBeadView;
import org.apache.flex.core.ILayoutParent;
import org.apache.flex.core.IParentIUIBase;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.UIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.html.Container;
import org.apache.flex.html.supportClasses.Border;
import org.apache.flex.html.supportClasses.ContainerContentArea;
import org.apache.flex.html.supportClasses.ScrollBar;
/**
* The ContainerView class is the default view for
* the org.apache.flex.html.Container class.
* It lets you use some CSS styles to manage the border, background
* and padding around the content area.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class ContainerView extends BeadViewBase implements IBeadView, ILayoutParent
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function ContainerView()
{
}
/**
* The actual parent that parents the children.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected var actualParent:UIBase;
/**
* @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;
var host:UIBase = value as UIBase;
if (_strand.getBeadByType(IBeadLayout) == null)
{
var c:Class = ValuesManager.valuesImpl.getValue(host, "iBeadLayout");
if (c)
{
var layout:IBeadLayout = new c() as IBeadLayout;
_strand.addBead(layout);
}
}
if (host.isWidthSizedToContent() && host.isHeightSizedToContent())
{
host.addEventListener("childrenAdded", changeHandler);
checkActualParent();
}
else
{
host.addEventListener("widthChanged", changeHandler);
host.addEventListener("heightChanged", changeHandler);
host.addEventListener("sizeChanged", sizeChangeHandler);
if (!isNaN(host.explicitWidth) && !isNaN(host.explicitHeight))
sizeChangeHandler(null);
else
checkActualParent();
}
}
private function checkActualParent():Boolean
{
var host:UIBase = UIBase(_strand);
if (contentAreaNeeded())
{
if (actualParent == null || actualParent == host)
{
actualParent = new ContainerContentArea();
host.addElement(actualParent);
Container(host).setActualParent(actualParent);
}
return true;
}
else
{
actualParent = host;
}
return false;
}
private function sizeChangeHandler(event:Event):void
{
var host:UIBase = UIBase(_strand);
host.addEventListener("childrenAdded", changeHandler);
host.addEventListener("layoutNeeded", changeHandler);
changeHandler(event);
}
private var inChangeHandler:Boolean;
/**
* React if the size changed or content changed
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected function changeHandler(event:Event):void
{
if (inChangeHandler) return;
inChangeHandler = true;
var host:UIBase = UIBase(_strand);
var padding:Object = determinePadding();
if (checkActualParent())
{
actualParent.x = padding.paddingLeft;
actualParent.y = padding.paddingTop;
var pb:Number = padding.paddingBottom;
if (isNaN(pb))
pb = 0;
var pr:Number = padding.paddingRight;
if (isNaN(pr))
pr = 0;
if (!isNaN(host.explicitWidth) || !isNaN(host.percentWidth))
actualParent.setWidth(host.width - padding.paddingLeft - pr);
else
host.dispatchEvent(new Event("widthChanged"));
if (!isNaN(host.explicitHeight) || !isNaN(host.percentHeight))
actualParent.setHeight(host.height - padding.paddingTop - pb);
else
host.dispatchEvent(new Event("heightChanged"));
}
var backgroundColor:Object = ValuesManager.valuesImpl.getValue(host, "background-color");
var backgroundImage:Object = ValuesManager.valuesImpl.getValue(host, "background-image");
if (backgroundColor != null || backgroundImage != null)
{
if (host.getBeadByType(IBackgroundBead) == null)
host.addBead(new (ValuesManager.valuesImpl.getValue(host, "iBackgroundBead")) as IBead);
}
var borderStyle:String;
var borderStyles:Object = ValuesManager.valuesImpl.getValue(host, "border");
if (borderStyles is Array)
{
borderStyle = borderStyles[1];
}
if (borderStyle == null)
{
borderStyle = ValuesManager.valuesImpl.getValue(host, "border-style") as String;
}
if (borderStyle != null && borderStyle != "none")
{
if (host.getBeadByType(IBorderBead) == null)
host.addBead(new (ValuesManager.valuesImpl.getValue(host, "iBorderBead")) as IBead);
}
inChangeHandler = false;
}
/**
* 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 padding:Object = ValuesManager.valuesImpl.getValue(_strand, "padding");
if (padding is Array)
{
if (padding.length == 1)
paddingLeft = paddingTop = padding[0];
else if (padding.length <= 3)
{
paddingLeft = padding[1];
paddingTop = padding[0];
}
else if (padding.length == 4)
{
paddingLeft = padding[3];
paddingTop = padding[0];
}
}
else if (padding == null)
{
paddingLeft = ValuesManager.valuesImpl.getValue(_strand, "padding-left");
paddingTop = ValuesManager.valuesImpl.getValue(_strand, "padding-top");
}
else
{
paddingLeft = paddingTop = padding;
}
var pl:Number = Number(paddingLeft);
var pt:Number = Number(paddingTop);
return {paddingLeft:pl, paddingTop:pt};
}
/**
* Returns true if container to create a separate ContainerContentArea.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected function contentAreaNeeded():Boolean
{
var padding:Object = determinePadding();
return (!isNaN(padding.paddingLeft) && padding.paddingLeft > 0 ||
!isNaN(padding.paddingTop) && padding.paddingTop > 0);
}
/**
* The parent of the children.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get contentView():IParentIUIBase
{
return actualParent;
}
/**
* The host component, which can resize to different slots.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get resizableView():IUIBase
{
return _strand as IUIBase;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.beads
{
import org.apache.flex.core.BeadViewBase;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IBeadLayout;
import org.apache.flex.core.IBeadView;
import org.apache.flex.core.ILayoutParent;
import org.apache.flex.core.IParentIUIBase;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.UIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.html.Container;
import org.apache.flex.html.supportClasses.Border;
import org.apache.flex.html.supportClasses.ContainerContentArea;
import org.apache.flex.html.supportClasses.ScrollBar;
/**
* The ContainerView class is the default view for
* the org.apache.flex.html.Container class.
* It lets you use some CSS styles to manage the border, background
* and padding around the content area.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class ContainerView extends BeadViewBase implements IBeadView, ILayoutParent
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function ContainerView()
{
}
/**
* The actual parent that parents the children.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected var actualParent:UIBase;
/**
* @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;
var host:UIBase = value as UIBase;
if (host.isWidthSizedToContent() && host.isHeightSizedToContent())
{
host.addEventListener("childrenAdded", changeHandler);
checkActualParent();
}
else
{
host.addEventListener("widthChanged", changeHandler);
host.addEventListener("heightChanged", changeHandler);
host.addEventListener("sizeChanged", sizeChangeHandler);
if (!isNaN(host.explicitWidth) && !isNaN(host.explicitHeight))
sizeChangeHandler(null);
else
checkActualParent();
}
if (_strand.getBeadByType(IBeadLayout) == null)
{
var c:Class = ValuesManager.valuesImpl.getValue(host, "iBeadLayout");
if (c)
{
var layout:IBeadLayout = new c() as IBeadLayout;
_strand.addBead(layout);
}
}
}
private function checkActualParent():Boolean
{
var host:UIBase = UIBase(_strand);
if (contentAreaNeeded())
{
if (actualParent == null || actualParent == host)
{
actualParent = new ContainerContentArea();
host.addElement(actualParent);
Container(host).setActualParent(actualParent);
}
return true;
}
else
{
actualParent = host;
}
return false;
}
private function sizeChangeHandler(event:Event):void
{
var host:UIBase = UIBase(_strand);
host.addEventListener("childrenAdded", changeHandler);
host.addEventListener("layoutNeeded", changeHandler);
changeHandler(event);
}
private var inChangeHandler:Boolean;
/**
* React if the size changed or content changed
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected function changeHandler(event:Event):void
{
if (inChangeHandler) return;
inChangeHandler = true;
var host:UIBase = UIBase(_strand);
var padding:Object = determinePadding();
if (checkActualParent())
{
actualParent.x = padding.paddingLeft;
actualParent.y = padding.paddingTop;
var pb:Number = padding.paddingBottom;
if (isNaN(pb))
pb = 0;
var pr:Number = padding.paddingRight;
if (isNaN(pr))
pr = 0;
if (!isNaN(host.explicitWidth) || !isNaN(host.percentWidth))
actualParent.setWidth(host.width - padding.paddingLeft - pr);
else
host.dispatchEvent(new Event("widthChanged"));
if (!isNaN(host.explicitHeight) || !isNaN(host.percentHeight))
actualParent.setHeight(host.height - padding.paddingTop - pb);
else
host.dispatchEvent(new Event("heightChanged"));
}
var backgroundColor:Object = ValuesManager.valuesImpl.getValue(host, "background-color");
var backgroundImage:Object = ValuesManager.valuesImpl.getValue(host, "background-image");
if (backgroundColor != null || backgroundImage != null)
{
if (host.getBeadByType(IBackgroundBead) == null)
host.addBead(new (ValuesManager.valuesImpl.getValue(host, "iBackgroundBead")) as IBead);
}
var borderStyle:String;
var borderStyles:Object = ValuesManager.valuesImpl.getValue(host, "border");
if (borderStyles is Array)
{
borderStyle = borderStyles[1];
}
if (borderStyle == null)
{
borderStyle = ValuesManager.valuesImpl.getValue(host, "border-style") as String;
}
if (borderStyle != null && borderStyle != "none")
{
if (host.getBeadByType(IBorderBead) == null)
host.addBead(new (ValuesManager.valuesImpl.getValue(host, "iBorderBead")) as IBead);
}
inChangeHandler = false;
}
/**
* 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 padding:Object = ValuesManager.valuesImpl.getValue(_strand, "padding");
if (padding is Array)
{
if (padding.length == 1)
paddingLeft = paddingTop = padding[0];
else if (padding.length <= 3)
{
paddingLeft = padding[1];
paddingTop = padding[0];
}
else if (padding.length == 4)
{
paddingLeft = padding[3];
paddingTop = padding[0];
}
}
else if (padding == null)
{
paddingLeft = ValuesManager.valuesImpl.getValue(_strand, "padding-left");
paddingTop = ValuesManager.valuesImpl.getValue(_strand, "padding-top");
}
else
{
paddingLeft = paddingTop = padding;
}
var pl:Number = Number(paddingLeft);
var pt:Number = Number(paddingTop);
return {paddingLeft:pl, paddingTop:pt};
}
/**
* Returns true if container to create a separate ContainerContentArea.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected function contentAreaNeeded():Boolean
{
var padding:Object = determinePadding();
return (!isNaN(padding.paddingLeft) && padding.paddingLeft > 0 ||
!isNaN(padding.paddingTop) && padding.paddingTop > 0);
}
/**
* The parent of the children.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get contentView():IParentIUIBase
{
return actualParent;
}
/**
* The host component, which can resize to different slots.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get resizableView():IUIBase
{
return _strand as IUIBase;
}
}
}
|
move when beads attached so that containerview can resize contentarea before layout
|
move when beads attached so that containerview can resize contentarea before layout
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
64b61de38b4644ee1528b59c68106187d1ec8e06
|
src/com/mangui/HLS/streaming/Buffer.as
|
src/com/mangui/HLS/streaming/Buffer.as
|
package com.mangui.HLS.streaming {
import com.mangui.HLS.*;
import com.mangui.HLS.muxing.*;
import com.mangui.HLS.streaming.*;
import com.mangui.HLS.parsing.*;
import com.mangui.HLS.utils.*;
import flash.media.*;
import flash.net.*;
import flash.utils.*;
/** Class that keeps the buffer filled. **/
public class Buffer {
/** Reference to the framework controller. **/
private var _hls:HLS;
/** The buffer with video tags. **/
private var _buffer:Vector.<Tag>;
/** NetConnection legacy stuff. **/
private var _connection:NetConnection;
/** The fragment loader. **/
private var _loader:Loader;
/** Store that a fragment load is in progress. **/
private var _loading:Boolean;
/** Interval for checking buffer and position. **/
private var _interval:Number;
/** Next loading fragment sequence number. **/
/** The start position of the stream. **/
public var PlaybackStartPosition:Number = 0;
/** start play time **/
private var _playback_start_time:Number;
/** playback start PTS. **/
private var _playback_start_pts:Number;
/** playlist start PTS when playback started. **/
private var _playlist_start_pts:Number;
/** Current play position (relative position from beginning of sliding window) **/
private var _playback_current_position:Number;
/** buffer last PTS. **/
private var _buffer_last_pts:Number;
/** next buffer time. **/
private var _buffer_next_time:Number;
/** previous buffer time. **/
private var _last_buffer:Number;
/** Current playback state. **/
private var _state:String;
/** Netstream instance used for playing the stream. **/
private var _stream:NetStream;
/** The last tag that was appended to the buffer. **/
private var _tag:Number;
/** soundtransform object. **/
private var _transform:SoundTransform;
/** Reference to the video object. **/
private var _video:Object;
/** Create the buffer. **/
public function Buffer(hls:HLS, loader:Loader, video:Object):void {
_hls = hls;
_loader = loader;
_video = video;
_hls.addEventListener(HLSEvent.MANIFEST,_manifestHandler);
_connection = new NetConnection();
_connection.connect(null);
_transform = new SoundTransform();
_transform.volume = 0.9;
_setState(HLSStates.IDLE);
};
/** Check the bufferlength. **/
private function _checkBuffer():void {
var reachedend:Boolean = false;
var buffer:Number = 0;
// Calculate the buffer and position.
if(_buffer.length) {
buffer = (_buffer_last_pts - _playback_start_pts)/1000 - _stream.time;
/** Current play time (time since beginning of playback) **/
var playback_current_time:Number = (Math.round(_stream.time*100 + _playback_start_time*100)/100);
var playliststartpts:Number = _loader.getPlayListStartPTS();
var play_position:Number;
if(playliststartpts < 0) {
play_position = 0;
} else {
play_position = playback_current_time -(playliststartpts-_playlist_start_pts)/1000;
}
if(play_position != _playback_current_position || buffer !=_last_buffer) {
if (play_position <0) {
play_position = 0;
}
_playback_current_position = play_position;
_last_buffer = buffer;
_hls.dispatchEvent(new HLSEvent(HLSEvent.MEDIA_TIME,{ position:_playback_current_position, buffer:buffer, duration:_loader.getPlayListDuration()}));
}
}
// Load new tags from fragment.
if(buffer < _loader.getBufferLength() && !_loading) {
var loadstatus:Number = _loader.loadfragment(_buffer_next_time,_buffer_last_pts,buffer,_loaderCallback,(_buffer.length == 0));
if (loadstatus == 0) {
// good, new fragment being loaded
_loading = true;
} else if (loadstatus < 0) {
/* it means PTS requested is smaller than playlist start PTS.
it could happen on live playlist :
- if bandwidth available is lower than lowest quality needed bandwidth
- after long pause
seek to offset 0 to force a restart of the playback session */
Log.txt("long pause on live stream or bad network quality");
seek(0);
return;
} else if(loadstatus > 0) {
//seqnum not available in playlist
if (_hls.getType() == HLSTypes.VOD) {
// if VOD playlist, it means we reached the end, on live playlist do nothing and wait ...
reachedend = true;
}
}
}
// Append tags to buffer.
if((_state == HLSStates.PLAYING && _stream.bufferLength < _loader.getSegmentMaxDuration()) ||
(_state == HLSStates.BUFFERING && buffer > _loader.getSegmentMaxDuration()))
{
//Log.txt("appending data");
while(_tag < _buffer.length && _stream.bufferLength < 2*_loader.getSegmentMaxDuration()) {
try {
_stream.appendBytes(_buffer[_tag].data);
} catch (error:Error) {
_errorHandler(new Error(_buffer[_tag].type+": "+ error.message));
}
// Last tag done? Then append sequence end.
if (reachedend ==true && _tag == _buffer.length - 1) {
_stream.appendBytesAction(NetStreamAppendBytesAction.END_SEQUENCE);
_stream.appendBytes(new ByteArray());
}
_tag++;
}
}
// Set playback state and complete.
if(_stream.bufferLength < 3) {
if(reachedend ==true) {
if(_stream.bufferLength == 0) {
_complete();
}
} else if(_state == HLSStates.PLAYING) {
_setState(HLSStates.BUFFERING);
}
} else if (_state == HLSStates.BUFFERING) {
_setState(HLSStates.PLAYING);
}
};
/** The video completed playback. **/
private function _complete():void {
_setState(HLSStates.IDLE);
clearInterval(_interval);
// _stream.pause();
_hls.dispatchEvent(new HLSEvent(HLSEvent.COMPLETE));
};
/** Dispatch an error to the controller. **/
private function _errorHandler(error:Error):void {
_hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR,error.toString()));
};
/** Return the current playback state. **/
public function getPosition():Number {
return _playback_current_position;
};
/** Return the current playback state. **/
public function getState():String {
return _state;
};
/** Add a fragment to the buffer. **/
private function _loaderCallback(tags:Vector.<Tag>,min_pts:Number,max_pts:Number):void {
_buffer = _buffer.slice(_tag);
_tag = 0;
if (_playback_start_pts == 0) {
_playback_start_pts = min_pts;
_playlist_start_pts = _loader.getPlayListStartPTS();
_playback_start_time = (_playback_start_pts-_playlist_start_pts)/1000;
}
_buffer_last_pts = max_pts;
tags.sort(_sortTagsbyDTS);
for each (var t:Tag in tags) {
_buffer.push(t);
}
_buffer_next_time=_playback_start_time+(_buffer_last_pts-_playback_start_pts)/1000;
Log.txt("_loaderCallback,_buffer_next_time:"+ _buffer_next_time);
_loading = false;
};
/** Start streaming on manifest load. **/
private function _manifestHandler(event:HLSEvent):void {
if(_state == HLSStates.IDLE) {
_stream = new NetStream(_connection);
_video.attachNetStream(_stream);
_stream.play(null);
_stream.soundTransform = _transform;
_stream.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN);
_stream.appendBytes(FLV.getHeader());
seek(PlaybackStartPosition);
}
};
/** Toggle playback. **/
public function pause():void {
clearInterval(_interval);
if(_state == HLSStates.PAUSED) {
_setState(HLSStates.BUFFERING);
_stream.resume();
_interval = setInterval(_checkBuffer,100);
} else if(_state == HLSStates.PLAYING) {
_setState(HLSStates.PAUSED);
_stream.pause();
}
};
/** Change playback state. **/
private function _setState(state:String):void {
if(state != _state) {
_state = state;
_hls.dispatchEvent(new HLSEvent(HLSEvent.STATE,_state));
}
};
/** Sort the buffer by tag. **/
private function _sortTagsbyDTS(x:Tag,y:Tag):Number {
if(x.dts < y.dts) {
return -1;
} else if (x.dts > y.dts) {
return 1;
} else {
if(x.type == Tag.AVC_HEADER || x.type == Tag.AAC_HEADER) {
return -1;
} else if (y.type == Tag.AVC_HEADER || y.type == Tag.AAC_HEADER) {
return 1;
} else {
if(x.type == Tag.AVC_NALU) {
return -1;
} else if (y.type == Tag.AVC_NALU) {
return 1;
} else {
return 0;
}
}
}
};
/** Start playing data in the buffer. **/
public function seek(position:Number):void {
_buffer = new Vector.<Tag>();
_loader.clearLoader();
_loading = false;
_tag = 0;
PlaybackStartPosition = position;
_stream.seek(0);
_stream.appendBytesAction(NetStreamAppendBytesAction.RESET_SEEK);
_playback_start_time = position;
_playback_start_pts = 0;
_buffer_next_time = _playback_start_time;
_buffer_last_pts = 0;
_last_buffer = 0;
_setState(HLSStates.BUFFERING);
clearInterval(_interval);
_interval = setInterval(_checkBuffer,100);
};
/** Stop playback. **/
public function stop():void {
if(_stream) {
_stream.pause();
}
_loading = false;
clearInterval(_interval);
_setState(HLSStates.IDLE);
};
/** Change the volume (set in the NetStream). **/
public function volume(percent:Number):void {
_transform.volume = percent/100;
if(_stream) {
_stream.soundTransform = _transform;
}
};
}
}
|
package com.mangui.HLS.streaming {
import com.mangui.HLS.*;
import com.mangui.HLS.muxing.*;
import com.mangui.HLS.streaming.*;
import com.mangui.HLS.parsing.*;
import com.mangui.HLS.utils.*;
import flash.media.*;
import flash.net.*;
import flash.utils.*;
/** Class that keeps the buffer filled. **/
public class Buffer {
/** Reference to the framework controller. **/
private var _hls:HLS;
/** The buffer with video tags. **/
private var _buffer:Vector.<Tag>;
/** NetConnection legacy stuff. **/
private var _connection:NetConnection;
/** The fragment loader. **/
private var _loader:Loader;
/** Store that a fragment load is in progress. **/
private var _loading:Boolean;
/** Interval for checking buffer and position. **/
private var _interval:Number;
/** Next loading fragment sequence number. **/
/** The start position of the stream. **/
public var PlaybackStartPosition:Number = 0;
/** start play time **/
private var _playback_start_time:Number;
/** playback start PTS. **/
private var _playback_start_pts:Number;
/** playlist start PTS when playback started. **/
private var _playlist_start_pts:Number;
/** Current play position (relative position from beginning of sliding window) **/
private var _playback_current_position:Number;
/** buffer last PTS. **/
private var _buffer_last_pts:Number;
/** next buffer time. **/
private var _buffer_next_time:Number;
/** previous buffer time. **/
private var _last_buffer:Number;
/** Current playback state. **/
private var _state:String;
/** Netstream instance used for playing the stream. **/
private var _stream:NetStream;
/** The last tag that was appended to the buffer. **/
private var _tag:Number;
/** soundtransform object. **/
private var _transform:SoundTransform;
/** Reference to the video object. **/
private var _video:Object;
/** Create the buffer. **/
public function Buffer(hls:HLS, loader:Loader, video:Object):void {
_hls = hls;
_loader = loader;
_video = video;
_hls.addEventListener(HLSEvent.MANIFEST,_manifestHandler);
_connection = new NetConnection();
_connection.connect(null);
_transform = new SoundTransform();
_transform.volume = 0.9;
_setState(HLSStates.IDLE);
};
/** Check the bufferlength. **/
private function _checkBuffer():void {
var reachedend:Boolean = false;
var buffer:Number = 0;
// Calculate the buffer and position.
if(_buffer.length) {
buffer = (_buffer_last_pts - _playback_start_pts)/1000 - _stream.time;
/** Current play time (time since beginning of playback) **/
var playback_current_time:Number = (Math.round(_stream.time*100 + _playback_start_time*100)/100);
var current_playlist_start_pts:Number = _loader.getPlayListStartPTS();
var play_position:Number;
if(current_playlist_start_pts < 0) {
play_position = 0;
} else {
play_position = playback_current_time -(current_playlist_start_pts-_playlist_start_pts)/1000;
}
if(play_position != _playback_current_position || buffer !=_last_buffer) {
if (play_position <0) {
play_position = 0;
}
_playback_current_position = play_position;
_last_buffer = buffer;
_hls.dispatchEvent(new HLSEvent(HLSEvent.MEDIA_TIME,{ position:_playback_current_position, buffer:buffer, duration:_loader.getPlayListDuration()}));
}
}
// Load new tags from fragment.
if(buffer < _loader.getBufferLength() && !_loading) {
var loadstatus:Number = _loader.loadfragment(_buffer_next_time,_buffer_last_pts,buffer,_loaderCallback,(_buffer.length == 0));
if (loadstatus == 0) {
// good, new fragment being loaded
_loading = true;
} else if (loadstatus < 0) {
/* it means PTS requested is smaller than playlist start PTS.
it could happen on live playlist :
- if bandwidth available is lower than lowest quality needed bandwidth
- after long pause
seek to offset 0 to force a restart of the playback session */
Log.txt("long pause on live stream or bad network quality");
seek(0);
return;
} else if(loadstatus > 0) {
//seqnum not available in playlist
if (_hls.getType() == HLSTypes.VOD) {
// if VOD playlist, it means we reached the end, on live playlist do nothing and wait ...
reachedend = true;
}
}
}
// Append tags to buffer.
if((_state == HLSStates.PLAYING && _stream.bufferLength < _loader.getSegmentMaxDuration()) ||
(_state == HLSStates.BUFFERING && buffer > _loader.getSegmentMaxDuration()))
{
//Log.txt("appending data");
while(_tag < _buffer.length && _stream.bufferLength < 2*_loader.getSegmentMaxDuration()) {
try {
_stream.appendBytes(_buffer[_tag].data);
} catch (error:Error) {
_errorHandler(new Error(_buffer[_tag].type+": "+ error.message));
}
// Last tag done? Then append sequence end.
if (reachedend ==true && _tag == _buffer.length - 1) {
_stream.appendBytesAction(NetStreamAppendBytesAction.END_SEQUENCE);
_stream.appendBytes(new ByteArray());
}
_tag++;
}
}
// Set playback state and complete.
if(_stream.bufferLength < 3) {
if(reachedend ==true) {
if(_stream.bufferLength == 0) {
_complete();
}
} else if(_state == HLSStates.PLAYING) {
_setState(HLSStates.BUFFERING);
}
} else if (_state == HLSStates.BUFFERING) {
_setState(HLSStates.PLAYING);
}
};
/** The video completed playback. **/
private function _complete():void {
_setState(HLSStates.IDLE);
clearInterval(_interval);
// _stream.pause();
_hls.dispatchEvent(new HLSEvent(HLSEvent.COMPLETE));
};
/** Dispatch an error to the controller. **/
private function _errorHandler(error:Error):void {
_hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR,error.toString()));
};
/** Return the current playback state. **/
public function getPosition():Number {
return _playback_current_position;
};
/** Return the current playback state. **/
public function getState():String {
return _state;
};
/** Add a fragment to the buffer. **/
private function _loaderCallback(tags:Vector.<Tag>,min_pts:Number,max_pts:Number):void {
_buffer = _buffer.slice(_tag);
_tag = 0;
if (_playback_start_pts == 0) {
_playback_start_pts = min_pts;
_playlist_start_pts = _loader.getPlayListStartPTS();
_playback_start_time = (_playback_start_pts-_playlist_start_pts)/1000;
}
_buffer_last_pts = max_pts;
tags.sort(_sortTagsbyDTS);
for each (var t:Tag in tags) {
_buffer.push(t);
}
_buffer_next_time=_playback_start_time+(_buffer_last_pts-_playback_start_pts)/1000;
Log.txt("_loaderCallback,_buffer_next_time:"+ _buffer_next_time);
_loading = false;
};
/** Start streaming on manifest load. **/
private function _manifestHandler(event:HLSEvent):void {
if(_state == HLSStates.IDLE) {
_stream = new NetStream(_connection);
_video.attachNetStream(_stream);
_stream.play(null);
_stream.soundTransform = _transform;
_stream.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN);
_stream.appendBytes(FLV.getHeader());
seek(PlaybackStartPosition);
}
};
/** Toggle playback. **/
public function pause():void {
clearInterval(_interval);
if(_state == HLSStates.PAUSED) {
_setState(HLSStates.BUFFERING);
_stream.resume();
_interval = setInterval(_checkBuffer,100);
} else if(_state == HLSStates.PLAYING) {
_setState(HLSStates.PAUSED);
_stream.pause();
}
};
/** Change playback state. **/
private function _setState(state:String):void {
if(state != _state) {
_state = state;
_hls.dispatchEvent(new HLSEvent(HLSEvent.STATE,_state));
}
};
/** Sort the buffer by tag. **/
private function _sortTagsbyDTS(x:Tag,y:Tag):Number {
if(x.dts < y.dts) {
return -1;
} else if (x.dts > y.dts) {
return 1;
} else {
if(x.type == Tag.AVC_HEADER || x.type == Tag.AAC_HEADER) {
return -1;
} else if (y.type == Tag.AVC_HEADER || y.type == Tag.AAC_HEADER) {
return 1;
} else {
if(x.type == Tag.AVC_NALU) {
return -1;
} else if (y.type == Tag.AVC_NALU) {
return 1;
} else {
return 0;
}
}
}
};
/** Start playing data in the buffer. **/
public function seek(position:Number):void {
_buffer = new Vector.<Tag>();
_loader.clearLoader();
_loading = false;
_tag = 0;
PlaybackStartPosition = position;
_stream.seek(0);
_stream.appendBytesAction(NetStreamAppendBytesAction.RESET_SEEK);
_playback_start_pts = 0;
_buffer_next_time = position;
_buffer_last_pts = 0;
_last_buffer = 0;
_setState(HLSStates.BUFFERING);
clearInterval(_interval);
_interval = setInterval(_checkBuffer,100);
};
/** Stop playback. **/
public function stop():void {
if(_stream) {
_stream.pause();
}
_loading = false;
clearInterval(_interval);
_setState(HLSStates.IDLE);
};
/** Change the volume (set in the NetStream). **/
public function volume(percent:Number):void {
_transform.volume = percent/100;
if(_stream) {
_stream.soundTransform = _transform;
}
};
}
}
|
rename variable
|
rename variable
|
ActionScript
|
mpl-2.0
|
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
|
08f2f7cbeac0a6a54a2ac06cc49a9ddeaa414c35
|
com/segonquart/idiomesAnimation.as
|
com/segonquart/idiomesAnimation.as
|
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
class com.segonquart.idiomesAnimation extends Movieclip
{
private var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr");
function idiomesAnimation():Void
{
this.stop();
this.onEnterFrame = this.enterSlide;
}
private function enterSlide()
{
arrayLang_arr[0].slideTo('0', '-40', 0.6, 'easeInOutBack', 1);
arrayLang_arr[1].slideTo('0', '-40', 0.8, 'easeInOutBack', 1.1);
arrayLang_arr[2].slideTo('0', '-40', 0.9, 'easeInOutBack', 1.2);
arrayLang_arr[3].slideTo('0', '-40', 1, 'easeInOutBack', 1.3);
}
public function IdiomesColour()
{
this.onRelease = this arrayColour;
target = this.arrayLang_arr[i];
target._tint = 0x8DC60D;
return this;
}
private function arrayColour()
{
for ( var:i:Number=0 ; arrayLang_arr[i].length <4; i++)
{
this.colorTo("#628D22", 0.3, "easeOutCirc");
_parent.colorTo('#4b4b4b', 1, 'linear', .2);
}
}
}
|
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
class com.segonquart.idiomesAnimation extends Movieclip
{
private var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr");
public function idiomesAnimation()
{
this.stop();
this.onEnterFrame = this.enterSlide;
}
private function enterSlide()
{
arrayLang_arr[0].slideTo('0', '-40', 0.6, 'easeInOutBack', 1);
arrayLang_arr[1].slideTo('0', '-40', 0.8, 'easeInOutBack', 1.1);
arrayLang_arr[2].slideTo('0', '-40', 0.9, 'easeInOutBack', 1.2);
arrayLang_arr[3].slideTo('0', '-40', 1, 'easeInOutBack', 1.3);
}
public function IdiomesColour()
{
this.onRelease = this.arrayColour;
target = this.arrayLang_arr[i];
target._tint = 0x8DC60D;
return this;
}
private function arrayColour()
{
for ( var:i:Number=0 ; arrayLang_arr[i].length <4; i++)
{
this.colorTo("#628D22", 0.3, "easeOutCirc");
_parent.colorTo('#4b4b4b', 1, 'linear', .2);
}
}
}
|
Update idiomesAnimation.as
|
Update idiomesAnimation.as
|
ActionScript
|
bsd-3-clause
|
delfiramirez/web-talking-wear,delfiramirez/web-talking-wear,delfiramirez/web-talking-wear
|
3292f719f6887c3d535e28e4842bd7ac4dcee42e
|
src/flash/display/MovieClip.as
|
src/flash/display/MovieClip.as
|
/*
* Copyright 2014 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package flash.display {
[native(cls='MovieClipClass')]
public dynamic class MovieClip extends Sprite {
public function MovieClip() {}
public native function get currentFrame():int;
public native function get framesLoaded():int;
public native function get totalFrames():int;
public native function get trackAsMenu():Boolean;
public native function set trackAsMenu(value:Boolean):void;
public native function get scenes():Array;
public native function get currentScene():Scene;
public native function get currentLabel():String;
public native function get currentFrameLabel():String;
public function get currentLabels():Array {
return currentScene.labels;
}
public native function get enabled():Boolean;
public native function set enabled(value:Boolean):void;
public native function get isPlaying():Boolean;
public native function play():void;
public native function stop():void;
public native function nextFrame():void;
public native function prevFrame():void;
public native function gotoAndPlay(frame:Object, scene:String = null):void;
public native function gotoAndStop(frame:Object, scene:String = null):void;
public native function addFrameScript():void;
public native function prevScene():void;
public native function nextScene():void;
}
}
|
/*
* Copyright 2014 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package flash.display {
[native(cls='MovieClipClass')]
public dynamic class MovieClip extends Sprite {
public native function MovieClip();
public native function get currentFrame():int;
public native function get framesLoaded():int;
public native function get totalFrames():int;
public native function get trackAsMenu():Boolean;
public native function set trackAsMenu(value:Boolean):void;
public native function get scenes():Array;
public native function get currentScene():Scene;
public native function get currentLabel():String;
public native function get currentFrameLabel():String;
public function get currentLabels():Array {
return currentScene.labels;
}
public native function get enabled():Boolean;
public native function set enabled(value:Boolean):void;
public native function get isPlaying():Boolean;
public native function play():void;
public native function stop():void;
public native function nextFrame():void;
public native function prevFrame():void;
public native function gotoAndPlay(frame:Object, scene:String = null):void;
public native function gotoAndStop(frame:Object, scene:String = null):void;
public native function addFrameScript():void;
public native function prevScene():void;
public native function nextScene():void;
}
}
|
Make the MovieClip constructor native
|
Make the MovieClip constructor native
No need to generate code for this: we already have the correct native ctor in place.
|
ActionScript
|
apache-2.0
|
tschneidereit/shumway,mbebenita/shumway,mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway,tschneidereit/shumway,mozilla/shumway,tschneidereit/shumway,mbebenita/shumway,mbebenita/shumway,tschneidereit/shumway,tschneidereit/shumway,yurydelendik/shumway,yurydelendik/shumway,yurydelendik/shumway,yurydelendik/shumway,mozilla/shumway,mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway,mozilla/shumway,mozilla/shumway,yurydelendik/shumway,mbebenita/shumway,mbebenita/shumway,mbebenita/shumway,mozilla/shumway,mozilla/shumway,mozilla/shumway,yurydelendik/shumway,mozilla/shumway,tschneidereit/shumway
|
10b994b85c65b594d1bfb594576930c5debbe438
|
test/trace/values.as
|
test/trace/values.as
|
// This ActionScript file defines a list of values that are considered
// important for checking various ActionScript operations.
// It defines 2 variables:
// - "values": The array of values to be checked
// - "names": The array of corresponding string representations for values.
// It's suggested to use these instead of using values directly to
// avoid spurious toString and valueOf calls.
printall = new Object ();
printall.valueOf = function () {
trace ("valueOf called");
return this;
};
printall.toString = function () {
trace ("toString called");
return this;
};
printtostring = new Object ();
printtostring.toString = function () {
trace ("toString called with " + arguments);
return this;
};
printvalueof = new Object ();
printvalueof.valueOf = function () {
trace ("valueOf called with " + arguments);
return this;
};
nothing = new Object ();
nothing.__proto__ = undefined;
values = [
undefined,
null,
true, false,
0, 1, 0.5, -1, -0.5, Infinity, -Infinity, NaN,
"", "0", "-0", "0.0", "1", "Hello World!", "true", "_level0",
this, new Object (), Function, printall, printtostring, printvalueof, nothing ];
var l = values.length;
var v = function () {
trace (this.nr + ": valueOf!");
return this.v;
};
var s = function () {
trace (this.nr + ": toString!");
return this.v;
};
for (i = 0; i < l; i++) {
var o = new Object ();
o.nr = i;
o.valueOf = v;
o.toString = s;
o.v = values[i];
values.push (o);
};
names = [];
for (i = 0; i < values.length; i++) {
names[i] = "(" + i + ") " + values[i] + " (" + typeof (values[i]) + ")";
};
|
// This ActionScript file defines a list of values that are considered
// important for checking various ActionScript operations.
// It defines 2 variables:
// - "values": The array of values to be checked
// - "names": The array of corresponding string representations for values.
// It's suggested to use these instead of using values directly to
// avoid spurious toString and valueOf calls.
printall = new Object ();
printall.valueOf = function () {
trace ("valueOf called");
return this;
};
printall.toString = function () {
trace ("toString called");
return this;
};
printtostring = new Object ();
printtostring.toString = function () {
trace ("toString called with " + arguments);
return this;
};
printvalueof = new Object ();
printvalueof.valueOf = function () {
trace ("valueOf called with " + arguments);
return this;
};
nothing = new Object ();
nothing.__proto__ = undefined;
values = [
undefined,
null,
true, false,
0, 1, 0.5, -1, -0.5, Infinity, -Infinity, NaN,
"", "0", "-0", "0.0", "1", "Hello World!", "true", "_level0", "äöü",
this, new Object (), Function, printall, printtostring, printvalueof, nothing ];
var l = values.length;
var v = function () {
trace (this.nr + ": valueOf!");
return this.v;
};
var s = function () {
trace (this.nr + ": toString!");
return this.v;
};
for (i = 0; i < l; i++) {
var o = new Object ();
o.nr = i;
o.valueOf = v;
o.toString = s;
o.v = values[i];
values.push (o);
};
names = [];
for (i = 0; i < values.length; i++) {
names[i] = "(" + i + ") " + values[i] + " (" + typeof (values[i]) + ")";
};
|
include a UTF-8 string in values.as
|
include a UTF-8 string in values.as
|
ActionScript
|
lgpl-2.1
|
freedesktop-unofficial-mirror/swfdec__swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,mltframework/swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,mltframework/swfdec
|
95cb5df944380b6406261766198cd83345a27862
|
frameworks/projects/HTML/asjs/src/org/apache/flex/html/beads/layouts/VerticalColumnLayout.as
|
frameworks/projects/HTML/asjs/src/org/apache/flex/html/beads/layouts/VerticalColumnLayout.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.IContainer;
import org.apache.flex.core.IMeasurementBead;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.UIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.utils.CSSUtils;
/**
* ColumnLayout is a class that organizes the positioning of children
* of a container into a set of columns where each column's width is set to
* the maximum size of all of the children in that column.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class VerticalColumnLayout implements IBeadLayout
{
/**
* constructor
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function VerticalColumnLayout()
{
}
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 _numColumns:int;
/**
* The number of columns.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get numColumns():int
{
return _numColumns;
}
public function set numColumns(value:int):void
{
_numColumns = value;
}
/**
* @copy org.apache.flex.core.IBeadLayout#layout
*/
public function layout():Boolean
{
var host:UIBase = UIBase(_strand);
var sw:Number = host.width;
var sh:Number = host.height;
var e:IUIBase;
var i:int;
var col:int = 0;
var columns:Array = [];
var rows:Array = [];
var data:Array = [];
for (i = 0; i < numColumns; i++)
columns[i] = 0;
var marginLeft:Object;
var marginRight:Object;
var marginTop:Object;
var marginBottom:Object;
var margin:Object;
var ml:Number;
var mr:Number;
var mt:Number;
var mb:Number;
var children:Array = IContainer(_strand).getChildren();
var n:int = children.length;
var rowData:Object = { rowHeight: 0 };
// determine max widths of columns
for (i = 0; i < n; i++) {
e = children[i];
margin = ValuesManager.valuesImpl.getValue(e, "margin");
marginLeft = ValuesManager.valuesImpl.getValue(e, "margin-left");
marginTop = ValuesManager.valuesImpl.getValue(e, "margin-top");
marginRight = ValuesManager.valuesImpl.getValue(e, "margin-right");
marginBottom = ValuesManager.valuesImpl.getValue(e, "margin-bottom");
mt = CSSUtils.getTopValue(marginTop, margin, sh);
mb = CSSUtils.getBottomValue(marginBottom, margin, sh);
mr = CSSUtils.getRightValue(marginRight, margin, sw);
ml = CSSUtils.getLeftValue(marginLeft, margin, sw);
data.push({ mt: mt, mb: mb, mr: mr, ml: ml});
var thisPrefWidth:int = 0;
if (e is IStrand)
{
var measure:IMeasurementBead = e.getBeadByType(IMeasurementBead) as IMeasurementBead;
if (measure)
thisPrefWidth = measure.measuredWidth + ml + mr;
else
thisPrefWidth = e.width + ml + mr;
}
else
thisPrefWidth = e.width + ml + mr;
rowData.rowHeight = Math.max(rowData.rowHeight, e.height + mt + mb);
columns[col] = Math.max(columns[col], thisPrefWidth);
col = col + 1;
if (col == numColumns)
{
rows.push(rowData);
rowData = {rowHeight: 0};
col = 0;
}
}
var lastmb:Number = 0;
var curx:int = 0;
var cury:int = 0;
var maxHeight:int = 0;
col = 0;
for (i = 0; i < n; i++)
{
e = children[i];
e.x = curx + ml;
e.y = cury + data[i].mt;
curx += columns[col++];
maxHeight = Math.max(maxHeight, e.y + e.height + data[i].mb);
if (col == numColumns)
{
cury += rows[0].rowHeight;
rows.shift();
col = 0;
curx = 0;
}
}
return true;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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.IContainer;
import org.apache.flex.core.IMeasurementBead;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.UIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.utils.CSSUtils;
/**
* ColumnLayout is a class that organizes the positioning of children
* of a container into a set of columns where each column's width is set to
* the maximum size of all of the children in that column.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class VerticalColumnLayout implements IBeadLayout
{
/**
* constructor
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function VerticalColumnLayout()
{
}
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 _numColumns:int;
/**
* The number of columns.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get numColumns():int
{
return _numColumns;
}
public function set numColumns(value:int):void
{
_numColumns = value;
}
private var lastWidth:Number = 0;
private var lastHeight:Number = 0;
/**
* @copy org.apache.flex.core.IBeadLayout#layout
*/
public function layout():Boolean
{
var host:UIBase = UIBase(_strand);
var sw:Number = host.width;
var sh:Number = host.height;
var hostWidth:* = ValuesManager.valuesImpl.getValue(host, "width");
var hasWidth:Boolean = (hostWidth !== undefined) && hostWidth != lastWidth;
var hostHeight:* = ValuesManager.valuesImpl.getValue(host, "height");
var hasHeight:Boolean = (hostHeight !== undefined) && hostHeight != lastHeight;
var e:IUIBase;
var i:int;
var col:int = 0;
var columns:Array = [];
var rows:Array = [];
var data:Array = [];
for (i = 0; i < numColumns; i++)
columns[i] = 0;
var marginLeft:Object;
var marginRight:Object;
var marginTop:Object;
var marginBottom:Object;
var margin:Object;
var ml:Number;
var mr:Number;
var mt:Number;
var mb:Number;
var children:Array = IContainer(_strand).getChildren();
var n:int = children.length;
var rowData:Object = { rowHeight: 0 };
// determine max widths of columns
for (i = 0; i < n; i++) {
e = children[i];
margin = ValuesManager.valuesImpl.getValue(e, "margin");
marginLeft = ValuesManager.valuesImpl.getValue(e, "margin-left");
marginTop = ValuesManager.valuesImpl.getValue(e, "margin-top");
marginRight = ValuesManager.valuesImpl.getValue(e, "margin-right");
marginBottom = ValuesManager.valuesImpl.getValue(e, "margin-bottom");
mt = CSSUtils.getTopValue(marginTop, margin, sh);
mb = CSSUtils.getBottomValue(marginBottom, margin, sh);
mr = CSSUtils.getRightValue(marginRight, margin, sw);
ml = CSSUtils.getLeftValue(marginLeft, margin, sw);
data.push({ mt: mt, mb: mb, mr: mr, ml: ml});
var thisPrefWidth:int = 0;
if (e is IStrand)
{
var measure:IMeasurementBead = e.getBeadByType(IMeasurementBead) as IMeasurementBead;
if (measure)
thisPrefWidth = measure.measuredWidth + ml + mr;
else
thisPrefWidth = e.width + ml + mr;
}
else
thisPrefWidth = e.width + ml + mr;
rowData.rowHeight = Math.max(rowData.rowHeight, e.height + mt + mb);
columns[col] = Math.max(columns[col], thisPrefWidth);
col = col + 1;
if (col == numColumns)
{
rows.push(rowData);
rowData = {rowHeight: 0};
col = 0;
}
}
var lastmb:Number = 0;
var curx:int = 0;
var cury:int = 0;
var maxHeight:int = 0;
var maxWidth:int = 0;
col = 0;
for (i = 0; i < n; i++)
{
e = children[i];
e.x = curx + ml;
e.y = cury + data[i].mt;
curx += columns[col++];
maxHeight = Math.max(maxHeight, e.y + e.height + data[i].mb);
maxWidth = Math.max(maxWidth, e.x + e.width + data[i].mr);
if (col == numColumns)
{
cury += rows[0].rowHeight;
rows.shift();
col = 0;
curx = 0;
}
}
if (!hasWidth && n > 0 && !isNaN(maxWidth) &&
(!(ValuesManager.valuesImpl.getValue(host, "left") !== undefined) &&
(ValuesManager.valuesImpl.getValue(host, "right") !== undefined)))
{
lastWidth = maxWidth;
host.setWidth(maxWidth, true);
}
if (!hasHeight && n > 0 && !isNaN(maxHeight) &&
(!(ValuesManager.valuesImpl.getValue(host, "top") !== undefined) &&
(ValuesManager.valuesImpl.getValue(host, "bottom") !== undefined)))
{
lastHeight = maxHeight;
host.setHeight(maxHeight, true);
}
return true;
}
}
}
|
set width/height if not specified
|
set width/height if not specified
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
d82a926ca16921897f1f9b289fafd7a7c55e410a
|
src/as/com/threerings/io/ObjectInputStream.as
|
src/as/com/threerings/io/ObjectInputStream.as
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2009 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.io {
import flash.errors.IOError;
import flash.errors.MemoryError;
import flash.utils.ByteArray;
import flash.utils.IDataInput;
import com.threerings.util.ClassUtil;
import com.threerings.util.Log;
import com.threerings.util.Long;
public class ObjectInputStream
{
/** Enables verbose object I/O debugging. */
public static const DEBUG :Boolean = false;
public static const log :Log = Log.getLog(ObjectInputStream);
public function ObjectInputStream (source :IDataInput = null, clientProps :Object = null)
{
_source = source || new ByteArray();
_cliProps = clientProps || {};
}
/**
* Set a new source from which to read our data.
*/
public function setSource (source :IDataInput) :void
{
_source = source;
}
/**
* Return a "client property" with the specified name.
* Actionscript only.
*/
public function getClientProperty (name :String) :*
{
return _cliProps[name];
}
/**
* Reads the next Object (or null) from the stream and returns it as * so that you may assign
* to any variable without casting. It is strongly recommended that you pass a 'checkType'
* parameter so that the type of the Object is verified to be what you believe it to be,
* thus helping you detect streaming errors as quickly as possible.
*
* @param checkType optional type to check the read object against
* @return the Object read, or null.
* @throws TypeError if the object is read successfully but is the wrong type
*/
public function readObject (checkType :Class = null) :*
//throws IOError
{
var DEBUG_ID :String = "[" + (++_debugObjectCounter) + "] ";
try {
// read in the class code for this instance
var code :int = readShort();
// a zero code indicates a null value
if (code == 0) {
if (DEBUG) log.debug(DEBUG_ID + "Read null");
return null;
}
var cmap :ClassMapping;
// if the code is negative, that means we've never seen it
// before and class metadata follows
if (code < 0) {
// first swap the code into positive land
code *= -1;
// read in the class metadata
var jname :String = readUTF();
// log.debug("read jname: " + jname);
var streamer :Streamer = Streamer.getStreamerByJavaName(jname);
if (streamer == null) {
log.warning("OMG, cannot stream " + jname);
return null;
}
if (DEBUG) log.debug(DEBUG_ID + "Got streamer (" + streamer + ")");
cmap = new ClassMapping(code, streamer);
_classMap[code] = cmap;
if (DEBUG) log.debug(DEBUG_ID + "Created mapping: (" + code + "): " + jname);
} else {
cmap = (_classMap[code] as ClassMapping);
if (null == cmap) {
throw new IOError("Read object for which we have no " +
"registered class metadata [code=" + code + "].");
}
if (DEBUG) {
log.debug(DEBUG_ID + "Read known code: (" + code + ": " +
cmap.streamer.getJavaClassName() + ")");
}
}
// log.debug("Creating object sleeve...");
var target :Object = cmap.streamer.createObject(this);
//log.debug("Reading object...");
readBareObjectImpl(target, cmap.streamer);
if (DEBUG) log.debug(DEBUG_ID + "Read object: " + target);
if (checkType != null && !(target is checkType)) {
throw new TypeError(
"Cannot convert " + ClassUtil.getClass(target) + " to " + checkType);
}
return target;
} catch (me :MemoryError) {
throw new IOError("out of memory" + me.message);
}
return null; // not reached: compiler dumb
}
public function readBareObject (obj :Object) :void
//throws IOError
{
readBareObjectImpl(obj, Streamer.getStreamer(obj));
}
public function readBareObjectImpl (obj :Object, streamer :Streamer) :void
{
_current = obj;
_streamer = streamer;
try {
_streamer.readObject(obj, this);
} finally {
// clear out our current object references
_current = null;
_streamer = null;
}
}
/**
* Called to read an Object of a known final type into a Streamable object.
*
* @param type either a String representing the java type,
* or a Class object representing the actionscript type.
*/
public function readField (type :Object) :Object
//throws IOError
{
if (!readBoolean()) {
return null;
}
var jname :String = type as String;
if (type is Class) {
jname = Translations.getToServer(ClassUtil.getClassName(type));
}
var streamer :Streamer = Streamer.getStreamerByJavaName(jname);
if (streamer == null) {
throw new Error("Cannot field stream " + type);
}
var obj :Object = streamer.createObject(this);
readBareObjectImpl(obj, streamer);
return obj;
}
public function defaultReadObject () :void
//throws IOError
{
_streamer.readObject(_current, this);
}
public function readBoolean () :Boolean
//throws IOError
{
return _source.readBoolean();
}
public function readByte () :int
//throws IOError
{
return _source.readByte();
}
/**
* Read bytes into the byte array. If length is not specified, then
* enough bytes to fill the array (from the offset) are read.
*/
public function readBytes (
bytes :ByteArray, offset :uint = 0, length :uint = uint.MAX_VALUE) :void
//throws IOError
{
// if no length specified then fill the ByteArray
if (length == uint.MAX_VALUE) {
length = bytes.length - offset;
}
// And, if we really want to read 0 bytes then just don't do anything, because an
// IDataInput will read *all available bytes* when the specified length is 0.
if (length > 0) {
_source.readBytes(bytes, offset, length);
}
}
public function readDouble () :Number
//throws IOError
{
return _source.readDouble();
}
public function readFloat () :Number
//throws IOError
{
return _source.readFloat();
}
public function readLong () :Long
{
const result :Long = new Long();
readBareObject(result);
return result;
}
public function readInt () :int
//throws IOError
{
return _source.readInt();
}
public function readShort () :int
//throws IOError
{
return _source.readShort();
}
public function readUTF () :String
//throws IOError
{
return _source.readUTF();
}
/** Named "client properties" that we can provide to deserialized objects. */
protected var _cliProps :Object;
/** The target DataInput that we route input from. */
protected var _source :IDataInput;
/** The object currently being read from the stream. */
protected var _current :Object;
/** The stramer being used currently. */
protected var _streamer :Streamer;
/** A map of short class code to ClassMapping info. */
protected var _classMap :Array = new Array();
private static var _debugObjectCounter :int = 0;
}
}
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2009 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.io {
import flash.errors.IOError;
import flash.errors.MemoryError;
import flash.utils.ByteArray;
import flash.utils.IDataInput;
import com.threerings.util.ClassUtil;
import com.threerings.util.Log;
import com.threerings.util.Long;
public class ObjectInputStream
{
/** Enables verbose object I/O debugging. */
public static const DEBUG :Boolean = false;
public static const log :Log = Log.getLog(ObjectInputStream);
public function ObjectInputStream (source :IDataInput = null, clientProps :Object = null)
{
_source = source || new ByteArray();
_cliProps = clientProps || {};
}
/**
* Set a new source from which to read our data.
*/
public function setSource (source :IDataInput) :void
{
_source = source;
}
/**
* Return a "client property" with the specified name.
* Actionscript only.
*/
public function getClientProperty (name :String) :*
{
return _cliProps[name];
}
/**
* Reads the next Object (or null) from the stream and returns it as * so that you may assign
* to any variable without casting. It is strongly recommended that you pass a 'checkType'
* parameter so that the type of the Object is verified to be what you believe it to be,
* thus helping you detect streaming errors as quickly as possible.
*
* @param checkType optional type to check the read object against
* @return the Object read, or null.
* @throws TypeError if the object is read successfully but is the wrong type
*
* @example
* <listing version="3.0">
*
* public function readObject (ins :ObjectInputStream) :void
* {
* _scoops = ins.readObject(Array);
* _coneType = ins.readObject(Cone);
* }
*
* protected var _scoops :Array;
* protected var _coneType :Cone;
* </listing>
*/
public function readObject (checkType :Class = null) :*
//throws IOError
{
var DEBUG_ID :String = "[" + (++_debugObjectCounter) + "] ";
try {
// read in the class code for this instance
var code :int = readShort();
// a zero code indicates a null value
if (code == 0) {
if (DEBUG) log.debug(DEBUG_ID + "Read null");
return null;
}
var cmap :ClassMapping;
// if the code is negative, that means we've never seen it
// before and class metadata follows
if (code < 0) {
// first swap the code into positive land
code *= -1;
// read in the class metadata
var jname :String = readUTF();
// log.debug("read jname: " + jname);
var streamer :Streamer = Streamer.getStreamerByJavaName(jname);
if (streamer == null) {
log.warning("OMG, cannot stream " + jname);
return null;
}
if (DEBUG) log.debug(DEBUG_ID + "Got streamer (" + streamer + ")");
cmap = new ClassMapping(code, streamer);
_classMap[code] = cmap;
if (DEBUG) log.debug(DEBUG_ID + "Created mapping: (" + code + "): " + jname);
} else {
cmap = (_classMap[code] as ClassMapping);
if (null == cmap) {
throw new IOError("Read object for which we have no " +
"registered class metadata [code=" + code + "].");
}
if (DEBUG) {
log.debug(DEBUG_ID + "Read known code: (" + code + ": " +
cmap.streamer.getJavaClassName() + ")");
}
}
// log.debug("Creating object sleeve...");
var target :Object = cmap.streamer.createObject(this);
//log.debug("Reading object...");
readBareObjectImpl(target, cmap.streamer);
if (DEBUG) log.debug(DEBUG_ID + "Read object: " + target);
if (checkType != null && !(target is checkType)) {
throw new TypeError(
"Cannot convert " + ClassUtil.getClass(target) + " to " + checkType);
}
return target;
} catch (me :MemoryError) {
throw new IOError("out of memory" + me.message);
}
return null; // not reached: compiler dumb
}
public function readBareObject (obj :Object) :void
//throws IOError
{
readBareObjectImpl(obj, Streamer.getStreamer(obj));
}
public function readBareObjectImpl (obj :Object, streamer :Streamer) :void
{
_current = obj;
_streamer = streamer;
try {
_streamer.readObject(obj, this);
} finally {
// clear out our current object references
_current = null;
_streamer = null;
}
}
/**
* Called to read an Object of a known final type into a Streamable object.
*
* @param type either a String representing the java type,
* or a Class object representing the actionscript type.
*/
public function readField (type :Object) :Object
//throws IOError
{
if (!readBoolean()) {
return null;
}
var jname :String = type as String;
if (type is Class) {
jname = Translations.getToServer(ClassUtil.getClassName(type));
}
var streamer :Streamer = Streamer.getStreamerByJavaName(jname);
if (streamer == null) {
throw new Error("Cannot field stream " + type);
}
var obj :Object = streamer.createObject(this);
readBareObjectImpl(obj, streamer);
return obj;
}
public function defaultReadObject () :void
//throws IOError
{
_streamer.readObject(_current, this);
}
public function readBoolean () :Boolean
//throws IOError
{
return _source.readBoolean();
}
public function readByte () :int
//throws IOError
{
return _source.readByte();
}
/**
* Read bytes into the byte array. If length is not specified, then
* enough bytes to fill the array (from the offset) are read.
*/
public function readBytes (
bytes :ByteArray, offset :uint = 0, length :uint = uint.MAX_VALUE) :void
//throws IOError
{
// if no length specified then fill the ByteArray
if (length == uint.MAX_VALUE) {
length = bytes.length - offset;
}
// And, if we really want to read 0 bytes then just don't do anything, because an
// IDataInput will read *all available bytes* when the specified length is 0.
if (length > 0) {
_source.readBytes(bytes, offset, length);
}
}
public function readDouble () :Number
//throws IOError
{
return _source.readDouble();
}
public function readFloat () :Number
//throws IOError
{
return _source.readFloat();
}
public function readLong () :Long
{
const result :Long = new Long();
readBareObject(result);
return result;
}
public function readInt () :int
//throws IOError
{
return _source.readInt();
}
public function readShort () :int
//throws IOError
{
return _source.readShort();
}
public function readUTF () :String
//throws IOError
{
return _source.readUTF();
}
/** Named "client properties" that we can provide to deserialized objects. */
protected var _cliProps :Object;
/** The target DataInput that we route input from. */
protected var _source :IDataInput;
/** The object currently being read from the stream. */
protected var _current :Object;
/** The stramer being used currently. */
protected var _streamer :Streamer;
/** A map of short class code to ClassMapping info. */
protected var _classMap :Array = new Array();
private static var _debugObjectCounter :int = 0;
}
}
|
Add an example to the docs.
|
Add an example to the docs.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5986 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
2458f34d0b845648b1425b3d34c82f71af103514
|
frameworks/as/src/org/apache/flex/html/staticControls/beads/layouts/NonVirtualVerticalScrollingLayout.as
|
frameworks/as/src/org/apache/flex/html/staticControls/beads/layouts/NonVirtualVerticalScrollingLayout.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.layouts
{
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import flash.events.IEventDispatcher;
import flash.geom.Rectangle;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IBorderModel;
import org.apache.flex.core.IScrollBarModel;
import org.apache.flex.core.IStrand;
import org.apache.flex.html.staticControls.beads.IListBead;
import org.apache.flex.html.staticControls.supportClasses.Border;
import org.apache.flex.html.staticControls.supportClasses.ScrollBar;
public class NonVirtualVerticalScrollingLayout implements IBead
{
public function NonVirtualVerticalScrollingLayout()
{
}
public var dataGroup:DisplayObjectContainer;
private var border:Border;
private var borderModel:IBorderModel
private var vScrollBar:ScrollBar;
private var listBead:IListBead;
private var _strand:IStrand;
public function set strand(value:IStrand):void
{
_strand = value;
listBead = value as IListBead;
dataGroup = listBead.dataGroup as DisplayObjectContainer;
border = listBead.border;
borderModel = border.model as IBorderModel;
IEventDispatcher(listBead.strand).addEventListener("heightChanged", changeHandler);
IEventDispatcher(listBead.strand).addEventListener("widthChanged", changeHandler);
changeHandler(null);
}
private function changeHandler(event:Event):void
{
var ww:Number = DisplayObject(listBead.strand).width;
var hh:Number = DisplayObject(listBead.strand).height;
border.width = ww;
border.height = hh;
dataGroup.width = ww - borderModel.offsets.left - borderModel.offsets.right;
dataGroup.height = hh - borderModel.offsets.top - borderModel.offsets.bottom;
dataGroup.x = borderModel.offsets.left;
dataGroup.y = borderModel.offsets.top;
var n:int = dataGroup.numChildren;
var yy:Number = 0;
for (var i:int = 0; i < n; i++)
{
var ir:DisplayObject = dataGroup.getChildAt(i);
ir.y = yy;
ir.width = dataGroup.width;
yy += ir.height;
}
if (yy > dataGroup.height)
{
vScrollBar = listBead.vScrollBar;
dataGroup.width -= vScrollBar.width;
IScrollBarModel(vScrollBar.model).maximum = yy;
IScrollBarModel(vScrollBar.model).pageSize = dataGroup.height;
IScrollBarModel(vScrollBar.model).pageStepSize = dataGroup.height;
vScrollBar.visible = true;
vScrollBar.height = dataGroup.height;
vScrollBar.y = dataGroup.y;
vScrollBar.x = dataGroup.width;
var vpos:Number = IScrollBarModel(vScrollBar.model).value;
dataGroup.scrollRect = new Rectangle(0, vpos, dataGroup.width, vpos + dataGroup.height);
vScrollBar.addEventListener("scroll", scrollHandler);
}
else if (vScrollBar)
vScrollBar.visible = false;
}
private function scrollHandler(event:Event):void
{
var vpos:Number = IScrollBarModel(vScrollBar.model).value;
dataGroup.scrollRect = new Rectangle(0, vpos, dataGroup.width, vpos + dataGroup.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.staticControls.beads.layouts
{
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import flash.events.IEventDispatcher;
import flash.geom.Rectangle;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IBorderModel;
import org.apache.flex.core.IScrollBarModel;
import org.apache.flex.core.IStrand;
import org.apache.flex.html.staticControls.beads.IListBead;
import org.apache.flex.html.staticControls.supportClasses.Border;
import org.apache.flex.html.staticControls.supportClasses.ScrollBar;
public class NonVirtualVerticalScrollingLayout implements IBead
{
public function NonVirtualVerticalScrollingLayout()
{
}
public var dataGroup:DisplayObjectContainer;
private var border:Border;
private var borderModel:IBorderModel
private var vScrollBar:ScrollBar;
private var listBead:IListBead;
private var _strand:IStrand;
public function set strand(value:IStrand):void
{
_strand = value;
listBead = value as IListBead;
dataGroup = listBead.dataGroup as DisplayObjectContainer;
border = listBead.border;
borderModel = border.model as IBorderModel;
IEventDispatcher(listBead.strand).addEventListener("heightChanged", changeHandler);
IEventDispatcher(listBead.strand).addEventListener("widthChanged", changeHandler);
changeHandler(null);
}
private function changeHandler(event:Event):void
{
var ww:Number = DisplayObject(listBead.strand).width;
var hh:Number = DisplayObject(listBead.strand).height;
border.width = ww;
border.height = hh;
dataGroup.width = ww - borderModel.offsets.left - borderModel.offsets.right;
dataGroup.height = hh - borderModel.offsets.top - borderModel.offsets.bottom;
dataGroup.x = borderModel.offsets.left;
dataGroup.y = borderModel.offsets.top;
var n:int = dataGroup.numChildren;
var yy:Number = 0;
for (var i:int = 0; i < n; i++)
{
var ir:DisplayObject = dataGroup.getChildAt(i);
ir.y = yy;
ir.width = dataGroup.width;
yy += ir.height;
}
if (yy > dataGroup.height)
{
vScrollBar = listBead.vScrollBar;
dataGroup.width -= vScrollBar.width;
IScrollBarModel(vScrollBar.model).maximum = yy;
IScrollBarModel(vScrollBar.model).pageSize = dataGroup.height;
IScrollBarModel(vScrollBar.model).pageStepSize = dataGroup.height;
vScrollBar.visible = true;
vScrollBar.height = dataGroup.height;
vScrollBar.y = dataGroup.y;
vScrollBar.x = dataGroup.width;
var vpos:Number = IScrollBarModel(vScrollBar.model).value;
dataGroup.scrollRect = new Rectangle(0, vpos, dataGroup.width, vpos + dataGroup.height);
vScrollBar.addEventListener("scroll", scrollHandler);
}
else if (vScrollBar)
{
dataGroup.scrollRect = null;
vScrollBar.visible = false;
}
}
private function scrollHandler(event:Event):void
{
var vpos:Number = IScrollBarModel(vScrollBar.model).value;
dataGroup.scrollRect = new Rectangle(0, vpos, dataGroup.width, vpos + dataGroup.height);
}
}
}
|
Remove scrollrect when scrollbar goes away
|
Remove scrollrect when scrollbar goes away
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
5b32cb68ca5aa99b05ed24b0e5c9733145825fa3
|
test/src/FRESteamWorksTest.as
|
test/src/FRESteamWorksTest.as
|
/*
* FRESteamWorks.h
* This file is part of FRESteamWorks.
*
* Created by David ´Oldes´ Oliva on 3/29/12.
* Contributors: Ventero <http://github.com/Ventero>
* Copyright (c) 2012 Amanita Design. All rights reserved.
* Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved.
*/
package
{
import com.amanitadesign.steam.FRESteamWorks;
import com.amanitadesign.steam.SteamConstants;
import com.amanitadesign.steam.SteamEvent;
import com.amanitadesign.steam.WorkshopConstants;
import flash.desktop.NativeApplication;
import flash.display.SimpleButton;
import flash.display.Sprite;
import flash.display.StageDisplayState;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.utils.ByteArray;
public class FRESteamWorksTest extends Sprite
{
public var Steamworks:FRESteamWorks = new FRESteamWorks();
public var tf:TextField;
private var _buttonPos:int = 5;
private var _appId:uint;
public function FRESteamWorksTest()
{
tf = new TextField();
tf.x = 160;
tf.width = stage.stageWidth - tf.x;
tf.height = stage.stageHeight;
addChild(tf);
addButton("Check stats/achievements", checkAchievements);
addButton("Toggle achievement", toggleAchievement);
addButton("Toggle cloud enabled", toggleCloudEnabled);
addButton("Toggle file", toggleFile);
addButton("Publish file", publishFile);
addButton("Toggle fullscreen", toggleFullscreen);
addButton("Show Friends overlay", activateOverlay);
addButton("List subscribed files", enumerateSubscribedFiles);
Steamworks.addEventListener(SteamEvent.STEAM_RESPONSE, onSteamResponse);
NativeApplication.nativeApplication.addEventListener(Event.EXITING, onExit);
try {
//Steamworks.useCrashHandler(480, "1.0", "Feb 20 2013", "21:42:20");
if(!Steamworks.init()){
log("STEAMWORKS API is NOT available");
return;
}
log("STEAMWORKS API is available\n");
log("User ID: " + Steamworks.getUserID());
_appId = Steamworks.getAppID();
log("App ID: " + _appId);
log("Persona name: " + Steamworks.getPersonaName());
log("isCloudEnabledForApp() == "+Steamworks.isCloudEnabledForApp() );
log("getFileCount() == "+Steamworks.getFileCount() );
log("fileExists('test.txt') == "+Steamworks.fileExists('test.txt') );
Steamworks.resetAllStats(true);
} catch(e:Error) {
log("*** ERROR ***");
log(e.message);
log(e.getStackTrace());
}
}
private function log(value:String):void{
tf.appendText(value+"\n");
tf.scrollV = tf.maxScrollV;
}
public function writeFileToCloud(fileName:String, data:String):Boolean {
var dataOut:ByteArray = new ByteArray();
dataOut.writeUTFBytes(data);
return Steamworks.fileWrite(fileName, dataOut);
}
public function readFileFromCloud(fileName:String):String {
var dataIn:ByteArray = new ByteArray();
var result:String;
dataIn.position = 0;
dataIn.length = Steamworks.getFileSize(fileName);
if(dataIn.length>0 && Steamworks.fileRead(fileName,dataIn)){
result = dataIn.readUTFBytes(dataIn.length);
}
return result;
}
private function checkAchievements(e:Event = null):void {
if(!Steamworks.isReady) return;
// current stats and achievement ids are from steam example app
log("isAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.isAchievement("ACH_WIN_ONE_GAME"));
log("isAchievement('ACH_TRAVEL_FAR_SINGLE') == "+Steamworks.isAchievement("ACH_TRAVEL_FAR_SINGLE"));
log("setStatFloat('FeetTraveled') == "+Steamworks.setStatFloat('FeetTraveled', 21.3));
log("setStatInt('NumGames', 2) == "+Steamworks.setStatInt('NumGames', 2));
Steamworks.storeStats();
log("getStatInt('NumGames') == "+Steamworks.getStatInt('NumGames'));
log("getStatFloat('FeetTraveled') == "+Steamworks.getStatFloat('FeetTraveled'));
}
private function toggleAchievement(e:Event = null):void{
if(!Steamworks.isReady) return;
var result:Boolean = Steamworks.isAchievement("ACH_WIN_ONE_GAME");
log("isAchievement('ACH_WIN_ONE_GAME') == " + result);
if(!result) {
log("setAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.setAchievement("ACH_WIN_ONE_GAME"));
} else {
log("clearAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.clearAchievement("ACH_WIN_ONE_GAME"));
}
}
private function toggleCloudEnabled(e:Event = null):void {
if(!Steamworks.isReady) return;
var enabled:Boolean = Steamworks.isCloudEnabledForApp();
log("isCloudEnabledForApp() == " + enabled);
log("setCloudEnabledForApp(" + !enabled + ") == " + Steamworks.setCloudEnabledForApp(!enabled));
log("isCloudEnabledForApp() == " + Steamworks.isCloudEnabledForApp());
}
private function toggleFile(e:Event = null):void {
if(!Steamworks.isReady) return;
var result:Boolean = Steamworks.fileExists('test.txt');
log("fileExists('test.txt') == " + result);
if(result){
log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') );
log("fileDelete('test.txt') == "+Steamworks.fileDelete('test.txt'));
} else {
log("writeFileToCloud('test.txt','click') == "+writeFileToCloud('test.txt','click'));
}
}
private function publishFile(e:Event = null):void {
if(!Steamworks.isReady) return;
var res:Boolean = Steamworks.publishWorkshopFile("test.txt", "", _appId,
"Test.txt", "Test.txt", WorkshopConstants.VISIBILITY_Private,
["TestTag"], WorkshopConstants.FILETYPE_Community);
log("publishWorkshopFile('test.txt' ...) == " + res);
}
private function toggleFullscreen(e:Event = null):void {
if(stage.displayState == StageDisplayState.NORMAL)
stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;
else
stage.displayState = StageDisplayState.NORMAL;
}
private function activateOverlay(e:Event = null):void {
if(!Steamworks.isReady) return;
log("isOverlayEnabled() == " + Steamworks.isOverlayEnabled());
log("activateGameOverlay('Friends') == " + Steamworks.activateGameOverlay("Friends"));
log("isOverlayEnabled() == " + Steamworks.isOverlayEnabled());
}
private function enumerateSubscribedFiles(e:Event = null):void {
if(!Steamworks.isReady) return;
log("enumerateUserSubscribedFiles(0) == " + Steamworks.enumerateUserSubscribedFiles(0));
}
private function onSteamResponse(e:SteamEvent):void{
switch(e.req_type){
case SteamConstants.RESPONSE_OnUserStatsStored:
log("RESPONSE_OnUserStatsStored: "+e.response);
break;
case SteamConstants.RESPONSE_OnUserStatsReceived:
log("RESPONSE_OnUserStatsReceived: "+e.response);
break;
case SteamConstants.RESPONSE_OnAchievementStored:
log("RESPONSE_OnAchievementStored: "+e.response);
break;
case SteamConstants.RESPONSE_OnPublishWorkshopFile:
log("RESPONSE_OnPublishWorkshopFile: " + e.response);
var file:String = Steamworks.publishWorkshopFileResult();
log("File published as " + file);
log("subscribePublishedFile(...) == " + Steamworks.subscribePublishedFile(file));
break;
case SteamConstants.RESPONSE_OnEnumerateUserSubscribedFiles:
log("RESPONSE_OnEnumerateUserSubscribedFiles: " + e.response);
var result:SubscribedFilesResult = Steamworks.enumerateUserSubscribedFilesResult();
log("User subscribed files: " + result.resultsReturned + "/" + result.totalResults);
for(var i:int = 0; i < result.resultsReturned; i++)
log(i + ": " + result.publishedFileId[i] + " (" + result.timeSubscribed[i] + ")");
break;
default:
log("STEAMresponse type:"+e.req_type+" response:"+e.response);
}
}
private function onExit(e:Event):void{
log("Exiting application, cleaning up");
Steamworks.dispose();
}
private function addButton(label:String, callback:Function):void {
var button:Sprite = new Sprite();
button.graphics.beginFill(0xaaaaaa);
button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5);
button.graphics.endFill();
button.buttonMode = true;
button.useHandCursor = true;
button.addEventListener(MouseEvent.CLICK, callback);
button.x = 5;
button.y = _buttonPos;
_buttonPos += button.height + 5;
var text:TextField = new TextField();
text.text = label;
text.width = 140;
text.height = 25;
text.x = 5;
text.y = 5;
text.mouseEnabled = false;
button.addChild(text);
addChild(button);
}
}
}
|
/*
* 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'));
log("getDLCCount() == " + Steamworks.getDLCCount());
Steamworks.resetAllStats(true);
} catch(e:Error) {
log("*** ERROR ***");
log(e.message);
log(e.getStackTrace());
}
}
private function log(value:String):void{
tf.appendText(value+"\n");
tf.scrollV = tf.maxScrollV;
}
public function writeFileToCloud(fileName:String, data:String):Boolean {
var dataOut:ByteArray = new ByteArray();
dataOut.writeUTFBytes(data);
return Steamworks.fileWrite(fileName, dataOut);
}
public function readFileFromCloud(fileName:String):String {
var dataIn:ByteArray = new ByteArray();
var result:String;
dataIn.position = 0;
dataIn.length = Steamworks.getFileSize(fileName);
if(dataIn.length>0 && Steamworks.fileRead(fileName,dataIn)){
result = dataIn.readUTFBytes(dataIn.length);
}
return result;
}
private function checkAchievements(e:Event = null):void {
if(!Steamworks.isReady) return;
// current stats and achievement ids are from steam example app
log("isAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.isAchievement("ACH_WIN_ONE_GAME"));
log("isAchievement('ACH_TRAVEL_FAR_SINGLE') == "+Steamworks.isAchievement("ACH_TRAVEL_FAR_SINGLE"));
log("setStatFloat('FeetTraveled') == "+Steamworks.setStatFloat('FeetTraveled', 21.3));
log("setStatInt('NumGames', 2) == "+Steamworks.setStatInt('NumGames', 2));
Steamworks.storeStats();
log("getStatInt('NumGames') == "+Steamworks.getStatInt('NumGames'));
log("getStatFloat('FeetTraveled') == "+Steamworks.getStatFloat('FeetTraveled'));
}
private function toggleAchievement(e:Event = null):void{
if(!Steamworks.isReady) return;
var result:Boolean = Steamworks.isAchievement("ACH_WIN_ONE_GAME");
log("isAchievement('ACH_WIN_ONE_GAME') == " + result);
if(!result) {
log("setAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.setAchievement("ACH_WIN_ONE_GAME"));
} else {
log("clearAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.clearAchievement("ACH_WIN_ONE_GAME"));
}
}
private function toggleCloudEnabled(e:Event = null):void {
if(!Steamworks.isReady) return;
var enabled:Boolean = Steamworks.isCloudEnabledForApp();
log("isCloudEnabledForApp() == " + enabled);
log("setCloudEnabledForApp(" + !enabled + ") == " + Steamworks.setCloudEnabledForApp(!enabled));
log("isCloudEnabledForApp() == " + Steamworks.isCloudEnabledForApp());
}
private function toggleFile(e:Event = null):void {
if(!Steamworks.isReady) return;
var result:Boolean = Steamworks.fileExists('test.txt');
log("fileExists('test.txt') == " + result);
if(result){
log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') );
log("fileDelete('test.txt') == "+Steamworks.fileDelete('test.txt'));
} else {
log("writeFileToCloud('test.txt','click') == "+writeFileToCloud('test.txt','click'));
}
}
private function publishFile(e:Event = null):void {
if(!Steamworks.isReady) return;
var res:Boolean = Steamworks.publishWorkshopFile("test.txt", "", _appId,
"Test.txt", "Test.txt", WorkshopConstants.VISIBILITY_Private,
["TestTag"], WorkshopConstants.FILETYPE_Community);
log("publishWorkshopFile('test.txt' ...) == " + res);
}
private function toggleFullscreen(e:Event = null):void {
if(stage.displayState == StageDisplayState.NORMAL)
stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;
else
stage.displayState = StageDisplayState.NORMAL;
}
private function activateOverlay(e:Event = null):void {
if(!Steamworks.isReady) return;
log("isOverlayEnabled() == " + Steamworks.isOverlayEnabled());
log("activateGameOverlay('Friends') == " + Steamworks.activateGameOverlay("Friends"));
log("isOverlayEnabled() == " + Steamworks.isOverlayEnabled());
}
private function enumerateSubscribedFiles(e:Event = null):void {
if(!Steamworks.isReady) return;
log("enumerateUserSubscribedFiles(0) == " + Steamworks.enumerateUserSubscribedFiles(0));
}
private function onSteamResponse(e:SteamEvent):void{
switch(e.req_type){
case SteamConstants.RESPONSE_OnUserStatsStored:
log("RESPONSE_OnUserStatsStored: "+e.response);
break;
case SteamConstants.RESPONSE_OnUserStatsReceived:
log("RESPONSE_OnUserStatsReceived: "+e.response);
break;
case SteamConstants.RESPONSE_OnAchievementStored:
log("RESPONSE_OnAchievementStored: "+e.response);
break;
case SteamConstants.RESPONSE_OnPublishWorkshopFile:
log("RESPONSE_OnPublishWorkshopFile: " + e.response);
var file:String = Steamworks.publishWorkshopFileResult();
log("File published as " + file);
log("subscribePublishedFile(...) == " + Steamworks.subscribePublishedFile(file));
break;
case SteamConstants.RESPONSE_OnEnumerateUserSubscribedFiles:
log("RESPONSE_OnEnumerateUserSubscribedFiles: " + e.response);
var result:SubscribedFilesResult = Steamworks.enumerateUserSubscribedFilesResult();
log("User subscribed files: " + result.resultsReturned + "/" + result.totalResults);
for(var i:int = 0; i < result.resultsReturned; i++)
log(i + ": " + result.publishedFileId[i] + " (" + result.timeSubscribed[i] + ")");
break;
default:
log("STEAMresponse type:"+e.req_type+" response:"+e.response);
}
}
private function onExit(e:Event):void{
log("Exiting application, cleaning up");
Steamworks.dispose();
}
private function addButton(label:String, callback:Function):void {
var button:Sprite = new Sprite();
button.graphics.beginFill(0xaaaaaa);
button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5);
button.graphics.endFill();
button.buttonMode = true;
button.useHandCursor = true;
button.addEventListener(MouseEvent.CLICK, callback);
button.x = 5;
button.y = _buttonPos;
_buttonPos += button.height + 5;
var text:TextField = new TextField();
text.text = label;
text.width = 140;
text.height = 25;
text.x = 5;
text.y = 5;
text.mouseEnabled = false;
button.addChild(text);
addChild(button);
}
}
}
|
Add test for getDLCCount
|
Add test for getDLCCount
|
ActionScript
|
bsd-2-clause
|
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
|
a31fa4d980ccda0cd18497667afdc1f30cec5b44
|
DroneAnarchy/Resources/Scripts/DroneAnarchy.as
|
DroneAnarchy/Resources/Scripts/DroneAnarchy.as
|
#include "LevelManager.as"
LevelManager@ levelManager_;
Scene@ scene_;
bool onQuit_ = false;
void Start()
{
SetWindowTitleAndIcon();
CreateDebugHud();
SubscribeToEvents();
CreateLevel();
}
void CreateDebugHud()
{
// Get default style
XMLFile@ xmlFile = cache.GetResource("XMLFile", "UI/DefaultStyle.xml");
if (xmlFile is null)
return;
// Create debug HUD
DebugHud@ debugHud = engine.CreateDebugHud();
debugHud.defaultStyle = xmlFile;
}
void SetWindowTitleAndIcon()
{
graphics.windowIcon = cache.GetResource("Image","Resources/Textures/drone_anarchy_icon.png");
graphics.windowTitle = "Drone Anarchy";
}
void CreateLevel()
{
XMLFile@ file = cache.GetResource("XMLFile", "Resources/Objects/Scene.xml");
scene_ = Scene();
scene_.LoadXML(file.root);
@levelManager_ = cast<LevelManager>(scene_.CreateScriptObject(scriptFile, "LevelOneManager"));
levelManager_.InitialiseAndActivate();
}
void SubscribeToEvents()
{
SubscribeToEvent("KeyDown","HandleKeyDown");
SubscribeToEvent("Update", "HandleUpdate");
SubscribeToEvent("MouseMove", "HandleMouseMove");
SubscribeToEvent("MouseButtonDown", "HandleMouseClick");
SubscribeToEvent("SoundFinished", "HandleSoundFinished");
}
void HandleKeyDown(StringHash eventType, VariantMap& eventData)
{
int key = eventData["key"].GetInt();
if(key == KEY_ESC)
onQuit_ = true;
else if(key == KEY_F2)
debugHud.ToggleAll();
else
{
eventData["ID"] = EVT_KEYDOWN;
levelManager_.HandleLevelEvent(eventData);
}
}
void HandleUpdate(StringHash eventType, VariantMap& eventData)
{
if(onQuit_)
{
engine.Exit();
}
else
{
eventData["ID"] = EVT_UPDATE;
levelManager_.HandleLevelEvent(eventData);
}
}
void HandleMouseMove(StringHash eventType, VariantMap& eventData)
{
eventData["ID"] = EVT_MOUSEMOVE;
levelManager_.HandleLevelEvent(eventData);
}
void HandleMouseClick(StringHash eventType, VariantMap& eventData)
{
eventData["ID"] = EVT_MOUSECLICK;
levelManager_.HandleLevelEvent(eventData);
}
void HandleSoundFinished(StringHash eventType, VariantMap& eventData)
{
eventData["ID"] = EVT_SOUNDFINISH;
levelManager_.HandleLevelEvent(eventData);
}
|
#include "LevelManager.as"
LevelManager@ levelManager_;
Scene@ scene_;
bool onQuit_ = false;
void Start()
{
SetWindowTitleAndIcon();
CreateDebugHud();
SubscribeToEvents();
CreateLevel();
}
void CreateDebugHud()
{
// Get default style
XMLFile@ xmlFile = cache.GetResource("XMLFile", "UI/DefaultStyle.xml");
if (xmlFile is null)
return;
// Create debug HUD
DebugHud@ debugHud = engine.CreateDebugHud();
debugHud.defaultStyle = xmlFile;
}
void SetWindowTitleAndIcon()
{
graphics.windowIcon = cache.GetResource("Image","Resources/Textures/drone_anarchy_icon.png");
graphics.windowTitle = "Drone Anarchy";
}
void CreateLevel()
{
XMLFile@ file = cache.GetResource("XMLFile", "Resources/Objects/Scene.xml");
scene_ = Scene();
scene_.LoadXML(file.root);
@levelManager_ = cast<LevelManager>(scene_.CreateScriptObject(scriptFile, "LevelOneManager"));
levelManager_.InitialiseAndActivate();
}
void SubscribeToEvents()
{
SubscribeToEvent("KeyDown","HandleKeyDown");
SubscribeToEvent("Update", "HandleUpdate");
SubscribeToEvent("MouseMove", "HandleMouseMove");
SubscribeToEvent("MouseButtonDown", "HandleMouseClick");
SubscribeToEvent("SoundFinished", "HandleSoundFinished");
}
void HandleKeyDown(StringHash eventType, VariantMap& eventData)
{
int key = eventData["key"].GetInt();
if(key == KEY_ESC)
onQuit_ = true;
else if(key == KEY_F2)
debugHud.ToggleAll();
else
{
eventData["ID"] = EVT_KEYDOWN;
levelManager_.HandleLevelEvent(eventData);
}
}
void HandleUpdate(StringHash eventType, VariantMap& eventData)
{
if(onQuit_)
{
engine.Exit();
}
else
{
eventData["ID"] = EVT_UPDATE;
levelManager_.HandleLevelEvent(eventData);
}
}
void HandleMouseMove(StringHash eventType, VariantMap& eventData)
{
eventData["ID"] = EVT_MOUSEMOVE;
levelManager_.HandleLevelEvent(eventData);
}
void HandleMouseClick(StringHash eventType, VariantMap& eventData)
{
eventData["ID"] = EVT_MOUSECLICK;
levelManager_.HandleLevelEvent(eventData);
}
void HandleSoundFinished(StringHash eventType, VariantMap& eventData)
{
eventData["ID"] = EVT_SOUNDFINISH;
levelManager_.HandleLevelEvent(eventData);
}
|
Trim space
|
Trim space
|
ActionScript
|
mit
|
DARKDOVE/Drone_Anarchy
|
393132517b439b055bce59be300b2b44fd41b047
|
src/ageofai/map/astar/AStar.as
|
src/ageofai/map/astar/AStar.as
|
package ageofai.map.astar {
import ageofai.map.geom.IntPoint;
import flash.utils.Dictionary;
public class AStar {
private var width:int;
private var height:int;
private var start:AStarNode;
private var goal:AStarNode;
private var map:Vector.<Vector.<AStarNode>>;
public var open:Vector.<AStarNode>;
public var closed:Vector.<AStarNode>;
private var dist:Function = distEuclidian;
//private var dist:Function = distManhattan;
private static const COST_ORTHOGONAL:Number = 1;
private static const COST_DIAGONAL:Number = 1.35;
public static var cachedMaps:Dictionary;
function AStar(map:IAStarSearchable, start:IntPoint, goal:IntPoint) {
width = map.getWidth();
height = map.getHeight();
this.start = new AStarNode(start.x, start.y);
this.goal = new AStarNode(goal.x, goal.y);
if (cachedMaps == null) {
cachedMaps = new Dictionary(true);
}
this.map = cachedMaps[map];
if (this.map == null) {
this.map = createMap(map);
cachedMaps[map] = this.map;
} else {
cleanMap(this.map);
}
}
public function solve():Vector.<IntPoint> {
var i:int, mneighbors:Vector.<AStarNode>, neighborCount:int;
open = new Vector.<AStarNode>();
closed = new Vector.<AStarNode>();
var node:AStarNode = start;
node.h = dist(goal);
open[open.length] = node;
var solved:Boolean = false;
if (!goal.equals(start) && !map[goal.x - 1][goal.y].walkable && !map[goal.x - 1][goal.y - 1].walkable &&
!map[goal.x][goal.y - 1].walkable && !map[goal.x + 1][goal.y - 1].walkable &&
!map[goal.x + 1][goal.y].walkable && !map[goal.x + 1][goal.y + 1].walkable &&
!map[goal.x][goal.y + 1].walkable && !map[goal.x - 1][goal.y + 1].walkable) {
return null;
}
while (!solved) {
open.sort(sortVector);
if (open.length <= 0) break;
node = open.shift();
closed[closed.length] = node;
if (node.x == goal.x && node.y == goal.y) {
solved = true;
break;
}
mneighbors = neighbors(node);
neighborCount = mneighbors.length;
for (i = 0; i < neighborCount; i++) {
var n:AStarNode = mneighbors[i];
if (open.indexOf(n) == -1 && closed.indexOf(n) == -1) {
open[open.length] = n;
n.parent = node;
n.h = dist(n);
// n.g = node.g;
} else {
var f:Number = n.g + node.g + n.h;
// trace(n.x, n.y, n.g, n.h, node.g);
if (f < n.f) {
n.parent = node;
n.g = node.g;
}
}
}
}
if (solved) {
i = 0;
var solution:Vector.<IntPoint> = new Vector.<IntPoint>();
solution[0] = new IntPoint(node.x, node.y);
while (node.parent && node.parent != start) {
node = node.parent;
solution[++i] = new IntPoint(node.x, node.y);
}
// solution[++i] = new UIntPoint(node.x, node.y);
solution[++i] = new IntPoint(start.x, start.y);;
return solution;
} else {
return null;
}
}
private function sortVector(x:AStarNode, y:AStarNode):int {
return (x.f >= y.f) ? 1 : -1;
}
private function distManhattan(n1:AStarNode, n2:AStarNode=null):Number {
if (n2 == null) n2 = goal;
return Math.abs(n1.x-n2.x)+Math.abs(n1.y-n2.y);
}
private function distEuclidian(n1:AStarNode, n2:AStarNode=null):Number {
if (n2 == null) n2 = goal;
return Math.sqrt(Math.pow((n1.x - n2.x), 2) + Math.pow((n1.y - n2.y), 2));
}
private function neighbors(node:AStarNode):Vector.<AStarNode> {
var x:int = node.x, y:int = node.y, i:int = -1;
var n:AStarNode;
var a:Vector.<AStarNode> = new Vector.<AStarNode>();
// N
if (x > 0) {
n = map[x-1][y];
if (n.walkable) {
n.g += COST_ORTHOGONAL;
a[++i] = n;
}
}
// E
if (x < width-1) {
n = map[x+1][y];
if (n.walkable) {
n.g += COST_ORTHOGONAL;
a[++i] = n;
}
}
// N
if (y > 0) {
n = map[x][y-1];
if (n.walkable) {
n.g += COST_ORTHOGONAL;
a[++i] = n;
}
}
// S
if (y < height-1) {
n = map[x][y+1];
if (n.walkable) {
n.g += COST_ORTHOGONAL;
a[++i] = n;
}
}
// NW
if (x > 0 && y > 0) {
n = map[x-1][y-1];
if (n.walkable && map[x-1][y].walkable && map[x][y-1].walkable) {
n.g += COST_DIAGONAL;
a[++i] = n;
}
}
// NE
if (x < width-1 && y > 0) {
n = map[x+1][y-1];
if (n.walkable && map[x+1][y].walkable && map[x][y-1].walkable) {
n.g += COST_DIAGONAL;
a[++i] = n;
}
}
// SW
if (x > 0 && y < height-1) {
n = map[x-1][y+1];
if (n.walkable && map[x-1][y].walkable && map[x][y+1].walkable) {
n.g += COST_DIAGONAL;
a[++i] = n;
}
}
// SE
if (x < width-1 && y < height-1) {
n = map[x+1][y+1];
if (n.walkable && map[x+1][y].walkable && map[x][y+1].walkable) {
n.g += COST_DIAGONAL;
a[++i] = n;
}
}
return a;
}
private function cleanMap(map:Vector.<Vector.<AStarNode>>):void {
for (var x:int = 0; x < width; x++) {
for (var y:int = 0; y < height; y++) {
var node:AStarNode = map[x][y];
node.g = 0;
node.h = 0;
node.parent = null;
}
}
}
private function createMap(map:IAStarSearchable):Vector.<Vector.<AStarNode>> {
var a:Vector.<Vector.<AStarNode>> = new Vector.<Vector.<AStarNode>>(width);
for (var x:int = 0; x < width; x++) {
a[x] = new Vector.<AStarNode>(height);
for (var y:int = 0; y < height; y++) {
var node:AStarNode = new AStarNode(x, y, map.isWalkable(x, y));
a[x][y] = node;
}
}
return a;
}
}
}
|
package ageofai.map.astar {
import ageofai.map.geom.IntPoint;
import flash.utils.Dictionary;
public class AStar {
private var width:int;
private var height:int;
private var start:AStarNode;
private var goal:AStarNode;
private var map:Vector.<Vector.<AStarNode>>;
public var open:Vector.<AStarNode>;
public var closed:Vector.<AStarNode>;
private var dist:Function = distEuclidian;
//private var dist:Function = distManhattan;
private static const COST_ORTHOGONAL:Number = 1;
private static const COST_DIAGONAL:Number = 1.35;
public static var cachedMaps:Dictionary;
function AStar(map:IAStarSearchable, start:IntPoint, goal:IntPoint) {
width = map.getWidth();
height = map.getHeight();
this.start = new AStarNode(start.x, start.y);
this.goal = new AStarNode(goal.x, goal.y);
if (cachedMaps == null) {
cachedMaps = new Dictionary(true);
}
this.map = cachedMaps[map];
if (this.map == null) {
this.map = createMap(map);
cachedMaps[map] = this.map;
} else {
cleanMap(this.map);
}
}
public function solve():Vector.<IntPoint> {
var i:int, mneighbors:Vector.<AStarNode>, neighborCount:int;
open = new Vector.<AStarNode>();
closed = new Vector.<AStarNode>();
var node:AStarNode = start;
node.h = dist(goal);
open[open.length] = node;
var solved:Boolean = false;
if (!goal.equals(start)) {
var accessible:Boolean;
for (i = goal.x - 1; i != goal.x + 1; i++)
{
for (var j:int = goal.y - 1; j != goal.y + 1; j++)
{
if (i == goal.x && j == goal.y) continue;
if (i >= 0 && j >= 0 && i < this.width && j < this.height && this.map[i][j].walkable)
{
accessible = true;
break;
}
}
if (accessible) break;
}
if (!accessible) return null;
}
while (!solved) {
open.sort(sortVector);
if (open.length <= 0) break;
node = open.shift();
closed[closed.length] = node;
if (node.x == goal.x && node.y == goal.y) {
solved = true;
break;
}
mneighbors = neighbors(node);
neighborCount = mneighbors.length;
for (i = 0; i < neighborCount; i++) {
var n:AStarNode = mneighbors[i];
if (open.indexOf(n) == -1 && closed.indexOf(n) == -1) {
open[open.length] = n;
n.parent = node;
n.h = dist(n);
// n.g = node.g;
} else {
var f:Number = n.g + node.g + n.h;
// trace(n.x, n.y, n.g, n.h, node.g);
if (f < n.f) {
n.parent = node;
n.g = node.g;
}
}
}
}
if (solved) {
i = 0;
var solution:Vector.<IntPoint> = new Vector.<IntPoint>();
solution[0] = new IntPoint(node.x, node.y);
while (node.parent && node.parent != start) {
node = node.parent;
solution[++i] = new IntPoint(node.x, node.y);
}
// solution[++i] = new UIntPoint(node.x, node.y);
solution[++i] = new IntPoint(start.x, start.y);;
return solution;
} else {
return null;
}
}
private function sortVector(x:AStarNode, y:AStarNode):int {
return (x.f >= y.f) ? 1 : -1;
}
private function distManhattan(n1:AStarNode, n2:AStarNode=null):Number {
if (n2 == null) n2 = goal;
return Math.abs(n1.x-n2.x)+Math.abs(n1.y-n2.y);
}
private function distEuclidian(n1:AStarNode, n2:AStarNode=null):Number {
if (n2 == null) n2 = goal;
return Math.sqrt(Math.pow((n1.x - n2.x), 2) + Math.pow((n1.y - n2.y), 2));
}
private function neighbors(node:AStarNode):Vector.<AStarNode> {
var x:int = node.x, y:int = node.y, i:int = -1;
var n:AStarNode;
var a:Vector.<AStarNode> = new Vector.<AStarNode>();
// N
if (x > 0) {
n = map[x-1][y];
if (n.walkable) {
n.g += COST_ORTHOGONAL;
a[++i] = n;
}
}
// E
if (x < width-1) {
n = map[x+1][y];
if (n.walkable) {
n.g += COST_ORTHOGONAL;
a[++i] = n;
}
}
// N
if (y > 0) {
n = map[x][y-1];
if (n.walkable) {
n.g += COST_ORTHOGONAL;
a[++i] = n;
}
}
// S
if (y < height-1) {
n = map[x][y+1];
if (n.walkable) {
n.g += COST_ORTHOGONAL;
a[++i] = n;
}
}
// NW
if (x > 0 && y > 0) {
n = map[x-1][y-1];
if (n.walkable && map[x-1][y].walkable && map[x][y-1].walkable) {
n.g += COST_DIAGONAL;
a[++i] = n;
}
}
// NE
if (x < width-1 && y > 0) {
n = map[x+1][y-1];
if (n.walkable && map[x+1][y].walkable && map[x][y-1].walkable) {
n.g += COST_DIAGONAL;
a[++i] = n;
}
}
// SW
if (x > 0 && y < height-1) {
n = map[x-1][y+1];
if (n.walkable && map[x-1][y].walkable && map[x][y+1].walkable) {
n.g += COST_DIAGONAL;
a[++i] = n;
}
}
// SE
if (x < width-1 && y < height-1) {
n = map[x+1][y+1];
if (n.walkable && map[x+1][y].walkable && map[x][y+1].walkable) {
n.g += COST_DIAGONAL;
a[++i] = n;
}
}
return a;
}
private function cleanMap(map:Vector.<Vector.<AStarNode>>):void {
for (var x:int = 0; x < width; x++) {
for (var y:int = 0; y < height; y++) {
var node:AStarNode = map[x][y];
node.g = 0;
node.h = 0;
node.parent = null;
}
}
}
private function createMap(map:IAStarSearchable):Vector.<Vector.<AStarNode>> {
var a:Vector.<Vector.<AStarNode>> = new Vector.<Vector.<AStarNode>>(width);
for (var x:int = 0; x < width; x++) {
a[x] = new Vector.<AStarNode>(height);
for (var y:int = 0; y < height; y++) {
var node:AStarNode = new AStarNode(x, y, map.isWalkable(x, y));
a[x][y] = node;
}
}
return a;
}
}
}
|
Fix astar bug
|
Fix astar bug
|
ActionScript
|
apache-2.0
|
goc-flashplusplus/ageofai
|
d98225cde7c46a2745a3cd0e7e46e7042ac61307
|
WeaveJS/src/weavejs/util/WeavePromise.as
|
WeaveJS/src/weavejs/util/WeavePromise.as
|
/* ***** BEGIN LICENSE BLOCK *****
*
* This file is part of Weave.
*
* The Initial Developer of Weave is the Institute for Visualization
* and Perception Research at the University of Massachusetts Lowell.
* Portions created by the Initial Developer are Copyright (C) 2008-2015
* the Initial Developer. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* ***** END LICENSE BLOCK ***** */
package weavejs.util
{
import weavejs.WeaveAPI;
import weavejs.api.core.IDisposableObject;
import weavejs.api.core.ILinkableObject;
/**
* Use this when you need a Promise chain to depend on ILinkableObjects and resolve multiple times.
*
* Adds support for <code>depend(...linkableObjects)</code>
*/
public class WeavePromise implements IDisposableObject
{
/**
* @param relevantContext This parameter may be null. If the relevantContext object is disposed, the promise will be disabled.
* @param resolver A function like function(resolve:Function, reject:Function):void which carries out the promise.
* If no resolver is given, setResult() or setError() should be called externally.
*/
public function WeavePromise(relevantContext:Object, resolver:Function = null)
{
if (relevantContext is WeavePromise)
{
// this is a child promise
this.rootPromise = (relevantContext as WeavePromise).rootPromise;
this.relevantContext = relevantContext = this.rootPromise.relevantContext;
}
else
{
// this is a new root promise
this.rootPromise = this;
this.relevantContext = relevantContext;
}
if (relevantContext)
Weave.disposableChild(relevantContext, this);
if (resolver != null)
{
setBusy(true);
resolver(this.setResult, this.setError);
}
}
private static function noop(value:Object):Object { return value; }
private var rootPromise:WeavePromise;
protected var relevantContext:Object;
private var result:* = undefined;
private var error:* = undefined;
private var handlers:Array = []; // array of Handler objects
private var dependencies:Array = [];
/**
* @return This WeavePromise
*/
public function setResult(result:Object):WeavePromise
{
if (Weave.wasDisposed(relevantContext))
{
setBusy(false);
return this;
}
this.result = undefined;
this.error = undefined;
if (result is JS.Promise)
{
result.then(setResult, setError);
}
else if (result is WeavePromise)
{
(result as WeavePromise).then(setResult, setError);
}
else
{
this.result = result as Object;
callHandlers();
}
return this;
}
public function getResult():Object
{
return result;
}
/**
* @return This WeavePromise
*/
public function setError(error:Object):WeavePromise
{
if (Weave.wasDisposed(relevantContext))
{
setBusy(false);
return this;
}
this.result = undefined;
this.error = error;
callHandlers();
return this;
}
public function getError():Object
{
return error;
}
private function setBusy(busy:Boolean):void
{
if (busy)
{
WeaveAPI.ProgressIndicator.addTask(rootPromise, relevantContext as ILinkableObject);
}
else
{
WeaveAPI.ProgressIndicator.removeTask(rootPromise);
}
}
private function callHandlers(newHandlersOnly:Boolean = false):void
{
if (dependencies.some(Weave.isBusy))
{
if (handlers.length)
setBusy(true);
return;
}
// if there are no more handlers, remove the task
if (handlers.length == 0)
setBusy(false);
if (Weave.wasDisposed(relevantContext))
{
setBusy(false);
return;
}
for (var i:int = 0; i < handlers.length; i++)
{
var handler:WeavePromiseHandler = handlers[i];
if (newHandlersOnly && handler.wasCalled)
continue;
if (result !== undefined)
handler.onResult(result);
else if (error !== undefined)
handler.onError(error);
}
}
public function then(onFulfilled:Function = null, onRejected:Function = null):WeavePromise
{
if (onFulfilled == null)
onFulfilled = noop;
if (onRejected == null)
onRejected = noop;
var next:WeavePromise = new WeavePromise(this);
next.result = undefined;
handlers.push(new WeavePromiseHandler(onFulfilled, onRejected, next));
if (result !== undefined || error !== undefined)
{
// callLater will not call the function if the context was disposed
WeaveAPI.Scheduler.callLater(relevantContext, callHandlers, [true]);
setBusy(true);
}
return next;
}
public function depend(...linkableObjects):WeavePromise
{
if (linkableObjects.length)
{
setBusy(true);
}
for each (var dependency:ILinkableObject in linkableObjects)
{
Weave.getCallbacks(dependency).addGroupedCallback(relevantContext, callHandlers, true);
}
return this;
}
public function getPromise():Object
{
var var_resolve:Function, var_reject:Function;
var promise:Object = new JS.Promise(function(resolve:Function, reject:Function):void {
var_resolve = resolve;
var_reject = reject;
});
then(var_resolve, var_reject);
return promise;
}
public function dispose():void
{
handlers.length = 0;
setBusy(false);
}
}
}
|
/* ***** BEGIN LICENSE BLOCK *****
*
* This file is part of Weave.
*
* The Initial Developer of Weave is the Institute for Visualization
* and Perception Research at the University of Massachusetts Lowell.
* Portions created by the Initial Developer are Copyright (C) 2008-2015
* the Initial Developer. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* ***** END LICENSE BLOCK ***** */
package weavejs.util
{
import weavejs.WeaveAPI;
import weavejs.api.core.IDisposableObject;
import weavejs.api.core.ILinkableObject;
/**
* Use this when you need a Promise chain to depend on ILinkableObjects and resolve multiple times.
*
* Adds support for <code>depend(...linkableObjects)</code>
*/
public class WeavePromise implements IDisposableObject
{
/**
* @param relevantContext This parameter may be null. If the relevantContext object is disposed, the promise will be disabled.
* @param resolver A function like function(resolve:Function, reject:Function):void which carries out the promise.
* If no resolver is given, setResult() or setError() should be called externally.
*/
public function WeavePromise(relevantContext:Object, resolver:Function = null)
{
if (relevantContext is WeavePromise)
{
// this is a child promise
this.rootPromise = (relevantContext as WeavePromise).rootPromise;
this.relevantContext = relevantContext = this.rootPromise.relevantContext;
}
else
{
// this is a new root promise
this.rootPromise = this;
this.relevantContext = relevantContext;
}
if (relevantContext)
Weave.disposableChild(relevantContext, this);
if (resolver != null)
{
setBusy(true);
resolver(this.setResult, this.setError);
}
}
private static function noop(value:Object):Object { return value; }
private var rootPromise:WeavePromise;
protected var relevantContext:Object;
private var result:* = undefined;
private var error:* = undefined;
private var handlers:Array = []; // array of Handler objects
private var dependencies:Array = [];
/**
* @return This WeavePromise
*/
public function setResult(result:Object):WeavePromise
{
if (Weave.wasDisposed(relevantContext))
{
setBusy(false);
return this;
}
this.result = undefined;
this.error = undefined;
if (result is JS.Promise)
{
result.then(setResult, setError);
}
else if (result is WeavePromise)
{
(result as WeavePromise).then(setResult, setError);
}
else
{
this.result = result as Object;
callHandlers();
}
return this;
}
public function getResult():Object
{
return result;
}
/**
* @return This WeavePromise
*/
public function setError(error:Object):WeavePromise
{
if (Weave.wasDisposed(relevantContext))
{
setBusy(false);
return this;
}
this.result = undefined;
this.error = error as Object;
callHandlers();
return this;
}
public function getError():Object
{
return error;
}
private function setBusy(busy:Boolean):void
{
if (busy)
{
WeaveAPI.ProgressIndicator.addTask(rootPromise, relevantContext as ILinkableObject);
}
else
{
WeaveAPI.ProgressIndicator.removeTask(rootPromise);
}
}
private function callHandlers(newHandlersOnly:Boolean = false):void
{
if (dependencies.some(Weave.isBusy))
{
if (handlers.length)
setBusy(true);
return;
}
// if there are no more handlers, remove the task
if (handlers.length == 0)
setBusy(false);
if (Weave.wasDisposed(relevantContext))
{
setBusy(false);
return;
}
for (var i:int = 0; i < handlers.length; i++)
{
var handler:WeavePromiseHandler = handlers[i];
if (newHandlersOnly && handler.wasCalled)
continue;
if (result !== undefined)
handler.onResult(result);
else if (error !== undefined)
handler.onError(error);
}
}
public function then(onFulfilled:Function = null, onRejected:Function = null):WeavePromise
{
if (onFulfilled == null)
onFulfilled = noop;
if (onRejected == null)
onRejected = noop;
var next:WeavePromise = new WeavePromise(this);
next.result = undefined;
handlers.push(new WeavePromiseHandler(onFulfilled, onRejected, next));
if (result !== undefined || error !== undefined)
{
// callLater will not call the function if the context was disposed
WeaveAPI.Scheduler.callLater(relevantContext, callHandlers, [true]);
setBusy(true);
}
return next;
}
public function depend(...linkableObjects):WeavePromise
{
if (linkableObjects.length)
{
setBusy(true);
}
for each (var dependency:ILinkableObject in linkableObjects)
{
Weave.getCallbacks(dependency).addGroupedCallback(relevantContext, callHandlers, true);
}
return this;
}
public function getPromise():Object
{
var var_resolve:Function, var_reject:Function;
var promise:Object = new JS.Promise(function(resolve:Function, reject:Function):void {
var_resolve = resolve;
var_reject = reject;
});
then(var_resolve, var_reject);
return promise;
}
public function dispose():void
{
handlers.length = 0;
setBusy(false);
}
}
}
|
add explicit cast in place of lost implicit cast
|
add explicit cast in place of lost implicit cast
|
ActionScript
|
mpl-2.0
|
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
|
1af47d96e061ab7bffc8d02f7efedee20a90b7e1
|
src/aerys/minko/scene/node/Scene.as
|
src/aerys/minko/scene/node/Scene.as
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.Effect;
import aerys.minko.render.Viewport;
import aerys.minko.scene.controller.scene.RenderingController;
import aerys.minko.scene.node.camera.AbstractCamera;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.loader.AssetsLibrary;
import flash.display.BitmapData;
import flash.utils.Dictionary;
import flash.utils.getTimer;
/**
* Scene objects are the root of any 3D scene.
*
* @author Jean-Marc Le Roux
*
*/
public final class Scene extends Group
{
use namespace minko_scene;
minko_scene var _camera : AbstractCamera;
private var _renderingCtrl : RenderingController;
private var _properties : DataProvider;
private var _bindings : DataBindings;
private var _numTriangles : uint;
private var _enterFrame : Signal;
private var _renderingBegin : Signal;
private var _renderingEnd : Signal;
private var _exitFrame : Signal;
private var _assets : AssetsLibrary;
public function get assets() : AssetsLibrary
{
return _assets;
}
public function get activeCamera() : AbstractCamera
{
return _camera;
}
public function get numPasses() : uint
{
return _renderingCtrl.numPasses;
}
public function get numEnabledPasses() : uint
{
return _renderingCtrl.numEnabledPasses;
}
public function get numTriangles() : uint
{
return _numTriangles;
}
public function get postProcessingEffect() : Effect
{
return _renderingCtrl.postProcessingEffect;
}
public function set postProcessingEffect(value : Effect) : void
{
_renderingCtrl.postProcessingEffect = value;
}
public function get postProcessingProperties() : DataProvider
{
return _renderingCtrl.postProcessingProperties;
}
public function get properties() : DataProvider
{
return _properties;
}
public function set properties(value : DataProvider) : void
{
if (_properties != value)
{
if (_properties)
_bindings.removeProvider(_properties);
_properties = value;
if (value)
_bindings.addProvider(value);
}
}
public function get bindings() : DataBindings
{
return _bindings;
}
/**
* The signal executed when the viewport is about to start rendering a frame.
* Callback functions for this signal should accept the following arguments:
* <ul>
* <li>viewport : Viewport, the viewport who starts rendering the frame</li>
* </ul>
* @return
*
*/
public function get enterFrame() : Signal
{
return _enterFrame;
}
/**
* The signal executed when the viewport is done rendering a frame.
* Callback functions for this signal should accept the following arguments:
* <ul>
* <li>viewport : Viewport, the viewport who just finished rendering the frame</li>
* </ul>
* @return
*
*/
public function get exitFrame() : Signal
{
return _exitFrame;
}
public function get renderingBegin() : Signal
{
return _renderingBegin;
}
public function get renderingEnd() : Signal
{
return _renderingEnd;
}
public function Scene(...children)
{
super(children);
}
override protected function initialize() : void
{
_bindings = new DataBindings(this);
_assets = new AssetsLibrary();
this.properties = new DataProvider(DataProviderUsage.EXCLUSIVE);
super.initialize();
}
override protected function initializeSignals() : void
{
super.initializeSignals();
_enterFrame = new Signal('Scene.enterFrame');
_renderingBegin = new Signal('Scene.renderingBegin');
_renderingEnd = new Signal('Scene.renderingEnd');
_exitFrame = new Signal('Scene.exitFrame');
}
override protected function initializeSignalHandlers() : void
{
super.initializeSignalHandlers();
added.add(addedHandler);
}
override protected function initializeContollers() : void
{
_renderingCtrl = new RenderingController();
addController(_renderingCtrl);
super.initializeContollers();
}
public function render(viewport : Viewport, destination : BitmapData = null) : void
{
_enterFrame.execute(this, viewport, destination, getTimer());
if (viewport.ready && viewport.visible)
{
_renderingBegin.execute(this, viewport, destination, getTimer());
_numTriangles = _renderingCtrl.render(viewport, destination);
_renderingEnd.execute(this, viewport, destination, getTimer());
}
_exitFrame.execute(this, viewport, destination, getTimer());
}
private function addedHandler(child : ISceneNode, parent : Group) : void
{
throw new Error();
}
}
}
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.Effect;
import aerys.minko.render.Viewport;
import aerys.minko.scene.controller.scene.RenderingController;
import aerys.minko.scene.node.camera.AbstractCamera;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.loader.AssetsLibrary;
import flash.display.BitmapData;
import flash.utils.Dictionary;
import flash.utils.getTimer;
/**
* Scene objects are the root of any 3D scene.
*
* @author Jean-Marc Le Roux
*
*/
public final class Scene extends Group
{
use namespace minko_scene;
minko_scene var _camera : AbstractCamera;
private var _renderingCtrl : RenderingController;
private var _properties : DataProvider;
private var _bindings : DataBindings;
private var _numTriangles : uint;
private var _enterFrame : Signal;
private var _renderingBegin : Signal;
private var _renderingEnd : Signal;
private var _exitFrame : Signal;
private var _assets : AssetsLibrary;
public function get assets() : AssetsLibrary
{
return _assets;
}
public function get activeCamera() : AbstractCamera
{
return _camera;
}
public function get numPasses() : uint
{
return _renderingCtrl.numPasses;
}
public function get numEnabledPasses() : uint
{
return _renderingCtrl.numEnabledPasses;
}
public function get numTriangles() : uint
{
return _numTriangles;
}
public function get postProcessingEffect() : Effect
{
return _renderingCtrl.postProcessingEffect;
}
public function set postProcessingEffect(value : Effect) : void
{
_renderingCtrl.postProcessingEffect = value;
}
public function get postProcessingProperties() : DataProvider
{
return _renderingCtrl.postProcessingProperties;
}
public function get properties() : DataProvider
{
return _properties;
}
public function set properties(value : DataProvider) : void
{
if (_properties != value)
{
if (_properties)
_bindings.removeProvider(_properties);
_properties = value;
if (value)
_bindings.addProvider(value);
}
}
public function get bindings() : DataBindings
{
return _bindings;
}
/**
* The signal executed when the viewport is about to start rendering a frame.
* Callback functions for this signal should accept the following arguments:
* <ul>
* <li>viewport : Viewport, the viewport who starts rendering the frame</li>
* </ul>
* @return
*
*/
public function get enterFrame() : Signal
{
return _enterFrame;
}
/**
* The signal executed when the viewport is done rendering a frame.
* Callback functions for this signal should accept the following arguments:
* <ul>
* <li>viewport : Viewport, the viewport who just finished rendering the frame</li>
* </ul>
* @return
*
*/
public function get exitFrame() : Signal
{
return _exitFrame;
}
public function get renderingBegin() : Signal
{
return _renderingBegin;
}
public function get renderingEnd() : Signal
{
return _renderingEnd;
}
public function Scene(...children)
{
super(children);
}
override protected function initialize() : void
{
_bindings = new DataBindings(this);
_assets = new AssetsLibrary();
this.properties = new DataProvider(DataProviderUsage.EXCLUSIVE);
super.initialize();
}
override protected function initializeSignals() : void
{
super.initializeSignals();
_enterFrame = new Signal('Scene.enterFrame');
_renderingBegin = new Signal('Scene.renderingBegin');
_renderingEnd = new Signal('Scene.renderingEnd');
_exitFrame = new Signal('Scene.exitFrame');
}
override protected function initializeSignalHandlers() : void
{
super.initializeSignalHandlers();
added.add(addedHandler);
}
override protected function initializeContollers() : void
{
_renderingCtrl = new RenderingController();
addController(_renderingCtrl);
super.initializeContollers();
}
public function render(viewport : Viewport, destination : BitmapData = null) : void
{
_enterFrame.execute(this, viewport, destination, getTimer());
if (viewport.ready && viewport.visible)
{
_renderingBegin.execute(this, viewport, destination, getTimer());
_numTriangles = _renderingCtrl.render(viewport, destination);
_renderingEnd.execute(this, viewport, destination, getTimer());
}
_exitFrame.execute(this, viewport, destination, getTimer());
}
private function addedHandler(child : ISceneNode, parent : Group) : void
{
throw new Error();
}
}
}
|
fix coding style
|
fix coding style
|
ActionScript
|
mit
|
aerys/minko-as3
|
5a0a30838ae3515302f39b2f3ccb3ea98aba5101
|
braineditor/Brain.as
|
braineditor/Brain.as
|
import Drawable;
import Lobe;
import Core;
class Brain{
static var brain = new Array();
var mSelectionManager:SelectionManager;
static function makenewlobe(){
var newmov=(new Lobe(_root,_root.getNextHighestDepth()));
var topleft = new Point(100,40);
var botright = new Point(200,140);
newmov.commitBox(topleft, botright, 0);
var keyListener = {};
keyListener.onKeyDown = function()
{
var k = Key.getCode();
if(k == Key.DELETEKEY){
Brain.makenewlobe();
}
};
}
function Brain (root_mc:MovieClip) {
mSelectionManager = new SelectionManager(root_mc);
}
}
|
import Drawable;
import Lobe;
import Core;
class Brain{
static var brain = new Array();
var mSelectionManager:SelectionManager;
static function makenewlobe(){
var newmov=(new Lobe(_root,_root.getNextHighestDepth()));
var topleft = new Point(100,40);
var botright = new Point(200,140);
newmov.commitBox(topleft, botright, 0);
}
function Brain (root_mc:MovieClip) {
mSelectionManager = new SelectionManager(root_mc);
var keyListener = {};
keyListener.onKeyDown = function()
{
var k = Key.getCode();
if(k == Key.DELETEKEY){
Brain.makenewlobe();
}
};
Key.addListener( keyListener );
}
}
|
Delete is now a non-core function
|
Delete is now a non-core function
git-svn-id: f772d44cbf86d9968f12179c1556189f5afcea6e@658 e0ac87d7-b42b-0410-9034-8248a05cb448
|
ActionScript
|
bsd-3-clause
|
elysia/elysia,elysia/elysia,elysia/elysia
|
d50f2ab17e82b18642a7c6494487b22959ba455d
|
swfcat.as
|
swfcat.as
|
package
{
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.net.Socket;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.utils.ByteArray;
import flash.utils.setTimeout;
public class swfcat extends Sprite
{
/* David's relay (nickname 3VXRyxz67OeRoqHn) that also serves a
crossdomain policy. */
private const DEFAULT_TOR_ADDR:Object = {
host: "173.255.221.44",
port: 9001
};
private const DEFAULT_FACILITATOR_ADDR:Object = {
host: "173.255.221.44",
port: 9002
};
private const MAX_NUM_PROXY_PAIRS:uint = 1;
// Milliseconds.
private const FACILITATOR_POLL_INTERVAL:int = 10000;
// Bytes per second. Set to undefined to disable limit.
public const RATE_LIMIT:Number = 10 * 1024;
// Seconds.
private const RATE_LIMIT_HISTORY:Number = 5.0;
// Socket to facilitator.
private var s_f:Socket;
/* TextField for debug output. */
private var output_text:TextField;
private var fac_addr:Object;
/* Number of proxy pairs currently connected (up to
MAX_NUM_PROXY_PAIRS). */
private var num_proxy_pairs:int = 0;
/* Number of proxy pairs ever connected. */
private var total_proxy_pairs:int = 0;
public var rate_limit:RateLimit;
/* Badge with a client counter */
[Embed(source="badge_con_counter.png")]
private var BadgeImage:Class;
private var client_count_tf:TextField;
private var client_count_fmt:TextFormat;
public function puts(s:String):void
{
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
public function update_client_count():void
{
if (String(total_proxy_pairs).length == 1)
client_count_tf.text = "0" + String(total_proxy_pairs);
else
client_count_tf.text = String(total_proxy_pairs);
}
public function swfcat()
{
// Absolute positioning.
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
output_text = new TextField();
output_text.width = stage.stageWidth;
output_text.height = stage.stageHeight;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44cc44;
/* Setup client counter for badge. */
client_count_fmt = new TextFormat();
client_count_fmt.color = 0xFFFFFF;
client_count_fmt.align = "center";
client_count_fmt.font = "courier-new";
client_count_fmt.bold = true;
client_count_fmt.size = 10;
client_count_tf = new TextField();
client_count_tf.width = 20;
client_count_tf.height = 17;
client_count_tf.background = false;
client_count_tf.defaultTextFormat = client_count_fmt;
client_count_tf.x=47;
client_count_tf.y=3;
/* Update the client counter on badge. */
update_client_count();
if (RATE_LIMIT)
rate_limit = new BucketRateLimit(RATE_LIMIT * RATE_LIMIT_HISTORY, RATE_LIMIT_HISTORY);
else
rate_limit = new RateUnlimit();
puts("Starting.");
// Wait until the query string parameters are loaded.
this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
}
private function loaderinfo_complete(e:Event):void
{
var fac_spec:String;
puts("Parameters loaded.");
if (this.loaderInfo.parameters["debug"])
addChild(output_text);
else {
addChild(new BadgeImage());
/* Tried unsuccessfully to add counter to badge. */
/* For now, need two addChilds :( */
addChild(client_count_tf);
}
fac_spec = this.loaderInfo.parameters["facilitator"];
if (fac_spec) {
puts("Facilitator spec: \"" + fac_spec + "\"");
fac_addr = parse_addr_spec(fac_spec);
if (!fac_addr) {
puts("Error: Facilitator spec must be in the form \"host:port\".");
return;
}
} else {
fac_addr = DEFAULT_FACILITATOR_ADDR;
}
main();
}
/* The main logic begins here, after start-up issues are taken care of. */
private function main():void
{
if (num_proxy_pairs >= MAX_NUM_PROXY_PAIRS) {
setTimeout(main, FACILITATOR_POLL_INTERVAL);
return;
}
s_f = new Socket();
s_f.addEventListener(Event.CONNECT, fac_connected);
s_f.addEventListener(Event.CLOSE, function (e:Event):void {
puts("Facilitator: closed connection.");
setTimeout(main, FACILITATOR_POLL_INTERVAL);
});
s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
});
s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
});
puts("Facilitator: connecting to " + fac_addr.host + ":" + fac_addr.port + ".");
s_f.connect(fac_addr.host, fac_addr.port);
}
private function fac_connected(e:Event):void
{
puts("Facilitator: connected.");
s_f.addEventListener(ProgressEvent.SOCKET_DATA, fac_data);
s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n");
}
private function fac_data(e:ProgressEvent):void
{
var client_spec:String;
var client_addr:Object;
var proxy_pair:Object;
client_spec = s_f.readMultiByte(e.bytesLoaded, "utf-8");
puts("Facilitator: got \"" + client_spec + "\".");
client_addr = parse_addr_spec(client_spec);
if (!client_addr) {
puts("Error: Client spec must be in the form \"host:port\".");
return;
}
num_proxy_pairs++;
total_proxy_pairs++;
proxy_pair = new ProxyPair(this, client_addr, DEFAULT_TOR_ADDR);
proxy_pair.addEventListener(Event.COMPLETE, function(e:Event):void {
proxy_pair.log("Complete.");
num_proxy_pairs--;
});
proxy_pair.connect();
/* Update the client count on the badge. */
update_client_count();
}
/* Parse an address in the form "host:port". Returns an Object with
keys "host" (String) and "port" (int). Returns null on error. */
private static function parse_addr_spec(spec:String):Object
{
var parts:Array;
var addr:Object;
parts = spec.split(":", 2);
if (parts.length != 2 || !parseInt(parts[1]))
return null;
addr = {}
addr.host = parts[0];
addr.port = parseInt(parts[1]);
return addr;
}
}
}
import flash.display.Sprite;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
import flash.utils.clearTimeout;
import flash.utils.getTimer;
import flash.utils.setTimeout;
class RateLimit
{
public function RateLimit()
{
}
public function update(n:Number):Boolean
{
return true;
}
public function when():Number
{
return 0.0;
}
public function is_limited():Boolean
{
return false;
}
}
class RateUnlimit extends RateLimit
{
public function RateUnlimit()
{
}
public override function update(n:Number):Boolean
{
return true;
}
public override function when():Number
{
return 0.0;
}
public override function is_limited():Boolean
{
return false;
}
}
class BucketRateLimit extends RateLimit
{
private var amount:Number;
private var capacity:Number;
private var time:Number;
private var last_update:uint;
public function BucketRateLimit(capacity:Number, time:Number)
{
this.amount = 0.0;
/* capacity / time is the rate we are aiming for. */
this.capacity = capacity;
this.time = time;
this.last_update = getTimer();
}
private function age():void
{
var now:uint;
var delta:Number;
now = getTimer();
delta = (now - last_update) / 1000.0;
last_update = now;
amount -= delta * capacity / time;
if (amount < 0.0)
amount = 0.0;
}
public override function update(n:Number):Boolean
{
age();
amount += n;
return amount <= capacity;
}
public override function when():Number
{
age();
return (amount - capacity) / (capacity / time);
}
public override function is_limited():Boolean
{
age();
return amount > capacity;
}
}
/* An instance of a client-relay connection. */
class ProxyPair extends EventDispatcher
{
// Address ({host, port}) of client.
private var addr_c:Object;
// Address ({host, port}) of relay.
private var addr_r:Object;
// Socket to client.
private var s_c:Socket;
// Socket to relay.
private var s_r:Socket;
// Parent swfcat, for UI updates and rate meter.
private var ui:swfcat;
// Pending byte read counts for relay and client sockets.
private var r2c_schedule:Array;
private var c2r_schedule:Array;
// Callback id.
private var flush_id:uint;
public function log(msg:String):void
{
ui.puts(id() + ": " + msg)
}
// String describing this pair for output.
public function id():String
{
return "<" + this.addr_c.host + ":" + this.addr_c.port +
"," + this.addr_r.host + ":" + this.addr_r.port + ">";
}
public function ProxyPair(ui:swfcat, addr_c:Object, addr_r:Object)
{
this.ui = ui;
this.addr_c = addr_c;
this.addr_r = addr_r;
this.c2r_schedule = [];
this.r2c_schedule = [];
}
public function connect():void
{
s_r = new Socket();
s_r.addEventListener(Event.CONNECT, tor_connected);
s_r.addEventListener(Event.CLOSE, function (e:Event):void {
log("Tor: closed.");
if (s_c.connected)
s_c.close();
dispatchEvent(new Event(Event.COMPLETE));
});
s_r.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Tor: I/O error: " + e.text + ".");
if (s_c.connected)
s_c.close();
dispatchEvent(new Event(Event.COMPLETE));
});
s_r.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Tor: security error: " + e.text + ".");
if (s_c.connected)
s_c.close();
dispatchEvent(new Event(Event.COMPLETE));
});
s_r.addEventListener(ProgressEvent.SOCKET_DATA, relay_to_client);
log("Tor: connecting to " + addr_r.host + ":" + addr_r.port + ".");
s_r.connect(addr_r.host, addr_r.port);
}
private function tor_connected(e:Event):void
{
log("Tor: connected.");
s_c = new Socket();
s_c.addEventListener(Event.CONNECT, client_connected);
s_c.addEventListener(Event.CLOSE, function (e:Event):void {
log("Client: closed.");
if (s_r.connected)
s_r.close();
dispatchEvent(new Event(Event.COMPLETE));
});
s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Client: I/O error: " + e.text + ".");
if (s_r.connected)
s_r.close();
dispatchEvent(new Event(Event.COMPLETE));
});
s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Client: security error: " + e.text + ".");
if (s_r.connected)
s_r.close();
dispatchEvent(new Event(Event.COMPLETE));
});
s_c.addEventListener(ProgressEvent.SOCKET_DATA, client_to_relay);
log("Client: connecting to " + addr_c.host + ":" + addr_c.port + ".");
s_c.connect(addr_c.host, addr_c.port);
}
private function relay_to_client(e:ProgressEvent):void
{
r2c_schedule.push(e.bytesLoaded);
flush();
}
private function client_to_relay(e:ProgressEvent):void
{
c2r_schedule.push(e.bytesLoaded);
flush();
}
private function client_connected(e:Event):void
{
log("Client: connected.");
}
private function transfer_chunk(s_from:Socket, s_to:Socket, n:uint,
label:String):void
{
var bytes:ByteArray;
bytes = new ByteArray();
s_from.readBytes(bytes, 0, n);
s_to.writeBytes(bytes);
ui.rate_limit.update(n);
log(label + ": read " + bytes.length + ".");
}
/* Send as much data as the rate limit currently allows. */
private function flush():void
{
if (flush_id)
clearTimeout(flush_id);
flush_id = undefined;
if (!(s_r.connected && s_c.connected))
/* Can't do anything until both sockets are connected. */
return;
while (!ui.rate_limit.is_limited() &&
(r2c_schedule.length > 0 || c2r_schedule.length > 0)) {
if (r2c_schedule.length > 0)
transfer_chunk(s_r, s_c, r2c_schedule.shift(), "Tor");
if (c2r_schedule.length > 0)
transfer_chunk(s_c, s_r, c2r_schedule.shift(), "Client");
}
/* Call again when safe, if necessary. */
if (r2c_schedule.length > 0 || c2r_schedule.length > 0)
flush_id = setTimeout(flush, ui.rate_limit.when() * 1000);
}
}
|
package
{
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.net.Socket;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.utils.ByteArray;
import flash.utils.setTimeout;
public class swfcat extends Sprite
{
/* David's relay (nickname 3VXRyxz67OeRoqHn) that also serves a
crossdomain policy. */
private const DEFAULT_TOR_ADDR:Object = {
host: "173.255.221.44",
port: 9001
};
private const DEFAULT_FACILITATOR_ADDR:Object = {
host: "173.255.221.44",
port: 9002
};
private const MAX_NUM_PROXY_PAIRS:uint = 1;
// Milliseconds.
private const FACILITATOR_POLL_INTERVAL:int = 10000;
// Bytes per second. Set to undefined to disable limit.
public const RATE_LIMIT:Number = undefined;
// Seconds.
private const RATE_LIMIT_HISTORY:Number = 5.0;
// Socket to facilitator.
private var s_f:Socket;
/* TextField for debug output. */
private var output_text:TextField;
private var fac_addr:Object;
/* Number of proxy pairs currently connected (up to
MAX_NUM_PROXY_PAIRS). */
private var num_proxy_pairs:int = 0;
/* Number of proxy pairs ever connected. */
private var total_proxy_pairs:int = 0;
public var rate_limit:RateLimit;
/* Badge with a client counter */
[Embed(source="badge_con_counter.png")]
private var BadgeImage:Class;
private var client_count_tf:TextField;
private var client_count_fmt:TextFormat;
public function puts(s:String):void
{
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
public function update_client_count():void
{
if (String(total_proxy_pairs).length == 1)
client_count_tf.text = "0" + String(total_proxy_pairs);
else
client_count_tf.text = String(total_proxy_pairs);
}
public function swfcat()
{
// Absolute positioning.
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
output_text = new TextField();
output_text.width = stage.stageWidth;
output_text.height = stage.stageHeight;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44cc44;
/* Setup client counter for badge. */
client_count_fmt = new TextFormat();
client_count_fmt.color = 0xFFFFFF;
client_count_fmt.align = "center";
client_count_fmt.font = "courier-new";
client_count_fmt.bold = true;
client_count_fmt.size = 10;
client_count_tf = new TextField();
client_count_tf.width = 20;
client_count_tf.height = 17;
client_count_tf.background = false;
client_count_tf.defaultTextFormat = client_count_fmt;
client_count_tf.x=47;
client_count_tf.y=3;
/* Update the client counter on badge. */
update_client_count();
if (RATE_LIMIT)
rate_limit = new BucketRateLimit(RATE_LIMIT * RATE_LIMIT_HISTORY, RATE_LIMIT_HISTORY);
else
rate_limit = new RateUnlimit();
puts("Starting.");
// Wait until the query string parameters are loaded.
this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
}
private function loaderinfo_complete(e:Event):void
{
var fac_spec:String;
puts("Parameters loaded.");
if (this.loaderInfo.parameters["debug"])
addChild(output_text);
else {
addChild(new BadgeImage());
/* Tried unsuccessfully to add counter to badge. */
/* For now, need two addChilds :( */
addChild(client_count_tf);
}
fac_spec = this.loaderInfo.parameters["facilitator"];
if (fac_spec) {
puts("Facilitator spec: \"" + fac_spec + "\"");
fac_addr = parse_addr_spec(fac_spec);
if (!fac_addr) {
puts("Error: Facilitator spec must be in the form \"host:port\".");
return;
}
} else {
fac_addr = DEFAULT_FACILITATOR_ADDR;
}
main();
}
/* The main logic begins here, after start-up issues are taken care of. */
private function main():void
{
if (num_proxy_pairs >= MAX_NUM_PROXY_PAIRS) {
setTimeout(main, FACILITATOR_POLL_INTERVAL);
return;
}
s_f = new Socket();
s_f.addEventListener(Event.CONNECT, fac_connected);
s_f.addEventListener(Event.CLOSE, function (e:Event):void {
puts("Facilitator: closed connection.");
setTimeout(main, FACILITATOR_POLL_INTERVAL);
});
s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
});
s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
});
puts("Facilitator: connecting to " + fac_addr.host + ":" + fac_addr.port + ".");
s_f.connect(fac_addr.host, fac_addr.port);
}
private function fac_connected(e:Event):void
{
puts("Facilitator: connected.");
s_f.addEventListener(ProgressEvent.SOCKET_DATA, fac_data);
s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n");
}
private function fac_data(e:ProgressEvent):void
{
var client_spec:String;
var client_addr:Object;
var proxy_pair:Object;
client_spec = s_f.readMultiByte(e.bytesLoaded, "utf-8");
puts("Facilitator: got \"" + client_spec + "\".");
client_addr = parse_addr_spec(client_spec);
if (!client_addr) {
puts("Error: Client spec must be in the form \"host:port\".");
return;
}
num_proxy_pairs++;
total_proxy_pairs++;
proxy_pair = new ProxyPair(this, client_addr, DEFAULT_TOR_ADDR);
proxy_pair.addEventListener(Event.COMPLETE, function(e:Event):void {
proxy_pair.log("Complete.");
num_proxy_pairs--;
});
proxy_pair.connect();
/* Update the client count on the badge. */
update_client_count();
}
/* Parse an address in the form "host:port". Returns an Object with
keys "host" (String) and "port" (int). Returns null on error. */
private static function parse_addr_spec(spec:String):Object
{
var parts:Array;
var addr:Object;
parts = spec.split(":", 2);
if (parts.length != 2 || !parseInt(parts[1]))
return null;
addr = {}
addr.host = parts[0];
addr.port = parseInt(parts[1]);
return addr;
}
}
}
import flash.display.Sprite;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
import flash.utils.clearTimeout;
import flash.utils.getTimer;
import flash.utils.setTimeout;
class RateLimit
{
public function RateLimit()
{
}
public function update(n:Number):Boolean
{
return true;
}
public function when():Number
{
return 0.0;
}
public function is_limited():Boolean
{
return false;
}
}
class RateUnlimit extends RateLimit
{
public function RateUnlimit()
{
}
public override function update(n:Number):Boolean
{
return true;
}
public override function when():Number
{
return 0.0;
}
public override function is_limited():Boolean
{
return false;
}
}
class BucketRateLimit extends RateLimit
{
private var amount:Number;
private var capacity:Number;
private var time:Number;
private var last_update:uint;
public function BucketRateLimit(capacity:Number, time:Number)
{
this.amount = 0.0;
/* capacity / time is the rate we are aiming for. */
this.capacity = capacity;
this.time = time;
this.last_update = getTimer();
}
private function age():void
{
var now:uint;
var delta:Number;
now = getTimer();
delta = (now - last_update) / 1000.0;
last_update = now;
amount -= delta * capacity / time;
if (amount < 0.0)
amount = 0.0;
}
public override function update(n:Number):Boolean
{
age();
amount += n;
return amount <= capacity;
}
public override function when():Number
{
age();
return (amount - capacity) / (capacity / time);
}
public override function is_limited():Boolean
{
age();
return amount > capacity;
}
}
/* An instance of a client-relay connection. */
class ProxyPair extends EventDispatcher
{
// Address ({host, port}) of client.
private var addr_c:Object;
// Address ({host, port}) of relay.
private var addr_r:Object;
// Socket to client.
private var s_c:Socket;
// Socket to relay.
private var s_r:Socket;
// Parent swfcat, for UI updates and rate meter.
private var ui:swfcat;
// Pending byte read counts for relay and client sockets.
private var r2c_schedule:Array;
private var c2r_schedule:Array;
// Callback id.
private var flush_id:uint;
public function log(msg:String):void
{
ui.puts(id() + ": " + msg)
}
// String describing this pair for output.
public function id():String
{
return "<" + this.addr_c.host + ":" + this.addr_c.port +
"," + this.addr_r.host + ":" + this.addr_r.port + ">";
}
public function ProxyPair(ui:swfcat, addr_c:Object, addr_r:Object)
{
this.ui = ui;
this.addr_c = addr_c;
this.addr_r = addr_r;
this.c2r_schedule = [];
this.r2c_schedule = [];
}
public function connect():void
{
s_r = new Socket();
s_r.addEventListener(Event.CONNECT, tor_connected);
s_r.addEventListener(Event.CLOSE, function (e:Event):void {
log("Tor: closed.");
if (s_c.connected)
s_c.close();
dispatchEvent(new Event(Event.COMPLETE));
});
s_r.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Tor: I/O error: " + e.text + ".");
if (s_c.connected)
s_c.close();
dispatchEvent(new Event(Event.COMPLETE));
});
s_r.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Tor: security error: " + e.text + ".");
if (s_c.connected)
s_c.close();
dispatchEvent(new Event(Event.COMPLETE));
});
s_r.addEventListener(ProgressEvent.SOCKET_DATA, relay_to_client);
log("Tor: connecting to " + addr_r.host + ":" + addr_r.port + ".");
s_r.connect(addr_r.host, addr_r.port);
}
private function tor_connected(e:Event):void
{
log("Tor: connected.");
s_c = new Socket();
s_c.addEventListener(Event.CONNECT, client_connected);
s_c.addEventListener(Event.CLOSE, function (e:Event):void {
log("Client: closed.");
if (s_r.connected)
s_r.close();
dispatchEvent(new Event(Event.COMPLETE));
});
s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Client: I/O error: " + e.text + ".");
if (s_r.connected)
s_r.close();
dispatchEvent(new Event(Event.COMPLETE));
});
s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Client: security error: " + e.text + ".");
if (s_r.connected)
s_r.close();
dispatchEvent(new Event(Event.COMPLETE));
});
s_c.addEventListener(ProgressEvent.SOCKET_DATA, client_to_relay);
log("Client: connecting to " + addr_c.host + ":" + addr_c.port + ".");
s_c.connect(addr_c.host, addr_c.port);
}
private function relay_to_client(e:ProgressEvent):void
{
r2c_schedule.push(e.bytesLoaded);
flush();
}
private function client_to_relay(e:ProgressEvent):void
{
c2r_schedule.push(e.bytesLoaded);
flush();
}
private function client_connected(e:Event):void
{
log("Client: connected.");
}
private function transfer_chunk(s_from:Socket, s_to:Socket, n:uint,
label:String):void
{
var bytes:ByteArray;
bytes = new ByteArray();
s_from.readBytes(bytes, 0, n);
s_to.writeBytes(bytes);
ui.rate_limit.update(n);
log(label + ": read " + bytes.length + ".");
}
/* Send as much data as the rate limit currently allows. */
private function flush():void
{
if (flush_id)
clearTimeout(flush_id);
flush_id = undefined;
if (!(s_r.connected && s_c.connected))
/* Can't do anything until both sockets are connected. */
return;
while (!ui.rate_limit.is_limited() &&
(r2c_schedule.length > 0 || c2r_schedule.length > 0)) {
if (r2c_schedule.length > 0)
transfer_chunk(s_r, s_c, r2c_schedule.shift(), "Tor");
if (c2r_schedule.length > 0)
transfer_chunk(s_c, s_r, c2r_schedule.shift(), "Client");
}
/* Call again when safe, if necessary. */
if (r2c_schedule.length > 0 || c2r_schedule.length > 0)
flush_id = setTimeout(flush, ui.rate_limit.when() * 1000);
}
}
|
Disable the bandwidth limit.
|
Disable the bandwidth limit.
|
ActionScript
|
mit
|
arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,infinity0/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,glamrock/flashproxy,glamrock/flashproxy,infinity0/flashproxy
|
2dd5c1d229e11949cf963c85b5b994a17940184c
|
src/com/mangui/HLS/muxing/PES.as
|
src/com/mangui/HLS/muxing/PES.as
|
package com.mangui.HLS.muxing {
import com.mangui.HLS.muxing.*;
import com.mangui.HLS.utils.*;
import flash.utils.ByteArray;
/** Representation of a Packetized Elementary Stream. **/
public class PES {
/** Timescale of pts/dts is 90khz. **/
public static var TIMESCALE:Number = 90;
/** Is it AAC audio or AVC video. **/
public var audio:Boolean;
/** The PES data (including headers). **/
public var data:ByteArray;
/** Start of the payload. **/
public var payload:Number;
/** Timestamp from the PTS header. **/
public var pts:Number;
/** Timestamp from the DTS header. **/
public var dts:Number;
/** Save the first chunk of PES data. **/
public function PES(dat:ByteArray,aud:Boolean) {
data = dat;
audio = aud;
};
/** Append PES data from additional TS packets. **/
public function append(dat:ByteArray):void {
data.writeBytes(dat,0,0);
};
/** When all data is appended, parse the PES headers. **/
public function parse():void {
data.position = 0;
// Start code prefix and packet ID.
var prefix:Number = data.readUnsignedInt();
if((audio && (prefix > 448 || prefix < 445)) ||
(!audio && prefix != 480 && prefix != 490)) {
throw new Error("PES start code not found or not AAC/AVC: " + prefix);
}
// Ignore packet length and marker bits.
data.position += 3;
// Check for PTS
var flags:uint = (data.readUnsignedByte() & 192) >> 6;
if(flags != 2 && flags != 3) {
throw new Error("No PTS/DTS in this PES packet");
}
// Check PES header length
var length:uint = data.readUnsignedByte();
// Grab the timestamp from PTS data (spread out over 5 bytes):
// XXXX---X -------- -------X -------- -------X
var _pts:uint = ((data.readUnsignedByte() & 14) << 29) +
((data.readUnsignedShort() & 65534) << 14) +
((data.readUnsignedShort() & 65534) >> 1);
length -= 5;
var _dts:uint = _pts;
if(flags == 3) {
// Grab the DTS (like PTS)
_dts = ((data.readUnsignedByte() & 14) << 29) +
((data.readUnsignedShort() & 65534) << 14) +
((data.readUnsignedShort() & 65534) >> 1);
length -= 5;
}
pts = Math.round(_pts / PES.TIMESCALE);
dts = Math.round(_dts / PES.TIMESCALE);
// Skip other header data and parse payload.
data.position += length;
payload = data.position;
};
}
}
|
package com.mangui.HLS.muxing {
import com.mangui.HLS.muxing.*;
import com.mangui.HLS.utils.*;
import flash.utils.ByteArray;
/** Representation of a Packetized Elementary Stream. **/
public class PES {
/** Timescale of pts/dts is 90khz. **/
public static var TIMESCALE:Number = 90;
/** Is it AAC audio or AVC video. **/
public var audio:Boolean;
/** The PES data (including headers). **/
public var data:ByteArray;
/** Start of the payload. **/
public var payload:Number;
/** Timestamp from the PTS header. **/
public var pts:Number;
/** Timestamp from the DTS header. **/
public var dts:Number;
/** Save the first chunk of PES data. **/
public function PES(dat:ByteArray,aud:Boolean) {
data = dat;
audio = aud;
};
/** Append PES data from additional TS packets. **/
public function append(dat:ByteArray):void {
data.writeBytes(dat,0,0);
};
/** When all data is appended, parse the PES headers. **/
public function parse():void {
data.position = 0;
// Start code prefix and packet ID.
var prefix:Number = data.readUnsignedInt();
if((audio && (prefix > 448 || prefix < 445)) ||
(!audio && prefix != 480 && prefix != 490)) {
throw new Error("PES start code not found or not AAC/AVC: " + prefix);
}
// Ignore packet length and marker bits.
data.position += 3;
// Check for PTS
var flags:uint = (data.readUnsignedByte() & 192) >> 6;
if(flags != 2 && flags != 3) {
throw new Error("No PTS/DTS in this PES packet");
}
// Check PES header length
var length:uint = data.readUnsignedByte();
// Grab the timestamp from PTS data (spread out over 5 bytes):
// XXXX---X -------- -------X -------- -------X
var _pts:Number = ((data.readUnsignedByte() & 0x0e) << 29) +
((data.readUnsignedShort() >> 1) << 15) +
(data.readUnsignedShort() >> 1);
length -= 5;
var _dts:Number = _pts;
if(flags == 3) {
// Grab the DTS (like PTS)
_dts = ((data.readUnsignedByte() & 0x0e) << 29) +
((data.readUnsignedShort() >> 1) << 15) +
(data.readUnsignedShort() >> 1);
length -= 5;
}
pts = Math.round(_pts / PES.TIMESCALE);
dts = Math.round(_dts / PES.TIMESCALE);
// Skip other header data and parse payload.
data.position += length;
payload = data.position;
};
}
}
|
fix PTS/DTS parsing, allow negative values
|
fix PTS/DTS parsing, allow negative values
|
ActionScript
|
mpl-2.0
|
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
|
808321e210714f97c81b7b2fc16744ae0df4d6fd
|
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.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 groundRobots:Object;
private var zombieRobots:Object;
private var archonsA:Object; // id -> DrawRobot
private var archonsB:Object; // id -> DrawRobot
// stats
private var aPoints:Number;
private var bPoints:Number;
private var roundNum:uint;
private var unitCounts:Object;
// rubble
private var rubble:Array; // Number[][]
private var parts:Array; // Number[][]
// immutables
private var map:GameMap;
private var origin:MapLocation;
public function DrawState(map:GameMap) {
groundRobots = {};
zombieRobots = {};
archonsA = {};
archonsB = {};
aPoints = 0;
bPoints = 0;
roundNum = 1;
unitCounts = {};
unitCounts[Team.A] = {};
unitCounts[Team.B] = {};
for each (var robotType:String in RobotType.units()) {
unitCounts[Team.A][robotType] = 0;
unitCounts[Team.B][robotType] = 0;
}
this.map = map;
this.origin = map.getOrigin();
var i:int = 0, j:int = 0;
var initialRubble:Array = map.getInitialRubble();
rubble = [];
for (i = 0; i < map.getHeight(); i++) {
rubble.push(new Array(map.getWidth()));
for (j = 0; j < map.getWidth(); j++) {
rubble[i][j] = initialRubble[i][j];
}
}
var initialParts:Array = map.getInitialParts();
parts = [];
for (i = 0; i < map.getHeight(); i++) {
parts.push(new Array(map.getWidth()));
for (j = 0; j < map.getWidth(); j++) {
parts[i][j] = initialParts[i][j];
}
}
}
///////////////////////////////////////////////////////
///////////////// PROPERTY GETTERS ////////////////////
///////////////////////////////////////////////////////
public function getGroundRobots():Object {
return groundRobots;
}
public function getZombieRobots():Object {
return zombieRobots;
}
public function getArchons(team:String):Object {
return team == Team.A ? archonsA : archonsB;
}
public function getPoints(team:String):uint {
return (team == Team.A) ? aPoints : bPoints;
}
public function getUnitCount(type:String, team:String):int {
return unitCounts[team][type];
}
public function getRubble():Array {
return rubble;
}
public function getParts():Array {
return parts;
}
///////////////////////////////////////////////////////
/////////////////// CORE FUNCTIONS ////////////////////
///////////////////////////////////////////////////////
private function copyStateFrom(state:DrawState):void {
var a:*, i:int;
groundRobots = {};
for (a in state.groundRobots) {
groundRobots[a] = state.groundRobots[a].clone();
}
zombieRobots = {};
for (a in state.zombieRobots) {
zombieRobots[a] = state.zombieRobots[a].clone();
}
archonsA = {};
for (a in state.archonsA) {
archonsA[a] = state.archonsA[a].clone();
}
archonsB = {};
for (a in state.archonsB) {
archonsB[a] = state.archonsB[a].clone();
}
unitCounts = {};
unitCounts[Team.A] = {};
unitCounts[Team.B] = {};
for (var robotType:String in RobotType.values()) {
unitCounts[Team.A][robotType] = state.unitCounts[Team.A][robotType];
unitCounts[Team.B][robotType] = state.unitCounts[Team.B][robotType];
}
rubble = [];
for (i = 0; i < state.rubble.length; i++) {
rubble.push(state.rubble[i].concat());
}
parts = [];
for (i = 0; i < state.parts.length; i++) {
parts.push(state.parts[i].concat());
}
roundNum = state.roundNum;
}
public function clone():DrawState {
var state:DrawState = new DrawState(map);
state.copyStateFrom(this);
return state;
}
public function applyDelta(delta:RoundDelta):void {
updateRound();
for each (var signal:Signal in delta.getSignals()) {
applySignal(signal);
}
processEndOfRound();
}
public function applySignal(signal:Signal):void {
if (signal != null) signal.accept(this);
}
public function applyStats(stats:RoundStats):void {
}
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 zombieRobots) {
o = zombieRobots[a] as DrawRobot;
o.updateRound();
if (!o.isAlive()) {
if (o.parent) {
o.parent.removeChild(o);
}
delete zombieRobots[a];
}
}
for (a in archonsA) {
o = archonsA[a] as DrawRobot;
o.updateRound();
}
for (a in archonsB) {
o = archonsB[a] as DrawRobot;
o.updateRound();
}
}
private function processEndOfRound():void {
roundNum++;
}
///////////////////////////////////////////////////////
////////////// PRIVATE HELPER FUNCTIONS ///////////////
///////////////////////////////////////////////////////
private function getRobot(id:uint):DrawRobot {
if (groundRobots[id]) return groundRobots[id] as DrawRobot;
if (zombieRobots[id]) return zombieRobots[id] as DrawRobot;
return null;
}
private function removeRobot(id:uint):void {
if (groundRobots[id]) delete groundRobots[id];
if (zombieRobots[id]) delete zombieRobots[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 visitDeathSignal(s:DeathSignal):* {
var robot:DrawRobot = getRobot(s.getRobotID());
robot.destroyUnit(!s.getDeathByActivation());
if (robot.getType() == RobotType.ARCHON) {
var archon:DrawRobot = robot.getTeam() == Team.A
? archonsA[robot.getRobotID()]
: archonsB[robot.getRobotID()];
archon.destroyUnit(!s.getDeathByActivation());
}
if (Team.isPlayer(robot.getTeam())) {
unitCounts[robot.getTeam()][robot.getType()]--;
}
}
override public function visitHealthChangeSignal(s:HealthChangeSignal):* {
var robotIDs:Array = s.getRobotIDs();
var healths:Array = s.getHealths();
for (var i:uint; i < robotIDs.length; i++) {
var robot:DrawRobot = getRobot(robotIDs[i]);
robot.setEnergon(healths[i]);
if (robot.getType() == RobotType.ARCHON) {
var archon:DrawRobot = robot.getTeam() == Team.A
? archonsA[robot.getRobotID()]
: archonsB[robot.getRobotID()];
archon.setEnergon(healths[i]);
}
}
}
override public function visitInfectionSignal(s:InfectionSignal):* {
var robotIDs:Array = s.getRobotIDs();
var zombieTurns:Array = s.getZombieTurns();
var viperTurns:Array = s.getViperTurns();
for (var i:uint; i < robotIDs.length; i++) {
var robot:DrawRobot = getRobot(robotIDs[i]);
robot.setZombieInfectedTurns(zombieTurns[i]);
robot.setViperInfectedTurns(viperTurns[i]);
if (robot.getType() == RobotType.ARCHON) {
var archon:DrawRobot = robot.getTeam() == Team.A
? archonsA[robot.getRobotID()]
: archonsB[robot.getRobotID()];
archon.setZombieInfectedTurns(zombieTurns[i]);
archon.setViperInfectedTurns(viperTurns[i]);
}
}
}
override public function visitIndicatorStringSignal(s:IndicatorStringSignal):* {
getRobot(s.getRobotID()).setIndicatorString(s.getIndicatorString(), s.getIndex());
}
override public function visitRubbleChangeSignal(s:RubbleChangeSignal):* {
// robots can clear rubble for OOB locations
if (!map.isOnMap(s.getLocation())) {
return;
}
var loc:MapLocation = translateCoordinates(s.getLocation());
rubble[loc.getY()][loc.getX()] = s.getRubble();
}
override public function visitPartsChangeSignal(s:PartsChangeSignal):* {
var loc:MapLocation = translateCoordinates(s.getLocation());
parts[loc.getY()][loc.getX()] = s.getParts();
}
override public function visitMovementSignal(s:MovementSignal):* {
getRobot(s.getRobotID()).moveToLocation(s.getTargetLoc(), s.getDelay());
}
override public function visitSpawnSignal(s:SpawnSignal):* {
var robot:DrawRobot = new DrawRobot(s.getRobotID(), s.getRobotType(), s.getTeam());
robot.setLocation(s.getLocation());
robot.spawn(s.getDelay());
if (s.getRobotType() == RobotType.ARCHON) {
if (s.getTeam() == Team.A) archonsA[s.getRobotID()] = robot.clone();
if (s.getTeam() == Team.B) archonsB[s.getRobotID()] = robot.clone();
}
if (RobotType.isZombie(s.getRobotType())) {
zombieRobots[s.getRobotID()] = robot;
} else {
groundRobots[s.getRobotID()] = robot;
}
if (Team.isPlayer(s.getTeam())) {
unitCounts[s.getTeam()][s.getRobotType()]++;
}
}
override public function visitTeamResourceSignal(s:TeamResourceSignal):* {
if (s.getTeam() == Team.A) {
aPoints = s.getResource();
} else if (s.getTeam() == Team.B) {
bPoints = s.getResource();
}
}
override public function visitTypeChangeSignal(s:TypeChangeSignal):* {
var r:DrawRobot = getRobot(s.getRobotID());
if (Team.isPlayer(r.getTeam())) {
unitCounts[r.getTeam()][r.getType()]--;
unitCounts[r.getTeam()][s.getType()]++;
}
r.setType(s.getType());
}
}
}
|
package battlecode.client.viewer.render {
import battlecode.common.MapLocation;
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 groundRobots:Object;
private var zombieRobots:Object;
private var archonsA:Object; // id -> DrawRobot
private var archonsB:Object; // id -> DrawRobot
// stats
private var aPoints:Number;
private var bPoints:Number;
private var roundNum:uint;
private var unitCounts:Object;
// rubble
private var rubble:Array; // Number[][]
private var parts:Array; // Number[][]
// immutables
private var map:GameMap;
private var origin:MapLocation;
public function DrawState(map:GameMap) {
groundRobots = {};
zombieRobots = {};
archonsA = {};
archonsB = {};
aPoints = 0;
bPoints = 0;
roundNum = 1;
unitCounts = {};
unitCounts[Team.A] = {};
unitCounts[Team.B] = {};
for each (var robotType:String in RobotType.units()) {
unitCounts[Team.A][robotType] = 0;
unitCounts[Team.B][robotType] = 0;
}
this.map = map;
this.origin = map.getOrigin();
var i:int = 0, j:int = 0;
var initialRubble:Array = map.getInitialRubble();
rubble = [];
for (i = 0; i < map.getHeight(); i++) {
rubble.push(new Array(map.getWidth()));
for (j = 0; j < map.getWidth(); j++) {
rubble[i][j] = initialRubble[i][j];
}
}
var initialParts:Array = map.getInitialParts();
parts = [];
for (i = 0; i < map.getHeight(); i++) {
parts.push(new Array(map.getWidth()));
for (j = 0; j < map.getWidth(); j++) {
parts[i][j] = initialParts[i][j];
}
}
}
///////////////////////////////////////////////////////
///////////////// PROPERTY GETTERS ////////////////////
///////////////////////////////////////////////////////
public function getGroundRobots():Object {
return groundRobots;
}
public function getZombieRobots():Object {
return zombieRobots;
}
public function getArchons(team:String):Object {
return team == Team.A ? archonsA : archonsB;
}
public function getPoints(team:String):uint {
return (team == Team.A) ? aPoints : bPoints;
}
public function getUnitCount(type:String, team:String):int {
return unitCounts[team][type];
}
public function getRubble():Array {
return rubble;
}
public function getParts():Array {
return parts;
}
///////////////////////////////////////////////////////
/////////////////// CORE FUNCTIONS ////////////////////
///////////////////////////////////////////////////////
private function copyStateFrom(state:DrawState):void {
var a:*, i:int;
groundRobots = {};
for (a in state.groundRobots) {
groundRobots[a] = state.groundRobots[a].clone();
}
zombieRobots = {};
for (a in state.zombieRobots) {
zombieRobots[a] = state.zombieRobots[a].clone();
}
archonsA = {};
for (a in state.archonsA) {
archonsA[a] = state.archonsA[a].clone();
}
archonsB = {};
for (a in state.archonsB) {
archonsB[a] = state.archonsB[a].clone();
}
unitCounts = {};
unitCounts[Team.A] = {};
unitCounts[Team.B] = {};
for each (var robotType:String in RobotType.values()) {
unitCounts[Team.A][robotType] = state.unitCounts[Team.A][robotType];
unitCounts[Team.B][robotType] = state.unitCounts[Team.B][robotType];
}
rubble = [];
for (i = 0; i < state.rubble.length; i++) {
rubble.push(state.rubble[i].concat());
}
parts = [];
for (i = 0; i < state.parts.length; i++) {
parts.push(state.parts[i].concat());
}
roundNum = state.roundNum;
}
public function clone():DrawState {
var state:DrawState = new DrawState(map);
state.copyStateFrom(this);
return state;
}
public function applyDelta(delta:RoundDelta):void {
updateRound();
for each (var signal:Signal in delta.getSignals()) {
applySignal(signal);
}
processEndOfRound();
}
public function applySignal(signal:Signal):void {
if (signal != null) signal.accept(this);
}
public function applyStats(stats:RoundStats):void {
}
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 zombieRobots) {
o = zombieRobots[a] as DrawRobot;
o.updateRound();
if (!o.isAlive()) {
if (o.parent) {
o.parent.removeChild(o);
}
delete zombieRobots[a];
}
}
for (a in archonsA) {
o = archonsA[a] as DrawRobot;
o.updateRound();
}
for (a in archonsB) {
o = archonsB[a] as DrawRobot;
o.updateRound();
}
}
private function processEndOfRound():void {
roundNum++;
}
///////////////////////////////////////////////////////
////////////// PRIVATE HELPER FUNCTIONS ///////////////
///////////////////////////////////////////////////////
private function getRobot(id:uint):DrawRobot {
if (groundRobots[id]) return groundRobots[id] as DrawRobot;
if (zombieRobots[id]) return zombieRobots[id] as DrawRobot;
return null;
}
private function removeRobot(id:uint):void {
if (groundRobots[id]) delete groundRobots[id];
if (zombieRobots[id]) delete zombieRobots[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 visitDeathSignal(s:DeathSignal):* {
var robot:DrawRobot = getRobot(s.getRobotID());
robot.destroyUnit(!s.getDeathByActivation());
if (robot.getType() == RobotType.ARCHON) {
var archon:DrawRobot = robot.getTeam() == Team.A
? archonsA[robot.getRobotID()]
: archonsB[robot.getRobotID()];
archon.destroyUnit(!s.getDeathByActivation());
}
if (Team.isPlayer(robot.getTeam())) {
unitCounts[robot.getTeam()][robot.getType()]--;
}
}
override public function visitHealthChangeSignal(s:HealthChangeSignal):* {
var robotIDs:Array = s.getRobotIDs();
var healths:Array = s.getHealths();
for (var i:uint; i < robotIDs.length; i++) {
var robot:DrawRobot = getRobot(robotIDs[i]);
robot.setEnergon(healths[i]);
if (robot.getType() == RobotType.ARCHON) {
var archon:DrawRobot = robot.getTeam() == Team.A
? archonsA[robot.getRobotID()]
: archonsB[robot.getRobotID()];
archon.setEnergon(healths[i]);
}
}
}
override public function visitInfectionSignal(s:InfectionSignal):* {
var robotIDs:Array = s.getRobotIDs();
var zombieTurns:Array = s.getZombieTurns();
var viperTurns:Array = s.getViperTurns();
for (var i:uint; i < robotIDs.length; i++) {
var robot:DrawRobot = getRobot(robotIDs[i]);
robot.setZombieInfectedTurns(zombieTurns[i]);
robot.setViperInfectedTurns(viperTurns[i]);
if (robot.getType() == RobotType.ARCHON) {
var archon:DrawRobot = robot.getTeam() == Team.A
? archonsA[robot.getRobotID()]
: archonsB[robot.getRobotID()];
archon.setZombieInfectedTurns(zombieTurns[i]);
archon.setViperInfectedTurns(viperTurns[i]);
}
}
}
override public function visitIndicatorStringSignal(s:IndicatorStringSignal):* {
getRobot(s.getRobotID()).setIndicatorString(s.getIndicatorString(), s.getIndex());
}
override public function visitRubbleChangeSignal(s:RubbleChangeSignal):* {
// robots can clear rubble for OOB locations
if (!map.isOnMap(s.getLocation())) {
return;
}
var loc:MapLocation = translateCoordinates(s.getLocation());
rubble[loc.getY()][loc.getX()] = s.getRubble();
}
override public function visitPartsChangeSignal(s:PartsChangeSignal):* {
var loc:MapLocation = translateCoordinates(s.getLocation());
parts[loc.getY()][loc.getX()] = s.getParts();
}
override public function visitMovementSignal(s:MovementSignal):* {
getRobot(s.getRobotID()).moveToLocation(s.getTargetLoc(), s.getDelay());
}
override public function visitSpawnSignal(s:SpawnSignal):* {
var robot:DrawRobot = new DrawRobot(s.getRobotID(), s.getRobotType(), s.getTeam());
robot.setLocation(s.getLocation());
robot.spawn(s.getDelay());
if (s.getRobotType() == RobotType.ARCHON) {
if (s.getTeam() == Team.A) archonsA[s.getRobotID()] = robot.clone();
if (s.getTeam() == Team.B) archonsB[s.getRobotID()] = robot.clone();
}
if (RobotType.isZombie(s.getRobotType())) {
zombieRobots[s.getRobotID()] = robot;
} else {
groundRobots[s.getRobotID()] = robot;
}
if (Team.isPlayer(s.getTeam())) {
unitCounts[s.getTeam()][s.getRobotType()]++;
}
}
override public function visitTeamResourceSignal(s:TeamResourceSignal):* {
if (s.getTeam() == Team.A) {
aPoints = s.getResource();
} else if (s.getTeam() == Team.B) {
bPoints = s.getResource();
}
}
override public function visitTypeChangeSignal(s:TypeChangeSignal):* {
var r:DrawRobot = getRobot(s.getRobotID());
if (Team.isPlayer(r.getTeam())) {
unitCounts[r.getTeam()][r.getType()]--;
unitCounts[r.getTeam()][s.getType()]++;
}
r.setType(s.getType());
}
}
}
|
fix iteration bug that causes unit counts to stop working
|
fix iteration bug that causes unit counts to stop working
|
ActionScript
|
mit
|
trun/battlecode-webclient
|
99301c4871eebcd89dcbe9b02f15d54aa5c55e1d
|
src/org/mangui/hls/demux/Nalu.as
|
src/org/mangui/hls/demux/Nalu.as
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls.demux {
import org.mangui.hls.HLSSettings;
import flash.utils.ByteArray;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
/** Constants and utilities for the H264 video format. **/
public class Nalu {
/** H264 NAL unit names. **/
private static const NAMES : Array = ['Unspecified', // 0
'NDR', // 1
'Partition A', // 2
'Partition B', // 3
'Partition C', // 4
'IDR', // 5
'SEI', // 6
'SPS', // 7
'PPS', // 8
'AUD', // 9
'End of Sequence', // 10
'End of Stream', // 11
'Filler Data'// 12
];
/** Return an array with NAL delimiter indexes. **/
public static function getNALU(nalu : ByteArray, position : uint) : Vector.<VideoFrame> {
var units : Vector.<VideoFrame> = new Vector.<VideoFrame>();
var unit_start : int;
var unit_type : int;
var unit_header : int;
// Loop through data to find NAL startcodes.
var window : uint = 0;
nalu.position = position;
while (nalu.bytesAvailable > 4) {
window = nalu.readUnsignedInt();
// Match four-byte startcodes
if ((window & 0xFFFFFFFF) == 0x01) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if (unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
unit_header = 4;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if (unit_type == 1 || unit_type == 5) {
break;
}
// Match three-byte startcodes
} else if ((window & 0xFFFFFF00) == 0x100) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if (unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
nalu.position--;
unit_header = 3;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if (unit_type == 1 || unit_type == 5) {
break;
}
} else {
nalu.position -= 3;
}
}
// Append the last NAL to the array.
if (unit_start) {
units.push(new VideoFrame(unit_header, nalu.length - unit_start, unit_start, unit_type));
}
// Reset position and return results.
CONFIG::LOGGING {
if (HLSSettings.logDebug2) {
if (units.length) {
var txt : String = "AVC: ";
for (var i : int = 0; i < units.length; i++) {
txt += NAMES[units[i].type] + ", ";
}
Log.debug2(txt.substr(0, txt.length - 2) + " slices");
} else {
Log.debug2('AVC: no NALU slices found');
}
}
}
nalu.position = position;
return units;
};
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls.demux {
import flash.utils.ByteArray;
CONFIG::LOGGING {
import org.mangui.hls.HLSSettings;
import org.mangui.hls.utils.Log;
}
/** Constants and utilities for the H264 video format. **/
public class Nalu {
/** H264 NAL unit names. **/
private static const NAMES : Array = ['Unspecified', // 0
'NDR', // 1
'Partition A', // 2
'Partition B', // 3
'Partition C', // 4
'IDR', // 5
'SEI', // 6
'SPS', // 7
'PPS', // 8
'AUD', // 9
'End of Sequence', // 10
'End of Stream', // 11
'Filler Data'// 12
];
/** Return an array with NAL delimiter indexes. **/
public static function getNALU(nalu : ByteArray, position : uint) : Vector.<VideoFrame> {
var units : Vector.<VideoFrame> = new Vector.<VideoFrame>();
var unit_start : int;
var unit_type : int;
var unit_header : int;
// Loop through data to find NAL startcodes.
var window : uint = 0;
nalu.position = position;
while (nalu.bytesAvailable > 4) {
window = nalu.readUnsignedInt();
// Match four-byte startcodes
if ((window & 0xFFFFFFFF) == 0x01) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if (unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
unit_header = 4;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if (unit_type == 1 || unit_type == 5) {
break;
}
// Match three-byte startcodes
} else if ((window & 0xFFFFFF00) == 0x100) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if (unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
nalu.position--;
unit_header = 3;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if (unit_type == 1 || unit_type == 5) {
break;
}
} else {
nalu.position -= 3;
}
}
// Append the last NAL to the array.
if (unit_start) {
units.push(new VideoFrame(unit_header, nalu.length - unit_start, unit_start, unit_type));
}
// Reset position and return results.
CONFIG::LOGGING {
if (HLSSettings.logDebug2) {
if (units.length) {
var txt : String = "AVC: ";
for (var i : int = 0; i < units.length; i++) {
txt += NAMES[units[i].type] + ", ";
}
Log.debug2(txt.substr(0, txt.length - 2) + " slices");
} else {
Log.debug2('AVC: no NALU slices found');
}
}
}
nalu.position = position;
return units;
};
}
}
|
Move HLSSettings importing into conditional compilation block
|
Move HLSSettings importing into conditional compilation block
HLSSettings is only used when LOGGING is true.
|
ActionScript
|
mpl-2.0
|
aevange/flashls,JulianPena/flashls,NicolasSiver/flashls,jlacivita/flashls,mangui/flashls,vidible/vdb-flashls,thdtjsdn/flashls,hola/flashls,fixedmachine/flashls,thdtjsdn/flashls,jlacivita/flashls,JulianPena/flashls,Boxie5/flashls,neilrackett/flashls,dighan/flashls,dighan/flashls,fixedmachine/flashls,clappr/flashls,loungelogic/flashls,Peer5/flashls,clappr/flashls,loungelogic/flashls,aevange/flashls,codex-corp/flashls,mangui/flashls,aevange/flashls,Boxie5/flashls,vidible/vdb-flashls,Corey600/flashls,aevange/flashls,tedconf/flashls,Peer5/flashls,NicolasSiver/flashls,tedconf/flashls,Peer5/flashls,neilrackett/flashls,hola/flashls,codex-corp/flashls,Corey600/flashls,Peer5/flashls
|
e5f0c4d6b19572a91abc7cd564a86f2504e0665b
|
Arguments/src/classes/Language.as
|
Arguments/src/classes/Language.as
|
package classes
{
/**
AGORA - an interactive and web-based argument mapping tool that stimulates reasoning,
reflection, critique, deliberation, and creativity in individual argument construction
and in collaborative or adversarial settings.
Copyright (C) 2011 Georgia Institute of Technology
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import mx.controls.Alert;
import org.osmf.layout.AbsoluteLayoutFacet;
public class Language
{
//I will set the language to either GERMAN, RUSSIAN or ENGLISH
//based on this, you could read the values into the variables
//by default, the language is EN-US
public static const GERMAN:String = "GER";
public static const ENGLISH:String = "EN-US";
public static const RUSSIAN:String = "RUS";
public static var language:String = RUSSIAN;
public static var xml:XML;
private static var ready:Boolean=false;
public static function init():void
{
[Embed(source="../../../translation.xml", mimeType="application/octet-stream")]
const MyData:Class;
var byteArray:ByteArray = new MyData() as ByteArray;
var x:XML = new XML(byteArray.readUTFBytes(byteArray.length));
xml = x;
ready=true;
}
/**The key function. Use this to look up a label from the translation document according to the set language.*/
public static function lookup(label:String):String{
if(!ready){
init();
}
trace("Now looking up:" + label);
var lbl:XMLList = xml.descendants(label);
var lang:XMLList = lbl.descendants(language);
var output:String = lang.attribute("text");
if(!output){
output = "error | ошибка | Fehler --- There was a problem getting the text for this item. The label was: " + label;
}
trace("Output is: " + output);
return output;
}
}
}
|
package classes
{
/**
AGORA - an interactive and web-based argument mapping tool that stimulates reasoning,
reflection, critique, deliberation, and creativity in individual argument construction
and in collaborative or adversarial settings.
Copyright (C) 2011 Georgia Institute of Technology
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import mx.controls.Alert;
import org.osmf.layout.AbsoluteLayoutFacet;
public class Language
{
//I will set the language to either GERMAN, RUSSIAN or ENGLISH
//based on this, you could read the values into the variables
//by default, the language is EN-US
public static const GERMAN:String = "GER";
public static const ENGLISH:String = "EN-US";
public static const RUSSIAN:String = "RUS";
public static var language:String = ENGLISH;
public static var xml:XML;
private static var ready:Boolean=false;
public static function init():void
{
[Embed(source="../../../translation.xml", mimeType="application/octet-stream")]
const MyData:Class;
var byteArray:ByteArray = new MyData() as ByteArray;
var x:XML = new XML(byteArray.readUTFBytes(byteArray.length));
xml = x;
ready=true;
}
/**The key function. Use this to look up a label from the translation document according to the set language.*/
public static function lookup(label:String):String{
if(!ready){
init();
}
trace("Now looking up:" + label);
var lbl:XMLList = xml.descendants(label);
var lang:XMLList = lbl.descendants(language);
var output:String = lang.attribute("text");
if(!output){
output = "error | ошибка | Fehler --- There was a problem getting the text for this item. The label was: " + label;
}
trace("Output is: " + output);
return output;
}
}
}
|
Switch langauge back to English
|
Switch langauge back to English
|
ActionScript
|
agpl-3.0
|
mbjornas3/AGORA,MichaelHoffmann/AGORA,MichaelHoffmann/AGORA,MichaelHoffmann/AGORA,mbjornas3/AGORA
|
431eb28a3643312c745092714c97e56c006b52c7
|
src/aerys/minko/render/Viewport.as
|
src/aerys/minko/render/Viewport.as
|
package aerys.minko.render
{
import aerys.minko.ns.minko_render;
import aerys.minko.ns.minko_scene;
import aerys.minko.render.resource.Context3DResource;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.Factory;
import aerys.minko.type.KeyboardManager;
import aerys.minko.type.MouseManager;
import aerys.minko.type.Signal;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.Graphics;
import flash.display.Shape;
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.Stage3D;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.display3D.Context3D;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TouchEvent;
import flash.geom.Point;
import flash.utils.getTimer;
/**
* The Viewport is the display area where a 3D scene can be rendered.
*
* @author Jean-Marc Le Roux
*
*/
public class Viewport extends Sprite
{
private static const ZERO2 : Point = new Point();
private var _stage3d : Stage3D = null;
private var _context3d : Context3DResource = null;
private var _width : uint = 0;
private var _height : uint = 0;
private var _autoResize : Boolean = false;
private var _antiAliasing : uint = 0;
private var _backgroundColor : uint = 0;
private var _backBuffer : RenderTarget = null;
private var _invalidBackBuffer : Boolean = false;
private var _alwaysOnTop : Boolean = false;
private var _mask : Shape = new Shape();
private var _mouseManager : MouseManager = new MouseManager();
private var _keyboardManager : KeyboardManager = new KeyboardManager();
private var _resized : Signal = new Signal('Viewport.resized');
minko_render function get context3D() : Context3DResource
{
return _context3d;
}
minko_render function get backBuffer() : RenderTarget
{
var positionOnStage : Point = localToGlobal(ZERO2);
if (_stage3d.x != positionOnStage.x || _stage3d.y != positionOnStage.y)
{
updateStage3D()
// updateBackBuffer();
}
return _backBuffer;
}
public function get ready() : Boolean
{
return _stage3d != null && _stage3d.context3D != null && _backBuffer != null;
}
/**
* Whether the viewport is visible or not.
* @return
*
*/
override public function get visible() : Boolean
{
return _stage3d.visible;
}
override public function set visible(value : Boolean) : void
{
_stage3d.visible = value;
super.visible = value;
}
override public function set x(value : Number) : void
{
super.x = value;
updateStage3D();
}
override public function set y(value : Number) : void
{
super.y = value;
updateStage3D();
}
/**
* The width of the display area.
* @return
*
*/
override public function get width() : Number
{
return _width;
}
override public function set width(value : Number) : void
{
resize(value, _height);
}
/**
* The height of the display area.
* @return
*
*/
override public function get height() : Number
{
return _height;
}
override public function set height(value : Number) : void
{
resize(_width, value);
}
public function get alwaysOnTop() : Boolean
{
return _alwaysOnTop;
}
public function set alwaysOnTop(value : Boolean) : void
{
_alwaysOnTop = value;
}
public function get keyboardManager() : KeyboardManager
{
return _keyboardManager;
}
public function get mouseManager() : MouseManager
{
return _mouseManager;
}
/**
* The signal executed when the viewport is resized.
* Callback functions for this signal should accept the following
* arguments:
* <ul>
* <li>viewport : Viewport, the viewport executing the signal</li>
* <li>width : Number, the new width of the viewport</li>
* <li>height : Number, the new height of the viewport</li>
* </ul>
* @return
*
*/
public function get resized() : Signal
{
return _resized;
}
/**
* The background color of the display area. This value must use the
* RGB format.
* @return
*
*/
public function get backgroundColor() : uint
{
return _backgroundColor;
}
public function set backgroundColor(value : uint) : void
{
_backgroundColor = value;
updateStage3D();
}
/**
* The anti-aliasing to use (0, 2, 4, 8 or 16). The actual anti-aliasing
* used for rendering depends on the hardware capabilities. If the specified
* anti-aliasing value is not supported, the value 0 will be used.
* @return
*
*/
public function get antiAliasing() : uint
{
return _antiAliasing;
}
public function set antiAliasing(value : uint) : void
{
_antiAliasing = value;
updateStage3D();
}
/**
* The driver informations provided by the Stage3D API.
*/
public function get driverInfo() : String
{
return _stage3d && _stage3d.context3D
? _stage3d.context3D.driverInfo
: null;
}
public function Viewport(antiAliasing : uint = 0,
width : uint = 0,
height : uint = 0)
{
_antiAliasing = antiAliasing;
if (width == 0 && height == 0)
_autoResize = true;
_width = width;
_height = height;
initialize();
}
private function initialize() : void
{
_mouseManager.bind(this);
addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
addEventListener(Event.REMOVED_FROM_STAGE, removedFromStageHandler);
}
private function addedToStageHandler(event : Event) : void
{
_keyboardManager.bind(stage);
parent.addEventListener(Event.RESIZE, parentResizedHandler);
stage.addEventListener(Event.ADDED_TO_STAGE, displayObjectAddedToStageHandler);
stage.addEventListener(Event.REMOVED_FROM_STAGE, displayObjectRemovedFromStageHandler);
stage.addEventListener(MouseEvent.CLICK, stageEventHandler);
stage.addEventListener(MouseEvent.DOUBLE_CLICK, stageEventHandler);
stage.addEventListener(MouseEvent.MOUSE_DOWN, stageEventHandler);
stage.addEventListener(MouseEvent.MOUSE_MOVE, stageEventHandler);
stage.addEventListener(MouseEvent.MOUSE_OUT, stageEventHandler);
stage.addEventListener(MouseEvent.MOUSE_OVER, stageEventHandler);
stage.addEventListener(MouseEvent.MOUSE_WHEEL, stageEventHandler);
stage.addEventListener(MouseEvent.ROLL_OUT, stageEventHandler);
stage.addEventListener(MouseEvent.ROLL_OVER, stageEventHandler);
stage.addEventListener(TouchEvent.TOUCH_BEGIN, stageEventHandler);
stage.addEventListener(TouchEvent.TOUCH_END, stageEventHandler);
stage.addEventListener(TouchEvent.TOUCH_MOVE, stageEventHandler);
setupOnStage(stage);
}
private function removedFromStageHandler(event : Event) : void
{
_keyboardManager.unbind(stage);
parent.removeEventListener(Event.RESIZE, parentResizedHandler);
stage.removeEventListener(Event.ADDED_TO_STAGE, displayObjectAddedToStageHandler);
stage.removeEventListener(Event.REMOVED_FROM_STAGE, displayObjectRemovedFromStageHandler);
stage.removeEventListener(MouseEvent.CLICK, stageEventHandler);
stage.removeEventListener(MouseEvent.DOUBLE_CLICK, stageEventHandler);
stage.removeEventListener(MouseEvent.MOUSE_DOWN, stageEventHandler);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, stageEventHandler);
stage.removeEventListener(MouseEvent.MOUSE_OUT, stageEventHandler);
stage.removeEventListener(MouseEvent.MOUSE_OVER, stageEventHandler);
stage.removeEventListener(MouseEvent.MOUSE_WHEEL, stageEventHandler);
stage.removeEventListener(MouseEvent.ROLL_OUT, stageEventHandler);
stage.removeEventListener(MouseEvent.ROLL_OVER, stageEventHandler);
stage.removeEventListener(TouchEvent.TOUCH_BEGIN, stageEventHandler);
stage.removeEventListener(TouchEvent.TOUCH_END, stageEventHandler);
stage.removeEventListener(TouchEvent.TOUCH_MOVE, stageEventHandler);
if (_stage3d != null)
_stage3d.visible = false;
}
private function setupOnStage(stage : Stage, stage3dId : uint = 0) : void
{
if (_autoResize)
{
_width = stage.stageWidth;
_height = stage.stageHeight;
}
if (!_stage3d)
{
_stage3d = stage.stage3Ds[stage3dId];
_stage3d.addEventListener(Event.CONTEXT3D_CREATE, context3dCreatedHandler);
_stage3d.requestContext3D();
}
else
{
_stage3d.visible = true;
}
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
}
/**
* Dispose the Viewport and all the Stage3D related objects. After this operation,
* the Viewport cannot be used anymore and is ready for garbage collection.
*/
public function dispose():void
{
if (_stage3d != null)
{
_stage3d.removeEventListener(Event.CONTEXT3D_CREATE, context3dCreatedHandler);
_stage3d = null;
}
if (_context3d != null)
{
_context3d.dispose();
_context3d = null;
}
return ;
}
/**
* Resize the display area. The "resized" signal is executed when the new width and
* height have be set.
* @param width
* @param height
*
*/
public function resize(width : Number, height : Number) : void
{
_autoResize = false;
setSize(width, height);
}
private function setSize(width : Number, height : Number) : void
{
if (width == _width && _height == height)
return ;
_width = width;
_height = height;
updateStage3D();
updateBackBuffer();
_resized.execute(this, width, height);
}
private function stageResizedHandler(event : Event) : void
{
updateMask();
}
private function parentResizedHandler(event : Event) : void
{
if (_autoResize)
{
if (parent == stage)
setSize(stage.stageWidth, stage.stageHeight);
else
setSize(parent.width, parent.height);
}
}
private function context3dCreatedHandler(event : Event) : void
{
_context3d = new Context3DResource(_stage3d.context3D);
updateStage3D();
updateBackBuffer();
dispatchEvent(new Event(Event.INIT));
}
private function updateBackBuffer() : void
{
if (_width == 0 || _height == 0 || _stage3d == null || _stage3d.context3D == null)
return ;
_invalidBackBuffer = false;
_stage3d.context3D.configureBackBuffer(_width, _height, _antiAliasing, true);
_backBuffer = new RenderTarget(_width, _height, null, 0, _backgroundColor);
graphics.clear();
graphics.beginFill(0, 0);
graphics.drawRect(0, 0, _width, _height);
}
private function updateStage3D() : void
{
if (_stage3d == null)
return ;
var upperLeft : Point = localToGlobal(ZERO2);
_stage3d.x = upperLeft.x;
_stage3d.y = upperLeft.y;
if (_width > 2048)
{
_stage3d.x = (_width - 2048) * 0.5;
_width = 2048;
}
else
_stage3d.x = upperLeft.x;
if (_height > 2048)
{
_stage3d.y = (_height - 2048) * 0.5;
_height = 2048;
}
else
_stage3d.y = upperLeft.y;
updateMask();
}
private function stageEventHandler(event : Object) : void
{
if (!_alwaysOnTop || event.target == this)
return ;
var stageX : Number = event.stageX;
var stageY : Number = event.stageY;
if (stageX > _stage3d.x && stageX < _stage3d.x + _width
&& stageY > _stage3d.y && stageY < _stage3d.y + _height)
{
dispatchEvent(event.clone());
}
}
private function updateMask() : void
{
if (!stage)
return ;
var numChildren : uint = stage.numChildren;
var i : uint = 0;
if (_alwaysOnTop)
{
var gfx : Graphics = _mask.graphics;
var stageWidth : int = stage.stageWidth;
var stageHeight : int = stage.stageHeight;
gfx.clear();
gfx.beginFill(0);
gfx.moveTo(0, 0);
gfx.lineTo(stageWidth, 0);
gfx.lineTo(stageWidth, stageHeight);
gfx.lineTo(0., stageHeight);
gfx.lineTo(0, 0);
gfx.moveTo(_stage3d.x, _stage3d.y);
gfx.lineTo(_stage3d.x, _stage3d.y + height);
gfx.lineTo(_stage3d.x + width, _stage3d.y + height);
gfx.lineTo(_stage3d.x + width, _stage3d.y);
gfx.lineTo(_stage3d.x, _stage3d.y);
gfx.endFill();
for (i = 0; i < numChildren; ++i)
stage.getChildAt(i).mask = _mask;
}
else
{
for (i = 0; i < numChildren; ++i)
{
var child : DisplayObject = stage.getChildAt(i);
if (child.mask == _mask)
child.mask = null;
}
}
}
private function displayObjectAddedToStageHandler(event : Event) : void
{
var displayObject : DisplayObject = event.target as DisplayObject;
if (displayObject.parent == stage)
updateMask();
}
private function displayObjectRemovedFromStageHandler(event : Event) : void
{
var displayObject : DisplayObject = event.target as DisplayObject;
if (_autoResize && displayObject.parent == stage)
displayObject.mask = null;
}
}
}
|
package aerys.minko.render
{
import aerys.minko.ns.minko_render;
import aerys.minko.render.resource.Context3DResource;
import aerys.minko.type.KeyboardManager;
import aerys.minko.type.MouseManager;
import aerys.minko.type.Signal;
import flash.display.DisplayObject;
import flash.display.Graphics;
import flash.display.Shape;
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.Stage3D;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TouchEvent;
import flash.geom.Point;
/**
* The Viewport is the display area where a 3D scene can be rendered.
*
* @author Jean-Marc Le Roux
*
*/
public class Viewport extends Sprite
{
private static const ZERO2 : Point = new Point();
private var _stage3d : Stage3D = null;
private var _context3d : Context3DResource = null;
private var _width : uint = 0;
private var _height : uint = 0;
private var _autoResize : Boolean = false;
private var _antiAliasing : uint = 0;
private var _backgroundColor : uint = 0;
private var _backBuffer : RenderTarget = null;
private var _invalidBackBuffer : Boolean = false;
private var _alwaysOnTop : Boolean = false;
private var _mask : Shape = new Shape();
private var _mouseManager : MouseManager = new MouseManager();
private var _keyboardManager : KeyboardManager = new KeyboardManager();
private var _resized : Signal = new Signal('Viewport.resized');
minko_render function get context3D() : Context3DResource
{
return _context3d;
}
minko_render function get backBuffer() : RenderTarget
{
var positionOnStage : Point = localToGlobal(ZERO2);
if (_stage3d.x != positionOnStage.x || _stage3d.y != positionOnStage.y)
updateStage3D()
return _backBuffer;
}
public function get ready() : Boolean
{
return _stage3d != null && _stage3d.context3D != null && _backBuffer != null;
}
/**
* Whether the viewport is visible or not.
* @return
*
*/
override public function get visible() : Boolean
{
return _stage3d.visible;
}
override public function set visible(value : Boolean) : void
{
_stage3d.visible = value;
super.visible = value;
}
override public function set x(value : Number) : void
{
super.x = value;
updateStage3D();
}
override public function set y(value : Number) : void
{
super.y = value;
updateStage3D();
}
/**
* The width of the display area.
* @return
*
*/
override public function get width() : Number
{
return _width;
}
override public function set width(value : Number) : void
{
resize(value, _height);
}
/**
* The height of the display area.
* @return
*
*/
override public function get height() : Number
{
return _height;
}
override public function set height(value : Number) : void
{
resize(_width, value);
}
public function get alwaysOnTop() : Boolean
{
return _alwaysOnTop;
}
public function set alwaysOnTop(value : Boolean) : void
{
_alwaysOnTop = value;
}
public function get keyboardManager() : KeyboardManager
{
return _keyboardManager;
}
public function get mouseManager() : MouseManager
{
return _mouseManager;
}
/**
* The signal executed when the viewport is resized.
* Callback functions for this signal should accept the following
* arguments:
* <ul>
* <li>viewport : Viewport, the viewport executing the signal</li>
* <li>width : Number, the new width of the viewport</li>
* <li>height : Number, the new height of the viewport</li>
* </ul>
* @return
*
*/
public function get resized() : Signal
{
return _resized;
}
/**
* The background color of the display area. This value must use the
* RGB format.
* @return
*
*/
public function get backgroundColor() : uint
{
return _backgroundColor;
}
public function set backgroundColor(value : uint) : void
{
_backgroundColor = value;
updateStage3D();
}
/**
* The anti-aliasing to use (0, 2, 4, 8 or 16). The actual anti-aliasing
* used for rendering depends on the hardware capabilities. If the specified
* anti-aliasing value is not supported, the value 0 will be used.
* @return
*
*/
public function get antiAliasing() : uint
{
return _antiAliasing;
}
public function set antiAliasing(value : uint) : void
{
_antiAliasing = value;
updateStage3D();
}
/**
* The driver informations provided by the Stage3D API.
*/
public function get driverInfo() : String
{
return _stage3d && _stage3d.context3D
? _stage3d.context3D.driverInfo
: null;
}
public function Viewport(antiAliasing : uint = 0,
width : uint = 0,
height : uint = 0)
{
_antiAliasing = antiAliasing;
if (width == 0 && height == 0)
_autoResize = true;
_width = width;
_height = height;
initialize();
}
private function initialize() : void
{
_mouseManager.bind(this);
addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
addEventListener(Event.REMOVED_FROM_STAGE, removedFromStageHandler);
}
private function addedToStageHandler(event : Event) : void
{
_keyboardManager.bind(stage);
parent.addEventListener(Event.RESIZE, parentResizedHandler);
stage.addEventListener(Event.ADDED_TO_STAGE, displayObjectAddedToStageHandler);
stage.addEventListener(Event.REMOVED_FROM_STAGE, displayObjectRemovedFromStageHandler);
setupOnStage(stage);
}
private function removedFromStageHandler(event : Event) : void
{
_keyboardManager.unbind(stage);
parent.removeEventListener(Event.RESIZE, parentResizedHandler);
stage.removeEventListener(Event.ADDED_TO_STAGE, displayObjectAddedToStageHandler);
stage.removeEventListener(Event.REMOVED_FROM_STAGE, displayObjectRemovedFromStageHandler);
if (_stage3d != null)
_stage3d.visible = false;
}
private function setupOnStage(stage : Stage, stage3dId : uint = 0) : void
{
if (_autoResize)
{
_width = stage.stageWidth;
_height = stage.stageHeight;
}
if (!_stage3d)
{
_stage3d = stage.stage3Ds[stage3dId];
_stage3d.addEventListener(Event.CONTEXT3D_CREATE, context3dCreatedHandler);
_stage3d.requestContext3D();
}
else
{
_stage3d.visible = true;
}
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
}
/**
* Dispose the Viewport and all the Stage3D related objects. After this operation,
* the Viewport cannot be used anymore and is ready for garbage collection.
*/
public function dispose():void
{
if (_stage3d != null)
{
_stage3d.removeEventListener(Event.CONTEXT3D_CREATE, context3dCreatedHandler);
_stage3d = null;
}
if (_context3d != null)
{
_context3d.dispose();
_context3d = null;
}
return ;
}
/**
* Resize the display area. The "resized" signal is executed when the new width and
* height have be set.
* @param width
* @param height
*
*/
public function resize(width : Number, height : Number) : void
{
_autoResize = false;
setSize(width, height);
}
private function setSize(width : Number, height : Number) : void
{
if (width == _width && _height == height)
return ;
_width = width;
_height = height;
updateStage3D();
updateBackBuffer();
_resized.execute(this, width, height);
}
private function stageResizedHandler(event : Event) : void
{
updateMask();
}
private function parentResizedHandler(event : Event) : void
{
if (_autoResize)
{
if (parent == stage)
setSize(stage.stageWidth, stage.stageHeight);
else
setSize(parent.width, parent.height);
}
}
private function context3dCreatedHandler(event : Event) : void
{
_context3d = new Context3DResource(_stage3d.context3D);
updateStage3D();
updateBackBuffer();
dispatchEvent(new Event(Event.INIT));
}
private function updateBackBuffer() : void
{
if (_width == 0 || _height == 0 || _stage3d == null || _stage3d.context3D == null)
return ;
_invalidBackBuffer = false;
_stage3d.context3D.configureBackBuffer(_width, _height, _antiAliasing, true);
_backBuffer = new RenderTarget(_width, _height, null, 0, _backgroundColor);
graphics.clear();
graphics.beginFill(0, 0);
graphics.drawRect(0, 0, _width, _height);
}
private function updateStage3D() : void
{
if (_stage3d == null)
return ;
var upperLeft : Point = localToGlobal(ZERO2);
_stage3d.x = upperLeft.x;
_stage3d.y = upperLeft.y;
if (_width > 2048)
{
_stage3d.x = (_width - 2048) * 0.5;
_width = 2048;
}
else
_stage3d.x = upperLeft.x;
if (_height > 2048)
{
_stage3d.y = (_height - 2048) * 0.5;
_height = 2048;
}
else
_stage3d.y = upperLeft.y;
updateMask();
}
private function updateMask() : void
{
if (!stage)
return ;
var numChildren : uint = stage.numChildren;
var i : uint = 0;
if (_alwaysOnTop)
{
var gfx : Graphics = _mask.graphics;
var stageWidth : int = stage.stageWidth;
var stageHeight : int = stage.stageHeight;
gfx.clear();
gfx.beginFill(0);
gfx.moveTo(0, 0);
gfx.lineTo(stageWidth, 0);
gfx.lineTo(stageWidth, stageHeight);
gfx.lineTo(0., stageHeight);
gfx.lineTo(0, 0);
gfx.moveTo(_stage3d.x, _stage3d.y);
gfx.lineTo(_stage3d.x, _stage3d.y + height);
gfx.lineTo(_stage3d.x + width, _stage3d.y + height);
gfx.lineTo(_stage3d.x + width, _stage3d.y);
gfx.lineTo(_stage3d.x, _stage3d.y);
gfx.endFill();
for (i = 0; i < numChildren; ++i)
stage.getChildAt(i).mask = _mask;
}
else
{
for (i = 0; i < numChildren; ++i)
{
var child : DisplayObject = stage.getChildAt(i);
if (child.mask == _mask)
child.mask = null;
}
}
}
private function displayObjectAddedToStageHandler(event : Event) : void
{
var displayObject : DisplayObject = event.target as DisplayObject;
if (displayObject.parent == stage)
updateMask();
}
private function displayObjectRemovedFromStageHandler(event : Event) : void
{
var displayObject : DisplayObject = event.target as DisplayObject;
if (_autoResize && displayObject.parent == stage)
displayObject.mask = null;
}
}
}
|
remove stage events handling in Viewport made useless by drawing a transparent rectangle on top of the viewport
|
remove stage events handling in Viewport made useless by drawing a transparent rectangle on top of the viewport
|
ActionScript
|
mit
|
aerys/minko-as3
|
3c26c9daacc2676d671e37eecd46f4ff7387e31d
|
as3/src/br/com/yuiti/lab/infiniship/InfiniShip.as
|
as3/src/br/com/yuiti/lab/infiniship/InfiniShip.as
|
package br.com.yuiti.lab.infiniship
{
import flash.display.MovieClip;
import flash.display.Shape;
import flash.display.Sprite;
/**
* InfiniShip | AS3 :: A procedural spaceship generator
* ======================================================================
*
* This is a remake of Dave Bollinger's "Pixel Spaceships", remade and
* fully commented.
*
* I tried to organize things inside and comment/explain everything, but I'm
* a little bit bad with programming so, sorry if I messed up something.
*
* The original script was made for Processing, in 2006, by Dave. But this
* version has also used "mtheall" HTML5 Canvas (from 2013) version as reference
* for some structure and methods.
*
* This version is intended to work the same way as Bollinger's original script,
* and it tries to follow the same rules for the ship's cell grid.
*
* NOTE: Some of the creative output (images) generated by this script remains
* property of Dave Bollinger, as this script follows his basic concept. Even
* though the possible combination of ships is huge, Dave still has copyright
* over his artistic output, so use this carefully.
*
* You are welcome (and highly encouraged) to fork, remix, create your
* own way to generate sprites and use this as reference to build your own
* generator. :)
*
* @author Fabio Y. Goto <[email protected]>
*/
public class InfiniShip extends Sprite
{
/* PRIVATE VARIABLES
* ====================================================================== */
/**
* Empty cell flag.
*/
private var S_EMPTY:Number = 0;
/**
* Solid cell flag.
*/
private var S_SOLID:Number = 1;
/**
* Main body cell flag.
*/
private var S_SHAPE:Number = 2;
/**
* Cockpit cell flag.
*/
private var S_CABIN:Number = 3;
/**
* Ship width, in pixels.
*/
private var SHIP_W:Number = 12;
/**
* Ship height, in pixels.
*/
private var SHIP_H:Number = 12;
/**
* Array containing saturation values, to be used when defining colors.
*/
private var sats:Array = [
40, 60, 80, 100, 80, 60, 80, 100, 120, 100, 80, 60
];
/**
* Array containing brightness values, to be used when defining colors.
*/
private var bris:Array = [
40, 70, 100, 130, 160, 190, 220, 220, 190, 160, 130, 100, 70, 40
];
/**
* Array containing the cell data for body cells in the ship's sprite.
*
* Content defined inside the constructor.
*/
private var solidCell:Array;
/**
* Array containing the cell data for cockpit cells in the ship's sprite.
*
* Content defined inside the constructor.
*/
private var shapeCell:Array;
/**
* Array containing the cell data for cockpit cells in the ship's sprite.
*
* Content defined inside the constructor.
*/
private var cabinCell:Array;
/**
* Main ship array, used when generating the ship, to define the ship's cells.
*/
private var shipCell:Array;
/**
* Pseudo-random integer, to be used a seed when defining the ship's shape.
*
* Content defined inside the constructor.
*/
private var mainseed:Number;
/**
* Pseudo-random integer, to be used a seed when defining the ship's color.
*
* Content defined inside the constructor.
*/
private var clrsseed:Number;
/**
* Main ship containter.
*/
private var ship:Shape;
/**
* Main ship wrapper. This is the object that will be added to the stage.
*/
private var wrap:MovieClip;
/* CONSTRUCTOR
* ====================================================================== */
public function InfiniShip()
{
// Defining seeds
mainseed = generateSeed();
clrsseed = generateSeed();
// Defining cell data
solidCell = [
cell(5, 2), cell(5, 3), cell(5, 4),
cell(5, 5), cell(5, 9)
];
shapeCell = [
cell(4, 1), cell(5, 1), cell(4, 2), cell(3, 3), cell(4, 3),
cell(3, 4), cell(4, 4), cell(2, 5), cell(3, 5), cell(4, 5),
cell(1, 6), cell(2, 6), cell(3, 6), cell(1, 7), cell(2, 7),
cell(3, 7), cell(1, 8), cell(2, 8), cell(3, 8), cell(1, 9),
cell(2, 9), cell(3, 9), cell(4, 9), cell(3, 10), cell(4, 10),
cell(5, 10)
];
cabinCell = [
cell(4,6), cell(5,6), cell(4,7), cell(5,7),
cell(4,8), cell(5,8)
];
// Generating ship
generateShip();
}
/* SEED GENERATION AND NUMBER OPERATIONS
* ====================================================================== */
/**
* Calculates the pixel index value.
* @param x
* @param y
* @return
*/
private function cell(x:Number, y:Number):Number
{
return (y * SHIP_W) + x;
}
/**
* Generates the seeds for defining the ship's shape and color.
*
* It tries to use something similar to the original script's seed generator.
*
* @return
*/
private function generateSeed():Number
{
return Math.floor(Math.random() * 4 * 1024 * 1024 * 1024);
}
/**
* Converts a decimal number to its HEX counterpart.
*
* Restricted from 0 to 255, if input is lower than 0 it will be changed
* to 0, and if bigger than 255 will be changed to 255.
*
* @param nums
* @return
*/
private function dechex(nums:Number):String
{
// Checking if lower than 0 or bigger than 255
if (nums < 0) nums = 0;
if (nums > 255) nums = 255;
// Converting to string and returning
return nums.toString(16).toUpperCase();
}
/**
* Returns the array length (number of items inside).
*
* @param array
* @return
*/
private function countArray(array:Array):Number
{
var length:int = 0;
for (var i:* in array) length++;
return length;
}
/* COLORS
* ====================================================================== */
/**
* Converts the HSV (Hue, Saturation and Brightness) values from a color
* into its RGB counterpart, returning them in a formatted object, with its
* RGB values.
*
* @param h
* @param s
* @param v
* @return
*/
private function HSVRGB(h:Number, s:Number, v:Number):Number
{
// Declaring internal variables
var r:Number, g:Number, b:Number, i:Number, f:Number, p:Number,
q:Number, t:Number;
// If saturation equals 0, returns a shade of gray
if (s == 0) {
// Generating shade of gray for all RGB channels
var gray:String = dechex(Math.floor(v * 255));
// Returning values
return parseInt("0x" + gray + gray + gray);
}
// Defining color values
i = Math.floor(h * 6);
f = h * 6 - i;
p = v * (1 - s);
q = v * (1 - f * s);
t = v * (1 * (1 - f) * s);
// Defining RGB values5
switch (i % 6) {
case 1:
r = q;
g = v;
b = p;
break;
case 2:
r = p;
g = v;
b = t;
break;
case 3:
r = p;
g = q;
b = v;
break;
case 4:
r = t;
g = p;
b = v;
break;
case 5:
r = v;
g = p;
b = q;
break;
default:
r = v;
g = t;
b = p;
break;
}
// Returning color
return parseInt(
"0x"
+ dechex(Math.floor(r * 255))
+ dechex(Math.floor(g * 255))
+ dechex(Math.floor(b * 255))
);
}
/**
* Defines the colors for a determined pixel, on the ship's body. Returns
* it as an integer corresponding to the RGB values of the defined color.
*
* @param x
* @param y
* @return
*/
private function shapeColor(x:Number, y:Number):Number
{
// Defining saturation
var s:Number = sats[y] / 255.0;
// Defining brightness
var b:Number = bris[x] / 255.0;
// Defining hue
var h:Number;
if (y < 6) {
h = (clrsseed >> 8) & 0xFF;
} else if (y < 9) {
h = (clrsseed >> 16) & 0xFF;
} else {
h = (clrsseed >> 24) & 0xFF;
}
// Returning
return HSVRGB(360 * h / 256, s, b);
}
/**
* Defines the colors for a determined pixel, on the ship's cockpit. Returns
* it as an integer corresponding to the RGB values of the defined color.
*
* @param x
* @param y
* @return
*/
private function cabinColor(x:Number, y:Number):Number
{
// Defining saturation
var s:Number = sats[y] / 255.0;
// Defining brightness
var b:Number = (bris[x] + 40) / 255.0;
// Defining hue
var h:Number = clrsseed & 0xFF;
// Returning
return HSVRGB(360 * h / 256, s, b);
}
/* SHIP GENERATION
* ====================================================================== */
/**
* Generates a single ship and adds it to the stage.
*/
private function generateShip():void
{
// Initializing ship sprite
ship = new Shape();
// Initializing sprite wrapper
wrap = new MovieClip();
// Initializing ship cell array
shipCell = new Array();
// Marking all cells as empty, to start
var area:Number = SHIP_W * SHIP_H;
for (var i:Number = 0; i < area; i++) {
shipCell[i] = S_EMPTY;
}
// Initializing always solid cells
for (var i = 0; i < countArray(solidCell); ++i ) {
shipCell[solidCell[i]] = S_SOLID;
}
// Marking body cells
for (var i:Number = 0; i < countArray(shapeCell); ++i ) {
if ((mainseed & (1 << i)) > 0) {
shipCell[shapeCell[i]] = S_SHAPE;
} else {
shipCell[shapeCell[i]] = S_EMPTY;
}
}
// Marking the cockpit cells
for (var i:Number = 0; i < countArray(cabinCell); ++i ) {
if ((mainseed & (1 << (countArray(shapeCell) + 1))) > 0) {
shipCell[cabinCell[i]] = S_SOLID;
} else {
shipCell[cabinCell[i]] = S_CABIN;
}
}
// Defining border cells
for (var y:Number = 0; y < SHIP_H; ++y) {
for (var x:Number = 0; x < (SHIP_W / 2); ++x) {
// If the cell is a body cell
if (shipCell[cell(x, y)] == S_SHAPE) {
// Top
if (y > 0 && shipCell[cell(x, y - 1)] == S_EMPTY) {
shipCell[cell(x, y - 1)] = S_SOLID;
}
// Left
if (x > 0 && shipCell[cell(x - 1, y)] == S_EMPTY) {
shipCell[cell(x - 1, y)] = S_SOLID;
}
// Right
if (
x < Math.floor(SHIP_W / 2) - 1
&& shipCell[cell(x + 1, y)] == S_EMPTY
) {
shipCell[cell(x + 1, y)] = S_SOLID;
}
// Bottom
if (y < SHIP_H && shipCell[cell(x, y + 1)] == S_EMPTY) {
shipCell[cell(x, y + 1)] = S_SOLID;
}
}
}
}
// Drawing the pixels inside the shape object
for (var y:Number = 0; y < SHIP_H; ++y) {
for (var x:Number = 0; x < (SHIP_W / 2); ++x) {
// If the current cell isn't an empty cell
if (shipCell[cell(x, y)] != S_EMPTY) {
// Defining colors to paint the ship
if (shipCell[cell(x, y)] == S_SOLID) {
// Border/solid cell color
ship.graphics.beginFill(0x000000, 1);
} else if (shipCell[cell(x, y)] == S_SHAPE) {
// Defining body color
var tint:Number = shapeColor(x, y);
// Begin filling with the current color
ship.graphics.beginFill(tint, 1);
} else if (shipCell[cell(x, y)] == S_CABIN) {
// Defining cockpit color
var tint:Number = cabinColor(x, y);
// Begin filling with the current color
ship.graphics.beginFill(tint, 1);
}
// Drawing the pixel
ship.graphics.drawRect(x, y, 1, 1);
// Drawing the mirrored pixel
ship.graphics.drawRect(SHIP_W - x - 1, y, 1, 1);
}
}
}
// Wrapping the ship and adjusting position (centering in x0, y0)
wrap.addChild(ship);
ship.x = -6;
ship.y = -6;
// Adding it to the stage
addChild(wrap);
}
}
}
|
package br.com.yuiti.lab.infiniship
{
import flash.display.MovieClip;
import flash.display.Shape;
import flash.display.Sprite;
/**
* InfiniShip | AS3 :: A procedural spaceship generator
* ======================================================================
*
* This is a remake of Dave Bollinger's "Pixel Spaceships", remade and
* fully commented.
*
* I tried to organize things inside and comment/explain everything, but I'm
* a little bit bad with programming so, sorry if I messed up something.
*
* The original script was made for Processing, in 2006, by Dave. But this
* version has also used "mtheall" HTML5 Canvas (from 2013) version as reference
* for some structure and methods.
*
* This version is intended to work the same way as Bollinger's original script,
* and it tries to follow the same rules for the ship's cell grid.
*
* NOTE: Some of the creative output (images) generated by this script remains
* property of Dave Bollinger, as this script follows his basic concept. Even
* though the possible combination of ships is huge, Dave still has copyright
* over his artistic output, so use this carefully.
*
* You are welcome (and highly encouraged) to fork, remix, create your
* own way to generate sprites and use this as reference to build your own
* generator. :)
*
* @author Fabio Y. Goto <[email protected]>
*/
public class InfiniShip extends Sprite
{
/* PRIVATE VARIABLES
* ====================================================================== */
/**
* Empty cell flag.
*/
private var S_EMPTY:Number = 0;
/**
* Solid cell flag.
*/
private var S_SOLID:Number = 1;
/**
* Main body cell flag.
*/
private var S_SHAPE:Number = 2;
/**
* Cockpit cell flag.
*/
private var S_CABIN:Number = 3;
/**
* Ship width, in pixels.
*/
private var SHIP_W:Number = 12;
/**
* Ship height, in pixels.
*/
private var SHIP_H:Number = 12;
/**
* Array containing saturation values, to be used when defining colors.
*/
private var sats:Array = [
40, 60, 80, 100, 80, 60, 80, 100, 120, 100, 80, 60
];
/**
* Array containing brightness values, to be used when defining colors.
*/
private var bris:Array = [
40, 70, 100, 130, 160, 190, 220, 220, 190, 160, 130, 100, 70, 40
];
/**
* Array containing the cell data for body cells in the ship's sprite.
*
* Content defined inside the constructor.
*/
private var solidCell:Array;
/**
* Array containing the cell data for cockpit cells in the ship's sprite.
*
* Content defined inside the constructor.
*/
private var shapeCell:Array;
/**
* Array containing the cell data for cockpit cells in the ship's sprite.
*
* Content defined inside the constructor.
*/
private var cabinCell:Array;
/**
* Main ship array, used when generating the ship, to define the ship's cells.
*/
private var shipCell:Array;
/**
* Pseudo-random integer, to be used a seed when defining the ship's shape.
*
* Content defined inside the constructor.
*/
private var mainseed:Number;
/**
* Pseudo-random integer, to be used a seed when defining the ship's color.
*
* Content defined inside the constructor.
*/
private var clrsseed:Number;
/**
* Main ship containter.
*/
private var ship:Shape;
/**
* Main ship wrapper. This is the object that will be added to the stage.
*/
private var wrap:MovieClip;
/* CONSTRUCTOR
* ====================================================================== */
public function InfiniShip()
{
// Defining seeds
mainseed = generateSeed();
clrsseed = generateSeed();
// Defining cell data
solidCell = [
cell(5, 2), cell(5, 3), cell(5, 4),
cell(5, 5), cell(5, 9)
];
shapeCell = [
cell(4, 1), cell(5, 1), cell(4, 2), cell(3, 3), cell(4, 3),
cell(3, 4), cell(4, 4), cell(2, 5), cell(3, 5), cell(4, 5),
cell(1, 6), cell(2, 6), cell(3, 6), cell(1, 7), cell(2, 7),
cell(3, 7), cell(1, 8), cell(2, 8), cell(3, 8), cell(1, 9),
cell(2, 9), cell(3, 9), cell(4, 9), cell(3, 10), cell(4, 10),
cell(5, 10)
];
cabinCell = [
cell(4,6), cell(5,6), cell(4,7), cell(5,7),
cell(4,8), cell(5,8)
];
// Generating ship
generateShip();
}
/* SEED GENERATION AND NUMBER OPERATIONS
* ====================================================================== */
/**
* Calculates the pixel index value.
* @param x
* @param y
* @return
*/
private function cell(x:Number, y:Number):Number
{
return (y * SHIP_W) + x;
}
/**
* Generates the seeds for defining the ship's shape and color.
*
* It tries to use something similar to the original script's seed generator.
*
* @return
*/
private function generateSeed():Number
{
return Math.floor(Math.random() * 4 * 1024 * 1024 * 1024);
}
/**
* Converts a decimal number to its HEX counterpart.
*
* Restricted from 0 to 255, if input is lower than 0 it will be changed
* to 0, and if bigger than 255 will be changed to 255.
*
* @param nums
* @return
*/
private function dechex(nums:Number):String
{
// Checking if lower than 0 or bigger than 255
if (nums < 0) nums = 0;
if (nums > 255) nums = 255;
// Converting to string and returning
return nums.toString(16).toUpperCase();
}
/**
* Returns the array length (number of items inside).
*
* @param array
* @return
*/
private function countArray(array:Array):Number
{
var length:int = 0;
for (var i:* in array) length++;
return length;
}
/* COLORS
* ====================================================================== */
/**
* Converts the HSV (Hue, Saturation and Brightness) values from a color
* into its RGB counterpart, returning them in a formatted object, with its
* RGB values.
*
* @param h
* @param s
* @param v
* @return
*/
private function HSVRGB(h:Number, s:Number, v:Number):Number
{
// Declaring internal variables
var r:Number, g:Number, b:Number, i:Number, f:Number, p:Number,
q:Number, t:Number;
// If saturation equals 0, returns a shade of gray
if (s == 0) {
// Generating shade of gray for all RGB channels
var gray:String = dechex(Math.floor(v * 255));
// Returning values
return parseInt("0x" + gray + gray + gray);
}
// Defining color values
i = Math.floor(h * 6);
f = h * 6 - i;
p = v * (1 - s);
q = v * (1 - f * s);
t = v * (1 * (1 - f) * s);
// Defining RGB values5
switch (i % 6) {
case 1:
r = q;
g = v;
b = p;
break;
case 2:
r = p;
g = v;
b = t;
break;
case 3:
r = p;
g = q;
b = v;
break;
case 4:
r = t;
g = p;
b = v;
break;
case 5:
r = v;
g = p;
b = q;
break;
default:
r = v;
g = t;
b = p;
break;
}
// Returning color
return parseInt(
"0x"
+ dechex(Math.floor(r * 255))
+ dechex(Math.floor(g * 255))
+ dechex(Math.floor(b * 255))
);
}
/**
* Defines the colors for a determined pixel, on the ship's body. Returns
* it as an integer corresponding to the RGB values of the defined color.
*
* @param x
* @param y
* @return
*/
private function shapeColor(x:Number, y:Number):Number
{
// Defining saturation
var s:Number = sats[y] / 255.0;
// Defining brightness
var b:Number = bris[x] / 255.0;
// Defining hue
var h:Number;
if (y < 6) {
h = (clrsseed >> 8) & 0xFF;
} else if (y < 9) {
h = (clrsseed >> 16) & 0xFF;
} else {
h = (clrsseed >> 24) & 0xFF;
}
// Returning
return HSVRGB(360 * h / 256, s, b);
}
/**
* Defines the colors for a determined pixel, on the ship's cockpit. Returns
* it as an integer corresponding to the RGB values of the defined color.
*
* @param x
* @param y
* @return
*/
private function cabinColor(x:Number, y:Number):Number
{
// Defining saturation
var s:Number = sats[y] / 255.0;
// Defining brightness
var b:Number = (bris[x] + 40) / 255.0;
// Defining hue
var h:Number = clrsseed & 0xFF;
// Returning
return HSVRGB(360 * h / 256, s, b);
}
/* SHIP GENERATION
* ====================================================================== */
/**
* Generates a single ship and adds it to the stage.
*/
private function generateShip():void
{
// Initializing ship sprite
ship = new Shape();
// Initializing sprite wrapper
wrap = new MovieClip();
// Initializing ship cell array
shipCell = new Array();
// Marking all cells as empty, to start
var area:Number = SHIP_W * SHIP_H;
for (var i:Number = 0; i < area; i++) {
shipCell[i] = S_EMPTY;
}
// Initializing always solid cells
for (var i = 0; i < countArray(solidCell); ++i ) {
shipCell[solidCell[i]] = S_SOLID;
}
// Marking body cells
for (var i:Number = 0; i < countArray(shapeCell); ++i ) {
if ((mainseed & (1 << i)) > 0) {
shipCell[shapeCell[i]] = S_SHAPE;
} else {
shipCell[shapeCell[i]] = S_EMPTY;
}
}
// Marking the cockpit cells
for (var i:Number = 0; i < countArray(cabinCell); ++i ) {
if ((mainseed & (1 << (countArray(shapeCell) + i))) > 0) {
shipCell[cabinCell[i]] = S_SOLID;
} else {
shipCell[cabinCell[i]] = S_CABIN;
}
}
// Defining border cells
for (var y:Number = 0; y < SHIP_H; ++y) {
for (var x:Number = 0; x < (SHIP_W / 2); ++x) {
// If the cell is a body cell
if (shipCell[cell(x, y)] == S_SHAPE) {
// Top
if (y > 0 && shipCell[cell(x, y - 1)] == S_EMPTY) {
shipCell[cell(x, y - 1)] = S_SOLID;
}
// Left
if (x > 0 && shipCell[cell(x - 1, y)] == S_EMPTY) {
shipCell[cell(x - 1, y)] = S_SOLID;
}
// Right
if (
x < Math.floor(SHIP_W / 2) - 1
&& shipCell[cell(x + 1, y)] == S_EMPTY
) {
shipCell[cell(x + 1, y)] = S_SOLID;
}
// Bottom
if (y < SHIP_H && shipCell[cell(x, y + 1)] == S_EMPTY) {
shipCell[cell(x, y + 1)] = S_SOLID;
}
}
}
}
// Drawing the pixels inside the shape object
for (var y:Number = 0; y < SHIP_H; ++y) {
for (var x:Number = 0; x < (SHIP_W / 2); ++x) {
// If the current cell isn't an empty cell
if (shipCell[cell(x, y)] != S_EMPTY) {
// Defining colors to paint the ship
if (shipCell[cell(x, y)] == S_SOLID) {
// Border/solid cell color
ship.graphics.beginFill(0x000000, 1);
} else if (shipCell[cell(x, y)] == S_SHAPE) {
// Defining body color
var tint:Number = shapeColor(x, y);
// Begin filling with the current color
ship.graphics.beginFill(tint, 1);
} else if (shipCell[cell(x, y)] == S_CABIN) {
// Defining cockpit color
var tint:Number = cabinColor(x, y);
// Begin filling with the current color
ship.graphics.beginFill(tint, 1);
}
// Drawing the pixel
ship.graphics.drawRect(x, y, 1, 1);
// Drawing the mirrored pixel
ship.graphics.drawRect(SHIP_W - x - 1, y, 1, 1);
}
}
}
// Wrapping the ship and adjusting position (centering in x0, y0)
wrap.addChild(ship);
ship.x = -6;
ship.y = -6;
// Adding it to the stage
addChild(wrap);
}
}
}
|
Update InfiniShip.as
|
Update InfiniShip.as
|
ActionScript
|
mit
|
yuigoto/infiniship,yuigoto/infiniship
|
71d8736700b241e06b9f18135ef23efb0545ae80
|
application/src/im/siver/logger/controllers/TraceController.as
|
application/src/im/siver/logger/controllers/TraceController.as
|
package im.siver.logger.controllers {
import flash.display.BitmapData;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.MouseEvent;
import flash.geom.Rectangle;
import im.siver.logger.models.Constants;
import im.siver.logger.utils.LoggerUtils;
import im.siver.logger.views.components.Filter;
import im.siver.logger.views.components.panels.TracePanel;
import im.siver.logger.views.components.windows.SnapshotWindow;
import im.siver.logger.views.components.windows.TraceWindow;
import mx.collections.ArrayCollection;
import mx.events.CollectionEvent;
import mx.events.FlexEvent;
import mx.events.ListEvent;
import mx.utils.StringUtil;
public final class TraceController extends EventDispatcher {
[Bindable]
private var _dataFilterd:ArrayCollection = new ArrayCollection();
private var _data:ArrayCollection = new ArrayCollection();
private var _panel:TracePanel;
private var _send:Function;
/**
* Save panel
*/
public function TraceController(panel:TracePanel, send:Function) {
_panel = panel;
_send = send;
_panel.addEventListener(FlexEvent.CREATION_COMPLETE, creationComplete, false, 0, true);
}
private function collectionDidChange(e:CollectionEvent):void {
if (_panel.autoScrollButton.selected) {
_panel.datagrid.validateNow();
_panel.datagrid.verticalScrollPosition = _panel.datagrid.maxVerticalScrollPosition;
}
}
/**
* Panel is ready to link data providers
*/
private function creationComplete(e:FlexEvent):void {
_panel.removeEventListener(FlexEvent.CREATION_COMPLETE, creationComplete);
_panel.datagrid.dataProvider = _dataFilterd;
_panel.datagrid.addEventListener(ListEvent.ITEM_DOUBLE_CLICK, showTrace, false, 0, true);
_panel.filter.addEventListener(Filter.CHANGED, filterChanged, false, 0, true);
_panel.clearButton.addEventListener(MouseEvent.CLICK, clear, false, 0, true);
_dataFilterd.addEventListener(CollectionEvent.COLLECTION_CHANGE, collectionDidChange, false, 0, true);
}
/**
* Show a trace in an output window
*/
private function filterChanged(event:Event):void {
_dataFilterd.removeAll();
// Check if a filter term is given
if (_panel.filter.words.length == 0) {
for (var i:int = 0; i < _data.length; i++) {
_dataFilterd.addItem(_data[i]);
}
return;
}
for (var n:int = 0; n < _data.length; n++) {
if (checkFilter(_data[n])) {
_dataFilterd.addItem(_data[n]);
}
}
}
private function addItem(item:Object):void {
if (_panel.filter.words.length == 0) {
_dataFilterd.addItem(item);
return;
}
if (checkFilter(item)) {
_dataFilterd.addItem(item);
}
}
/**
* Loop through the search terms and compare strings
*/
private function checkFilter(item:Object):Boolean {
var message:String = item.message;
var target:String = item.target;
var label:String = item.label;
var person:String = item.person;
if (message == null) message = "";
if (target == null) target = "";
if (label == null) label = "";
if (person == null) person = "";
message = StringUtil.trim(message).toLowerCase();
target = StringUtil.trim(target).toLowerCase();
label = StringUtil.trim(label).toLowerCase();
person = StringUtil.trim(person).toLowerCase();
var i:int;
// Clone words
var words:Array = [];
for (i = 0; i < _panel.filter.words.length; i++) {
words[i] = _panel.filter.words[i];
}
if (message != "") {
for (i = 0; i < words.length; i++) {
if (message.indexOf(words[i]) != -1) {
words.splice(i, 1);
i--;
}
}
}
if (words.length == 0) return true;
if (target != "") {
for (i = 0; i < words.length; i++) {
if (target.indexOf(words[i]) != -1) {
words.splice(i, 1);
i--;
}
}
}
if (words.length == 0) return true;
if (label != "") {
for (i = 0; i < words.length; i++) {
if (label.indexOf(words[i]) != -1) {
words.splice(i, 1);
i--;
}
}
}
if (words.length == 0) return true;
if (person != "") {
for (i = 0; i < words.length; i++) {
if (person.indexOf(words[i]) != -1) {
words.splice(i, 1);
i--;
}
}
}
if (words.length == 0) return true;
return false;
}
/**
* Show a trace in an output window
*/
private function showTrace(event:ListEvent):void {
// Check if the selected item is still available
if (event.currentTarget.selectedItem != null) {
// Get the data
var item:Object = _dataFilterd.getItemAt(event.currentTarget.selectedIndex);
// Check the window to open
if (item.message == "Snapshot" && item.xml == null) {
var snapshotWindow:SnapshotWindow = new SnapshotWindow();
snapshotWindow.setData(item);
snapshotWindow.open();
} else {
var traceWindow:TraceWindow = new TraceWindow();
traceWindow.setData(item);
traceWindow.open();
}
}
}
/**
* Clear traces
*/
public function clear(event:MouseEvent = null):void {
_data.removeAll();
_dataFilterd.removeAll();
_panel.datagrid.horizontalScrollPosition = 0;
}
/**
* Data handler from client
*/
public function setData(data:Object):void {
// Vars for loop
var date:Date;
var hours:String;
var minutes:String;
var seconds:String;
var miliseconds:String;
var time:String;
var memory:String;
var traceItem:Object;
switch (data["command"]) {
case Constants.COMMAND_CLEAR_TRACES:
clear();
break;
case Constants.COMMAND_TRACE:
// Format the properties
date = data["date"];
time = zeroPad(date.getHours(), 2) + ":" + zeroPad(date.getMinutes(), 2) + ":" + zeroPad(date.getSeconds(), 2) + "." + zeroPad(date.getMilliseconds(), 3);
memory = Math.round(data["memory"] / 1024) + " Kb";
// Create the trace object
traceItem = {};
// Check the label
if (data["xml"]..node.length() > 1 && data["xml"]..node.length() <= 3) {
if (data["xml"].node[0].@type == Constants.TYPE_STRING || data["xml"].node[0].@type == Constants.TYPE_BOOLEAN || data["xml"].node[0].@type == Constants.TYPE_NUMBER || data["xml"].node[0].@type == Constants.TYPE_INT || data["xml"].node[0].@type == Constants.TYPE_UINT) {
traceItem.message = LoggerUtils.stripBreaks(LoggerUtils.htmlUnescape(data["xml"].node.children()[0].@label));
} else {
traceItem.message = LoggerUtils.stripBreaks(LoggerUtils.htmlUnescape(data["xml"].node.@label)) + " ...";
}
} else {
traceItem.message = LoggerUtils.stripBreaks(LoggerUtils.htmlUnescape(data["xml"].node.@label)) + " ...";
}
// Clean target
if (data['target'].indexOf('object') != -1) {
traceItem.target = String(data['target']).replace('object ', '');
} else {
traceItem.target = data["target"];
}
// Add extra info
traceItem.line = _data.length + 1;
traceItem.time = time;
traceItem.memory = memory;
traceItem.reference = data["reference"];
traceItem.label = data["label"];
traceItem.person = data["person"];
traceItem.color = data["color"];
traceItem.xml = data["xml"];
// Add to list
_data.addItem(traceItem);
addItem(traceItem);
break;
case Constants.COMMAND_SNAPSHOT:
// Format the properties
date = data["date"];
hours = (date.getHours() < 10) ? "0" + date.getHours().toString() : date.getHours().toString();
minutes = (date.getMinutes() < 10) ? "0" + date.getMinutes().toString() : date.getMinutes().toString();
seconds = (date.getSeconds() < 10) ? "0" + date.getSeconds().toString() : date.getSeconds().toString();
miliseconds = date.getMilliseconds().toString();
time = hours + ":" + minutes + ":" + seconds + "." + miliseconds;
memory = Math.round(data["memory"] / 1024) + " Kb";
// Read the bitmap
try {
var bitmapData:BitmapData = new BitmapData(data["width"], data["height"]);
bitmapData.setPixels(new Rectangle(0, 0, data["width"], data["height"]), data["bytes"]);
} catch (e:Error) {
return;
}
// Create the trace object
traceItem = {};
traceItem.line = _data.length + 1;
traceItem.time = time;
traceItem.memory = memory;
traceItem.width = data["width"];
traceItem.height = data["height"];
traceItem.bitmapData = bitmapData;
traceItem.message = "Snapshot";
traceItem.target = data["target"];
traceItem.label = data["label"];
traceItem.person = data["person"];
traceItem.color = data["color"];
traceItem.xml = null;
// Add to list
_data.addItem(traceItem);
addItem(traceItem);
break;
}
}
private function zeroPad(value:int, length:int, pad:String = '0'):String {
var result:String = String(value);
while (result.length < length) {
result = pad + result;
}
return result;
}
}
}
|
package im.siver.logger.controllers {
import flash.display.BitmapData;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.MouseEvent;
import flash.geom.Rectangle;
import im.siver.logger.models.Constants;
import im.siver.logger.utils.LoggerUtils;
import im.siver.logger.views.components.Filter;
import im.siver.logger.views.components.panels.TracePanel;
import im.siver.logger.views.components.windows.SnapshotWindow;
import im.siver.logger.views.components.windows.TraceWindow;
import mx.collections.ArrayCollection;
import mx.events.CollectionEvent;
import mx.events.FlexEvent;
import mx.events.ListEvent;
import mx.utils.StringUtil;
public final class TraceController extends EventDispatcher {
[Bindable]
private var _dataFilterd:ArrayCollection = new ArrayCollection();
private var _data:ArrayCollection = new ArrayCollection();
private var _panel:TracePanel;
private var _send:Function;
/**
* Save panel
*/
public function TraceController(panel:TracePanel, send:Function) {
_panel = panel;
_send = send;
_panel.addEventListener(FlexEvent.CREATION_COMPLETE, creationComplete, false, 0, true);
}
private function collectionDidChange(e:CollectionEvent):void {
if (_panel.autoScrollButton.selected) {
_panel.datagrid.validateNow();
_panel.datagrid.verticalScrollPosition = _panel.datagrid.maxVerticalScrollPosition;
}
}
/**
* Panel is ready to link data providers
*/
private function creationComplete(e:FlexEvent):void {
_panel.removeEventListener(FlexEvent.CREATION_COMPLETE, creationComplete);
_panel.datagrid.dataProvider = _dataFilterd;
_panel.datagrid.addEventListener(ListEvent.ITEM_DOUBLE_CLICK, showTrace, false, 0, true);
_panel.filter.addEventListener(Filter.CHANGED, filterChanged, false, 0, true);
_panel.clearButton.addEventListener(MouseEvent.CLICK, clear, false, 0, true);
_dataFilterd.addEventListener(CollectionEvent.COLLECTION_CHANGE, collectionDidChange, false, 0, true);
}
/**
* Show a trace in an output window
*/
private function filterChanged(event:Event):void {
// Check if a filter term is given
if (_panel.filter.words.length == 0) {
_dataFilterd.filterFunction = null;
_dataFilterd.refresh();
} else {
_dataFilterd.filterFunction = checkFilter;
_dataFilterd.refresh();
}
}
private function addItem(item:Object):void {
_dataFilterd.addItem(item);
}
private function simpleFilter(item:Object):Boolean {
return false;
}
/**
* Loop through the search terms and compare strings
*/
private function checkFilter(item:Object):Boolean {
var message:String = item.message;
var target:String = item.target;
var label:String = item.label;
var person:String = item.person;
if (message == null) message = "";
if (target == null) target = "";
if (label == null) label = "";
if (person == null) person = "";
message = StringUtil.trim(message).toLowerCase();
target = StringUtil.trim(target).toLowerCase();
label = StringUtil.trim(label).toLowerCase();
person = StringUtil.trim(person).toLowerCase();
var i:int;
// Clone words
var words:Array = [];
for (i = 0; i < _panel.filter.words.length; i++) {
words[i] = _panel.filter.words[i];
}
if (message != "") {
for (i = 0; i < words.length; i++) {
if (message.indexOf(words[i]) != -1) {
words.splice(i, 1);
i--;
}
}
}
if (words.length == 0) return true;
if (target != "") {
for (i = 0; i < words.length; i++) {
if (target.indexOf(words[i]) != -1) {
words.splice(i, 1);
i--;
}
}
}
if (words.length == 0) return true;
if (label != "") {
for (i = 0; i < words.length; i++) {
if (label.indexOf(words[i]) != -1) {
words.splice(i, 1);
i--;
}
}
}
if (words.length == 0) return true;
if (person != "") {
for (i = 0; i < words.length; i++) {
if (person.indexOf(words[i]) != -1) {
words.splice(i, 1);
i--;
}
}
}
if (words.length == 0) return true;
return false;
}
/**
* Show a trace in an output window
*/
private function showTrace(event:ListEvent):void {
// Check if the selected item is still available
if (event.currentTarget.selectedItem != null) {
// Get the data
var item:Object = _dataFilterd.getItemAt(event.currentTarget.selectedIndex);
// Check the window to open
if (item.message == "Snapshot" && item.xml == null) {
var snapshotWindow:SnapshotWindow = new SnapshotWindow();
snapshotWindow.setData(item);
snapshotWindow.open();
} else {
var traceWindow:TraceWindow = new TraceWindow();
traceWindow.setData(item);
traceWindow.open();
}
}
}
/**
* Clear traces
*/
public function clear(event:MouseEvent = null):void {
_data.removeAll();
_dataFilterd.removeAll();
_panel.datagrid.horizontalScrollPosition = 0;
}
/**
* Data handler from client
*/
public function setData(data:Object):void {
// Vars for loop
var date:Date;
var hours:String;
var minutes:String;
var seconds:String;
var miliseconds:String;
var time:String;
var memory:String;
var traceItem:Object;
switch (data["command"]) {
case Constants.COMMAND_CLEAR_TRACES:
clear();
break;
case Constants.COMMAND_TRACE:
// Format the properties
date = data["date"];
time = zeroPad(date.getHours(), 2) + ":" + zeroPad(date.getMinutes(), 2) + ":" + zeroPad(date.getSeconds(), 2) + "." + zeroPad(date.getMilliseconds(), 3);
memory = Math.round(data["memory"] / 1024) + " Kb";
// Create the trace object
traceItem = {};
// Check the label
if (data["xml"]..node.length() > 1 && data["xml"]..node.length() <= 3) {
if (data["xml"].node[0].@type == Constants.TYPE_STRING || data["xml"].node[0].@type == Constants.TYPE_BOOLEAN || data["xml"].node[0].@type == Constants.TYPE_NUMBER || data["xml"].node[0].@type == Constants.TYPE_INT || data["xml"].node[0].@type == Constants.TYPE_UINT) {
traceItem.message = LoggerUtils.stripBreaks(LoggerUtils.htmlUnescape(data["xml"].node.children()[0].@label));
} else {
traceItem.message = LoggerUtils.stripBreaks(LoggerUtils.htmlUnescape(data["xml"].node.@label)) + " ...";
}
} else {
traceItem.message = LoggerUtils.stripBreaks(LoggerUtils.htmlUnescape(data["xml"].node.@label)) + " ...";
}
// Clean target
if (data['target'].indexOf('object') != -1) {
traceItem.target = String(data['target']).replace('object ', '');
} else {
traceItem.target = data["target"];
}
// Add extra info
traceItem.line = _data.length + 1;
traceItem.time = time;
traceItem.memory = memory;
traceItem.reference = data["reference"];
traceItem.label = data["label"];
traceItem.person = data["person"];
traceItem.color = data["color"];
traceItem.xml = data["xml"];
// Add to list
_data.addItem(traceItem);
addItem(traceItem);
break;
case Constants.COMMAND_SNAPSHOT:
// Format the properties
date = data["date"];
hours = (date.getHours() < 10) ? "0" + date.getHours().toString() : date.getHours().toString();
minutes = (date.getMinutes() < 10) ? "0" + date.getMinutes().toString() : date.getMinutes().toString();
seconds = (date.getSeconds() < 10) ? "0" + date.getSeconds().toString() : date.getSeconds().toString();
miliseconds = date.getMilliseconds().toString();
time = hours + ":" + minutes + ":" + seconds + "." + miliseconds;
memory = Math.round(data["memory"] / 1024) + " Kb";
// Read the bitmap
try {
var bitmapData:BitmapData = new BitmapData(data["width"], data["height"]);
bitmapData.setPixels(new Rectangle(0, 0, data["width"], data["height"]), data["bytes"]);
} catch (e:Error) {
return;
}
// Create the trace object
traceItem = {};
traceItem.line = _data.length + 1;
traceItem.time = time;
traceItem.memory = memory;
traceItem.width = data["width"];
traceItem.height = data["height"];
traceItem.bitmapData = bitmapData;
traceItem.message = "Snapshot";
traceItem.target = data["target"];
traceItem.label = data["label"];
traceItem.person = data["person"];
traceItem.color = data["color"];
traceItem.xml = null;
// Add to list
_data.addItem(traceItem);
addItem(traceItem);
break;
}
}
private function zeroPad(value:int, length:int, pad:String = '0'):String {
var result:String = String(value);
while (result.length < length) {
result = pad + result;
}
return result;
}
}
}
|
Use of native filter
|
Use of native filter
|
ActionScript
|
mit
|
NicolasSiver/as3-logger
|
ad3c79e3028a1736d7034f5b0e2105d1bbc55987
|
Game/Resources/elevatorScene/Scripts/LightsOutScript.as
|
Game/Resources/elevatorScene/Scripts/LightsOutScript.as
|
class LightsOutScript {
Hub @hub;
Entity @self;
Entity @board;
Entity @rightController;
array<Entity@> buttons(25);
array<bool> buttonStates(25);
int numPressedButtons = 0;
bool gameWon = false;
bool isPressed = false;
LightsOutScript(Entity @entity){
@hub = Managers();
@self = @entity;
@board = GetEntityByGUID(1511530025);
@rightController = GetEntityByGUID(1508919758);
for (int row = 0; row < 5; ++row) {
for (int column = 0; column < 5; ++column) {
Entity @btn = board.GetChild("btn-" + row + "-" + column);
@buttons[row * 5 + column] = btn.GetChild("btn-" + row + "-" + column).GetChild("button");
buttonStates[row * 5 + column] = false;
}
}
RegisterUpdate();
}
void Update(float deltaTime) {
if (isPressed && !Input(Trigger, rightController)) {
isPressed = false;
}
}
void Toggle(int index) {
bool pressed = !buttonStates[index];
buttonStates[index] = pressed;
if (pressed) {
buttons[index].position.x = -0.06f;
numPressedButtons += 1;
} else {
buttons[index].position.x = 0.0f;
numPressedButtons -= 1;
}
}
bool IsValid(int index) {
return index >= 0 && index <= 24;
}
// Index goes first row 0 -> 4, second row 5 -> 9 etc.
void ButtonPress(int index) {
if (gameWon) {
return;
}
if (!isPressed && Input(Trigger, rightController)) {
isPressed = true;
int left = index - 1;
if (index % 5 != 0 && IsValid(left)) {
Toggle(left);
}
int right = index + 1;
if (index % 5 != 4 && IsValid(right)) {
Toggle(right);
}
int up = index - 5;
if (index > 4 && IsValid(up)) {
Toggle(up);
}
int down = index + 5;
if (index < 20 && IsValid(down)) {
Toggle(down);
}
Toggle(index);
if (numPressedButtons == 25) {
gameWon = true;
//SendMessage(somewhere);
print("Won the game of lights out.\n");
}
}
}
void b_0_0() {
ButtonPress(0);
}
void b_0_1() {
ButtonPress(1);
}
void b_0_2() {
ButtonPress(2);
}
void b_0_3() {
ButtonPress(3);
}
void b_0_4() {
ButtonPress(4);
}
void b_1_0() {
ButtonPress(5);
}
void b_1_1() {
ButtonPress(6);
}
void b_1_2() {
ButtonPress(7);
}
void b_1_3() {
ButtonPress(8);
}
void b_1_4() {
ButtonPress(9);
}
void b_2_0() {
ButtonPress(10);
}
void b_2_1() {
ButtonPress(11);
}
void b_2_2() {
ButtonPress(12);
}
void b_2_3() {
ButtonPress(13);
}
void b_2_4() {
ButtonPress(14);
}
void b_3_0() {
ButtonPress(15);
}
void b_3_1() {
ButtonPress(16);
}
void b_3_2() {
ButtonPress(17);
}
void b_3_3() {
ButtonPress(18);
}
void b_3_4() {
ButtonPress(19);
}
void b_4_0() {
ButtonPress(20);
}
void b_4_1() {
ButtonPress(21);
}
void b_4_2() {
ButtonPress(22);
}
void b_4_3() {
ButtonPress(23);
}
void b_4_4() {
ButtonPress(24);
}
}
|
class LightsOutScript {
Entity @board;
Entity @rightController;
array<Entity@> buttons(25);
array<bool> buttonStates(25);
int numPressedButtons = 0;
bool gameWon = false;
bool isPressed = false;
LightsOutScript(Entity @entity){
@board = GetEntityByGUID(1511530025);
@rightController = GetEntityByGUID(1508919758);
for (int row = 0; row < 5; ++row) {
for (int column = 0; column < 5; ++column) {
Entity @btn = board.GetChild("btn-" + row + "-" + column);
@buttons[row * 5 + column] = btn.GetChild("btn-" + row + "-" + column).GetChild("button");
buttonStates[row * 5 + column] = false;
}
}
RegisterUpdate();
}
void Update(float deltaTime) {
if (isPressed && !Input(Trigger, rightController)) {
isPressed = false;
}
}
void Toggle(int index) {
bool pressed = !buttonStates[index];
buttonStates[index] = pressed;
if (pressed) {
buttons[index].position.x = -0.06f;
numPressedButtons += 1;
} else {
buttons[index].position.x = 0.0f;
numPressedButtons -= 1;
}
}
bool IsValid(int index) {
return index >= 0 && index <= 24;
}
// Index goes first row 0 -> 4, second row 5 -> 9 etc.
void ButtonPress(int index) {
if (gameWon) {
return;
}
if (!isPressed && Input(Trigger, rightController)) {
isPressed = true;
int left = index - 1;
if (index % 5 != 0 && IsValid(left)) {
Toggle(left);
}
int right = index + 1;
if (index % 5 != 4 && IsValid(right)) {
Toggle(right);
}
int up = index - 5;
if (index > 4 && IsValid(up)) {
Toggle(up);
}
int down = index + 5;
if (index < 20 && IsValid(down)) {
Toggle(down);
}
Toggle(index);
if (numPressedButtons == 25) {
gameWon = true;
//SendMessage(somewhere);
print("Won the game of lights out.\n");
}
}
}
void b_0_0() {
ButtonPress(0);
}
void b_0_1() {
ButtonPress(1);
}
void b_0_2() {
ButtonPress(2);
}
void b_0_3() {
ButtonPress(3);
}
void b_0_4() {
ButtonPress(4);
}
void b_1_0() {
ButtonPress(5);
}
void b_1_1() {
ButtonPress(6);
}
void b_1_2() {
ButtonPress(7);
}
void b_1_3() {
ButtonPress(8);
}
void b_1_4() {
ButtonPress(9);
}
void b_2_0() {
ButtonPress(10);
}
void b_2_1() {
ButtonPress(11);
}
void b_2_2() {
ButtonPress(12);
}
void b_2_3() {
ButtonPress(13);
}
void b_2_4() {
ButtonPress(14);
}
void b_3_0() {
ButtonPress(15);
}
void b_3_1() {
ButtonPress(16);
}
void b_3_2() {
ButtonPress(17);
}
void b_3_3() {
ButtonPress(18);
}
void b_3_4() {
ButtonPress(19);
}
void b_4_0() {
ButtonPress(20);
}
void b_4_1() {
ButtonPress(21);
}
void b_4_2() {
ButtonPress(22);
}
void b_4_3() {
ButtonPress(23);
}
void b_4_4() {
ButtonPress(24);
}
}
|
Remove unused variables in the lights out script.
|
Remove unused variables in the lights out script.
|
ActionScript
|
mit
|
Chainsawkitten/LargeGameProjectEngine,Chainsawkitten/LargeGameProjectEngine
|
d70b65f00d676ee1c8063d0ba3d78df7ae64bcc8
|
assets/scripts/input/play_state.as
|
assets/scripts/input/play_state.as
|
void move_forward_begin() {
auto player = get_entity(player_id);
auto player_state = player.get_state_component();
if (player_state.current_state() != "run") {
player_state.change_state("run");
}
player.get_character_physics_component().velocity(3.f);
}
void move_forward_end() {
auto player = get_entity(player_id);
auto player_state = player.get_state_component();
if (player_state.current_state() == "run") {
player_state.change_state("stand");
player.get_character_physics_component().velocity(0.f);
}
}
void move_backward_begin() {
auto player = get_entity(player_id);
auto player_state = player.get_state_component();
if (player_state.current_state() != "walk_backward") {
player_state.change_state("walk_backward");
}
player.get_character_physics_component().velocity(-1.f);
}
void move_backward_end() {
auto player = get_entity(player_id);
auto player_state = player.get_state_component();
if (player_state.current_state() == "walk_backward") {
player_state.change_state("stand");
player.get_character_physics_component().velocity(0.f);
}
}
void move_right_begin() {
auto player = get_entity(player_id);
player.get_character_physics_component().angular_velocity(-1.0f);
if (player.get_state_component().current_state() == "stand") {
if (!player.get_animation_component().is_playing("turn_right")) {
player.get_animation_component().play_ani("turn_right");
}
}
}
void move_right_end() {
auto player = get_entity(player_id);
player.get_character_physics_component().angular_velocity(0.0f);
if (player.get_state_component().current_state() == "stand") {
player.get_animation_component().play_ani("stand");
}
}
void move_left_begin() {
auto player = get_entity(player_id);
player.get_character_physics_component().angular_velocity(1.0f);
if (player.get_state_component().current_state() == "stand") {
if (!player.get_animation_component().is_playing("turn_right")) {
player.get_animation_component().play_ani("turn_right");
}
}
}
void move_left_end() {
auto player = get_entity(player_id);
player.get_character_physics_component().angular_velocity(0.0f);
if (player.get_state_component().current_state() == "stand") {
player.get_animation_component().play_ani("stand");
}
}
void stand_begin() {
auto player = get_entity(player_id);
auto player_state = player.get_state_component();
if (player_state.current_state() != "stand") {
player_state.change_state("stand");
}
}
|
#include "../../assets/scripts/entities/light_cube.as"
void move_forward_begin() {
auto player = get_entity(player_id);
auto player_state = player.get_state_component();
if (player_state.current_state() != "run") {
player_state.change_state("run");
}
player.get_character_physics_component().velocity(3.f);
}
void move_forward_end() {
auto player = get_entity(player_id);
auto player_state = player.get_state_component();
if (player_state.current_state() == "run") {
player_state.change_state("stand");
player.get_character_physics_component().velocity(0.f);
}
}
void move_backward_begin() {
auto player = get_entity(player_id);
auto player_state = player.get_state_component();
if (player_state.current_state() != "walk_backward") {
player_state.change_state("walk_backward");
}
player.get_character_physics_component().velocity(-1.f);
}
void move_backward_end() {
auto player = get_entity(player_id);
auto player_state = player.get_state_component();
if (player_state.current_state() == "walk_backward") {
player_state.change_state("stand");
player.get_character_physics_component().velocity(0.f);
}
}
void move_right_begin() {
auto player = get_entity(player_id);
player.get_character_physics_component().angular_velocity(-1.0f);
if (player.get_state_component().current_state() == "stand") {
if (!player.get_animation_component().is_playing("turn_right")) {
player.get_animation_component().play_ani("turn_right");
}
}
}
void move_right_end() {
auto player = get_entity(player_id);
player.get_character_physics_component().angular_velocity(0.0f);
if (player.get_state_component().current_state() == "stand") {
player.get_animation_component().play_ani("stand");
}
}
void move_left_begin() {
auto player = get_entity(player_id);
player.get_character_physics_component().angular_velocity(1.0f);
if (player.get_state_component().current_state() == "stand") {
if (!player.get_animation_component().is_playing("turn_right")) {
player.get_animation_component().play_ani("turn_right");
}
}
}
void move_left_end() {
auto player = get_entity(player_id);
player.get_character_physics_component().angular_velocity(0.0f);
if (player.get_state_component().current_state() == "stand") {
player.get_animation_component().play_ani("stand");
}
}
void stand_begin() {
auto player = get_entity(player_id);
auto player_state = player.get_state_component();
if (player_state.current_state() != "stand") {
player_state.change_state("stand");
}
}
void throw_light_begin() {
auto player = get_entity(player_id);
glm::vec3 direction = player.get_character_physics_component().direction();
glm::vec3 position = player.position();
light_cube lc(position + direction * 2.f, player.rotation());
lc.impl().get_physics_component().apply_central_impulse((direction + glm::vec3(0.f, 0.2f, 0.f)) * 5.f);
}
void throw_light_end() {
}
|
add input callback for throwing light cubes with spaces
|
add input callback for throwing light cubes with spaces
|
ActionScript
|
mit
|
kasoki/project-zombye,kasoki/project-zombye,kasoki/project-zombye
|
aefd1089a53dfa96766c747fa6e15250f7051ab7
|
bin/otp.replace.as
|
bin/otp.replace.as
|
#!/bin/bash -e
# ========================================================================
# Copyright (c) 2015-2017 T. R. Burghart.
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
# ========================================================================
#
# Build and install/replace an OTP instance from source.
#
readonly sdir="$(cd "$(dirname "$0")" && pwd)"
readonly sname="${0##*/}"
readonly spath="$sdir/$sname"
readonly makejobs='5'
readonly verbosity="${V:-0}"
usage()
{
echo "Usage: $sname [-h{0|1|2}] otp-name-or-path otp-inst-label" >&2
exit 1
}
case "$1" in
'-h0' )
hipe_modes='false'
shift
;;
'-h1' )
hipe_modes='true'
shift
;;
'-h2' )
hipe_modes='false true'
shift
;;
* )
unset hipe_modes
;;
esac
[[ $# -eq 2 ]] || usage
[[ "$2" != */* ]] || usage
readonly otp_name="${2}"
case "$1" in
*/* )
otp_src_dir="$1"
;;
. )
otp_src_dir="$(pwd)"
;;
.. )
otp_src_dir="$(dirname "$(pwd)")"
;;
* )
if [[ -d "$1" ]]
then
otp_src_dir="$1"
else
otp_src_dir="$BASHO_PRJ_BASE/$1"
fi
;;
esac
kerl_deactivate 2>/dev/null || true
reset_lenv 2>/dev/null || true
cd "$otp_src_dir"
readonly otp_src_dir="$(pwd)"
unset ERL_TOP ERL_LIBS MAKEFLAGS V
unset EXCLUDE_OSX_RT_VERS_FLAG
for n in \
os.type \
otp.install.base \
otp.source.base \
otp.source.version \
env.tool.defaults \
otp.config.opts
do
. "$LOCAL_ENV_DIR/$n" || exit $?
done
if [[ -n "$hipe_modes" ]]
then
if [[ " $hipe_modes " == *\ true\ * ]] && ! $otp_hipe_supported
then
echo HiPE is not supported on this Release/Platform >&2
exit 1
fi
elif $otp_hipe_supported
then
hipe_modes='false true'
else
hipe_modes='false'
fi
ERL_TOP="$(pwd)"
[[ "$PATH" == "$ERL_TOP/bin":* ]] || PATH="$ERL_TOP/bin:$PATH"
export ERL_TOP PATH
case " $otp_config_opts " in
*\ --with-odbc[\ =]*)
;;
*\ --without-odbc\ *)
;;
*)
otp_config_opts+=' --without-odbc'
;;
esac
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 $otp_config_opts $hipe_flag"
build_log="build.$os_type.$otp_label.txt"
docs_log="docs.$os_type.$otp_label.txt"
install_log="install.$os_type.$otp_label.txt"
$GIT clean -fdqx -e /env -e /.idea/ -e '*.iml' -e '/*.txt' \
|| $GIT clean -f -f -dqx -e /env -e /.idea/ -e '*.iml' -e '/*.txt' \
|| true
[[ $makejobs -lt 2 ]] || export MAKEFLAGS="-j$makejobs"
[[ $verbosity -lt 1 ]] || export V="$verbosity"
printf 'commit:\t' >"$build_log"
$GIT show-ref --heads --head --hash | head -1 >>"$build_log"
/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
/bin/rm -rf "$otp_dest/bin" "$otp_dest/lib" "$otp_dest/index.html"
else
/bin/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"
$ECP "$build_log" "$install_log" "$otp_dest"
[[ -e "$otp_dest/activate" ]] || \
ln -s "$LOCAL_ENV_DIR/otp.activate" "$otp_dest/activate"
if [[ "$otp_install_base/otp-$otp_src_vsn_major" -ef "$otp_dest" ]]
then
# run this before installing QuickCheck - no debug info in EQC beams
echo "otp.gen.plt $otp_label" | tee -a "$install_log"
otp.gen.plt "$otp_label" 1>>"$install_log" 2>&1
echo "/opt/QuickCheck/install_qc $otp_dest" | tee -a "$install_log"
if ! /opt/QuickCheck/install_qc "$otp_dest" 1>>"$install_log" 2>&1
then
echo 'Failed to install QuickCheck into' "$otp_dest" >&2
fi
/bin/date >>"$install_log"
$ECP "$install_log" "$otp_dest"
/bin/date >"$docs_log"
echo "$MAKE docs install-docs" | tee -a "$docs_log"
$MAKE docs install-docs 1>>"$docs_log" 2>&1
echo "otp.gen.doc.index $otp_label" | tee -a "$docs_log"
otp.gen.doc.index "$otp_label" >>"$docs_log"
/bin/date >>"$docs_log"
$ECP $docs_log "$otp_dest"
fi
done
|
#!/bin/bash -e
# ========================================================================
# Copyright (c) 2015-2017 T. R. Burghart.
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
# ========================================================================
#
# Build and install/replace an OTP instance from source.
#
readonly sdir="$(cd "$(dirname "$0")" && pwd)"
readonly sname="${0##*/}"
readonly spath="$sdir/$sname"
readonly makejobs='5'
readonly verbosity="${V:-0}"
usage()
{
echo "Usage: $sname [-h{0|1|2}] otp-name-or-path otp-inst-label" >&2
exit 1
}
case "$1" in
'-h0' )
hipe_modes='false'
shift
;;
'-h1' )
hipe_modes='true'
shift
;;
'-h2' )
hipe_modes='false true'
shift
;;
* )
unset hipe_modes
;;
esac
[[ $# -eq 2 ]] || usage
[[ "$2" != */* ]] || usage
readonly otp_name="${2}"
case "$1" in
*/* )
otp_src_dir="$1"
;;
. )
otp_src_dir="$(pwd)"
;;
.. )
otp_src_dir="$(dirname "$(pwd)")"
;;
* )
if [[ -d "$1" ]]
then
otp_src_dir="$1"
else
otp_src_dir="$BASHO_PRJ_BASE/$1"
fi
;;
esac
kerl_deactivate 2>/dev/null || true
reset_lenv 2>/dev/null || true
cd "$otp_src_dir"
readonly otp_src_dir="$(pwd)"
unset ERL_TOP ERL_LIBS MAKEFLAGS V
unset EXCLUDE_OSX_RT_VERS_FLAG
for n in \
os.type \
otp.install.base \
otp.source.base \
otp.source.version \
env.tool.defaults \
otp.config.opts
do
. "$LOCAL_ENV_DIR/$n" || exit $?
done
if [[ -n "$hipe_modes" ]]
then
if [[ " $hipe_modes " == *\ true\ * ]] && ! $otp_hipe_supported
then
echo HiPE is not supported on this Release/Platform >&2
exit 1
fi
elif $otp_hipe_supported
then
hipe_modes='false true'
else
hipe_modes='false'
fi
ERL_TOP="$(pwd)"
[[ "$PATH" == "$ERL_TOP/bin":* ]] || PATH="$ERL_TOP/bin:$PATH"
export ERL_TOP PATH
case " $otp_config_opts " in
*\ --with-odbc[\ =]*)
;;
*\ --without-odbc\ *)
;;
*)
otp_config_opts+=' --without-odbc'
;;
esac
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 $otp_config_opts $hipe_flag"
build_log="build.$os_type.$otp_label.txt"
docs_log="docs.$os_type.$otp_label.txt"
install_log="install.$os_type.$otp_label.txt"
$GIT clean -fdqx -e /env -e /.idea/ -e '*.iml' -e '/*.txt' \
|| $GIT clean -f -f -dqx -e /env -e /.idea/ -e '*.iml' -e '/*.txt' \
|| true
[[ $makejobs -lt 2 ]] || export MAKEFLAGS="-j$makejobs"
[[ $verbosity -lt 1 ]] || export V="$verbosity"
printf 'commit:\t' >"$build_log"
$GIT show-ref --heads --head --hash | head -1 >>"$build_log"
/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
/bin/rm -rf "$otp_dest/bin" "$otp_dest/lib" "$otp_dest/index.html"
else
/bin/mkdir -m 2775 "$otp_dest"
fi
/bin/date >"$install_log"
echo "$MAKE install" | tee -a "$install_log"
$MAKE install 1>>"$install_log" 2>&1
if [[ $otp_src_vsn_major -ge 20 && ! -f "$otp_dest/bin/rebar3" ]]
then
echo "Installing $otp_dest/bin/rebar3" >>"$install_log"
wget -O "$otp_dest/bin/rebar3" 'https://s3.amazonaws.com/rebar3/rebar3'
/bin/chmod +x "$otp_dest/bin/rebar3"
fi
/bin/date >>"$install_log"
$ECP "$build_log" "$install_log" "$otp_dest"
[[ -e "$otp_dest/activate" ]] || \
ln -s "$LOCAL_ENV_DIR/otp.activate" "$otp_dest/activate"
if [[ "$otp_install_base/otp-$otp_src_vsn_major" -ef "$otp_dest" ]]
then
# run this before installing QuickCheck - no debug info in EQC beams
echo "otp.gen.plt $otp_label" | tee -a "$install_log"
otp.gen.plt "$otp_label" 1>>"$install_log" 2>&1
echo "/opt/QuickCheck/install_qc $otp_dest" | tee -a "$install_log"
if ! /opt/QuickCheck/install_qc "$otp_dest" 1>>"$install_log" 2>&1
then
echo 'Failed to install QuickCheck into' "$otp_dest" >&2
fi
/bin/date >>"$install_log"
$ECP "$install_log" "$otp_dest"
/bin/date >"$docs_log"
echo "$MAKE docs install-docs" | tee -a "$docs_log"
$MAKE docs install-docs 1>>"$docs_log" 2>&1
echo "otp.gen.doc.index $otp_label" | tee -a "$docs_log"
otp.gen.doc.index "$otp_label" >>"$docs_log"
/bin/date >>"$docs_log"
$ECP $docs_log "$otp_dest"
fi
done
|
install rebar3 to OTP-20+ bin directory
|
install rebar3 to OTP-20+ bin directory
|
ActionScript
|
isc
|
tburghart/local_env,tburghart/local_env
|
7a2af33efc04defeb1c75e6eda54834801f3680b
|
runtime/src/main/as/flump/display/LibraryLoader.as
|
runtime/src/main/as/flump/display/LibraryLoader.as
|
//
// Flump - Copyright 2013 Flump Authors
package flump.display {
import flash.utils.ByteArray;
import flump.executor.Executor;
import flump.executor.Future;
import starling.core.Starling;
/**
* Loads zip files created by the flump exporter and parses them into Library instances.
*/
public class LibraryLoader
{
/**
* Loads a Library from the zip in the given bytes.
*
* @param bytes The bytes containing the zip
*
* @param executor The executor on which the loading should run. If not specified, it'll run on
* a new single-use executor.
*
* @param scaleFactor the desired scale factor of the textures to load. If the Library contains
* textures with multiple scale factors, loader will load the textures with the scale factor
* closest to this value. If scaleFactor <= 0 (the default), Starling.contentScaleFactor will be
* used.
*
* @return a Future to use to track the success or failure of loading the resources out of the
* bytes. If the loading succeeds, the Future's onSuccess will fire with an instance of
* Library. If it fails, the Future's onFail will fire with the Error that caused the
* loading failure.
*/
public static function loadBytes (bytes :ByteArray, executor :Executor=null, scaleFactor :Number=-1) :Future {
return (executor || new Executor(1)).submit(new Loader(bytes, scaleFactor).load);
}
/**
* Loads a Library from the zip at the given url.
*
* @param bytes The url where the zip can be found
*
* @param executor The executor on which the loading should run. If not specified, it'll run on
* a new single-use executor.
*
* @param scaleFactor the desired scale factor of the textures to load. If the Library contains
* textures with multiple scale factors, loader will load the textures with the scale factor
* closest to this value. If scaleFactor <= 0 (the default), Starling.contentScaleFactor will be
* used.
*
* @return a Future to use to track the success or failure of loading the resources from the
* url. If the loading succeeds, the Future's onSuccess will fire with an instance of
* Library. If it fails, the Future's onFail will fire with the Error that caused the
* loading failure.
*/
public static function loadURL (url :String, executor :Executor=null, scaleFactor :Number=-1) :Future {
return (executor || new Executor(1)).submit(new Loader(url, scaleFactor).load);
}
/** @private */
public static const LIBRARY_LOCATION :String = "library.json";
/** @private */
public static const MD5_LOCATION :String = "md5";
/** @private */
public static const VERSION_LOCATION :String = "version";
/**
* @private
* The version produced and parsable by this version of the code. The version in a resources
* zip must equal the version compiled into the parsing code for parsing to succeed.
*/
public static const VERSION :String = "2";
}
}
import deng.fzip.FZip;
import deng.fzip.FZipErrorEvent;
import deng.fzip.FZipEvent;
import deng.fzip.FZipFile;
import flash.events.Event;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import flump.display.Library;
import flump.display.LibraryLoader;
import flump.display.Movie;
import flump.executor.Executor;
import flump.executor.Future;
import flump.executor.FutureTask;
import flump.executor.load.ImageLoader;
import flump.executor.load.LoadedImage;
import flump.mold.AtlasMold;
import flump.mold.AtlasTextureMold;
import flump.mold.LibraryMold;
import flump.mold.MovieMold;
import flump.mold.TextureGroupMold;
import starling.core.Starling;
import starling.display.DisplayObject;
import starling.display.Image;
import starling.textures.Texture;
interface SymbolCreator
{
function create (library :Library) :DisplayObject;
}
class LibraryImpl
implements Library
{
public function LibraryImpl (baseTextures :Vector.<Texture>, creators :Dictionary) {
_baseTextures = baseTextures;
_creators = creators;
}
public function createMovie (symbol :String) :Movie {
return Movie(createDisplayObject(symbol));
}
public function createImage (symbol :String) :Image {
const disp :DisplayObject = createDisplayObject(symbol);
if (disp is Movie) throw new Error(symbol + " is not an Image");
return Image(disp);
}
public function getImageTexture (symbol :String) :Texture {
checkNotDisposed();
var creator :SymbolCreator = requireSymbolCreator(symbol);
if (!(creator is ImageCreator)) throw new Error(symbol + " is not an Image");
return ImageCreator(creator).texture;
}
public function get movieSymbols () :Vector.<String> {
checkNotDisposed();
const names :Vector.<String> = new <String>[];
for (var creatorName :String in _creators) {
if (_creators[creatorName] is MovieCreator) names.push(creatorName);
}
return names;
}
public function get imageSymbols () :Vector.<String> {
checkNotDisposed();
const names :Vector.<String> = new <String>[];
for (var creatorName :String in _creators) {
if (_creators[creatorName] is ImageCreator) names.push(creatorName);
}
return names;
}
public function createDisplayObject (name :String) :DisplayObject {
checkNotDisposed();
return requireSymbolCreator(name).create(this);
}
public function dispose () :void {
checkNotDisposed();
for each (var tex :Texture in _baseTextures) {
tex.dispose();
}
_baseTextures = null;
_creators = null;
}
protected function requireSymbolCreator (name :String) :SymbolCreator {
var creator :SymbolCreator = _creators[name];
if (creator == null) throw new Error("No such id '" + name + "'");
return creator;
}
protected function checkNotDisposed () :void {
if (_baseTextures == null) {
throw new Error("This Library has been disposed");
}
}
protected var _creators :Dictionary;
protected var _baseTextures :Vector.<Texture>;
}
class Loader
{
public function Loader (toLoad :Object, scaleFactor :Number) {
_scaleFactor = (scaleFactor > 0 ? scaleFactor : Starling.contentScaleFactor);
_toLoad = toLoad;
}
public function load (future :FutureTask) :void {
_future = future;
_zip.addEventListener(Event.COMPLETE, _future.monitoredCallback(onZipLoadingComplete));
_zip.addEventListener(FZipErrorEvent.PARSE_ERROR, _future.fail);
_zip.addEventListener(FZipEvent.FILE_LOADED, _future.monitoredCallback(onFileLoaded));
if (_toLoad is String) _zip.load(new URLRequest(String(_toLoad)));
else _zip.loadBytes(ByteArray(_toLoad));
}
protected function onFileLoaded (e :FZipEvent) :void {
const loaded :FZipFile = _zip.removeFileAt(_zip.getFileCount() - 1);
const name :String = loaded.filename;
if (name == LibraryLoader.LIBRARY_LOCATION) {
const jsonString :String = loaded.content.readUTFBytes(loaded.content.length);
_lib = LibraryMold.fromJSON(JSON.parse(jsonString));
} else if (name.indexOf(PNG, name.length - PNG.length) != -1) {
_pngBytes[name] = loaded.content;
} else if (name == LibraryLoader.VERSION_LOCATION) {
const zipVersion :String = loaded.content.readUTFBytes(loaded.content.length)
if (zipVersion != LibraryLoader.VERSION) {
throw new Error("Zip is version " + zipVersion + " but the code needs " + LibraryLoader.VERSION);
}
_versionChecked = true;
} else if (name == LibraryLoader.MD5_LOCATION ) { // Nothing to verify
} else {} // ignore unknown files
}
protected function onZipLoadingComplete (..._) :void {
_zip = null;
if (_lib == null) throw new Error(LibraryLoader.LIBRARY_LOCATION + " missing from zip");
if (!_versionChecked) throw new Error(LibraryLoader.VERSION_LOCATION + " missing from zip");
const loader :ImageLoader = new ImageLoader();
_pngLoaders.terminated.add(_future.monitoredCallback(onPngLoadingComplete));
// Determine the scale factor we want to use
var textureGroup :TextureGroupMold = _lib.bestTextureGroupForScaleFactor(_scaleFactor);
if (textureGroup != null) {
for each (var atlas :AtlasMold in textureGroup.atlases) {
loadAtlas(loader, atlas);
}
}
_pngLoaders.shutdown();
}
protected function loadAtlas (loader :ImageLoader, atlas :AtlasMold) :void {
const pngBytes :* = _pngBytes[atlas.file];
if (pngBytes === undefined) {
throw new Error("Expected an atlas '" + atlas.file + "', but it wasn't in the zip");
}
const atlasFuture :Future = loader.loadFromBytes(pngBytes, _pngLoaders);
atlasFuture.failed.add(onPngLoadingFailed);
atlasFuture.succeeded.add(function (img :LoadedImage) :void {
var scale :Number = atlas.scaleFactor;
const baseTexture :Texture = Texture.fromBitmapData(
img.bitmapData,
false, // generateMipMaps
false, // optimizeForRenderToTexture
scale);
_baseTextures.push(baseTexture);
if (!Starling.handleLostContext) {
img.bitmapData.dispose();
}
for each (var atlasTexture :AtlasTextureMold in atlas.textures) {
var bounds :Rectangle = atlasTexture.bounds;
var offset :Point = atlasTexture.origin;
// Starling expects subtexture bounds to be unscaled
if (scale != 1) {
bounds = bounds.clone();
bounds.x /= scale;
bounds.y /= scale;
bounds.width /= scale;
bounds.height /= scale;
offset = offset.clone();
offset.x /= scale;
offset.y /= scale;
}
_creators[atlasTexture.symbol] = new ImageCreator(
Texture.fromTexture(baseTexture, bounds),
offset,
atlasTexture.symbol);
}
});
}
protected function onPngLoadingComplete (..._) :void {
for each (var movie :MovieMold in _lib.movies) {
movie.fillLabels();
_creators[movie.id] = new MovieCreator(movie, _lib.frameRate);
}
_future.succeed(new LibraryImpl(_baseTextures, _creators));
}
protected function onPngLoadingFailed (e :*) :void {
if (_future.isComplete) return;
_future.fail(e);
_pngLoaders.shutdownNow();
}
protected var _toLoad :Object;
protected var _scaleFactor :Number;
protected var _future :FutureTask;
protected var _versionChecked :Boolean;
protected var _zip :FZip = new FZip();
protected var _lib :LibraryMold;
protected const _baseTextures :Vector.<Texture> = new <Texture>[];
protected const _creators :Dictionary = new Dictionary();//<name, ImageCreator/MovieCreator>
protected const _pngBytes :Dictionary = new Dictionary();//<String name, ByteArray>
protected const _pngLoaders :Executor = new Executor(1);
protected static const PNG :String = ".png";
}
class ImageCreator
implements SymbolCreator
{
public var texture :Texture;
public var origin :Point;
public var symbol :String;
public function ImageCreator (texture :Texture, origin :Point, symbol :String) {
this.texture = texture;
this.origin = origin;
this.symbol = symbol;
}
public function create (library :Library) :DisplayObject {
const image :Image = new Image(texture);
image.pivotX = origin.x;
image.pivotY = origin.y;
image.name = symbol;
return image;
}
}
class MovieCreator
implements SymbolCreator
{
public var mold :MovieMold;
public var frameRate :Number;
public function MovieCreator (mold :MovieMold, frameRate :Number) {
this.mold = mold;
this.frameRate = frameRate;
}
public function create (library :Library) :DisplayObject {
return new Movie(mold, frameRate, library);
}
}
|
//
// Flump - Copyright 2013 Flump Authors
package flump.display {
import flash.utils.ByteArray;
import flump.executor.Executor;
import flump.executor.Future;
import starling.core.Starling;
/**
* Loads zip files created by the flump exporter and parses them into Library instances.
*/
public class LibraryLoader
{
/**
* Loads a Library from the zip in the given bytes.
*
* @param bytes The bytes containing the zip
*
* @param executor The executor on which the loading should run. If not specified, it'll run on
* a new single-use executor.
*
* @param scaleFactor the desired scale factor of the textures to load. If the Library contains
* textures with multiple scale factors, loader will load the textures with the scale factor
* closest to this value. If scaleFactor <= 0 (the default), Starling.contentScaleFactor will be
* used.
*
* @return a Future to use to track the success or failure of loading the resources out of the
* bytes. If the loading succeeds, the Future's onSuccess will fire with an instance of
* Library. If it fails, the Future's onFail will fire with the Error that caused the
* loading failure.
*/
public static function loadBytes (bytes :ByteArray, executor :Executor=null, scaleFactor :Number=-1) :Future {
return (executor || new Executor(1)).submit(new Loader(bytes, scaleFactor).load);
}
/**
* Loads a Library from the zip at the given url.
*
* @param bytes The url where the zip can be found
*
* @param executor The executor on which the loading should run. If not specified, it'll run on
* a new single-use executor.
*
* @param scaleFactor the desired scale factor of the textures to load. If the Library contains
* textures with multiple scale factors, loader will load the textures with the scale factor
* closest to this value. If scaleFactor <= 0 (the default), Starling.contentScaleFactor will be
* used.
*
* @return a Future to use to track the success or failure of loading the resources from the
* url. If the loading succeeds, the Future's onSuccess will fire with an instance of
* Library. If it fails, the Future's onFail will fire with the Error that caused the
* loading failure.
*/
public static function loadURL (url :String, executor :Executor=null, scaleFactor :Number=-1) :Future {
return (executor || new Executor(1)).submit(new Loader(url, scaleFactor).load);
}
/** @private */
public static const LIBRARY_LOCATION :String = "library.json";
/** @private */
public static const MD5_LOCATION :String = "md5";
/** @private */
public static const VERSION_LOCATION :String = "version";
/**
* @private
* The version produced and parsable by this version of the code. The version in a resources
* zip must equal the version compiled into the parsing code for parsing to succeed.
*/
public static const VERSION :String = "2";
}
}
import deng.fzip.FZip;
import deng.fzip.FZipErrorEvent;
import deng.fzip.FZipEvent;
import deng.fzip.FZipFile;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import flump.display.Library;
import flump.display.LibraryLoader;
import flump.display.Movie;
import flump.executor.Executor;
import flump.executor.Future;
import flump.executor.FutureTask;
import flump.executor.load.ImageLoader;
import flump.executor.load.LoadedImage;
import flump.mold.AtlasMold;
import flump.mold.AtlasTextureMold;
import flump.mold.LibraryMold;
import flump.mold.MovieMold;
import flump.mold.TextureGroupMold;
import starling.core.Starling;
import starling.display.DisplayObject;
import starling.display.Image;
import starling.textures.Texture;
interface SymbolCreator
{
function create (library :Library) :DisplayObject;
}
class LibraryImpl
implements Library
{
public function LibraryImpl (baseTextures :Vector.<Texture>, creators :Dictionary) {
_baseTextures = baseTextures;
_creators = creators;
}
public function createMovie (symbol :String) :Movie {
return Movie(createDisplayObject(symbol));
}
public function createImage (symbol :String) :Image {
const disp :DisplayObject = createDisplayObject(symbol);
if (disp is Movie) throw new Error(symbol + " is not an Image");
return Image(disp);
}
public function getImageTexture (symbol :String) :Texture {
checkNotDisposed();
var creator :SymbolCreator = requireSymbolCreator(symbol);
if (!(creator is ImageCreator)) throw new Error(symbol + " is not an Image");
return ImageCreator(creator).texture;
}
public function get movieSymbols () :Vector.<String> {
checkNotDisposed();
const names :Vector.<String> = new <String>[];
for (var creatorName :String in _creators) {
if (_creators[creatorName] is MovieCreator) names.push(creatorName);
}
return names;
}
public function get imageSymbols () :Vector.<String> {
checkNotDisposed();
const names :Vector.<String> = new <String>[];
for (var creatorName :String in _creators) {
if (_creators[creatorName] is ImageCreator) names.push(creatorName);
}
return names;
}
public function createDisplayObject (name :String) :DisplayObject {
checkNotDisposed();
return requireSymbolCreator(name).create(this);
}
public function dispose () :void {
checkNotDisposed();
for each (var tex :Texture in _baseTextures) {
tex.dispose();
}
_baseTextures = null;
_creators = null;
}
protected function requireSymbolCreator (name :String) :SymbolCreator {
var creator :SymbolCreator = _creators[name];
if (creator == null) throw new Error("No such id '" + name + "'");
return creator;
}
protected function checkNotDisposed () :void {
if (_baseTextures == null) {
throw new Error("This Library has been disposed");
}
}
protected var _creators :Dictionary;
protected var _baseTextures :Vector.<Texture>;
}
class Loader
{
public function Loader (toLoad :Object, scaleFactor :Number) {
_scaleFactor = (scaleFactor > 0 ? scaleFactor : Starling.contentScaleFactor);
_toLoad = toLoad;
}
public function load (future :FutureTask) :void {
_future = future;
_zip.addEventListener(Event.COMPLETE, _future.monitoredCallback(onZipLoadingComplete));
_zip.addEventListener(IOErrorEvent.IO_ERROR, _future.fail);
_zip.addEventListener(FZipErrorEvent.PARSE_ERROR, _future.fail);
_zip.addEventListener(FZipEvent.FILE_LOADED, _future.monitoredCallback(onFileLoaded));
if (_toLoad is String) _zip.load(new URLRequest(String(_toLoad)));
else _zip.loadBytes(ByteArray(_toLoad));
}
protected function onFileLoaded (e :FZipEvent) :void {
const loaded :FZipFile = _zip.removeFileAt(_zip.getFileCount() - 1);
const name :String = loaded.filename;
if (name == LibraryLoader.LIBRARY_LOCATION) {
const jsonString :String = loaded.content.readUTFBytes(loaded.content.length);
_lib = LibraryMold.fromJSON(JSON.parse(jsonString));
} else if (name.indexOf(PNG, name.length - PNG.length) != -1) {
_pngBytes[name] = loaded.content;
} else if (name == LibraryLoader.VERSION_LOCATION) {
const zipVersion :String = loaded.content.readUTFBytes(loaded.content.length)
if (zipVersion != LibraryLoader.VERSION) {
throw new Error("Zip is version " + zipVersion + " but the code needs " + LibraryLoader.VERSION);
}
_versionChecked = true;
} else if (name == LibraryLoader.MD5_LOCATION ) { // Nothing to verify
} else {} // ignore unknown files
}
protected function onZipLoadingComplete (..._) :void {
_zip = null;
if (_lib == null) throw new Error(LibraryLoader.LIBRARY_LOCATION + " missing from zip");
if (!_versionChecked) throw new Error(LibraryLoader.VERSION_LOCATION + " missing from zip");
const loader :ImageLoader = new ImageLoader();
_pngLoaders.terminated.add(_future.monitoredCallback(onPngLoadingComplete));
// Determine the scale factor we want to use
var textureGroup :TextureGroupMold = _lib.bestTextureGroupForScaleFactor(_scaleFactor);
if (textureGroup != null) {
for each (var atlas :AtlasMold in textureGroup.atlases) {
loadAtlas(loader, atlas);
}
}
_pngLoaders.shutdown();
}
protected function loadAtlas (loader :ImageLoader, atlas :AtlasMold) :void {
const pngBytes :* = _pngBytes[atlas.file];
if (pngBytes === undefined) {
throw new Error("Expected an atlas '" + atlas.file + "', but it wasn't in the zip");
}
const atlasFuture :Future = loader.loadFromBytes(pngBytes, _pngLoaders);
atlasFuture.failed.add(onPngLoadingFailed);
atlasFuture.succeeded.add(function (img :LoadedImage) :void {
var scale :Number = atlas.scaleFactor;
const baseTexture :Texture = Texture.fromBitmapData(
img.bitmapData,
false, // generateMipMaps
false, // optimizeForRenderToTexture
scale);
_baseTextures.push(baseTexture);
if (!Starling.handleLostContext) {
img.bitmapData.dispose();
}
for each (var atlasTexture :AtlasTextureMold in atlas.textures) {
var bounds :Rectangle = atlasTexture.bounds;
var offset :Point = atlasTexture.origin;
// Starling expects subtexture bounds to be unscaled
if (scale != 1) {
bounds = bounds.clone();
bounds.x /= scale;
bounds.y /= scale;
bounds.width /= scale;
bounds.height /= scale;
offset = offset.clone();
offset.x /= scale;
offset.y /= scale;
}
_creators[atlasTexture.symbol] = new ImageCreator(
Texture.fromTexture(baseTexture, bounds),
offset,
atlasTexture.symbol);
}
});
}
protected function onPngLoadingComplete (..._) :void {
for each (var movie :MovieMold in _lib.movies) {
movie.fillLabels();
_creators[movie.id] = new MovieCreator(movie, _lib.frameRate);
}
_future.succeed(new LibraryImpl(_baseTextures, _creators));
}
protected function onPngLoadingFailed (e :*) :void {
if (_future.isComplete) return;
_future.fail(e);
_pngLoaders.shutdownNow();
}
protected var _toLoad :Object;
protected var _scaleFactor :Number;
protected var _future :FutureTask;
protected var _versionChecked :Boolean;
protected var _zip :FZip = new FZip();
protected var _lib :LibraryMold;
protected const _baseTextures :Vector.<Texture> = new <Texture>[];
protected const _creators :Dictionary = new Dictionary();//<name, ImageCreator/MovieCreator>
protected const _pngBytes :Dictionary = new Dictionary();//<String name, ByteArray>
protected const _pngLoaders :Executor = new Executor(1);
protected static const PNG :String = ".png";
}
class ImageCreator
implements SymbolCreator
{
public var texture :Texture;
public var origin :Point;
public var symbol :String;
public function ImageCreator (texture :Texture, origin :Point, symbol :String) {
this.texture = texture;
this.origin = origin;
this.symbol = symbol;
}
public function create (library :Library) :DisplayObject {
const image :Image = new Image(texture);
image.pivotX = origin.x;
image.pivotY = origin.y;
image.name = symbol;
return image;
}
}
class MovieCreator
implements SymbolCreator
{
public var mold :MovieMold;
public var frameRate :Number;
public function MovieCreator (mold :MovieMold, frameRate :Number) {
this.mold = mold;
this.frameRate = frameRate;
}
public function create (library :Library) :DisplayObject {
return new Movie(mold, frameRate, library);
}
}
|
handle IO error failure
|
LibraryLoader: handle IO error failure
|
ActionScript
|
mit
|
mathieuanthoine/flump,funkypandagame/flump,tconkling/flump,tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump,funkypandagame/flump
|
6cf61bb4c8c1a068b7588029ae6079cf57a65e8f
|
flash/src/lambmei/starling/display/HandleSheet.as
|
flash/src/lambmei/starling/display/HandleSheet.as
|
package lambmei.starling.display
{
import flash.display.MovieClip;
import flash.geom.Point;
import flash.system.System;
import starling.display.Button;
import starling.display.DisplayObject;
import starling.display.DisplayObjectContainer;
import starling.display.Shape;
import starling.display.Sprite;
import starling.events.Event;
import starling.events.Touch;
import starling.events.TouchEvent;
import starling.events.TouchPhase;
import starling.textures.Texture;
import starling.utils.Line;
public class HandleSheet extends Sprite
{
/** 點擊 將物件移動到前方 **/
protected var _touchBringToFront:Boolean
public function get touchBringToFront():Boolean { return _touchBringToFront;}
public function set touchBringToFront(value:Boolean):void{ _touchBringToFront = value; }
/** 是否選擇 **/
protected var _selected:Boolean
public function get selected():Boolean { return _selected;}
public function set selected(value:Boolean):void
{
if(value!=_selected){
_selected = value;
_selectedGroup.visible = _selected
}
}
/** 是否有使用 控制按鈕 Read Only **/
protected var _useCtrlButton:Boolean
public function get useCtrlButton():Boolean
{
return _useCtrlButton;
}
// public function set useCtrlButton(value:Boolean):void
// {
// _useCtrlButton = value;
// }
//Const Vars
protected static const CTRL_BUTTON_NAME:String = "HandlectrlBtn"
public static const ALIGN_CENTER:String = "center"
public static const ALIGN_LT:String = "LT"
//UI
protected var _contents:DisplayObject
protected var _ctrlButton:DisplayObject
protected var _selectedGroup:Sprite
protected var _shape:Shape
public function HandleSheet(contents:DisplayObject=null)
{
addEventListener(TouchEvent.TOUCH, onTouch);
useHandCursor = true;
_touchBringToFront = true
if (contents)
{
var _w:Number = contents.width
var _h:Number = contents.height
var _halfW:Number = _w/2
var _halfH:Number= _h/2
//將物件置中
contents.x = int(_halfW * -1);
contents.y = int(_halfH * -1);
addChild(contents);
_contents = contents
}
//init SelectGroup
initSelectedGroup()
}
/** 初始化選擇的群組**/
protected function initSelectedGroup():void
{
_selectedGroup = new Sprite()
this.addChild(this._selectedGroup);
_shape = new Shape()
updateLine()
_selectedGroup.addChild(_shape)
_selectedGroup.visible = _selected
}
/**重新計算**/
protected function render(scale=1):void
{
updateLine(scale)
}
/**更新框線**/
protected function updateLine(scale=1):void
{
if(_contents && _shape){
_shape.graphics.lineStyle(10,0xFFffFF);
_shape.graphics.clear();
System.gc();
var _w:Number = _contents.width
var _h:Number = _contents.height
var _halfW:Number = _w/2
var _halfH:Number= _h/2
_shape.graphics.lineStyle(2 * scale,0xFFFFFF);
//_shape.graphics.drawRoundRect( -_halfW, -_halfH, _w, _h, 10 );
_shape.graphics.drawRect(-_halfW, -_halfH, _w, _h);
//trace("scale",scale)
}
}
public function setCtrlButtonInitByTexture(upTexture:Texture , downTexture:Texture = null ):void
{
_useCtrlButton = true
if ( upTexture !=null)
{
_ctrlButton = new Button(upTexture,"",downTexture);
setCtrlButtonInitByObject(_ctrlButton )
}else{
throw new ArgumentError("Texture is Null!")
}
}
/** 設定控制按鈕 by 物件 可以是 image sprite button **/
public function setCtrlButtonInitByObject( obj:DisplayObject ):void
{
_useCtrlButton = true
if (_contents)
{
_ctrlButton = obj
var _w:Number = _contents.width
var _h:Number = _contents.height
var _halfW:Number = _w/2
var _halfH:Number= _h/2
//放置右上角
_ctrlButton.x = int(_halfW)
_ctrlButton.y = - int(_halfH)
//置中對齊
_ctrlButton.x -= int(_ctrlButton.width/2)
_ctrlButton.y -= int(_ctrlButton.height/2)
_selectedGroup.addChild(_ctrlButton)
}
}
protected function onTouch(event:TouchEvent):void
{
var touches:Vector.<Touch> = event.getTouches(this, TouchPhase.MOVED);
var touch:Touch
touch = event.getTouch(this, TouchPhase.BEGAN);
onTouchBegan(touch)
//一隻手指
if (touches.length == 1)
{
//檢查是否是Ctrl
if(isTouchCtrlButton(event.target) )
{
resizeAndRotationByCtrlButton(touches)
}
else
{
//一隻手指平移
var delta:Point = touches[0].getMovement(parent);
x += delta.x;
y += delta.y;
}
}
else if (touches.length == 2)
{
//兩隻手指
resizeAndRotationByTwoFingers(touches)
}
touch = event.getTouch(this, TouchPhase.ENDED);
onTouchEnd(touch)
}
/**當touch開始**/
protected function onTouchBegan(touch:Touch):void
{
//touch 開始要做的事情
if(touch){
if(_touchBringToFront){
parent.addChild(this);
}
selected = true
}
}
/**當touch結束**/
protected function onTouchEnd(touch:Touch):void
{
}
/**檢查是否touch 控制按鈕**/
protected function isTouchCtrlButton(target:*):Boolean
{
var _do :DisplayObject
var _doc :DisplayObjectContainer
if(_ctrlButton is DisplayObjectContainer){
_doc = _ctrlButton as DisplayObjectContainer
return _doc.contains(target)
}
else if(_ctrlButton is DisplayObject)
{
_do = _ctrlButton as DisplayObject
return _do == target
}
return false
}
/** 單隻手指使用控制按鈕 放大縮小旋轉 **/
protected function resizeAndRotationByCtrlButton(touches:Vector.<Touch>):void
{
var touchA:Touch = touches[0];
var touchB:Touch = touchA.clone(); //模擬B點
var n:Point = touchA.getLocation(this);
//鏡射A點坐標
touchB.globalX = n.x * 1
touchB.globalY = n.y * -1
var currentPosA:Point = touchA.getLocation(this);
var previousPosA:Point = touchA.getPreviousLocation(this);
//鏡射A點
var currentPosB:Point = currentPosA.clone();
currentPosB.x *=-1;
currentPosB.y *=-1;
//鏡射A點
var previousPosB:Point = previousPosA.clone();
previousPosB.x *=-1;
previousPosB.y *=-1;
var currentVector:Point = currentPosA.subtract(currentPosB);
var previousVector:Point = previousPosA.subtract(previousPosB);
var currentAngle:Number = Math.atan2(currentVector.y, currentVector.x);
var previousAngle:Number = Math.atan2(previousVector.y, previousVector.x);
var deltaAngle:Number = currentAngle - previousAngle;
// rotate
rotation += deltaAngle;
// scale
var sizeDiff:Number = currentVector.length / previousVector.length;
scaleX *= sizeDiff;
scaleY *= sizeDiff;
//_ctrlButton 保持原比例
if(_ctrlButton){
_ctrlButton.scaleX /= sizeDiff
_ctrlButton.scaleY /= sizeDiff
}
render(_ctrlButton.scaleX)
}
/** 使用兩隻手指 使用放大縮小旋轉 保留官方功能 **/
protected function resizeAndRotationByTwoFingers(touches:Vector.<Touch>):void
{
//保留官方原本兩隻手指操作的功能
// two fingers touching -> rotate and scale
var touchA:Touch = touches[0];
var touchB:Touch = touches[1];
var currentPosA:Point = touchA.getLocation(parent);
var previousPosA:Point = touchA.getPreviousLocation(parent);
var currentPosB:Point = touchB.getLocation(parent);
var previousPosB:Point = touchB.getPreviousLocation(parent);
var currentVector:Point = currentPosA.subtract(currentPosB);
var previousVector:Point = previousPosA.subtract(previousPosB);
var currentAngle:Number = Math.atan2(currentVector.y, currentVector.x);
var previousAngle:Number = Math.atan2(previousVector.y, previousVector.x);
var deltaAngle:Number = currentAngle - previousAngle;
// update pivot point based on previous center
var previousLocalA:Point = touchA.getPreviousLocation(this);
var previousLocalB:Point = touchB.getPreviousLocation(this);
trace(previousLocalA , previousLocalB)
pivotX = (previousLocalA.x + previousLocalB.x) * 0.5;
pivotY = (previousLocalA.y + previousLocalB.y) * 0.5;
// update location based on the current center
x = (currentPosA.x + currentPosB.x) * 0.5;
y = (currentPosA.y + currentPosB.y) * 0.5;
// rotate
rotation += deltaAngle;
// scale
var sizeDiff:Number = currentVector.length / previousVector.length;
scaleX *= sizeDiff;
scaleY *= sizeDiff;
render(_ctrlButton.scaleX)
}
public override function dispose():void
{
removeEventListener(TouchEvent.TOUCH, onTouch);
if(_contents){
_contents.dispose()
}
super.dispose();
}
}
}
|
package lambmei.starling.display
{
import flash.display.MovieClip;
import flash.geom.Point;
import flash.system.System;
import starling.display.Button;
import starling.display.DisplayObject;
import starling.display.DisplayObjectContainer;
import starling.display.Shape;
import starling.display.Sprite;
import starling.events.Event;
import starling.events.Touch;
import starling.events.TouchEvent;
import starling.events.TouchPhase;
import starling.textures.Texture;
import starling.utils.Line;
[Event(name="handleSheetSelected" ,type="starling.events.Event")]
public class HandleSheet extends Sprite
{
/** 點擊 將物件移動到前方 **/
protected var _touchBringToFront:Boolean
public function get touchBringToFront():Boolean { return _touchBringToFront;}
public function set touchBringToFront(value:Boolean):void{ _touchBringToFront = value; }
/** 是否選擇 **/
protected var _selected:Boolean
public function get selected():Boolean { return _selected;}
public function set selected(value:Boolean):void
{
if(value!=_selected){
_selected = value;
_selectedGroup.visible = _selected
}
}
/** 是否有使用 控制按鈕 Read Only **/
protected var _useCtrlButton:Boolean
public function get useCtrlButton():Boolean
{
return _useCtrlButton;
}
//Const Vars
protected static const CTRL_BUTTON_NAME:String = "HandlectrlBtn"
public static const ALIGN_CENTER:String = "center"
public static const ALIGN_LT:String = "LT"
public static const EVENT_SELECTED:String = "handleSheetSelected"
//UI
protected var _contents:DisplayObject
protected var _ctrlButton:DisplayObject
protected var _selectedGroup:Sprite
protected var _shape:Shape
public function HandleSheet(contents:DisplayObject=null)
{
addEventListener(TouchEvent.TOUCH, onTouch);
useHandCursor = true;
_touchBringToFront = true
if (contents)
{
var _w:Number = contents.width
var _h:Number = contents.height
var _halfW:Number = _w/2
var _halfH:Number= _h/2
//將物件置中
contents.x = int(_halfW * -1);
contents.y = int(_halfH * -1);
addChild(contents);
_contents = contents
}
//init SelectGroup
initSelectedGroup()
}
/** 初始化選擇的群組**/
protected function initSelectedGroup():void
{
_selectedGroup = new Sprite()
this.addChild(this._selectedGroup);
_shape = new Shape()
_selectedGroup.addChild(_shape)
_selectedGroup.visible = _selected
}
/**重新計算**/
protected function render(sizeDiff:Number , deltaAngle:Number):void
{
rotation += deltaAngle;
scaleX *= sizeDiff;
scaleY *= sizeDiff;
//_ctrlButton 保持原比例
if(_ctrlButton){
_ctrlButton.scaleX /= sizeDiff
_ctrlButton.scaleY /= sizeDiff
//size 變更後需要重新定位
updateCtrlButtonPosition()
}
updateLine(_ctrlButton.scaleX)
}
/**計算CtrlButton 放置位置**/
protected function updateCtrlButtonPosition():void
{
if(_contents && _ctrlButton){
var _w:Number = _contents.width
var _h:Number = _contents.height
var _halfW:Number = _w/2
var _halfH:Number= _h/2
//放置右上角
_ctrlButton.x = int(_halfW)
_ctrlButton.y = - int(_halfH)
//置中對齊
_ctrlButton.x -= int(_ctrlButton.width/2)
_ctrlButton.y -= int(_ctrlButton.height/2)
}
}
/**更新框線**/
protected function updateLine(sizeRate:Number):void
{
if(_contents && _shape){
_shape.graphics.lineStyle(10,0xFFffFF);
_shape.graphics.clear();
System.gc();
var _w:Number = _contents.width
var _h:Number = _contents.height
var _halfW:Number = _w/2
var _halfH:Number= _h/2
_shape.graphics.lineStyle(2 * sizeRate ,0xFFFFFF);
//_shape.graphics.drawRoundRect( -_halfW, -_halfH, _w, _h, 10 );
_shape.graphics.drawRect(-_halfW, -_halfH, _w, _h);
//trace("scale",scale)
}
}
public function setCtrlButtonInitByTexture(upTexture:Texture , downTexture:Texture = null ):void
{
_useCtrlButton = true
if ( upTexture !=null)
{
_ctrlButton = new Button(upTexture,"",downTexture);
setCtrlButtonInitByObject(_ctrlButton )
}else{
throw new ArgumentError("Texture is Null!")
}
}
/** 設定控制按鈕 by 物件 可以是 image sprite button **/
public function setCtrlButtonInitByObject( obj:DisplayObject ):void
{
_useCtrlButton = true
if (_contents)
{
//避免讓外部物件Size != 1 影響計算
var _container:Sprite = new Sprite()
_container.addChild(obj)
_ctrlButton = _container
//定位
updateCtrlButtonPosition()
_selectedGroup.addChild(_ctrlButton)
}
}
protected function onTouch(event:TouchEvent):void
{
var touches:Vector.<Touch> = event.getTouches(this, TouchPhase.MOVED);
var touch:Touch
touch = event.getTouch(this, TouchPhase.BEGAN);
onTouchBegan(touch)
//一隻手指
if (touches.length == 1)
{
//檢查是否是Ctrl
if(isTouchCtrlButton(event.target) )
{
resizeAndRotationByCtrlButton(touches)
}
else
{
//一隻手指平移
var delta:Point = touches[0].getMovement(parent);
x += delta.x;
y += delta.y;
}
}
else if (touches.length == 2)
{
//兩隻手指
resizeAndRotationByTwoFingers(touches)
}
touch = event.getTouch(this, TouchPhase.ENDED);
onTouchEnd(touch)
}
/**當touch開始**/
protected function onTouchBegan(touch:Touch):void
{
//touch 開始要做的事情
if(touch){
if(_touchBringToFront){
parent.addChild(this);
}
selected = true
render(1, 0)
dispatchEventWith(EVENT_SELECTED,false)
}
}
/**當touch結束**/
protected function onTouchEnd(touch:Touch):void
{
}
/**檢查是否touch 控制按鈕**/
protected function isTouchCtrlButton(target:*):Boolean
{
var _do :DisplayObject
var _doc :DisplayObjectContainer
if(_ctrlButton is DisplayObjectContainer){
_doc = _ctrlButton as DisplayObjectContainer
return _doc.contains(target)
}
else if(_ctrlButton is DisplayObject)
{
_do = _ctrlButton as DisplayObject
return _do == target
}
return false
}
/** 單隻手指使用控制按鈕 放大縮小旋轉 **/
protected function resizeAndRotationByCtrlButton(touches:Vector.<Touch>):void
{
var touchA:Touch = touches[0];
var touchB:Touch = touchA.clone(); //模擬B點
var n:Point = touchA.getLocation(this);
//鏡射A點坐標
touchB.globalX = n.x * 1
touchB.globalY = n.y * -1
var currentPosA:Point = touchA.getLocation(this);
var previousPosA:Point = touchA.getPreviousLocation(this);
//鏡射A點
var currentPosB:Point = currentPosA.clone();
currentPosB.x *=-1;
currentPosB.y *=-1;
//鏡射A點
var previousPosB:Point = previousPosA.clone();
previousPosB.x *=-1;
previousPosB.y *=-1;
var currentVector:Point = currentPosA.subtract(currentPosB);
var previousVector:Point = previousPosA.subtract(previousPosB);
var currentAngle:Number = Math.atan2(currentVector.y, currentVector.x);
var previousAngle:Number = Math.atan2(previousVector.y, previousVector.x);
var deltaAngle:Number = currentAngle - previousAngle;
// rotate
//rotation += deltaAngle;
// scale
var sizeDiff:Number = currentVector.length / previousVector.length;
// scaleX *= sizeDiff;
// scaleY *= sizeDiff;
render(sizeDiff , deltaAngle)
}
/** 使用兩隻手指 使用放大縮小旋轉 保留官方功能 **/
protected function resizeAndRotationByTwoFingers(touches:Vector.<Touch>):void
{
//保留官方原本兩隻手指操作的功能
// two fingers touching -> rotate and scale
var touchA:Touch = touches[0];
var touchB:Touch = touches[1];
var currentPosA:Point = touchA.getLocation(parent);
var previousPosA:Point = touchA.getPreviousLocation(parent);
var currentPosB:Point = touchB.getLocation(parent);
var previousPosB:Point = touchB.getPreviousLocation(parent);
var currentVector:Point = currentPosA.subtract(currentPosB);
var previousVector:Point = previousPosA.subtract(previousPosB);
var currentAngle:Number = Math.atan2(currentVector.y, currentVector.x);
var previousAngle:Number = Math.atan2(previousVector.y, previousVector.x);
var deltaAngle:Number = currentAngle - previousAngle;
// update pivot point based on previous center
var previousLocalA:Point = touchA.getPreviousLocation(this);
var previousLocalB:Point = touchB.getPreviousLocation(this);
trace(previousLocalA , previousLocalB)
pivotX = (previousLocalA.x + previousLocalB.x) * 0.5;
pivotY = (previousLocalA.y + previousLocalB.y) * 0.5;
// update location based on the current center
x = (currentPosA.x + currentPosB.x) * 0.5;
y = (currentPosA.y + currentPosB.y) * 0.5;
// rotate
// rotation += deltaAngle;
// scale
var sizeDiff:Number = currentVector.length / previousVector.length;
// scaleX *= sizeDiff;
// scaleY *= sizeDiff;
render(sizeDiff , deltaAngle)
}
public override function dispose():void
{
removeEventListener(TouchEvent.TOUCH, onTouch);
if(_contents){
_contents.dispose()
}
super.dispose();
}
}
}
|
fix CtrlButton 位置 SELECT 觸發事件
|
fix CtrlButton 位置 SELECT 觸發事件
|
ActionScript
|
mit
|
lamb-mei/HandleSheet
|
26c3d58db1a7c0efebd4e96b96b6305ca958e4a9
|
src/com/mangui/HLS/muxing/PES.as
|
src/com/mangui/HLS/muxing/PES.as
|
package com.mangui.HLS.muxing {
import com.mangui.HLS.muxing.*;
import com.mangui.HLS.utils.*;
import flash.utils.ByteArray;
/** Representation of a Packetized Elementary Stream. **/
public class PES {
/** Timescale of pts/dts is 90khz. **/
public static var TIMESCALE:Number = 90;
/** Is it AAC audio or AVC video. **/
public var audio:Boolean;
/** The PES data (including headers). **/
public var data:ByteArray;
/** Start of the payload. **/
public var payload:Number;
/** Timestamp from the PTS header. **/
public var pts:Number;
/** Timestamp from the DTS header. **/
public var dts:Number;
/** Save the first chunk of PES data. **/
public function PES(dat:ByteArray,aud:Boolean) {
data = dat;
audio = aud;
};
/** Append PES data from additional TS packets. **/
public function append(dat:ByteArray):void {
data.writeBytes(dat,0,0);
};
/** When all data is appended, parse the PES headers. **/
public function parse():void {
data.position = 0;
// Start code prefix and packet ID.
var prefix:Number = data.readUnsignedInt();
if((audio && (prefix > 448 || prefix < 445)) ||
(!audio && prefix != 480 && prefix != 490)) {
throw new Error("PES start code not found or not AAC/AVC: " + prefix);
}
// Ignore packet length and marker bits.
data.position += 3;
// Check for PTS
var flags:uint = (data.readUnsignedByte() & 192) >> 6;
if(flags != 2 && flags != 3) {
throw new Error("No PTS/DTS in this PES packet");
}
// Check PES header length
var length:uint = data.readUnsignedByte();
// Grab the timestamp from PTS data (spread out over 5 bytes):
// XXXX---X -------- -------X -------- -------X
var _pts:uint = ((data.readUnsignedByte() & 14) << 29) +
((data.readUnsignedShort() & 65535) << 14) +
((data.readUnsignedShort() & 65535) >> 1);
length -= 5;
var _dts:uint = _pts;
if(flags == 3) {
// Grab the DTS (like PTS)
_dts = ((data.readUnsignedByte() & 14) << 29) +
((data.readUnsignedShort() & 65535) << 14) +
((data.readUnsignedShort() & 65535) >> 1);
length -= 5;
}
pts = Math.round(_pts / PES.TIMESCALE);
dts = Math.round(_dts / PES.TIMESCALE);
// Skip other header data and parse payload.
data.position += length;
payload = data.position;
};
}
}
|
package com.mangui.HLS.muxing {
import com.mangui.HLS.muxing.*;
import com.mangui.HLS.utils.*;
import flash.utils.ByteArray;
/** Representation of a Packetized Elementary Stream. **/
public class PES {
/** Timescale of pts/dts is 90khz. **/
public static var TIMESCALE:Number = 90;
/** Is it AAC audio or AVC video. **/
public var audio:Boolean;
/** The PES data (including headers). **/
public var data:ByteArray;
/** Start of the payload. **/
public var payload:Number;
/** Timestamp from the PTS header. **/
public var pts:Number;
/** Timestamp from the DTS header. **/
public var dts:Number;
/** Save the first chunk of PES data. **/
public function PES(dat:ByteArray,aud:Boolean) {
data = dat;
audio = aud;
};
/** Append PES data from additional TS packets. **/
public function append(dat:ByteArray):void {
data.writeBytes(dat,0,0);
};
/** When all data is appended, parse the PES headers. **/
public function parse():void {
data.position = 0;
// Start code prefix and packet ID.
var prefix:Number = data.readUnsignedInt();
if((audio && (prefix > 448 || prefix < 445)) ||
(!audio && prefix != 480 && prefix != 490)) {
throw new Error("PES start code not found or not AAC/AVC: " + prefix);
}
// Ignore packet length and marker bits.
data.position += 3;
// Check for PTS
var flags:uint = (data.readUnsignedByte() & 192) >> 6;
if(flags != 2 && flags != 3) {
throw new Error("No PTS/DTS in this PES packet");
}
// Check PES header length
var length:uint = data.readUnsignedByte();
// Grab the timestamp from PTS data (spread out over 5 bytes):
// XXXX---X -------- -------X -------- -------X
var _pts:uint = ((data.readUnsignedByte() & 14) << 29) +
((data.readUnsignedShort() & 65534) << 14) +
((data.readUnsignedShort() & 65534) >> 1);
length -= 5;
var _dts:uint = _pts;
if(flags == 3) {
// Grab the DTS (like PTS)
_dts = ((data.readUnsignedByte() & 14) << 29) +
((data.readUnsignedShort() & 65534) << 14) +
((data.readUnsignedShort() & 65534) >> 1);
length -= 5;
}
pts = Math.round(_pts / PES.TIMESCALE);
dts = Math.round(_dts / PES.TIMESCALE);
// Skip other header data and parse payload.
data.position += length;
payload = data.position;
};
}
}
|
correct PTS/DTS parsing according to http://dvd.sourceforge.net/dvdinfo/pes-hdr.html, bit 0 is not used. change mask accordingly.
|
correct PTS/DTS parsing
according to http://dvd.sourceforge.net/dvdinfo/pes-hdr.html, bit 0 is not used. change mask accordingly.
|
ActionScript
|
mpl-2.0
|
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
|
53bb4bc0e71b3dc78a77908c7c55ca957cc64ded
|
build-aux/children.as
|
build-aux/children.as
|
# -*- shell-script -*-
##
## children.as: This file is part of build-aux.
## Copyright (C) Gostai S.A.S., 2006-2008.
##
## This software is provided "as is" without warranty of any kind,
## either expressed or implied, including but not limited to the
## implied warranties of fitness for a particular purpose.
##
## See the LICENSE file for more information.
## For comments, bug reports and feedback: http://www.urbiforge.com
##
m4_defun([URBI_CHILDREN_PREPARE],
[
# run TITLE COMMAND...
# --------------------
# Run the COMMAND... (which may use its stdin) and output detailed
# logs about the execution.
#
# Leave un $run_prefix.{cmd, out, sta, err, val} the command, standard
# output, exit status, standard error, and instrumentation output.
run_counter=0
run_prefix=
run ()
{
local title=$[1]
run_prefix=$run_counter-$(echo $[1] |
sed -e 's/[[^a-zA-Z0-9][^a-zA-Z0-9]]*/-/g;s/-$//')
run_counter=$(($run_counter + 1))
shift
echo "$[@]"> $run_prefix.cmd
# Beware of set -e.
local sta
if "$[@]" >$run_prefix.out 2>$run_prefix.err; then
sta=0
else
sta=$?
title="$title FAIL ($sta)"
fi
echo $sta >$run_prefix.sta
rst_subsection "$me: $title"
rst_run_report "$title" "$run_prefix"
return $sta
}
## ------------------------------------------------- ##
## PID sets -- Lower layer for children management. ##
## ------------------------------------------------- ##
# pids_alive PIDS
# ---------------
# Return whether some of the PIDs point to alive processes,
# i.e., return 1 iff there are no children alive.
pids_alive ()
{
local pid
for pid
do
# Using "ps PID" to test whether a processus is alive is,
# unfortunately, non portable. OS X Tiger always return 0, and
# outputs the ps-banner and the line of the processus (if there is
# none, it outputs just the banner). On Cygwin, "ps PID" outputs
# everything, and "ps -p PID" outputs the banner, and the process
# line if alive. In both cases it exits with success.
#
# We once used grep to check the result:
#
# ps -p $pid | grep ["^[ ]*$pid[^0-9]"]
#
# Unfortunately sometimes there are flags displayed before the
# process number. Since we never saw a "ps -p PID" that does not
# display the title line, we expect two lines.
case $(ps -p $pid | wc -l | sed -e '[s/^[ ]*//]') in
1) # process is dead.
;;
2) # Process is live.
return 0;;
*) error SOFTWARE "unexpected ps output:" "$(ps -p $pid)" ;;
esac
done
return 1
}
# pids_kill PIDS
# --------------
# Kill all the PIDS. This function can be called twice: once
# before cleaning the components, and once when exiting, so it's
# robust to children no longer in the process table.
pids_kill ()
{
local pid
for pid
do
if pids_alive $pid; then
local name
name=$(cat $pid.name)
echo "Killing $name (kill -ALRM $pid)"
kill -ALRM $pid 2>&1 || true
fi
done
}
# pids_wait TIMEOUT PIDS
# ----------------------
pids_wait ()
{
local timeout=$[1]
shift
if $INSTRUMENT; then
timeout=$(($timeout * 5))
fi
while pids_alive "$[@]"; do
if test $timeout -le 0; then
pids_kill "$[@]"
break
fi
sleep 1
timeout=$(($timeout - 1))
done
}
## ---------- ##
## Children. ##
## ---------- ##
# rst_run_report $TITLE $FILE-PREFIX
# ----------------------------------
# Report the input and output for $FILE-PREFIX.
rst_run_report ()
{
local title=$[1]
case $title in
?*) title="$title ";;
esac
rst_pre "${title}Command" $[2].cmd
rst_pre "${title}Pid" $[2].pid
rst_pre "${title}Status" $[2].sta
rst_pre "${title}Input" $[2].in
rst_pre "${title}Output" $[2].out
rst_pre "${title}Error" $[2].err
rst_pre "${title}Valgrind" $[2].val
}
# children_alive [CHILDREN]
# -------------------------
# Return whether there are still some children running,
# i.e., return 1 iff there are no children alive.
children_alive ()
{
local pid
local pids
pids=$(children_pid "$[@]")
for pid in $pids
do
# Using "ps PID" to test whether a processus is alive is,
# unfortunately, non portable. OS X Tiger always return 0, and
# outputs the ps-banner and the line of the processus (if there is
# none, it outputs just the banner). On Cygwin, "ps PID" outputs
# everything, and "ps -p PID" outputs the banner, and the process
# line if alive. In both cases it exits with success.
#
# We once used grep to check the result:
#
# ps -p $pid | grep ["^[ ]*$pid[^0-9]"]
#
# Unfortunately sometimes there are flags displayed before the
# process number. Since we never saw a "ps -p PID" that does not
# display the title line, we expect two lines.
case $(ps -p $pid | wc -l | sed -e '[s/^[ ]*//]') in
1) # process is dead.
;;
2) # Process is live.
return 0;;
*) error SOFTWARE "unexpected ps output:" "$(ps -p $pid)" ;;
esac
done
return 1
}
# children_clean [CHILDREN]
# --------------------------
# Remove the children files.
children_clean ()
{
test $[#] -ne 0 ||
{ set x $children; shift; }
local i
for i
do
rm -f $i.{cmd,pid,sta,in,out,err,val}
done
}
# children_pid [CHILDREN]
# -----------------------
# Return the PIDs of the CHILDREN (whether alive or not).
children_pid ()
{
test $[#] -ne 0 ||
{ set x $children; shift; }
local i
for i
do
test -f $i.pid ||
error SOFTWARE "children_pid: cannot find $i.pid."
cat $i.pid
done
}
# children_register NAME
# ----------------------
# It is very important that we do not leave some random exit status
# from some previous runs. Standard output etc. are not a problem:
# they *are* created during the run, while *.sta is created *only* if
# it does not already exists (this is because you can call "wait" only
# once per processus, so to enable calling children_harvest multiple
# times, we create *.sta only if it does not exist).
#
# Creates NAME.pid which contains the PID, and PID.name which contains
# the name.
children_register ()
{
test $[#] -eq 1
rm -f $[1].sta
children="$children $[1]"
echo $! >$[1].pid
echo $[1] >$!.name
}
# children_report [CHILDREN]
# --------------------------
# Produce an RST report for the CHILDREN.
children_report ()
{
test $[#] -ne 0 ||
{ set x $children; shift; }
local i
for i
do
rst_run_report "$i" "$i"
done
}
# children_kill [CHILDREN]
# ------------------------
# Kill all the children. This function can be called twice: once
# before cleaning the components, and once when exiting, so it's
# robust to children no longer in the process table.
children_kill ()
{
local pids
pids=$(children_pid "$[@]")
pids_kill "$pids"
}
# children_harvest [CHILDREN]
# ---------------------------
# Report the exit status of the children. Can be run several times.
# You might want to call it once in the regular control flow to fetch
# some exit status, but also in a trap, if you were interrupted. So
# it is meant to be callable multiple times, which might be a danger
# wrt *.sta (cf., children_register).
children_harvest ()
{
# Harvest exit status.
test $[#] -ne 0 ||
{ set x $children; shift; }
local i
for i
do
# Don't wait for children we already waited for.
if ! test -e $i.sta; then
local pid
pid=$(children_pid $i)
# Beware of set -e.
local sta
if wait $pid 2>&1; then
sta=$?
else
sta=$?
fi
echo "$sta$(ex_to_string $sta)" >$i.sta
fi
done
}
# children_status [CHILDREN]
# --------------------------
# Return the exit status of CHILD. Must be run after harvesting.
# If several CHILD are given, return the highest exit status.
children_status ()
{
test $[#] -ne 0 ||
{ set x $children; shift; }
local res=0
local i
for i
do
# We need to have waited for these children.
test -f $i.sta ||
error SOFTWARE "children_status: cannot find $i.sta." \
"Was children_harvest called?" \
"Maybe children_cleanup was already called..."
local sta=$(sed -n '1{s/^\([[0-9][0-9]]*\).*/\1/;p;q;}' <$i.sta)
if test $res -lt $sta; then
res=$sta
fi
done
echo $res
}
# children_wait TIMEOUT [CHILDREN]
# --------------------------------
# Wait for the registered children, and passed TIMEOUT, kill the remaining
# ones. TIMEOUT is increased by 5 if instrumenting.
children_wait ()
{
local timeout=$[1]
shift
local pids
pids=$(children_pid "$[@]")
pids_wait $timeout $pids
}
])
|
# -*- shell-script -*-
##
## children.as: This file is part of build-aux.
## Copyright (C) Gostai S.A.S., 2006-2008.
##
## This software is provided "as is" without warranty of any kind,
## either expressed or implied, including but not limited to the
## implied warranties of fitness for a particular purpose.
##
## See the LICENSE file for more information.
## For comments, bug reports and feedback: http://www.urbiforge.com
##
m4_defun([URBI_CHILDREN_PREPARE],
[
# run TITLE COMMAND...
# --------------------
# Run the COMMAND... (which may use its stdin) and output detailed
# logs about the execution.
#
# Leave un $run_prefix.{cmd, out, sta, err, val} the command, standard
# output, exit status, standard error, and instrumentation output.
run_counter=0
run_prefix=
run ()
{
local title=$[1]
run_prefix=$run_counter-$(echo $[1] |
sed -e 's/[[^a-zA-Z0-9][^a-zA-Z0-9]]*/-/g;s/-$//')
run_counter=$(($run_counter + 1))
shift
echo "$[@]"> $run_prefix.cmd
# Beware of set -e.
local sta
if "$[@]" >$run_prefix.out 2>$run_prefix.err; then
sta=0
else
sta=$?
title="$title FAIL ($sta)"
fi
echo $sta >$run_prefix.sta
rst_subsection "$me: $title"
rst_run_report "$title" "$run_prefix"
return $sta
}
## ------------------------------------------------- ##
## PID sets -- Lower layer for children management. ##
## ------------------------------------------------- ##
# pids_alive PIDS
# ---------------
# Return whether some of the PIDs point to alive processes,
# i.e., return 1 iff there are no children alive.
pids_alive ()
{
local pid
for pid
do
# Using "ps PID" to test whether a processus is alive is,
# unfortunately, non portable. OS X Tiger always return 0, and
# outputs the ps-banner and the line of the processus (if there is
# none, it outputs just the banner). On Cygwin, "ps PID" outputs
# everything, and "ps -p PID" outputs the banner, and the process
# line if alive. In both cases it exits with success.
#
# We once used grep to check the result:
#
# ps -p $pid | grep ["^[ ]*$pid[^0-9]"]
#
# Unfortunately sometimes there are flags displayed before the
# process number. Since we never saw a "ps -p PID" that does not
# display the title line, we expect two lines.
case $(ps -p $pid | wc -l | sed -e '[s/^[ ]*//]') in
1) # process is dead.
;;
2) # Process is live.
return 0;;
*) error SOFTWARE "unexpected ps output:" "$(ps -p $pid)" ;;
esac
done
return 1
}
# pids_kill PIDS
# --------------
# Kill all the PIDS. This function can be called twice: once
# before cleaning the components, and once when exiting, so it's
# robust to children no longer in the process table.
pids_kill ()
{
local pid
for pid
do
if pids_alive $pid; then
local name
name=$(cat $pid.name)
echo "Killing $name (kill -ALRM $pid)"
kill -ALRM $pid 2>&1 || true
fi
done
}
# pids_wait TIMEOUT PIDS
# ----------------------
pids_wait ()
{
local timeout=$[1]
shift
if $INSTRUMENT; then
timeout=$(($timeout * 5))
fi
while pids_alive "$[@]"; do
if test $timeout -le 0; then
pids_kill "$[@]"
break
fi
sleep 1
timeout=$(($timeout - 1))
done
}
## ---------- ##
## Children. ##
## ---------- ##
# rst_run_report $TITLE $FILE-PREFIX
# ----------------------------------
# Report the input and output for $FILE-PREFIX.
rst_run_report ()
{
local title=$[1]
case $title in
?*) title="$title ";;
esac
rst_pre "${title}Command" $[2].cmd
rst_pre "${title}Pid" $[2].pid
rst_pre "${title}Status" $[2].sta
rst_pre "${title}Input" $[2].in
rst_pre "${title}Output" $[2].out
rst_pre "${title}Error" $[2].err
rst_pre "${title}Valgrind" $[2].val
}
# children_alive [CHILDREN]
# -------------------------
# Return whether there are still some children running,
# i.e., return 1 iff there are no children alive.
children_alive ()
{
local pid
local pids
pids=$(children_pid "$[@]")
for pid in $pids
do
# Using "ps PID" to test whether a processus is alive is,
# unfortunately, non portable. OS X Tiger always return 0, and
# outputs the ps-banner and the line of the processus (if there is
# none, it outputs just the banner). On Cygwin, "ps PID" outputs
# everything, and "ps -p PID" outputs the banner, and the process
# line if alive. In both cases it exits with success.
#
# We once used grep to check the result:
#
# ps -p $pid | grep ["^[ ]*$pid[^0-9]"]
#
# Unfortunately sometimes there are flags displayed before the
# process number. Since we never saw a "ps -p PID" that does not
# display the title line, we expect two lines.
case $(ps -p $pid | wc -l | sed -e '[s/^[ ]*//]') in
1) # process is dead.
;;
2) # Process is live.
return 0;;
*) error SOFTWARE "unexpected ps output:" "$(ps -p $pid)" ;;
esac
done
return 1
}
# children_clean [CHILDREN]
# --------------------------
# Remove the children files.
children_clean ()
{
test $[#] -ne 0 ||
{ set x $children; shift; }
local i
for i
do
rm -f $i.{cmd,pid,sta,in,out,err,val}
done
}
# children_pid [CHILDREN]
# -----------------------
# Return the PIDs of the CHILDREN (whether alive or not).
children_pid ()
{
test $[#] -ne 0 ||
{ set x $children; shift; }
local i
for i
do
test -f $i.pid ||
error SOFTWARE "children_pid: cannot find $i.pid."
cat $i.pid
done
}
# children_register NAME
# ----------------------
# It is very important that we do not leave some random exit status
# from some previous runs. Standard output etc. are not a problem:
# they *are* created during the run, while *.sta is created *only* if
# it does not already exists (this is because you can call "wait" only
# once per processus, so to enable calling children_harvest multiple
# times, we create *.sta only if it does not exist).
#
# Creates NAME.pid which contains the PID, and PID.name which contains
# the name.
children_register ()
{
test $[#] -eq 1
rm -f $[1].sta
children="$children $[1]"
echo $! >$[1].pid
echo $[1] >$!.name
}
# children_report [CHILDREN]
# --------------------------
# Produce an RST report for the CHILDREN.
children_report ()
{
test $[#] -ne 0 ||
{ set x $children; shift; }
local i
for i
do
rst_run_report "$i" "$i"
done
}
# children_kill [CHILDREN]
# ------------------------
# Kill all the children. This function can be called twice: once
# before cleaning the components, and once when exiting, so it's
# robust to children no longer in the process table.
children_kill ()
{
local pids
pids=$(children_pid "$[@]")
pids_kill $pids
}
# children_harvest [CHILDREN]
# ---------------------------
# Report the exit status of the children. Can be run several times.
# You might want to call it once in the regular control flow to fetch
# some exit status, but also in a trap, if you were interrupted. So
# it is meant to be callable multiple times, which might be a danger
# wrt *.sta (cf., children_register).
children_harvest ()
{
# Harvest exit status.
test $[#] -ne 0 ||
{ set x $children; shift; }
local i
for i
do
# Don't wait for children we already waited for.
if ! test -e $i.sta; then
local pid
pid=$(children_pid $i)
# Beware of set -e.
local sta
if wait $pid 2>&1; then
sta=$?
else
sta=$?
fi
echo "$sta$(ex_to_string $sta)" >$i.sta
fi
done
}
# children_status [CHILDREN]
# --------------------------
# Return the exit status of CHILD. Must be run after harvesting.
# If several CHILD are given, return the highest exit status.
children_status ()
{
test $[#] -ne 0 ||
{ set x $children; shift; }
local res=0
local i
for i
do
# We need to have waited for these children.
test -f $i.sta ||
error SOFTWARE "children_status: cannot find $i.sta." \
"Was children_harvest called?" \
"Maybe children_cleanup was already called..."
local sta=$(sed -n '1{s/^\([[0-9][0-9]]*\).*/\1/;p;q;}' <$i.sta)
if test $res -lt $sta; then
res=$sta
fi
done
echo $res
}
# children_wait TIMEOUT [CHILDREN]
# --------------------------------
# Wait for the registered children, and passed TIMEOUT, kill the remaining
# ones. TIMEOUT is increased by 5 if instrumenting.
children_wait ()
{
local timeout=$[1]
shift
local pids
pids=$(children_pid "$[@]")
pids_wait $timeout $pids
}
])
|
Fix shell quotation.
|
Fix shell quotation.
* build-aux/children.as (children_kill): We do want to split the
$pids.
|
ActionScript
|
bsd-3-clause
|
aldebaran/libport,aldebaran/libport,aldebaran/libport,aldebaran/libport,aldebaran/libport
|
ffc78a54b885ea7d1c790218d012c9373d02a092
|
src/com/google/analytics/core/IdleTimer.as
|
src/com/google/analytics/core/IdleTimer.as
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
* Marc Alcaraz <[email protected]>.
*/
package com.google.analytics.core
{
import com.google.analytics.debug.DebugConfiguration;
import com.google.analytics.debug.VisualDebugMode;
import com.google.analytics.v4.Configuration;
import flash.display.DisplayObject;
import flash.display.Stage;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.utils.getTimer;
/**
* The Idle Timer class.
*/
public class IdleTimer
{
private var _loop:Timer;
private var _session:Timer;
private var _debug:DebugConfiguration;
private var _stage:Stage;
private var _buffer:Buffer;
private var _lastMove:int;
private var _inactivity:Number;
/**
* Create an instance of the IdleTimer
*
* note:
* the timer will loop every <delay> seconds
* on each loop
* we compare the <last mouse move time> to the <current time>
* and if the result is equal or bigger than the
* <inativity> seconds we start a sessionTimer
* -> if the mouse move again we reset the sessionTimer
* -> if the mouse does not move till we reach the end of the sessionTimeout
* we reset the session
*
* @param delay number of seconds to check for idle
* @param inactivity number of seconds to check for inactivity
* @param sessionTimeout number of seconds to end the session
*/
public function IdleTimer( config:Configuration, debug:DebugConfiguration,
display:DisplayObject, buffer:Buffer )
{
var delay:Number = config.idleLoop;
var inactivity:Number = config.idleTimeout;
var sessionTimeout:Number = config.sessionTimeout;
_loop = new Timer( delay * 1000 ); //milliseconds
_session = new Timer( sessionTimeout * 1000, 1 ); //milliseconds
_debug = debug;
_stage = display.stage;
_buffer = buffer;
_lastMove = getTimer();
_inactivity = inactivity * 1000; //milliseconds
_loop.addEventListener( TimerEvent.TIMER, checkForIdle );
_session.addEventListener( TimerEvent.TIMER_COMPLETE, endSession );
_stage.addEventListener( MouseEvent.MOUSE_MOVE, onMouseMove );
_debug.info( "delay: " + delay + "sec , inactivity: " + inactivity + "sec, sessionTimeout: " + sessionTimeout, VisualDebugMode.geek );
_loop.start();
}
private function onMouseMove( event:MouseEvent ):void
{
_lastMove = getTimer();
if( _session.running )
{
_debug.info( "session timer reset", VisualDebugMode.geek );
_session.reset();
}
}
public function checkForIdle( event:TimerEvent ):void
{
var current:int = getTimer();
if( (current - _lastMove) >= _inactivity )
{
if( !_session.running )
{
_debug.info( "session timer start", VisualDebugMode.geek );
_session.start();
}
}
}
public function endSession( event:TimerEvent ):void
{
_session.removeEventListener( TimerEvent.TIMER_COMPLETE, endSession );
_debug.info( "session timer end session", VisualDebugMode.geek );
_session.reset();
_buffer.resetCurrentSession();
_debug.info( _buffer.utmb.toString(), VisualDebugMode.geek );
_debug.info( _buffer.utmc.toString(), VisualDebugMode.geek );
_session.addEventListener( TimerEvent.TIMER_COMPLETE, endSession );
}
}
}
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
* Marc Alcaraz <[email protected]>.
*/
package com.google.analytics.core
{
import com.google.analytics.debug.DebugConfiguration;
import com.google.analytics.debug.VisualDebugMode;
import com.google.analytics.v4.Configuration;
import flash.display.DisplayObject;
import flash.display.Stage;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.utils.getTimer;
/**
* The Idle Timer class.
*/
public class IdleTimer
{
private var _loop:Timer;
private var _session:Timer;
private var _debug:DebugConfiguration;
private var _stage:Stage;
private var _buffer:Buffer;
private var _lastMove:int;
private var _inactivity:Number;
/* note:
the timer will loop every <delay> seconds
on each loop
we compare the <last mouse move time> to the <current time>
and if the result is equal or bigger than the
<inativity> seconds we start a sessionTimer
-> if the mouse move again we reset the sessionTimer
-> if the mouse does not move till we reach the end of the sessionTimeout
we reset the session
*/
/**
* Create an instance of the IdleTimer
*
* @param delay number of seconds to check for idle
* @param inactivity number of seconds to check for inactivity
* @param sessionTimeout number of seconds to end the session
*/
public function IdleTimer( config:Configuration, debug:DebugConfiguration,
display:DisplayObject, buffer:Buffer )
{
var delay:Number = config.idleLoop;
var inactivity:Number = config.idleTimeout;
var sessionTimeout:Number = config.sessionTimeout;
_loop = new Timer( delay * 1000 ); //milliseconds
_session = new Timer( sessionTimeout * 1000, 1 ); //milliseconds
_debug = debug;
_stage = display.stage;
_buffer = buffer;
_lastMove = getTimer();
_inactivity = inactivity * 1000; //milliseconds
_loop.addEventListener( TimerEvent.TIMER, checkForIdle );
_session.addEventListener( TimerEvent.TIMER_COMPLETE, endSession );
_stage.addEventListener( MouseEvent.MOUSE_MOVE, onMouseMove );
_debug.info( "delay: " + delay + "sec , inactivity: " + inactivity + "sec, sessionTimeout: " + sessionTimeout, VisualDebugMode.geek );
_loop.start();
}
private function onMouseMove( event:MouseEvent ):void
{
_lastMove = getTimer();
if( _session.running )
{
_debug.info( "session timer reset", VisualDebugMode.geek );
_session.reset();
}
}
public function checkForIdle( event:TimerEvent ):void
{
var current:int = getTimer();
if( (current - _lastMove) >= _inactivity )
{
if( !_session.running )
{
_debug.info( "session timer start", VisualDebugMode.geek );
_session.start();
}
}
}
public function endSession( event:TimerEvent ):void
{
_session.removeEventListener( TimerEvent.TIMER_COMPLETE, endSession );
_debug.info( "session timer end session", VisualDebugMode.geek );
_session.reset();
_buffer.resetCurrentSession();
_debug.info( _buffer.utmb.toString(), VisualDebugMode.geek );
_debug.info( _buffer.utmc.toString(), VisualDebugMode.geek );
_session.addEventListener( TimerEvent.TIMER_COMPLETE, endSession );
}
}
}
|
fix comment for asdoc
|
fix comment for asdoc
|
ActionScript
|
apache-2.0
|
mrthuanvn/gaforflash,mrthuanvn/gaforflash,DimaBaliakin/gaforflash,jisobkim/gaforflash,DimaBaliakin/gaforflash,Miyaru/gaforflash,drflash/gaforflash,Vigmar/gaforflash,Miyaru/gaforflash,dli-iclinic/gaforflash,Vigmar/gaforflash,jisobkim/gaforflash,soumavachakraborty/gaforflash,soumavachakraborty/gaforflash,drflash/gaforflash,dli-iclinic/gaforflash,jeremy-wischusen/gaforflash,jeremy-wischusen/gaforflash
|
92c1e63a5c5ab6140f10f565b8cf7b99b947d807
|
src/org/jivesoftware/xiff/data/Presence.as
|
src/org/jivesoftware/xiff/data/Presence.as
|
package org.jivesoftware.xiff.data{
/*
* Copyright (C) 2003-2007
* Nick Velloff <[email protected]>
* Derrick Grigg <[email protected]>
* Sean Voisen <[email protected]>
* Sean Treadway <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
import org.jivesoftware.xiff.data.ISerializable;
import org.jivesoftware.xiff.data.XMPPStanza;
import flash.xml.XMLNode;
/**
* This class provides encapsulation for manipulation of presence data for sending and receiving.
*
* @author Sean Voisen
* @since 2.0.0
* @availability Flash Player 7
* @param recipient The recipient of the presence, usually in the form of a JID.
* @param sender The sender of the presence, usually in the form of a JID.
* @param presenceType The type of presence as a string. There are predefined static variables for this.
* @param showVal What to show for this presence (away, online, etc.) There are predefined static variables for this.
* @param statusVal The status; usually used for the "away message."
* @param priorityVal The priority of this presence; usually on a scale of 1-5.
* @toc-path Data
* @toc-sort 1
*/
public class Presence extends XMPPStanza implements ISerializable
{
// Static variables for specific type strings
public static var AVAILABLE_TYPE:String = "available";
public static var UNAVAILABLE_TYPE:String = "unavailable";
public static var PROBE_TYPE:String = "probe";
public static var SUBSCRIBE_TYPE:String = "subscribe";
public static var UNSUBSCRIBE_TYPE:String = "unsubscribe";
public static var SUBSCRIBED_TYPE:String = "subscribed";
public static var UNSUBSCRIBED_TYPE:String = "unsubscribed";
public static var ERROR_TYPE:String = "error";
// Static variables for show values
public static var SHOW_AWAY:String = "away";
public static var SHOW_CHAT:String = "chat";
public static var SHOW_DND:String = "dnd";
public static var SHOW_NORMAL:String = "normal";
public static var SHOW_XA:String = "xa";
public static var SHOW_OFFLINE:String = "offline";
// Private node references for property lookups
private var myShowNode:XMLNode;
private var myStatusNode:XMLNode;
private var myPriorityNode:XMLNode;
public function Presence( recipient:String=null, sender:String=null, presenceType:String=null, showVal:String=null, statusVal:String=null, priorityVal:Number=0 )
{
super( recipient, sender, presenceType, null, "presence" );
show = showVal;
status = statusVal;
priority = priorityVal;
}
/**
* Serializes the Presence into XML form for sending to a server.
*
* @return An indication as to whether serialization was successful
* @availability Flash Player 7
*/
override public function serialize( parentNode:XMLNode ):Boolean
{
return super.serialize( parentNode );
}
/**
* Deserializes an XML object and populates the Presence instance with its data.
*
* @param xmlNode The XML to deserialize
* @return An indication as to whether deserialization was sucessful
* @availability Flash Player 7
*/
override public function deserialize( xmlNode:XMLNode ):Boolean
{
var isDeserialized:Boolean = super.deserialize( xmlNode );
if (isDeserialized) {
var children:Array = xmlNode.childNodes;
for( var i:String in children )
{
switch( children[i].nodeName )
{
case "show":
myShowNode = children[i];
break;
case "status":
myStatusNode = children[i];
break;
case "priority":
myPriorityNode = children[i];
break;
}
}
}
return isDeserialized;
}
/**
* The show value; away, online, etc. There are predefined static variables in the Presence
* class for this:
* <ul>
* <li>Presence.SHOW_AWAY</li>
* <li>Presence.SHOW_CHAT</li>
* <li>Presence.SHOW_DND</li>
* <li>Presence.SHOW_NORMAL</li>
* <li>Presence.SHOW_XA</li>
* </ul>
*
* @availability Flash Player 7
*/
public function get show():String
{
if (myShowNode == null) return null;
if (!exists(myShowNode.firstChild)){
return Presence.SHOW_NORMAL;
}
return myShowNode.firstChild.nodeValue;
}
public function set show( showVal:String ):void
{
myShowNode = replaceTextNode(getNode(), myShowNode, "show", showVal);
}
/**
* The status; usually used for "away messages."
*
* @availability Flash Player 7
*/
public function get status():String {
if (myStatusNode == null || myStatusNode.firstChild == null) return null;
return myStatusNode.firstChild.nodeValue;
}
public function set status( statusVal:String ):void
{
myStatusNode = replaceTextNode(getNode(), myStatusNode, "status", statusVal);
}
/**
* The priority of the presence, usually on a scale of 1-5.
*
* @availability Flash Player 7
*/
public function get priority():Number
{
if (myPriorityNode == null) return NaN;
var p:Number = Number(myPriorityNode.firstChild.nodeValue);
if( isNaN( p ) ) {
return NaN;
}
else {
return p;
}
}
public function set priority( priorityVal:Number ):void
{
myPriorityNode = replaceTextNode(getNode(), myPriorityNode, "priority", priorityVal.toString());
}
}
}
|
package org.jivesoftware.xiff.data{
/*
* Copyright (C) 2003-2007
* Nick Velloff <[email protected]>
* Derrick Grigg <[email protected]>
* Sean Voisen <[email protected]>
* Sean Treadway <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
import org.jivesoftware.xiff.data.ISerializable;
import org.jivesoftware.xiff.data.XMPPStanza;
import flash.xml.XMLNode;
/**
* This class provides encapsulation for manipulation of presence data for sending and receiving.
*
* @author Sean Voisen
* @since 2.0.0
* @availability Flash Player 7
* @param recipient The recipient of the presence, usually in the form of a JID.
* @param sender The sender of the presence, usually in the form of a JID.
* @param presenceType The type of presence as a string. There are predefined static variables for this.
* @param showVal What to show for this presence (away, online, etc.) There are predefined static variables for this.
* @param statusVal The status; usually used for the "away message."
* @param priorityVal The priority of this presence; usually on a scale of 1-5.
* @toc-path Data
* @toc-sort 1
*/
public class Presence extends XMPPStanza implements ISerializable
{
// Static constants for specific type strings
public static const AVAILABLE_TYPE:String = "available";
public static const UNAVAILABLE_TYPE:String = "unavailable";
public static const PROBE_TYPE:String = "probe";
public static const SUBSCRIBE_TYPE:String = "subscribe";
public static const UNSUBSCRIBE_TYPE:String = "unsubscribe";
public static const SUBSCRIBED_TYPE:String = "subscribed";
public static const UNSUBSCRIBED_TYPE:String = "unsubscribed";
public static const ERROR_TYPE:String = "error";
// Static constants for show values
public static const SHOW_AWAY:String = "away";
public static const SHOW_CHAT:String = "chat";
public static const SHOW_DND:String = "dnd";
public static const SHOW_NORMAL:String = "normal";
public static const SHOW_XA:String = "xa";
public static const SHOW_OFFLINE:String = "offline";
// Private node references for property lookups
private var myShowNode:XMLNode;
private var myStatusNode:XMLNode;
private var myPriorityNode:XMLNode;
public function Presence( recipient:String=null, sender:String=null, presenceType:String=null, showVal:String=null, statusVal:String=null, priorityVal:Number=0 )
{
super( recipient, sender, presenceType, null, "presence" );
show = showVal;
status = statusVal;
priority = priorityVal;
}
/**
* Serializes the Presence into XML form for sending to a server.
*
* @return An indication as to whether serialization was successful
* @availability Flash Player 7
*/
override public function serialize( parentNode:XMLNode ):Boolean
{
return super.serialize( parentNode );
}
/**
* Deserializes an XML object and populates the Presence instance with its data.
*
* @param xmlNode The XML to deserialize
* @return An indication as to whether deserialization was sucessful
* @availability Flash Player 7
*/
override public function deserialize( xmlNode:XMLNode ):Boolean
{
var isDeserialized:Boolean = super.deserialize( xmlNode );
if (isDeserialized) {
var children:Array = xmlNode.childNodes;
for( var i:String in children )
{
switch( children[i].nodeName )
{
case "show":
myShowNode = children[i];
break;
case "status":
myStatusNode = children[i];
break;
case "priority":
myPriorityNode = children[i];
break;
}
}
}
return isDeserialized;
}
/**
* The show value; away, online, etc. There are predefined static variables in the Presence
* class for this:
* <ul>
* <li>Presence.SHOW_AWAY</li>
* <li>Presence.SHOW_CHAT</li>
* <li>Presence.SHOW_DND</li>
* <li>Presence.SHOW_NORMAL</li>
* <li>Presence.SHOW_XA</li>
* </ul>
*
* @availability Flash Player 7
*/
public function get show():String
{
if (myShowNode == null) return null;
if (!exists(myShowNode.firstChild)){
return Presence.SHOW_NORMAL;
}
return myShowNode.firstChild.nodeValue;
}
public function set show( showVal:String ):void
{
myShowNode = replaceTextNode(getNode(), myShowNode, "show", showVal);
}
/**
* The status; usually used for "away messages."
*
* @availability Flash Player 7
*/
public function get status():String {
if (myStatusNode == null || myStatusNode.firstChild == null) return null;
return myStatusNode.firstChild.nodeValue;
}
public function set status( statusVal:String ):void
{
myStatusNode = replaceTextNode(getNode(), myStatusNode, "status", statusVal);
}
/**
* The priority of the presence, usually on a scale of 1-5.
*
* @availability Flash Player 7
*/
public function get priority():Number
{
if (myPriorityNode == null) return NaN;
var p:Number = Number(myPriorityNode.firstChild.nodeValue);
if( isNaN( p ) ) {
return NaN;
}
else {
return p;
}
}
public function set priority( priorityVal:Number ):void
{
myPriorityNode = replaceTextNode(getNode(), myPriorityNode, "priority", priorityVal.toString());
}
}
}
|
Make the constants const so it doesn't warn when I use them in data binding expressions
|
Make the constants const so it doesn't warn when I use them in data binding expressions
|
ActionScript
|
apache-2.0
|
igniterealtime/XIFF
|
3cfcc0dcab1f8235bc847b12b03e265006575382
|
swfcat.as
|
swfcat.as
|
package
{
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.events.Event;
import flash.utils.setTimeout;
import FacilitatorSocket;
import events.FacilitatorSocketEvent;
import ProxyPair;
import RTMFPProxyPair;
import SQSProxyPair;
import TCPProxyPair;
import rtmfp.CirrusSocket;
import rtmfp.events.CirrusSocketEvent;
public class swfcat extends Sprite
{
/* Adobe's Cirrus server for RTMFP connections.
The Cirrus key is defined at compile time by
reading from the CIRRUS_KEY environment var. */
private const DEFAULT_CIRRUS_ADDR:String = "rtmfp://p2p.rtmfp.net";
private const DEFAULT_CIRRUS_KEY:String = RTMFP::CIRRUS_KEY;
private const DEFAULT_FACILITATOR_ADDR:Object = {
host: "tor-facilitator.bamsoftware.com",
port: 9002
};
/* Default Tor client to use in case of RTMFP connection */
private const DEFAULT_TOR_CLIENT_ADDR:Object = {
host: "127.0.0.1",
port: 9002
};
// Milliseconds.
private const FACILITATOR_POLL_INTERVAL:int = 10000;
// Socket to Cirrus server
private var s_c:CirrusSocket;
// Socket to facilitator.
private var s_f:FacilitatorSocket;
// Handle local-remote traffic
private var p_p:ProxyPair;
private var client_id:String;
private var proxy_pair_factory:Function;
private var proxy_pairs:Array;
private var debug_mode:Boolean;
private var proxy_mode:Boolean;
/* TextField for debug output. */
private var output_text:TextField;
/* Badge for display */
private var badge:Badge;
private var fac_addr:Object;
private var relay_addr:Object;
public function swfcat()
{
proxy_mode = false;
debug_mode = false;
// Absolute positioning.
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
// Wait until the query string parameters are loaded.
this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
}
public function puts(s:String):void
{
if (output_text != null) {
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
}
private function loaderinfo_complete(e:Event):void
{
var fac_spec:String;
var relay_spec:String;
debug_mode = (this.loaderInfo.parameters["debug"] != null)
proxy_mode = (this.loaderInfo.parameters["proxy"] != null);
if (proxy_mode && !debug_mode) {
badge = new Badge();
addChild(badge);
} else {
output_text = new TextField();
output_text.width = stage.stageWidth;
output_text.height = stage.stageHeight;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44cc44;
addChild(output_text);
}
puts("Starting: parameters loaded.");
/* TODO: use this to have multiple proxies going at once */
proxy_pairs = new Array();
fac_spec = this.loaderInfo.parameters["facilitator"];
if (fac_spec) {
puts("Facilitator spec: \"" + fac_spec + "\"");
fac_addr = parse_addr_spec(fac_spec);
if (!fac_addr) {
puts("Error: Facilitator spec must be in the form \"host:port\".");
return;
}
} else {
fac_addr = DEFAULT_FACILITATOR_ADDR;
}
main();
}
/* The main logic begins here, after start-up issues are taken care of. */
private function main():void
{
if (proxy_mode) {
establish_facilitator_connection();
} else {
establish_cirrus_connection();
}
}
private function establish_cirrus_connection():void
{
s_c = new CirrusSocket();
s_c.addEventListener(CirrusSocketEvent.CONNECT_SUCCESS, function (e:CirrusSocketEvent):void {
puts("Cirrus: connected with id " + s_c.id + ".");
if (proxy_mode) {
start_proxy_pair();
s_c.send_hello(client_id);
} else {
establish_facilitator_connection();
}
});
s_c.addEventListener(CirrusSocketEvent.CONNECT_FAILED, function (e:CirrusSocketEvent):void {
puts("Error: failed to connect to Cirrus.");
});
s_c.addEventListener(CirrusSocketEvent.CONNECT_CLOSED, function (e:CirrusSocketEvent):void {
puts("Cirrus: closed connection.");
});
s_c.addEventListener(CirrusSocketEvent.HELLO_RECEIVED, function (e:CirrusSocketEvent):void {
puts("Cirrus: received hello from peer " + e.peer);
/* don't bother if we already have a proxy going */
if (p_p != null && p_p.connected) {
return;
}
/* if we're in proxy mode, we should have already set
up a proxy pair */
if (!proxy_mode) {
relay_addr = DEFAULT_TOR_CLIENT_ADDR;
proxy_pair_factory = rtmfp_proxy_pair_factory;
start_proxy_pair();
s_c.send_hello(e.peer);
} else if (!debug_mode && badge != null) {
badge.proxy_begin();
}
p_p.client = {peer: e.peer, stream: e.stream};
});
s_c.connect(DEFAULT_CIRRUS_ADDR, DEFAULT_CIRRUS_KEY);
}
private function establish_facilitator_connection():void
{
s_f = new FacilitatorSocket(fac_addr.host, fac_addr.port);
s_f.addEventListener(FacilitatorSocketEvent.CONNECT_FAILED, function (e:Event):void {
puts("Facilitator: connect failed.");
setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL);
});
if (proxy_mode) {
s_f.addEventListener(FacilitatorSocketEvent.REGISTRATION_RECEIVED, function (e:FacilitatorSocketEvent):void {
var client_addr:Object = parse_addr_spec(e.client);
relay_addr = parse_addr_spec(e.relay);
if (client_addr == null) {
puts("Facilitator: got registration " + e.client);
proxy_pair_factory = rtmfp_proxy_pair_factory;
if (s_c == null || !s_c.connected) {
client_id = e.client;
establish_cirrus_connection();
} else {
start_proxy_pair();
s_c.send_hello(e.client);
}
} else {
proxy_pair_factory = tcp_proxy_pair_factory;
start_proxy_pair();
p_p.client = client_addr;
}
});
s_f.addEventListener(FacilitatorSocketEvent.REGISTRATIONS_EMPTY, function (e:Event):void {
puts("Facilitator: no registrations available.");
setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL);
});
puts("Facilitator: getting registration.");
s_f.get_registration();
} else {
s_f.addEventListener(FacilitatorSocketEvent.REGISTRATION_FAILED, function (e:Event):void {
puts("Facilitator: registration failed.");
setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL);
});
puts("Facilitator: posting registration.");
s_f.post_registration(s_c.id);
}
}
private function start_proxy_pair():void
{
p_p = proxy_pair_factory();
p_p.addEventListener(Event.CONNECT, function (e:Event):void {
puts("ProxyPair: connected!");
});
p_p.addEventListener(Event.CLOSE, function (e:Event):void {
puts("ProxyPair: connection closed.");
p_p = null;
if (proxy_mode && !debug_mode && badge != null) {
badge.proxy_end();
}
establish_facilitator_connection();
});
p_p.relay = relay_addr;
}
private function rtmfp_proxy_pair_factory():ProxyPair
{
return new RTMFPProxyPair(this, s_c, s_c.local_stream_name);
}
// currently is the same as TCPProxyPair
// could be interesting to see how this works
// can't imagine it will work terribly well...
private function sqs_proxy_pair_factory():ProxyPair
{
return new SQSProxyPair(this);
}
private function tcp_proxy_pair_factory():ProxyPair
{
return new TCPProxyPair(this);
}
/* Parse an address in the form "host:port". Returns an Object with
keys "host" (String) and "port" (int). Returns null on error. */
private function parse_addr_spec(spec:String):Object
{
var parts:Array;
var addr:Object;
parts = spec.split(":", 2);
if (parts.length != 2 || !parseInt(parts[1]))
return null;
addr = {}
addr.host = parts[0];
addr.port = parseInt(parts[1]);
return addr;
}
}
}
import flash.text.TextFormat;
import flash.text.TextField;
class Badge extends flash.display.Sprite
{
/* Number of proxy pairs currently connected. */
private var num_proxy_pairs:int = 0;
/* Number of proxy pairs ever connected. */
private var total_proxy_pairs:int = 0;
[Embed(source="badge.png")]
private var BadgeImage:Class;
private var tot_client_count_tf:TextField;
private var tot_client_count_fmt:TextFormat;
private var cur_client_count_tf:TextField;
private var cur_client_count_fmt:TextFormat;
public function Badge()
{
/* Setup client counter for badge. */
tot_client_count_fmt = new TextFormat();
tot_client_count_fmt.color = 0xFFFFFF;
tot_client_count_fmt.align = "center";
tot_client_count_fmt.font = "courier-new";
tot_client_count_fmt.bold = true;
tot_client_count_fmt.size = 10;
tot_client_count_tf = new TextField();
tot_client_count_tf.width = 20;
tot_client_count_tf.height = 17;
tot_client_count_tf.background = false;
tot_client_count_tf.defaultTextFormat = tot_client_count_fmt;
tot_client_count_tf.x=47;
tot_client_count_tf.y=0;
cur_client_count_fmt = new TextFormat();
cur_client_count_fmt.color = 0xFFFFFF;
cur_client_count_fmt.align = "center";
cur_client_count_fmt.font = "courier-new";
cur_client_count_fmt.bold = true;
cur_client_count_fmt.size = 10;
cur_client_count_tf = new TextField();
cur_client_count_tf.width = 20;
cur_client_count_tf.height = 17;
cur_client_count_tf.background = false;
cur_client_count_tf.defaultTextFormat = cur_client_count_fmt;
cur_client_count_tf.x=47;
cur_client_count_tf.y=6;
addChild(new BadgeImage());
addChild(tot_client_count_tf);
addChild(cur_client_count_tf);
/* Update the client counter on badge. */
update_client_count();
}
public function proxy_begin():void
{
num_proxy_pairs++;
total_proxy_pairs++;
update_client_count();
}
public function proxy_end():void
{
num_proxy_pairs--;
update_client_count();
}
private function update_client_count():void
{
/* Update total client count. */
if (String(total_proxy_pairs).length == 1)
tot_client_count_tf.text = "0" + String(total_proxy_pairs);
else
tot_client_count_tf.text = String(total_proxy_pairs);
/* Update current client count. */
cur_client_count_tf.text = "";
for(var i:Number = 0; i < num_proxy_pairs; i++)
cur_client_count_tf.appendText(".");
}
}
|
package
{
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.events.Event;
import flash.utils.setTimeout;
import FacilitatorSocket;
import events.FacilitatorSocketEvent;
import ProxyPair;
import RTMFPProxyPair;
import SQSProxyPair;
import TCPProxyPair;
import rtmfp.CirrusSocket;
import rtmfp.events.CirrusSocketEvent;
public class swfcat extends Sprite
{
/* Adobe's Cirrus server for RTMFP connections.
The Cirrus key is defined at compile time by
reading from the CIRRUS_KEY environment var. */
private const DEFAULT_CIRRUS_ADDR:String = "rtmfp://p2p.rtmfp.net";
private const DEFAULT_CIRRUS_KEY:String = RTMFP::CIRRUS_KEY;
private const DEFAULT_FACILITATOR_ADDR:Object = {
host: "tor-facilitator.bamsoftware.com",
port: 9002
};
/* Default Tor client to use in case of RTMFP connection */
private const DEFAULT_TOR_CLIENT_ADDR:Object = {
host: "127.0.0.1",
port: 9002
};
// Milliseconds.
private const FACILITATOR_POLL_INTERVAL:int = 10000;
// Socket to Cirrus server
private var s_c:CirrusSocket;
// Socket to facilitator.
private var s_f:FacilitatorSocket;
// Handle local-remote traffic
private var p_p:ProxyPair;
private var client_id:String;
private var proxy_pair_factory:Function;
private var proxy_pairs:Array;
private var debug_mode:Boolean;
private var proxy_mode:Boolean;
/* TextField for debug output. */
private var output_text:TextField;
/* Badge for display */
private var badge:Badge;
private var fac_addr:Object;
private var relay_addr:Object;
public function swfcat()
{
proxy_mode = false;
debug_mode = false;
// Absolute positioning.
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
// Wait until the query string parameters are loaded.
this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
}
public function puts(s:String):void
{
if (output_text != null) {
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
}
private function loaderinfo_complete(e:Event):void
{
var fac_spec:String;
var relay_spec:String;
debug_mode = (this.loaderInfo.parameters["debug"] != null)
proxy_mode = (this.loaderInfo.parameters["proxy"] != null);
if (proxy_mode && !debug_mode) {
badge = new Badge();
addChild(badge);
} else {
output_text = new TextField();
output_text.width = stage.stageWidth;
output_text.height = stage.stageHeight;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44cc44;
addChild(output_text);
}
puts("Starting: parameters loaded.");
/* TODO: use this to have multiple proxies going at once */
proxy_pairs = new Array();
fac_spec = this.loaderInfo.parameters["facilitator"];
if (fac_spec) {
puts("Facilitator spec: \"" + fac_spec + "\"");
fac_addr = parse_addr_spec(fac_spec);
if (!fac_addr) {
puts("Error: Facilitator spec must be in the form \"host:port\".");
return;
}
} else {
fac_addr = DEFAULT_FACILITATOR_ADDR;
}
main();
}
/* The main logic begins here, after start-up issues are taken care of. */
private function main():void
{
if (proxy_mode) {
establish_facilitator_connection();
} else {
establish_cirrus_connection();
}
}
private function establish_cirrus_connection():void
{
s_c = new CirrusSocket();
s_c.addEventListener(CirrusSocketEvent.CONNECT_SUCCESS, function (e:CirrusSocketEvent):void {
puts("Cirrus: connected with id " + s_c.id + ".");
if (proxy_mode) {
start_proxy_pair();
s_c.send_hello(client_id);
} else {
establish_facilitator_connection();
}
});
s_c.addEventListener(CirrusSocketEvent.CONNECT_FAILED, function (e:CirrusSocketEvent):void {
puts("Error: failed to connect to Cirrus.");
});
s_c.addEventListener(CirrusSocketEvent.CONNECT_CLOSED, function (e:CirrusSocketEvent):void {
puts("Cirrus: closed connection.");
});
s_c.addEventListener(CirrusSocketEvent.HELLO_RECEIVED, function (e:CirrusSocketEvent):void {
puts("Cirrus: received hello from peer " + e.peer);
/* don't bother if we already have a proxy going */
if (p_p != null && p_p.connected) {
return;
}
/* if we're in proxy mode, we should have already set
up a proxy pair */
if (!proxy_mode) {
relay_addr = DEFAULT_TOR_CLIENT_ADDR;
proxy_pair_factory = rtmfp_proxy_pair_factory;
start_proxy_pair();
s_c.send_hello(e.peer);
} else if (!debug_mode && badge != null) {
badge.proxy_begin();
}
p_p.client = {peer: e.peer, stream: e.stream};
});
s_c.connect(DEFAULT_CIRRUS_ADDR, DEFAULT_CIRRUS_KEY);
}
private function establish_facilitator_connection():void
{
s_f = new FacilitatorSocket(fac_addr.host, fac_addr.port);
s_f.addEventListener(FacilitatorSocketEvent.CONNECT_FAILED, function (e:Event):void {
puts("Facilitator: connect failed.");
setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL);
});
if (proxy_mode) {
s_f.addEventListener(FacilitatorSocketEvent.REGISTRATION_RECEIVED, function (e:FacilitatorSocketEvent):void {
var client_addr:Object = parse_addr_spec(e.client);
relay_addr = parse_addr_spec(e.relay);
if (client_addr == null) {
puts("Facilitator: got registration " + e.client);
proxy_pair_factory = rtmfp_proxy_pair_factory;
if (s_c == null || !s_c.connected) {
client_id = e.client;
establish_cirrus_connection();
} else {
start_proxy_pair();
s_c.send_hello(e.client);
}
} else {
proxy_pair_factory = tcp_proxy_pair_factory;
start_proxy_pair();
p_p.client = client_addr;
}
});
s_f.addEventListener(FacilitatorSocketEvent.REGISTRATIONS_EMPTY, function (e:Event):void {
puts("Facilitator: no registrations available.");
setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL);
});
puts("Facilitator: getting registration.");
s_f.get_registration();
} else {
s_f.addEventListener(FacilitatorSocketEvent.REGISTRATION_FAILED, function (e:Event):void {
puts("Facilitator: registration failed.");
setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL);
});
puts("Facilitator: posting registration.");
s_f.post_registration(s_c.id);
}
}
private function start_proxy_pair():void
{
p_p = proxy_pair_factory();
p_p.addEventListener(Event.CONNECT, function (e:Event):void {
puts("ProxyPair: connected!");
});
p_p.addEventListener(Event.CLOSE, function (e:Event):void {
puts("ProxyPair: connection closed.");
p_p = null;
if (proxy_mode && !debug_mode && badge != null) {
badge.proxy_end();
}
establish_facilitator_connection();
});
p_p.relay = relay_addr;
}
private function rtmfp_proxy_pair_factory():ProxyPair
{
return new RTMFPProxyPair(this, s_c, s_c.local_stream_name);
}
// currently is the same as TCPProxyPair
// could be interesting to see how this works
// can't imagine it will work terribly well...
private function sqs_proxy_pair_factory():ProxyPair
{
return new SQSProxyPair(this);
}
private function tcp_proxy_pair_factory():ProxyPair
{
return new TCPProxyPair(this);
}
/* Parse an address in the form "host:port". Returns an Object with
keys "host" (String) and "port" (int). Returns null on error. */
private static function parse_addr_spec(spec:String):Object
{
var parts:Array;
var addr:Object;
parts = spec.split(":", 2);
if (parts.length != 2 || !parseInt(parts[1]))
return null;
addr = {}
addr.host = parts[0];
addr.port = parseInt(parts[1]);
return addr;
}
}
}
import flash.text.TextFormat;
import flash.text.TextField;
class Badge extends flash.display.Sprite
{
/* Number of proxy pairs currently connected. */
private var num_proxy_pairs:int = 0;
/* Number of proxy pairs ever connected. */
private var total_proxy_pairs:int = 0;
[Embed(source="badge.png")]
private var BadgeImage:Class;
private var tot_client_count_tf:TextField;
private var tot_client_count_fmt:TextFormat;
private var cur_client_count_tf:TextField;
private var cur_client_count_fmt:TextFormat;
public function Badge()
{
/* Setup client counter for badge. */
tot_client_count_fmt = new TextFormat();
tot_client_count_fmt.color = 0xFFFFFF;
tot_client_count_fmt.align = "center";
tot_client_count_fmt.font = "courier-new";
tot_client_count_fmt.bold = true;
tot_client_count_fmt.size = 10;
tot_client_count_tf = new TextField();
tot_client_count_tf.width = 20;
tot_client_count_tf.height = 17;
tot_client_count_tf.background = false;
tot_client_count_tf.defaultTextFormat = tot_client_count_fmt;
tot_client_count_tf.x=47;
tot_client_count_tf.y=0;
cur_client_count_fmt = new TextFormat();
cur_client_count_fmt.color = 0xFFFFFF;
cur_client_count_fmt.align = "center";
cur_client_count_fmt.font = "courier-new";
cur_client_count_fmt.bold = true;
cur_client_count_fmt.size = 10;
cur_client_count_tf = new TextField();
cur_client_count_tf.width = 20;
cur_client_count_tf.height = 17;
cur_client_count_tf.background = false;
cur_client_count_tf.defaultTextFormat = cur_client_count_fmt;
cur_client_count_tf.x=47;
cur_client_count_tf.y=6;
addChild(new BadgeImage());
addChild(tot_client_count_tf);
addChild(cur_client_count_tf);
/* Update the client counter on badge. */
update_client_count();
}
public function proxy_begin():void
{
num_proxy_pairs++;
total_proxy_pairs++;
update_client_count();
}
public function proxy_end():void
{
num_proxy_pairs--;
update_client_count();
}
private function update_client_count():void
{
/* Update total client count. */
if (String(total_proxy_pairs).length == 1)
tot_client_count_tf.text = "0" + String(total_proxy_pairs);
else
tot_client_count_tf.text = String(total_proxy_pairs);
/* Update current client count. */
cur_client_count_tf.text = "";
for(var i:Number = 0; i < num_proxy_pairs; i++)
cur_client_count_tf.appendText(".");
}
}
|
Make parse_addr_spec static.
|
Make parse_addr_spec static.
Uniformity with master.
|
ActionScript
|
mit
|
infinity0/flashproxy,infinity0/flashproxy,glamrock/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,infinity0/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy
|
60875f4cdc443f6b18fe717a32e2eb90238ad0f1
|
swfcat.as
|
swfcat.as
|
package
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.net.Socket;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.utils.ByteArray;
public class swfcat extends Sprite
{
private const TOR_ADDRESS:String = "173.255.221.44";
private const TOR_PORT:int = 9001;
private var output_text:TextField;
// Socket to Tor relay.
private var s_t:Socket;
// Socket to Facilitator.
private var s_f:Socket;
// Socket to client.
private var s_c:Socket;
private var fac_address:String;
private var fac_port:int;
private var client_address:String;
private var client_port:int;
private function puts(s:String):void
{
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
public function swfcat()
{
output_text = new TextField();
output_text.width = 400;
output_text.height = 300;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44CC44;
addChild(output_text);
puts("Starting.");
// Wait until the query string parameters are loaded.
this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
}
private function loaderinfo_complete(e:Event):void
{
var fac_spec:String, parts:Array;
puts("Parameters loaded.");
fac_spec = this.loaderInfo.parameters["facilitator"];
if (!fac_spec) {
puts("Error: no \"facilitator\" specification provided.");
return;
}
puts("Facilitator spec: \"" + fac_spec + "\"");
parts = fac_spec.split(":", 2);
if (parts.length != 2 || !parseInt(parts[1])) {
puts("Error: Facilitator spec must be in the form \"host:port\".");
return;
}
fac_address = parts[0];
fac_port = parseInt(parts[1]);
go(TOR_ADDRESS, TOR_PORT);
}
/* We connect first to the Tor relay; once that happens we connect to
the facilitator to get a client address; once we have the address
of a waiting client then we connect to the client and BAM! we're in business. */
private function go(tor_address:String, tor_port:int):void
{
s_t = new Socket();
s_t.addEventListener(Event.CONNECT, tor_connected);
s_t.addEventListener(Event.CLOSE, function (e:Event):void {
puts("Tor: closed.");
if (s_c.connected)
s_c.close();
});
s_t.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Tor: I/O error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
s_t.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Tor: security error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
puts("Tor: connecting to " + tor_address + ":" + tor_port + ".");
s_t.connect(tor_address, tor_port);
}
private function tor_connected(e:Event):void
{
/* Got a connection to tor, now let's get served a client from the facilitator */
s_f = new Socket();
puts("Tor: connected.");
s_f.addEventListener(Event.CONNECT, fac_connected);
s_f.addEventListener(Event.CLOSE, function (e:Event):void {
puts("Facilitator: closed connection.");
});
s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
if (s_t.connected)
s_t.close();
});
s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
if (s_t.connected)
s_t.close();
});
puts("Facilitator: connecting to " + fac_address + ":" + fac_port + ".");
s_f.connect(fac_address, fac_port);
/*s_c = new Socket();
puts("Tor: connected.");
s_c.addEventListener(Event.CONNECT, client_connected);
s_c.addEventListener(Event.CLOSE, function (e:Event):void {
puts("Client: closed.");
if (s_t.connected)
s_t.close();
});
s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Client: I/O error: " + e.text + ".");
if (s_t.connected)
s_t.close();
});
s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Client: security error: " + e.text + ".");
if (s_t.connected)
s_t.close();
});
puts("Client: connecting to " + client_address + ":" + client_port + ".");
s_c.connect(client_address, client_port);*/
}
private function fac_connected(e:Event):void
{
puts("Facilitator: connected.");
s_f.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var client_spec:String = new String();
client_spec = s_f.readMultiByte(0, "utf-8");
puts("Facilitator: got \"" + client_spec + "\"");
//s_c.writeBytes(bytes);
/* Need to parse the bytes to get the new client. Fill out client_address and client_port */
});
s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n");
}
private function client_connected(e:Event):void
{
puts("Client: connected.");
s_t.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_t.readBytes(bytes, 0, e.bytesLoaded);
puts("Tor: read " + bytes.length + ".");
s_c.writeBytes(bytes);
});
s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_c.readBytes(bytes, 0, e.bytesLoaded);
puts("Client: read " + bytes.length + ".");
s_t.writeBytes(bytes);
});
}
}
}
|
package
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.net.Socket;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.utils.ByteArray;
public class swfcat extends Sprite
{
private const TOR_ADDRESS:String = "173.255.221.44";
private const TOR_PORT:int = 9001;
private var output_text:TextField;
// Socket to Tor relay.
private var s_t:Socket;
// Socket to Facilitator.
private var s_f:Socket;
// Socket to client.
private var s_c:Socket;
private var fac_address:String;
private var fac_port:int;
private var client_address:String;
private var client_port:int;
private function puts(s:String):void
{
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
public function swfcat()
{
output_text = new TextField();
output_text.width = 400;
output_text.height = 300;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44CC44;
addChild(output_text);
puts("Starting.");
// Wait until the query string parameters are loaded.
this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
}
private function loaderinfo_complete(e:Event):void
{
var fac_spec:String, parts:Array;
puts("Parameters loaded.");
fac_spec = this.loaderInfo.parameters["facilitator"];
if (!fac_spec) {
puts("Error: no \"facilitator\" specification provided.");
return;
}
puts("Facilitator spec: \"" + fac_spec + "\"");
parts = fac_spec.split(":", 2);
if (parts.length != 2 || !parseInt(parts[1])) {
puts("Error: Facilitator spec must be in the form \"host:port\".");
return;
}
fac_address = parts[0];
fac_port = parseInt(parts[1]);
go(TOR_ADDRESS, TOR_PORT);
}
/* We connect first to the Tor relay; once that happens we connect to
the facilitator to get a client address; once we have the address
of a waiting client then we connect to the client and BAM! we're in business. */
private function go(tor_address:String, tor_port:int):void
{
s_t = new Socket();
s_t.addEventListener(Event.CONNECT, tor_connected);
s_t.addEventListener(Event.CLOSE, function (e:Event):void {
puts("Tor: closed.");
if (s_c.connected)
s_c.close();
});
s_t.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Tor: I/O error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
s_t.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Tor: security error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
puts("Tor: connecting to " + tor_address + ":" + tor_port + ".");
s_t.connect(tor_address, tor_port);
}
private function tor_connected(e:Event):void
{
/* Got a connection to tor, now let's get served a client from the facilitator */
s_f = new Socket();
puts("Tor: connected.");
s_f.addEventListener(Event.CONNECT, fac_connected);
s_f.addEventListener(Event.CLOSE, function (e:Event):void {
puts("Facilitator: closed connection.");
});
s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
if (s_t.connected)
s_t.close();
});
s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
if (s_t.connected)
s_t.close();
});
puts("Facilitator: connecting to " + fac_address + ":" + fac_port + ".");
s_f.connect(fac_address, fac_port);
/*s_c = new Socket();
puts("Tor: connected.");
s_c.addEventListener(Event.CONNECT, client_connected);
s_c.addEventListener(Event.CLOSE, function (e:Event):void {
puts("Client: closed.");
if (s_t.connected)
s_t.close();
});
s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Client: I/O error: " + e.text + ".");
if (s_t.connected)
s_t.close();
});
s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Client: security error: " + e.text + ".");
if (s_t.connected)
s_t.close();
});
puts("Client: connecting to " + client_address + ":" + client_port + ".");
s_c.connect(client_address, client_port);*/
}
private function fac_connected(e:Event):void
{
puts("Facilitator: connected.");
s_f.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var client_spec:String = new String();
client_spec = s_f.readMultiByte(e.bytesLoaded, "utf-8");
puts("Facilitator: got \"" + client_spec + "\"");
//s_c.writeBytes(bytes);
/* Need to parse the bytes to get the new client. Fill out client_address and client_port */
});
s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n");
}
private function client_connected(e:Event):void
{
puts("Client: connected.");
s_t.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_t.readBytes(bytes, 0, e.bytesLoaded);
puts("Tor: read " + bytes.length + ".");
s_c.writeBytes(bytes);
});
s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_c.readBytes(bytes, 0, e.bytesLoaded);
puts("Client: read " + bytes.length + ".");
s_t.writeBytes(bytes);
});
}
}
}
|
Use e.bytesLoaded, not 0, to read the client address.
|
Use e.bytesLoaded, not 0, to read the client address.
An argument of 0 works for Jonathan but for be it returns a 0-length
string.
|
ActionScript
|
mit
|
glamrock/flashproxy,glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,infinity0/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,infinity0/flashproxy,infinity0/flashproxy,infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,glamrock/flashproxy
|
e1e55a7e0dd60493fbde13b609aaa7417b511a8a
|
com/segonquart/idiomesAnimation.as
|
com/segonquart/idiomesAnimation.as
|
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
class idiomesAnimation extends Movieclip
{
private var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr");
function idiomesAnimation():Void
{
this.onEnterFrame = this.enterSlide;
}
private function enterSlide():Void
{
arrayLang_arr[0].slideTo('0', '-40', 0.6, 'easeInOutBack', 1);
arrayLang_arr[1].slideTo('0', '-40', 0.8, 'easeInOutBack', 1.1);
arrayLang_arr[2].slideTo('0', '-40', 0.9, 'easeInOutBack', 1.2);
arrayLang_arr[3].slideTo('0', '-40', 1, 'easeInOutBack', 1.3);
return this;
}
public function IdiomesColour():Void
{
this.onRelease = this arrayColour;
target = this.arrayLang_arr[i];
target._tint = 0x8DC60D;
return this;
}
private function arrayColour():Void
{
for ( var:i ; arrayLang_arr[i] <4; i++)
{
this.colorTo("#628D22", 0.3, "easeOutCirc");
_parent.colorTo('#4b4b4b', 1, 'linear', .2);
}
}
}
|
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
class idiomesAnimation extends Movieclip
{
private var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr");
function idiomesAnimation():Void
{
this.onEnterFrame = this.enterSlide;
}
private function enterSlide()
{
arrayLang_arr[0].slideTo('0', '-40', 0.6, 'easeInOutBack', 1);
arrayLang_arr[1].slideTo('0', '-40', 0.8, 'easeInOutBack', 1.1);
arrayLang_arr[2].slideTo('0', '-40', 0.9, 'easeInOutBack', 1.2);
arrayLang_arr[3].slideTo('0', '-40', 1, 'easeInOutBack', 1.3);
return this;
}
public function IdiomesColour()
{
this.onRelease = this arrayColour;
target = this.arrayLang_arr[i];
target._tint = 0x8DC60D;
return this;
}
private function arrayColour()
{
for ( var:i ; arrayLang_arr[i] <4; i++)
{
this.colorTo("#628D22", 0.3, "easeOutCirc");
_parent.colorTo('#4b4b4b', 1, 'linear', .2);
}
}
}
|
Update idiomesAnimation.as
|
Update idiomesAnimation.as
|
ActionScript
|
bsd-3-clause
|
delfiramirez/web-talking-wear,delfiramirez/web-talking-wear,delfiramirez/web-talking-wear
|
11cfba3b3703489d80702bd2de2bd64b7ac424be
|
src/org/mangui/hls/HLSSettings.as
|
src/org/mangui/hls/HLSSettings.as
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls {
import org.mangui.hls.constant.HLSSeekMode;
import org.mangui.hls.constant.HLSMaxLevelCappingMode;
public final class HLSSettings extends Object {
/**
* Limit levels usable in auto-quality by the stage dimensions (width and height).
* true - level width and height (defined in m3u8 playlist) will be compared with the player width and height (stage.stageWidth and stage.stageHeight).
* Max level will be set depending on the maxLevelCappingMode option.
* false - levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration.
*
* Note: this setting is ignored in manual mode so all the levels could be selected manually.
*
* Default is false
*/
public static var capLevelToStage : Boolean = false;
/**
* Defines the max level capping mode to the one available in HLSMaxLevelCappingMode
* HLSMaxLevelCappingMode.DOWNSCALE - max capped level should be the one with the dimensions equal or greater than the stage dimensions (so the video will be downscaled)
* HLSMaxLevelCappingMode.UPSCALE - max capped level should be the one with the dimensions equal or lower than the stage dimensions (so the video will be upscaled)
*
* Default is HLSMaxLevelCappingMode.DOWNSCALE
*/
public static var maxLevelCappingMode : String = HLSMaxLevelCappingMode.DOWNSCALE;
// // // // // // /////////////////////////////////
//
// org.mangui.hls.stream.HLSNetStream
//
// // // // // // /////////////////////////////////
/**
* Defines minimum buffer length in seconds before playback can start, after seeking or buffer stalling.
*
* Default is -1 = auto
*/
public static var minBufferLength : Number = -1;
/**
* Defines maximum buffer length in seconds.
* (0 means infinite buffering)
*
* Default is 120.
*/
public static var maxBufferLength : Number = 120;
/**
* Defines maximum back buffer length in seconds.
* (0 means infinite back buffering)
*
* Default is 30.
*/
public static var maxBackBufferLength : Number = 30;
/**
* Defines low buffer length in seconds.
* When crossing down this threshold, HLS will switch to buffering state.
*
* Default is 3.
*/
public static var lowBufferLength : Number = 3;
/**
* Defines seek mode to one form available in HLSSeekMode class:
* HLSSeekMode.ACCURATE_SEEK - accurate seeking to exact requested position
* HLSSeekMode.KEYFRAME_SEEK - key-frame based seeking (seek to nearest key frame before requested seek position)
*
* Default is HLSSeekMode.KEYFRAME_SEEK.
*/
public static var seekMode : String = HLSSeekMode.KEYFRAME_SEEK;
/** max nb of retries for Key Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var keyLoadMaxRetry : int = -1;
/** keyLoadMaxRetryTimeout
* Maximum key retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on key request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until keyLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var keyLoadMaxRetryTimeout : Number = 64000;
/** max nb of retries for Fragment Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var fragmentLoadMaxRetry : int = 4000;
/** fragmentLoadMaxRetryTimeout
* Maximum Fragment retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until fragmentLoadMaxRetryTimeout is reached.
*
* Default is 4000.
*/
public static var fragmentLoadMaxRetryTimeout : Number = 64000;
/** fragmentLoadSkipAfterMaxRetry
* control behaviour in case fragment load still fails after max retry timeout
* if set to true, fragment will be skipped and next one will be loaded.
* If set to false, an I/O Error will be raised.
*
* Default is true.
*/
public static var fragmentLoadSkipAfterMaxRetry : Boolean = true;
/**
* If set to true, live playlist will be flushed from URL cache before reloading
* (this is to workaround some cache issues with some combination of Flash Player / IE version)
*
* Default is false
*/
public static var flushLiveURLCache : Boolean = false;
/** max nb of retries for Manifest Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var manifestLoadMaxRetry : int = -1;
/** manifestLoadMaxRetryTimeout
* Maximum Manifest retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until manifestLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var manifestLoadMaxRetryTimeout : Number = 64000;
/**
* If greater than 0, specifies the preferred bitrate.
* If -1, and startFromLevel is not specified, automatic start level selection will be used.
* This parameter, if set, will take priority over startFromLevel.
*/
public static var startFromBitrate : Number = -1;
/** start level :
* from 0 to 1 : indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
* -2 : playback will start from the first level appearing in Manifest (not sorted by bitrate)
*/
public static var startFromLevel : Number = -1;
/** seek level :
* from 0 to 1 : indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, keep previous level matching previous download bandwidth
*/
public static var seekFromLevel : Number = -1;
/** use hardware video decoder :
* it will set NetStream.useHardwareDecoder
* refer to http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#useHardwareDecoder
*/
public static var useHardwareVideoDecoder : Boolean = false;
/**
* Defines whether INFO level log messages will will appear in the console
* Default is true.
*/
public static var logInfo : Boolean = true;
/**
* Defines whether DEBUG level log messages will will appear in the console
* Default is false.
*/
public static var logDebug : Boolean = false;
/**
* Defines whether DEBUG2 level log messages will will appear in the console
* Default is false.
*/
public static var logDebug2 : Boolean = false;
/**
* Defines whether WARN level log messages will will appear in the console
* Default is true.
*/
public static var logWarn : Boolean = true;
/**
* Defines whether ERROR level log messages will will appear in the console
* Default is true.
*/
public static var logError : Boolean = true;
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls {
import org.mangui.hls.constant.HLSSeekMode;
import org.mangui.hls.constant.HLSMaxLevelCappingMode;
public final class HLSSettings extends Object {
/**
* Limit levels usable in auto-quality by the stage dimensions (width and height).
* true - level width and height (defined in m3u8 playlist) will be compared with the player width and height (stage.stageWidth and stage.stageHeight).
* Max level will be set depending on the maxLevelCappingMode option.
* false - levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration.
*
* Note: this setting is ignored in manual mode so all the levels could be selected manually.
*
* Default is false
*/
public static var capLevelToStage : Boolean = false;
/**
* Defines the max level capping mode to the one available in HLSMaxLevelCappingMode
* HLSMaxLevelCappingMode.DOWNSCALE - max capped level should be the one with the dimensions equal or greater than the stage dimensions (so the video will be downscaled)
* HLSMaxLevelCappingMode.UPSCALE - max capped level should be the one with the dimensions equal or lower than the stage dimensions (so the video will be upscaled)
*
* Default is HLSMaxLevelCappingMode.DOWNSCALE
*/
public static var maxLevelCappingMode : String = HLSMaxLevelCappingMode.DOWNSCALE;
// // // // // // /////////////////////////////////
//
// org.mangui.hls.stream.HLSNetStream
//
// // // // // // /////////////////////////////////
/**
* Defines minimum buffer length in seconds before playback can start, after seeking or buffer stalling.
*
* Default is -1 = auto
*/
public static var minBufferLength : Number = -1;
/**
* Defines maximum buffer length in seconds.
* (0 means infinite buffering)
*
* Default is 120.
*/
public static var maxBufferLength : Number = 120;
/**
* Defines maximum back buffer length in seconds.
* (0 means infinite back buffering)
*
* Default is 30.
*/
public static var maxBackBufferLength : Number = 30;
/**
* Defines low buffer length in seconds.
* When crossing down this threshold, HLS will switch to buffering state.
*
* Default is 3.
*/
public static var lowBufferLength : Number = 3;
/**
* Defines seek mode to one form available in HLSSeekMode class:
* HLSSeekMode.ACCURATE_SEEK - accurate seeking to exact requested position
* HLSSeekMode.KEYFRAME_SEEK - key-frame based seeking (seek to nearest key frame before requested seek position)
*
* Default is HLSSeekMode.KEYFRAME_SEEK.
*/
public static var seekMode : String = HLSSeekMode.KEYFRAME_SEEK;
/** max nb of retries for Key Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var keyLoadMaxRetry : int = -1;
/** keyLoadMaxRetryTimeout
* Maximum key retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on key request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until keyLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var keyLoadMaxRetryTimeout : Number = 64000;
/** max nb of retries for Fragment Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var fragmentLoadMaxRetry : int = 4000;
/** fragmentLoadMaxRetryTimeout
* Maximum Fragment retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until fragmentLoadMaxRetryTimeout is reached.
*
* Default is 4000.
*/
public static var fragmentLoadMaxRetryTimeout : Number = 64000;
/** fragmentLoadSkipAfterMaxRetry
* control behaviour in case fragment load still fails after max retry timeout
* if set to true, fragment will be skipped and next one will be loaded.
* If set to false, an I/O Error will be raised.
*
* Default is true.
*/
public static var fragmentLoadSkipAfterMaxRetry : Boolean = true;
/**
* If set to true, live playlist will be flushed from URL cache before reloading
* (this is to workaround some cache issues with some combination of Flash Player / IE version)
*
* Default is false
*/
public static var flushLiveURLCache : Boolean = false;
/** max nb of retries for Manifest Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var manifestLoadMaxRetry : int = -1;
/** manifestLoadMaxRetryTimeout
* Maximum Manifest retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until manifestLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var manifestLoadMaxRetryTimeout : Number = 64000;
/**
* If greater than 0, specifies the preferred bitrate.
* If -1, and startFromLevel is not specified, automatic start level selection will be used.
* This parameter, if set, will take priority over startFromLevel.
*/
public static var startFromBitrate : Number = -1;
/** start level :
* from 0 to 1 : indicates the "normalized" preferred level. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
* -2 : playback will start from the first level appearing in Manifest (not sorted by bitrate)
*/
public static var startFromLevel : Number = -1;
/** seek level :
* from 0 to 1 : indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, keep previous level matching previous download bandwidth
*/
public static var seekFromLevel : Number = -1;
/** use hardware video decoder :
* it will set NetStream.useHardwareDecoder
* refer to http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#useHardwareDecoder
*/
public static var useHardwareVideoDecoder : Boolean = false;
/**
* Defines whether INFO level log messages will will appear in the console
* Default is true.
*/
public static var logInfo : Boolean = true;
/**
* Defines whether DEBUG level log messages will will appear in the console
* Default is false.
*/
public static var logDebug : Boolean = false;
/**
* Defines whether DEBUG2 level log messages will will appear in the console
* Default is false.
*/
public static var logDebug2 : Boolean = false;
/**
* Defines whether WARN level log messages will will appear in the console
* Default is true.
*/
public static var logWarn : Boolean = true;
/**
* Defines whether ERROR level log messages will will appear in the console
* Default is true.
*/
public static var logError : Boolean = true;
}
}
|
fix typo
|
fix typo
|
ActionScript
|
mpl-2.0
|
dighan/flashls,mangui/flashls,clappr/flashls,fixedmachine/flashls,suuhas/flashls,NicolasSiver/flashls,codex-corp/flashls,vidible/vdb-flashls,neilrackett/flashls,suuhas/flashls,tedconf/flashls,mangui/flashls,thdtjsdn/flashls,Boxie5/flashls,Boxie5/flashls,Peer5/flashls,clappr/flashls,hola/flashls,aevange/flashls,fixedmachine/flashls,codex-corp/flashls,aevange/flashls,Corey600/flashls,jlacivita/flashls,thdtjsdn/flashls,suuhas/flashls,dighan/flashls,loungelogic/flashls,Peer5/flashls,Corey600/flashls,tedconf/flashls,JulianPena/flashls,neilrackett/flashls,hola/flashls,suuhas/flashls,aevange/flashls,Peer5/flashls,jlacivita/flashls,aevange/flashls,NicolasSiver/flashls,loungelogic/flashls,JulianPena/flashls,Peer5/flashls,vidible/vdb-flashls
|
a7b9e1275e7e95b24650d11cc7e1d68872a521ad
|
src/com/mangui/HLS/muxing/AVC.as
|
src/com/mangui/HLS/muxing/AVC.as
|
package com.mangui.HLS.muxing {
import com.mangui.HLS.utils.*;
import flash.utils.ByteArray;
/** Constants and utilities for the H264 video format. **/
public class AVC {
/** H264 NAL unit names. **/
public static const NAMES:Array = [
'Unspecified',
'NDR',
'Partition A',
'Partition B',
'Partition C',
'IDR',
'SEI',
'SPS',
'PPS',
'AUD',
'End of Sequence',
'End of Stream',
'Filler Data'
];
/** H264 profiles. **/
public static const PROFILES:Object = {
'66': 'H264 Baseline',
'77': 'H264 Main',
'100': 'H264 High'
};
/** Get Avcc header from AVC stream. **/
public static function getAVCC(nalu:ByteArray,position:Number=0):ByteArray {
// Find SPS and PPS units in AVC stream.
var units:Array = AVC.getNALU(nalu,position,false);
var sps:Number = -1;
var pps:Number = -1;
for(var i:Number = 0; i< units.length; i++) {
if(units[i].type == 7 && sps == -1) {
sps = i;
} else if (units[i].type == 8 && pps == -1) {
pps = i;
}
}
// Throw errors if units not found.
if(sps == -1) {
throw new Error("No SPS NAL unit found in this stream.");
} else if (pps == -1) {
throw new Error("No PPS NAL unit found in this stream.");
}
// Write startbyte, profile, compatibility and level.
var avcc:ByteArray = new ByteArray();
avcc.writeByte(0x01);
avcc.writeBytes(nalu,units[sps].start+1, 3);
// 111111 + NALU bytesize length (4?)
avcc.writeByte(0xFF);
// Number of SPS, Bytesize and data.
avcc.writeByte(0xE1);
avcc.writeShort(units[sps].length);
avcc.writeBytes(nalu,units[sps].start,units[sps].length);
// Number of PPS, Bytesize and data.
avcc.writeByte(0x01);
avcc.writeShort(units[pps].length);
avcc.writeBytes(nalu,units[pps].start,units[pps].length);
// Grab profile/level
avcc.position = 1;
var prf:Number = avcc.readByte();
avcc.position = 3;
var lvl:Number = avcc.readByte();
avcc.position = 0;
// Log.txt("AVC: "+PROFILES[prf]+' level '+lvl);
return avcc;
};
/** Return an array with NAL delimiter indexes. **/
public static function getNALU(nalu:ByteArray,position:Number=0,log:Boolean=true):Array {
var units:Array = [];
var unit_start:Number;
var unit_type:Number;
var unit_header:Number;
// Loop through data to find NAL startcodes.
var window:uint = 0;
nalu.position = position;
while(nalu.bytesAvailable > 4) {
window = nalu.readUnsignedInt();
// Match four-byte startcodes
if((window & 0xFFFFFFFF) == 0x01) {
if(unit_start) {
units.push({
length: nalu.position - 4 - unit_start,
start: unit_start,
type: unit_type
});
}
unit_header = 4;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
if(unit_type == 1 || unit_type == 5) { break; }
// Match three-byte startcodes
} else if((window & 0xFFFFFF00) == 0x100) {
if(unit_start) {
units.push({
header: unit_header,
length: nalu.position - 4 - unit_start,
start: unit_start,
type: unit_type
});
}
nalu.position--;
unit_header = 3;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
if(unit_type == 1 || unit_type == 5) { break; }
} else {
nalu.position -= 3;
}
}
// Append the last NAL to the array.
if(unit_start) {
units.push({
header: unit_header,
length: nalu.length - unit_start,
start: unit_start,
type: unit_type
});
}
// Reset position and return results.
if(log) {
if(units.length) {
var txt:String = "AVC: ";
for(var i:Number=0; i<units.length; i++) {
txt += NAMES[units[i].type] + ", ";
}
// Log.txt(txt.substr(0,txt.length-2) + " slices");
} else {
// Log.txt('AVC: no NALU slices found');
}
}
nalu.position = position;
return units;
};
}
}
|
package com.mangui.HLS.muxing {
import com.mangui.HLS.utils.*;
import flash.utils.ByteArray;
/** Constants and utilities for the H264 video format. **/
public class AVC {
/** H264 NAL unit names. **/
public static const NAMES:Array = [
'Unspecified',
'NDR',
'Partition A',
'Partition B',
'Partition C',
'IDR',
'SEI',
'SPS',
'PPS',
'AUD',
'End of Sequence',
'End of Stream',
'Filler Data'
];
/** H264 profiles. **/
public static const PROFILES:Object = {
'66': 'H264 Baseline',
'77': 'H264 Main',
'100': 'H264 High'
};
/** Get Avcc header from AVC stream. **/
public static function getAVCC(nalu:ByteArray,position:Number=0):ByteArray {
// Find SPS and PPS units in AVC stream.
var units:Array = AVC.getNALU(nalu,position,false);
var sps:Number = -1;
var pps:Number = -1;
for(var i:Number = 0; i< units.length; i++) {
if(units[i].type == 7 && sps == -1) {
sps = i;
} else if (units[i].type == 8 && pps == -1) {
pps = i;
}
}
// Throw errors if units not found.
if(sps == -1) {
throw new Error("No SPS NAL unit found in this stream.");
} else if (pps == -1) {
throw new Error("No PPS NAL unit found in this stream.");
}
// Write startbyte
var avcc:ByteArray = new ByteArray();
avcc.writeByte(0x01);
// Write profile, compatibility and level.
avcc.writeBytes(nalu,units[sps].start+1, 3);
// reserved (6 bits), NALU length size - 1 (2 bits)
avcc.writeByte(0xFC | 3);
// reserved (3 bits), num of SPS (5 bits)
avcc.writeByte(0xE0 | 1);
// 2 bytes for length of SPS
avcc.writeShort(units[sps].length);
// data of SPS
avcc.writeBytes(nalu,units[sps].start,units[sps].length);
// Number of PPS
avcc.writeByte(0x01);
// 2 bytes for length of PPS
avcc.writeShort(units[pps].length);
// data of PPS
avcc.writeBytes(nalu,units[pps].start,units[pps].length);
// Grab profile/level
avcc.position = 1;
var prf:Number = avcc.readByte();
avcc.position = 3;
var lvl:Number = avcc.readByte();
avcc.position = 0;
// Log.txt("AVC: "+PROFILES[prf]+' level '+lvl);
return avcc;
};
/** Return an array with NAL delimiter indexes. **/
public static function getNALU(nalu:ByteArray,position:Number=0,log:Boolean=true):Array {
var units:Array = [];
var unit_start:Number;
var unit_type:Number;
var unit_header:Number;
// Loop through data to find NAL startcodes.
var window:uint = 0;
nalu.position = position;
while(nalu.bytesAvailable > 4) {
window = nalu.readUnsignedInt();
// Match four-byte startcodes
if((window & 0xFFFFFFFF) == 0x01) {
if(unit_start) {
units.push({
length: nalu.position - 4 - unit_start,
start: unit_start,
type: unit_type
});
}
unit_header = 4;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if(unit_type == 1 || unit_type == 5) { break; }
// Match three-byte startcodes
} else if((window & 0xFFFFFF00) == 0x100) {
if(unit_start) {
units.push({
header: unit_header,
length: nalu.position - 4 - unit_start,
start: unit_start,
type: unit_type
});
}
nalu.position--;
unit_header = 3;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if(unit_type == 1 || unit_type == 5) { break; }
} else {
nalu.position -= 3;
}
}
// Append the last NAL to the array.
if(unit_start) {
units.push({
header: unit_header,
length: nalu.length - unit_start,
start: unit_start,
type: unit_type
});
}
// Reset position and return results.
if(log) {
if(units.length) {
var txt:String = "AVC: ";
for(var i:Number=0; i<units.length; i++) {
txt += NAMES[units[i].type] + ", ";
}
// Log.txt(txt.substr(0,txt.length-2) + " slices");
} else {
// Log.txt('AVC: no NALU slices found');
}
}
nalu.position = position;
return units;
};
}
}
|
add comments for NAL unit parsing
|
add comments for NAL unit parsing
|
ActionScript
|
mpl-2.0
|
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
|
4fa07e9cc32797cf9f7222628381f271a3c9ae4a
|
src/com/axis/rtspclient/RTSPClient.as
|
src/com/axis/rtspclient/RTSPClient.as
|
package com.axis.rtspclient {
import flash.events.EventDispatcher;
import flash.events.Event;
import flash.utils.ByteArray;
import flash.net.Socket;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.media.Video;
import mx.utils.StringUtil;
import com.axis.rtspclient.FLVMux;
import com.axis.rtspclient.RTP;
import com.axis.rtspclient.SDP;
import com.axis.http.url;
import com.axis.http.request;
import com.axis.http.auth;
import com.axis.IClient;
import com.axis.ClientEvent;
public class RTSPClient extends EventDispatcher implements IClient {
[Embed(source = "../../../../VERSION", mimeType = "application/octet-stream")] private var Version:Class;
private var userAgent:String;
private static var STATE_INITIAL:uint = 1 << 0;
private static var STATE_OPTIONS:uint = 1 << 1;
private static var STATE_DESCRIBE:uint = 1 << 2;
private static var STATE_SETUP:uint = 1 << 3;
private static var STATE_PLAY:uint = 1 << 4;
private static var STATE_PLAYING:uint = 1 << 5;
private static var STATE_PAUSE:uint = 1 << 6;
private static var STATE_PAUSED:uint = 1 << 7;
private static var STATE_TEARDOWN:uint = 1 << 8;
private var state:int = STATE_INITIAL;
private var handle:IRTSPHandle;
private var ns:NetStream;
private var video:Video;
private var sdp:SDP = new SDP();
private var flvmux:FLVMux;
private var urlParsed:Object;
private var cSeq:uint = 1;
private var session:String;
private var contentBase:String;
private var interleaveChannelIndex:uint = 0;
private var methods:Array = [];
private var data:ByteArray = new ByteArray();
private var rtpLength:int = -1;
private var rtpChannel:int = -1;
private var tracks:Array;
private var authState:String = "none";
private var authOpts:Object = {};
private var digestNC:uint = 1;
public function RTSPClient(video:Video, urlParsed:Object, handle:IRTSPHandle) {
this.userAgent = "Slush " + StringUtil.trim(new Version().toString());
this.state = STATE_INITIAL;
this.handle = handle;
this.ns = ns;
this.video = video;
this.urlParsed = urlParsed;
handle.addEventListener('data', this.onData);
}
public function start():Boolean {
var self:RTSPClient = this;
handle.addEventListener('connected', function():void {
if (state !== STATE_INITIAL) {
trace('Cannot start unless in initial state.');
return;
}
/* If the handle closes, take care of it */
handle.addEventListener('closed', self.onClose);
if (0 === self.methods.length) {
/* We don't know the options yet. Start with that. */
sendOptionsReq();
} else {
/* Already queried the options (and perhaps got unauthorized on describe) */
sendDescribeReq();
}
});
var nc:NetConnection = new NetConnection();
nc.connect(null);
this.ns = new NetStream(nc);
dispatchEvent(new ClientEvent(ClientEvent.NETSTREAM_CREATED, { ns : this.ns }));
video.attachNetStream(this.ns);
handle.connect();
return true;
}
public function pause():Boolean
{
if (state !== STATE_PLAYING) {
trace('Unable to pause a stream if not playing.');
return false;
}
try {
sendPauseReq();
} catch (err:Error) {
trace("Unable to pause: " + err.message);
return false;
}
return true;
}
public function resume():Boolean
{
if (state !== STATE_PAUSED) {
trace('Unable to resume a stream if not paused.');
return false;
}
sendPlayReq();
return true;
}
public function stop():Boolean
{
if (state < STATE_PLAY) {
trace('Unable to stop if we never reached play.');
return false;
}
sendTeardownReq();
return true;
}
private function onClose(event:Event):void
{
if (state === STATE_TEARDOWN) {
dispatchEvent(new ClientEvent(ClientEvent.STOPPED));
} else {
trace('RTSPClient: Handle unexpectedly closed.');
}
}
private function onData(event:Event):void
{
/* read one byte to determine destination */
if (0 < data.bytesAvailable) {
/* Determining byte have already been read. This is a continuation */
} else {
/* Read the determining byte */
handle.readBytes(data, 0, 1);
}
switch(data[0]) {
case 0x52:
/* ascii 'R', start of RTSP */
onRTSPCommand();
break;
case 0x24:
/* ascii '$', start of interleaved packet */
onInterleavedData();
break;
default:
trace('Unknown determining byte:', data[0]);
break;
}
}
private function requestReset():void
{
var copy:ByteArray = new ByteArray();
data.readBytes(copy);
data.clear();
copy.readBytes(data);
rtpLength = -1;
rtpChannel = -1;
}
private function readRequest(oBody:ByteArray):*
{
var parsed:* = request.readHeaders(handle, data);
if (false === parsed) {
return false;
}
if (401 === parsed.code) {
/* Unauthorized, change authState and (possibly) try again */
authOpts = parsed.headers['www-authenticate'];
var newAuthState:String = auth.nextMethod(authState, authOpts);
if (authState === newAuthState) {
trace('GET: Exhausted all authentication methods.');
trace('GET: Unable to authorize to ' + urlParsed.host);
return false;
}
trace('RTSPClient: switching http-authorization from ' + authState + ' to ' + newAuthState);
authState = newAuthState;
state = STATE_INITIAL;
data = new ByteArray();
handle.reconnect();
return false;
}
if (data.bytesAvailable < parsed.headers['content-length']) {
return false;
}
/* RTSP commands contain no heavy body, so it's safe to read everything */
data.readBytes(oBody, 0, parsed.headers['content-length']);
requestReset();
return parsed;
}
private function onRTSPCommand():void {
var parsed:*, body:ByteArray = new ByteArray();
if (false === (parsed = readRequest(body))) {
return;
}
if (200 !== parsed.code) {
trace('RTSPClient: Invalid RTSP response - ', parsed.code, parsed.message);
return;
}
switch (state) {
case STATE_INITIAL:
trace("RTSPClient: STATE_INITIAL");
case STATE_OPTIONS:
trace("RTSPClient: STATE_DESCRIBE");
this.methods = parsed.headers.public.split(/[ ]*,[ ]*/);
sendDescribeReq();
break;
case STATE_DESCRIBE:
trace("RTSPClient: STATE_DESCRIBE");
if (!sdp.parse(body)) {
trace("RTSPClient:Failed to parse SDP file");
return;
}
if (!parsed.headers['content-base']) {
trace('RTSPClient: no content-base in describe reply');
return;
}
contentBase = parsed.headers['content-base'];
tracks = sdp.getMediaBlockList();
trace('SDP contained ' + tracks.length + ' track(s). Calling SETUP for each.');
if (0 === tracks.length) {
trace('No tracks in SDP file.');
return;
}
/* Fall through, it's time for setup */
case STATE_SETUP:
trace("RTSPClient: STATE_SETUP");
if (parsed.headers['session']) {
session = parsed.headers['session'];
}
if (0 !== tracks.length) {
/* More tracks we must setup before playing */
var block:Object = tracks.shift();
sendSetupReq(block);
return;
}
/* All tracks setup and ready to go! */
sendPlayReq();
break;
case STATE_PLAY:
trace("RTSPClient: STATE_PLAY");
state = STATE_PLAYING;
if (this.flvmux) {
/* If the flvmux have been initialized don't do it again.
this is probably a resume after pause */
break;
}
this.flvmux = new FLVMux(this.ns, this.sdp);
var analu:ANALU = new ANALU();
var aaac:AAAC = new AAAC(sdp);
this.addEventListener("VIDEO_PACKET", analu.onRTPPacket);
this.addEventListener("AUDIO_PACKET", aaac.onRTPPacket);
analu.addEventListener(NALU.NEW_NALU, flvmux.onNALU);
aaac.addEventListener(AACFrame.NEW_FRAME, flvmux.onAACFrame);
break;
case STATE_PLAYING:
trace("RTSPClient: STATE_PLAYING");
break;
case STATE_PAUSE:
trace("RTSPClient: STATE_PAUSE");
state = STATE_PAUSED;
break;
case STATE_TEARDOWN:
trace('RTSPClient: STATE_TEARDOWN');
handle.disconnect();
break;
}
if (0 < data.bytesAvailable) {
onData(null);
}
}
private function onInterleavedData():void
{
handle.readBytes(data, data.length);
if (-1 == rtpLength && 0x24 === data[0]) {
/* This is the beginning of a new RTP package */
data.readByte();
rtpChannel = data.readByte();
rtpLength = data.readShort();
}
if (data.bytesAvailable < rtpLength) {
/* The complete RTP package is not here yet, wait for more data */
return;
}
var pkgData:ByteArray = new ByteArray();
data.readBytes(pkgData, 0, rtpLength);
if (rtpChannel === 0 || rtpChannel === 2) {
/* We're discarding the RTCP counter parts for now */
var rtppkt:RTP = new RTP(pkgData, sdp);
dispatchEvent(rtppkt);
}
requestReset();
if (0 < data.bytesAvailable) {
onData(null);
}
}
private function supportCommand(command:String):Boolean
{
return (-1 !== this.methods.indexOf(command));
}
private function sendOptionsReq():void {
state = STATE_OPTIONS;
var req:String =
"OPTIONS * RTSP/1.0\r\n" +
"CSeq: " + (++cSeq) + "\r\n" +
"User-Agent: " + userAgent + "\r\n" +
"\r\n";
handle.writeUTFBytes(req);
}
private function sendDescribeReq():void {
state = STATE_DESCRIBE;
var u:String = 'rtsp://' + urlParsed.host + ":" + urlParsed.port + urlParsed.urlpath;
var req:String =
"DESCRIBE " + u + " RTSP/1.0\r\n" +
"CSeq: " + (++cSeq) + "\r\n" +
"User-Agent: " + userAgent + "\r\n" +
"Accept: application/sdp\r\n" +
auth.authorizationHeader("DESCRIBE", authState, authOpts, urlParsed, digestNC++) +
"\r\n";
handle.writeUTFBytes(req);
}
private function sendSetupReq(block:Object):void {
state = STATE_SETUP;
var interleavedChannels:String = interleaveChannelIndex++ + "-" + interleaveChannelIndex++;
var p:String = url.isAbsolute(block.control) ? block.control : contentBase + block.control;
trace('Setting up track: ' + p);
var req:String =
"SETUP " + p + " RTSP/1.0\r\n" +
"CSeq: " + (++cSeq) + "\r\n" +
"User-Agent: " + userAgent + "\r\n" +
(session ? ("Session: " + session + "\r\n") : "") +
"Transport: RTP/AVP/TCP;unicast;interleaved=" + interleavedChannels + "\r\n" +
auth.authorizationHeader("SETUP", authState, authOpts, urlParsed, digestNC++) +
"Date: " + new Date().toUTCString() + "\r\n" +
"\r\n";
handle.writeUTFBytes(req);
}
private function sendPlayReq():void {
/* Put the NetStream in 'Data Generation Mode'. Data is generated by FLVMux */
this.ns.play(null);
state = STATE_PLAY;
var req:String =
"PLAY " + contentBase + " RTSP/1.0\r\n" +
"CSeq: " + (++cSeq) + "\r\n" +
"User-Agent: " + userAgent + "\r\n" +
"Session: " + session + "\r\n" +
auth.authorizationHeader("PLAY", authState, authOpts, urlParsed, digestNC++) +
"\r\n";
handle.writeUTFBytes(req);
}
private function sendPauseReq():void {
if (-1 === this.supportCommand("PAUSE")) {
throw new Error('Pause is not supported by server.');
}
state = STATE_PAUSE;
/* NetStream must be closed here, otherwise it will think of this rtsp pause
as a very bad connection and buffer a lot before playing again. Not
excellent for live data. */
this.ns.close();
var req:String =
"PAUSE " + contentBase + " RTSP/1.0\r\n" +
"CSeq: " + (++cSeq) + "\r\n" +
"User-Agent: " + userAgent + "\r\n" +
"Session: " + session + "\r\n" +
auth.authorizationHeader("PAUSE", authState, authOpts, urlParsed, digestNC++) +
"\r\n";
handle.writeUTFBytes(req);
}
private function sendTeardownReq():void {
state = STATE_TEARDOWN;
var req:String =
"TEARDOWN " + contentBase + " RTSP/1.0\r\n" +
"CSeq: " + (++cSeq) + "\r\n" +
"User-Agent: " + userAgent + "\r\n" +
"Session: " + session + "\r\n" +
auth.authorizationHeader("TEARDOWN", authState, authOpts, urlParsed, digestNC++) +
"\r\n";
handle.writeUTFBytes(req);
}
}
}
|
package com.axis.rtspclient {
import flash.events.EventDispatcher;
import flash.events.Event;
import flash.utils.ByteArray;
import flash.net.Socket;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.media.Video;
import mx.utils.StringUtil;
import com.axis.rtspclient.FLVMux;
import com.axis.rtspclient.RTP;
import com.axis.rtspclient.SDP;
import com.axis.http.url;
import com.axis.http.request;
import com.axis.http.auth;
import com.axis.IClient;
import com.axis.ClientEvent;
public class RTSPClient extends EventDispatcher implements IClient {
[Embed(source = "../../../../VERSION", mimeType = "application/octet-stream")] private var Version:Class;
private var userAgent:String;
private static var STATE_INITIAL:uint = 1 << 0;
private static var STATE_OPTIONS:uint = 1 << 1;
private static var STATE_DESCRIBE:uint = 1 << 2;
private static var STATE_SETUP:uint = 1 << 3;
private static var STATE_PLAY:uint = 1 << 4;
private static var STATE_PLAYING:uint = 1 << 5;
private static var STATE_PAUSE:uint = 1 << 6;
private static var STATE_PAUSED:uint = 1 << 7;
private static var STATE_TEARDOWN:uint = 1 << 8;
private var state:int = STATE_INITIAL;
private var handle:IRTSPHandle;
private var ns:NetStream;
private var video:Video;
private var sdp:SDP = new SDP();
private var flvmux:FLVMux;
private var urlParsed:Object;
private var cSeq:uint = 1;
private var session:String;
private var contentBase:String;
private var interleaveChannelIndex:uint = 0;
private var methods:Array = [];
private var data:ByteArray = new ByteArray();
private var rtpLength:int = -1;
private var rtpChannel:int = -1;
private var tracks:Array;
private var authState:String = "none";
private var authOpts:Object = {};
private var digestNC:uint = 1;
public function RTSPClient(video:Video, urlParsed:Object, handle:IRTSPHandle) {
this.userAgent = "Slush " + StringUtil.trim(new Version().toString());
this.state = STATE_INITIAL;
this.handle = handle;
this.ns = ns;
this.video = video;
this.urlParsed = urlParsed;
handle.addEventListener('data', this.onData);
}
public function start():Boolean {
var self:RTSPClient = this;
handle.addEventListener('connected', function():void {
if (state !== STATE_INITIAL) {
trace('Cannot start unless in initial state.');
return;
}
/* If the handle closes, take care of it */
handle.addEventListener('closed', self.onClose);
if (0 === self.methods.length) {
/* We don't know the options yet. Start with that. */
sendOptionsReq();
} else {
/* Already queried the options (and perhaps got unauthorized on describe) */
sendDescribeReq();
}
});
var nc:NetConnection = new NetConnection();
nc.connect(null);
this.ns = new NetStream(nc);
dispatchEvent(new ClientEvent(ClientEvent.NETSTREAM_CREATED, { ns : this.ns }));
video.attachNetStream(this.ns);
handle.connect();
return true;
}
public function pause():Boolean
{
if (state !== STATE_PLAYING) {
trace('Unable to pause a stream if not playing.');
return false;
}
try {
sendPauseReq();
} catch (err:Error) {
trace("Unable to pause: " + err.message);
return false;
}
return true;
}
public function resume():Boolean
{
if (state !== STATE_PAUSED) {
trace('Unable to resume a stream if not paused.');
return false;
}
sendPlayReq();
return true;
}
public function stop():Boolean
{
if (state < STATE_PLAY) {
trace('Unable to stop if we never reached play.');
return false;
}
sendTeardownReq();
return true;
}
private function onClose(event:Event):void
{
if (state === STATE_TEARDOWN) {
dispatchEvent(new ClientEvent(ClientEvent.STOPPED));
} else {
trace('RTSPClient: Handle unexpectedly closed.');
}
}
private function onData(event:Event):void
{
/* read one byte to determine destination */
if (0 < data.bytesAvailable) {
/* Determining byte have already been read. This is a continuation */
} else {
/* Read the determining byte */
handle.readBytes(data, 0, 1);
}
switch(data[0]) {
case 0x52:
/* ascii 'R', start of RTSP */
onRTSPCommand();
break;
case 0x24:
/* ascii '$', start of interleaved packet */
onInterleavedData();
break;
default:
trace('Unknown determining byte:', data[0]);
break;
}
}
private function requestReset():void
{
var copy:ByteArray = new ByteArray();
data.readBytes(copy);
data.clear();
copy.readBytes(data);
rtpLength = -1;
rtpChannel = -1;
}
private function readRequest(oBody:ByteArray):*
{
var parsed:* = request.readHeaders(handle, data);
if (false === parsed) {
return false;
}
if (401 === parsed.code) {
/* Unauthorized, change authState and (possibly) try again */
authOpts = parsed.headers['www-authenticate'];
var newAuthState:String = auth.nextMethod(authState, authOpts);
if (authState === newAuthState) {
trace('GET: Exhausted all authentication methods.');
trace('GET: Unable to authorize to ' + urlParsed.host);
return false;
}
trace('RTSPClient: switching http-authorization from ' + authState + ' to ' + newAuthState);
authState = newAuthState;
state = STATE_INITIAL;
data = new ByteArray();
handle.reconnect();
return false;
}
if (data.bytesAvailable < parsed.headers['content-length']) {
return false;
}
/* RTSP commands contain no heavy body, so it's safe to read everything */
data.readBytes(oBody, 0, parsed.headers['content-length']);
requestReset();
return parsed;
}
private function onRTSPCommand():void {
var parsed:*, body:ByteArray = new ByteArray();
if (false === (parsed = readRequest(body))) {
return;
}
if (200 !== parsed.code) {
trace('RTSPClient: Invalid RTSP response - ', parsed.code, parsed.message);
return;
}
switch (state) {
case STATE_INITIAL:
trace("RTSPClient: STATE_INITIAL");
case STATE_OPTIONS:
trace("RTSPClient: STATE_OPTIONS");
this.methods = parsed.headers.public.split(/[ ]*,[ ]*/);
sendDescribeReq();
break;
case STATE_DESCRIBE:
trace("RTSPClient: STATE_DESCRIBE");
if (!sdp.parse(body)) {
trace("RTSPClient:Failed to parse SDP file");
return;
}
if (!parsed.headers['content-base']) {
trace('RTSPClient: no content-base in describe reply');
return;
}
contentBase = parsed.headers['content-base'];
tracks = sdp.getMediaBlockList();
trace('SDP contained ' + tracks.length + ' track(s). Calling SETUP for each.');
if (0 === tracks.length) {
trace('No tracks in SDP file.');
return;
}
/* Fall through, it's time for setup */
case STATE_SETUP:
trace("RTSPClient: STATE_SETUP");
if (parsed.headers['session']) {
session = parsed.headers['session'];
}
if (0 !== tracks.length) {
/* More tracks we must setup before playing */
var block:Object = tracks.shift();
sendSetupReq(block);
return;
}
/* All tracks setup and ready to go! */
sendPlayReq();
break;
case STATE_PLAY:
trace("RTSPClient: STATE_PLAY");
state = STATE_PLAYING;
if (this.flvmux) {
/* If the flvmux have been initialized don't do it again.
this is probably a resume after pause */
break;
}
this.flvmux = new FLVMux(this.ns, this.sdp);
var analu:ANALU = new ANALU();
var aaac:AAAC = new AAAC(sdp);
this.addEventListener("VIDEO_PACKET", analu.onRTPPacket);
this.addEventListener("AUDIO_PACKET", aaac.onRTPPacket);
analu.addEventListener(NALU.NEW_NALU, flvmux.onNALU);
aaac.addEventListener(AACFrame.NEW_FRAME, flvmux.onAACFrame);
break;
case STATE_PLAYING:
trace("RTSPClient: STATE_PLAYING");
break;
case STATE_PAUSE:
trace("RTSPClient: STATE_PAUSE");
state = STATE_PAUSED;
break;
case STATE_TEARDOWN:
trace('RTSPClient: STATE_TEARDOWN');
handle.disconnect();
break;
}
if (0 < data.bytesAvailable) {
onData(null);
}
}
private function onInterleavedData():void
{
handle.readBytes(data, data.length);
if (-1 == rtpLength && 0x24 === data[0]) {
/* This is the beginning of a new RTP package */
data.readByte();
rtpChannel = data.readByte();
rtpLength = data.readShort();
}
if (data.bytesAvailable < rtpLength) {
/* The complete RTP package is not here yet, wait for more data */
return;
}
var pkgData:ByteArray = new ByteArray();
data.readBytes(pkgData, 0, rtpLength);
if (rtpChannel === 0 || rtpChannel === 2) {
/* We're discarding the RTCP counter parts for now */
var rtppkt:RTP = new RTP(pkgData, sdp);
dispatchEvent(rtppkt);
}
requestReset();
if (0 < data.bytesAvailable) {
onData(null);
}
}
private function supportCommand(command:String):Boolean
{
return (-1 !== this.methods.indexOf(command));
}
private function sendOptionsReq():void {
state = STATE_OPTIONS;
var req:String =
"OPTIONS * RTSP/1.0\r\n" +
"CSeq: " + (++cSeq) + "\r\n" +
"User-Agent: " + userAgent + "\r\n" +
"\r\n";
handle.writeUTFBytes(req);
}
private function sendDescribeReq():void {
state = STATE_DESCRIBE;
var u:String = 'rtsp://' + urlParsed.host + ":" + urlParsed.port + urlParsed.urlpath;
var req:String =
"DESCRIBE " + u + " RTSP/1.0\r\n" +
"CSeq: " + (++cSeq) + "\r\n" +
"User-Agent: " + userAgent + "\r\n" +
"Accept: application/sdp\r\n" +
auth.authorizationHeader("DESCRIBE", authState, authOpts, urlParsed, digestNC++) +
"\r\n";
handle.writeUTFBytes(req);
}
private function sendSetupReq(block:Object):void {
state = STATE_SETUP;
var interleavedChannels:String = interleaveChannelIndex++ + "-" + interleaveChannelIndex++;
var p:String = url.isAbsolute(block.control) ? block.control : contentBase + block.control;
trace('Setting up track: ' + p);
var req:String =
"SETUP " + p + " RTSP/1.0\r\n" +
"CSeq: " + (++cSeq) + "\r\n" +
"User-Agent: " + userAgent + "\r\n" +
(session ? ("Session: " + session + "\r\n") : "") +
"Transport: RTP/AVP/TCP;unicast;interleaved=" + interleavedChannels + "\r\n" +
auth.authorizationHeader("SETUP", authState, authOpts, urlParsed, digestNC++) +
"Date: " + new Date().toUTCString() + "\r\n" +
"\r\n";
handle.writeUTFBytes(req);
}
private function sendPlayReq():void {
/* Put the NetStream in 'Data Generation Mode'. Data is generated by FLVMux */
this.ns.play(null);
state = STATE_PLAY;
var req:String =
"PLAY " + contentBase + " RTSP/1.0\r\n" +
"CSeq: " + (++cSeq) + "\r\n" +
"User-Agent: " + userAgent + "\r\n" +
"Session: " + session + "\r\n" +
auth.authorizationHeader("PLAY", authState, authOpts, urlParsed, digestNC++) +
"\r\n";
handle.writeUTFBytes(req);
}
private function sendPauseReq():void {
if (-1 === this.supportCommand("PAUSE")) {
throw new Error('Pause is not supported by server.');
}
state = STATE_PAUSE;
/* NetStream must be closed here, otherwise it will think of this rtsp pause
as a very bad connection and buffer a lot before playing again. Not
excellent for live data. */
this.ns.close();
var req:String =
"PAUSE " + contentBase + " RTSP/1.0\r\n" +
"CSeq: " + (++cSeq) + "\r\n" +
"User-Agent: " + userAgent + "\r\n" +
"Session: " + session + "\r\n" +
auth.authorizationHeader("PAUSE", authState, authOpts, urlParsed, digestNC++) +
"\r\n";
handle.writeUTFBytes(req);
}
private function sendTeardownReq():void {
state = STATE_TEARDOWN;
var req:String =
"TEARDOWN " + contentBase + " RTSP/1.0\r\n" +
"CSeq: " + (++cSeq) + "\r\n" +
"User-Agent: " + userAgent + "\r\n" +
"Session: " + session + "\r\n" +
auth.authorizationHeader("TEARDOWN", authState, authOpts, urlParsed, digestNC++) +
"\r\n";
handle.writeUTFBytes(req);
}
}
}
|
Correct state debug output
|
RTSPClient: Correct state debug output
|
ActionScript
|
bsd-3-clause
|
AxisCommunications/locomote-video-player,gaetancollaud/locomote-video-player
|
986fef252966225153d3fa3aaeabe163124770a3
|
src/org/mangui/HLS/muxing/AVC.as
|
src/org/mangui/HLS/muxing/AVC.as
|
package org.mangui.HLS.muxing {
import flash.utils.ByteArray;
import org.mangui.HLS.utils.Log;
/** Constants and utilities for the H264 video format. **/
public class AVC {
/** H264 NAL unit names. **/
private static const NAMES:Array = [
'Unspecified', // 0
'NDR', // 1
'Partition A', // 2
'Partition B', // 3
'Partition C', // 4
'IDR', // 5
'SEI', // 6
'SPS', // 7
'PPS', // 8
'AUD', // 9
'End of Sequence', // 10
'End of Stream', // 11
'Filler Data' // 12
];
/** H264 profiles. **/
private static const PROFILES:Object = {
'66': 'H264 Baseline',
'77': 'H264 Main',
'100': 'H264 High'
};
/** Get Avcc header from AVC stream
See ISO 14496-15, 5.2.4.1 for the description of AVCDecoderConfigurationRecord
**/
public static function getAVCC(nalu:ByteArray,position:Number=0):ByteArray {
// Find SPS and PPS units in AVC stream.
var units:Vector.<VideoFrame> = AVC.getNALU(nalu,position);
var sps:Number = -1;
var pps:Number = -1;
for(var i:Number = 0; i< units.length; i++) {
if(units[i].type == 7 && sps == -1) {
sps = i;
} else if (units[i].type == 8 && pps == -1) {
pps = i;
}
}
// Throw errors if units not found.
if(sps == -1) {
throw new Error("No SPS NAL unit found in this stream.");
} else if (pps == -1) {
throw new Error("No PPS NAL unit found in this stream.");
}
// Write startbyte
var avcc:ByteArray = new ByteArray();
avcc.writeByte(0x01);
// Write profile, compatibility and level.
avcc.writeBytes(nalu,units[sps].start+1, 3);
// reserved (6 bits), NALU length size - 1 (2 bits)
avcc.writeByte(0xFC | 3);
// reserved (3 bits), num of SPS (5 bits)
avcc.writeByte(0xE0 | 1);
// 2 bytes for length of SPS
avcc.writeShort(units[sps].length);
// data of SPS
avcc.writeBytes(nalu,units[sps].start,units[sps].length);
// Number of PPS
avcc.writeByte(0x01);
// 2 bytes for length of PPS
avcc.writeShort(units[pps].length);
// data of PPS
avcc.writeBytes(nalu,units[pps].start,units[pps].length);
// Grab profile/level
avcc.position = 1;
var prf:Number = avcc.readByte();
avcc.position = 3;
var lvl:Number = avcc.readByte();
Log.debug("AVC: "+PROFILES[prf]+' level '+lvl);
avcc.position = 0;
return avcc;
};
/** Return an array with NAL delimiter indexes. **/
public static function getNALU(nalu:ByteArray,position:Number=0):Vector.<VideoFrame> {
var units:Vector.<VideoFrame> = new Vector.<VideoFrame>();
var unit_start:Number;
var unit_type:Number;
var unit_header:Number;
// Loop through data to find NAL startcodes.
var window:uint = 0;
nalu.position = position;
while(nalu.bytesAvailable > 4) {
window = nalu.readUnsignedInt();
// Match four-byte startcodes
if((window & 0xFFFFFFFF) == 0x01) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if(unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
unit_header = 4;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if(unit_type == 1 || unit_type == 5) { break; }
// Match three-byte startcodes
} else if((window & 0xFFFFFF00) == 0x100) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if(unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
nalu.position--;
unit_header = 3;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if(unit_type == 1 || unit_type == 5) { break; }
} else {
nalu.position -= 3;
}
}
// Append the last NAL to the array.
if(unit_start) {
units.push(new VideoFrame(unit_header, nalu.length - unit_start, unit_start, unit_type));
}
// Reset position and return results.
if(Log.LOG_DEBUG2_ENABLED) {
if(units.length) {
var txt:String = "AVC: ";
for(var i:Number=0; i<units.length; i++) {
txt += NAMES[units[i].type] + ", ";
}
Log.debug2(txt.substr(0,txt.length-2) + " slices");
} else {
Log.debug2('AVC: no NALU slices found');
}
}
nalu.position = position;
return units;
};
}
}
|
package org.mangui.HLS.muxing {
import flash.utils.ByteArray;
import org.mangui.HLS.utils.Log;
/** Constants and utilities for the H264 video format. **/
public class AVC {
/** H264 NAL unit names. **/
private static const NAMES:Array = [
'Unspecified', // 0
'NDR', // 1
'Partition A', // 2
'Partition B', // 3
'Partition C', // 4
'IDR', // 5
'SEI', // 6
'SPS', // 7
'PPS', // 8
'AUD', // 9
'End of Sequence', // 10
'End of Stream', // 11
'Filler Data' // 12
];
/** H264 profiles. **/
private static const PROFILES:Object = {
'66': 'H264 Baseline',
'77': 'H264 Main',
'100': 'H264 High'
};
/** Get Avcc header from AVC stream
See ISO 14496-15, 5.2.4.1 for the description of AVCDecoderConfigurationRecord
**/
public static function getAVCC(nalu:ByteArray,position:Number):ByteArray {
// Find SPS and PPS units in AVC stream.
var units:Vector.<VideoFrame> = AVC.getNALU(nalu,position);
var sps:Number = -1;
var pps:Number = -1;
for(var i:Number = 0; i< units.length; i++) {
if(units[i].type == 7 && sps == -1) {
sps = i;
} else if (units[i].type == 8 && pps == -1) {
pps = i;
}
}
// Throw errors if units not found.
if(sps == -1) {
throw new Error("No SPS NAL unit found in this stream.");
} else if (pps == -1) {
throw new Error("No PPS NAL unit found in this stream.");
}
// Write startbyte
var avcc:ByteArray = new ByteArray();
avcc.writeByte(0x01);
// Write profile, compatibility and level.
avcc.writeBytes(nalu,units[sps].start+1, 3);
// reserved (6 bits), NALU length size - 1 (2 bits)
avcc.writeByte(0xFC | 3);
// reserved (3 bits), num of SPS (5 bits)
avcc.writeByte(0xE0 | 1);
// 2 bytes for length of SPS
avcc.writeShort(units[sps].length);
// data of SPS
avcc.writeBytes(nalu,units[sps].start,units[sps].length);
// Number of PPS
avcc.writeByte(0x01);
// 2 bytes for length of PPS
avcc.writeShort(units[pps].length);
// data of PPS
avcc.writeBytes(nalu,units[pps].start,units[pps].length);
// Grab profile/level
avcc.position = 1;
var prf:Number = avcc.readByte();
avcc.position = 3;
var lvl:Number = avcc.readByte();
Log.debug("AVC: "+PROFILES[prf]+' level '+lvl);
avcc.position = 0;
return avcc;
};
/** Return an array with NAL delimiter indexes. **/
public static function getNALU(nalu:ByteArray,position:Number):Vector.<VideoFrame> {
var units:Vector.<VideoFrame> = new Vector.<VideoFrame>();
var unit_start:Number;
var unit_type:Number;
var unit_header:Number;
// Loop through data to find NAL startcodes.
var window:uint = 0;
nalu.position = position;
while(nalu.bytesAvailable > 4) {
window = nalu.readUnsignedInt();
// Match four-byte startcodes
if((window & 0xFFFFFFFF) == 0x01) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if(unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
unit_header = 4;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if(unit_type == 1 || unit_type == 5) { break; }
// Match three-byte startcodes
} else if((window & 0xFFFFFF00) == 0x100) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if(unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
nalu.position--;
unit_header = 3;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if(unit_type == 1 || unit_type == 5) { break; }
} else {
nalu.position -= 3;
}
}
// Append the last NAL to the array.
if(unit_start) {
units.push(new VideoFrame(unit_header, nalu.length - unit_start, unit_start, unit_type));
}
// Reset position and return results.
if(Log.LOG_DEBUG2_ENABLED) {
if(units.length) {
var txt:String = "AVC: ";
for(var i:Number=0; i<units.length; i++) {
txt += NAMES[units[i].type] + ", ";
}
Log.debug2(txt.substr(0,txt.length-2) + " slices");
} else {
Log.debug2('AVC: no NALU slices found');
}
}
nalu.position = position;
return units;
};
}
}
|
remove useless optional parameter values
|
remove useless optional parameter values
|
ActionScript
|
mpl-2.0
|
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
|
7ab2c542dac574ed9417ed276c206381f449179c
|
src/as/com/threerings/util/Log.as
|
src/as/com/threerings/util/Log.as
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util {
import flash.utils.getQualifiedClassName;
/**
* A simple logging mechanism.
*
* Log instances are created for modules, and the logging level can be configured per
* module in a hierarchical fashion.
*
* Typically, you should create a module name based on the full path to a class:
* calling getLog() and passing an object or Class will do this. Alternattely, you
* may create a Log to share in several classes in a package, in which case the
* module name can be like "com.foocorp.games.bunnywar". Finally, you can just
* create made-up module names like "mygame" or "util", but this is not recommended.
* You really should name things based on your packages, and your packages should be
* named according to Sun's recommendations for Java packages.
*
* Typical usage for creating a Log to be used by the entire class would be:
* public class MyClass
* {
* private static const log :Log = Log.getLog(MyClass);
* ...
*
* OR, if you just need a one-off Log:
* protected function doStuff (thingy :Thingy) :void
* {
* if (!isValid(thingy)) {
* Log.getLog(this).warn("Invalid thingy specified", "thingy", thingy);
* ....
*/
public class Log
{
/** Log level constants. */
public static const DEBUG :int = 0;
public static const INFO :int = 1;
public static const WARNING :int = 2;
public static const OFF :int = 3;
// if you add to this, update LEVEL_NAMES and stringToLevel() at the bottom...
/**
* Retrieve a Log for the specified module.
*
* @param moduleSpec can be a String of the module name, or any Object or Class to
* have the module name be the full package and name of the class (recommended).
*/
public static function getLog (moduleSpec :*) :Log
{
const module :String = (moduleSpec is String) ? String(moduleSpec)
: getQualifiedClassName(moduleSpec).replace("::", ".");
return new Log(module);
}
/**
* A convenience function for quickly and easily inserting printy
* statements during application development.
*/
public static function testing (... params) :void
{
var log :Log = new Log("testing");
log.debug.apply(log, params);
}
/**
* A convenience function for quickly printing a stack trace
* to the log, useful for debugging.
*/
public static function dumpStack () :void
{
testing(new Error("dumpStack").getStackTrace());
}
/**
* Add a logging target.
*/
public static function addTarget (target :LogTarget) :void
{
_targets.push(target);
}
/**
* Remove a logging target.
*/
public static function removeTarget (target :LogTarget) :void
{
var dex :int = _targets.indexOf(target);
if (dex != -1) {
_targets.splice(dex, 1);
}
}
/**
* Set the log level for the specified module.
*
* @param module The smallest prefix desired to configure a log level.
* For example, you can set the global level with Log.setLevel("", Log.INFO);
* Then you can Log.setLevel("com.foo.game", Log.DEBUG). Now, everything
* logs at INFO level except for modules within com.foo.game, which is at DEBUG.
*/
public static function setLevel (module :String, level :int) :void
{
_setLevels[module] = level;
_levels = {}; // reset cached levels
}
/**
* Parses a String in the form of ":info;com.foo.game:debug;com.bar.util:warning"
*
* Semicolons separate modules, colons separate a module name from the log level.
* An empty string specifies the top-level (global) module.
*/
public static function setLevels (settingString :String) :void
{
for each (var module :String in settingString.split(";")) {
var setting :Array = module.split(":");
_setLevels[setting[0]] = stringToLevel(String(setting[1]));
}
_levels = {}; // reset cached levels
}
/**
* Use Log.getLog();
*
* @private
*/
public function Log (module :String)
{
if (module == null) module = "";
_module = module;
}
/**
* Log a message with 'debug' priority.
*
* @param args The first argument is the actual message to log. After that, each pair
* of parameters is printed in key/value form, the benefit being that if no log
* message is generated then toString() will not be called on the values.
* A final parameter may be an Error, in which case the stack trace is printed.
*
* @example
* <listing version="3.0">
* log.debug("Message", "key1", value1, "key2", value2, optionalError);
* </listing>
*/
public function debug (... args) :void
{
doLog(DEBUG, args);
}
/**
* Log a message with 'info' priority.
*
* @param args The first argument is the actual message to log. After that, each pair
* of parameters is printed in key/value form, the benefit being that if no log
* message is generated then toString() will not be called on the values.
* A final parameter may be an Error, in which case the stack trace is printed.
*
* @example
* <listing version="3.0">
* log.info("Message", "key1", value1, "key2", value2, optionalError);
* </listing>
*/
public function info (... args) :void
{
doLog(INFO, args);
}
/**
* Log a message with 'warning' priority.
*
* @param args The first argument is the actual message to log. After that, each pair
* of parameters is printed in key/value form, the benefit being that if no log
* message is generated then toString() will not be called on the values.
* A final parameter may be an Error, in which case the stack trace is printed.
*
* @example
* <listing version="3.0">
* log.warning("Message", "key1", value1, "key2", value2, optionalError);
* </listing>
*/
public function warning (... args) :void
{
doLog(WARNING, args);
}
/**
* Log just a stack trace with 'warning' priority.
*/
public function logStackTrace (error :Error) :void
{
warning(error.getStackTrace());
}
protected function doLog (level :int, args :Array) :void
{
if (level < getLevel(_module)) {
return; // we don't want to log it!
}
var logMessage :String = formatMessage(level, args);
trace(logMessage);
// possibly also dispatch to any other log targets.
for each (var target :LogTarget in _targets) {
target.log(logMessage);
}
}
protected function formatMessage (level :int, args :Array) :String
{
var msg :String = getTimeStamp() + " " + LEVEL_NAMES[level] + ": " + _module;
if (args.length > 0) {
msg += " " + String(args[0]); // the primary log message
var err :Error = null;
if (args.length % 2 == 0) { // there's one extra arg
var lastArg :Object = args.pop();
if (lastArg is Error) {
err = lastArg as Error; // ok, it's an error, we like those
} else {
args.push(lastArg, ""); // what? Well, cope by pushing it back with a ""
}
}
if (args.length > 1) {
for (var ii :int = 1; ii < args.length; ii += 2) {
msg += (ii == 1) ? " [" : ", ";
msg += String(args[ii]) + "=" + String(args[ii + 1]);
}
msg += "]";
}
if (err != null) {
msg += "\n" + err.getStackTrace();
}
}
return msg;
}
protected function getTimeStamp () :String
{
var d :Date = new Date();
// return d.toLocaleTimeString();
// format it like the date format in our java logs
return d.fullYear + "/" +
StringUtil.prepad(String(d.month + 1), 2, "0") + "/" +
StringUtil.prepad(String(d.date), 2, "0") + " " +
StringUtil.prepad(String(d.hours), 2, "0") + ":" +
StringUtil.prepad(String(d.minutes), 2, "0") + ":" +
StringUtil.prepad(String(d.seconds), 2, "0") + "," +
StringUtil.prepad(String(d.milliseconds), 3, "0");
}
/**
* Get the logging level for the specified module.
*/
protected static function getLevel (module :String) :int
{
// we probably already have the level cached for this module
var lev :Object = _levels[module];
if (lev == null) {
// cache miss- copy some parent module's level...
var ancestor :String = module;
while (true) {
lev = _setLevels[ancestor];
if (lev != null || ancestor == "") {
// bail if we found a setting or get to the top level,
// but always save the level from _setLevels into _levels
_levels[module] = int(lev); // if lev was null, this will become 0 (DEBUG)
break;
}
var dex :int = ancestor.lastIndexOf(".");
ancestor = (dex == -1) ? "" : ancestor.substring(0, dex);
}
}
return int(lev);
}
protected static function stringToLevel (s :String) :int
{
switch (s.toLowerCase()) {
default: // default to DEBUG
case "debug": return DEBUG;
case "info": return INFO;
case "warning": case "warn": return WARNING;
case "off": return OFF;
}
}
/** The module to which this log instance applies. */
protected var _module :String;
/** Other registered LogTargets, besides the trace log. */
protected static var _targets :Array = [];
/** A cache of log levels, copied from _setLevels. */
protected static var _levels :Object = {};
/** The configured log levels. */
protected static var _setLevels :Object = { "": DEBUG }; // global: debug
/** The names of each level. The last one isn't used, it corresponds with OFF. */
protected static const LEVEL_NAMES :Array = [ "[debug]", "[INFO]", "[WARNING]", false ];
}
}
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util {
import flash.utils.getQualifiedClassName;
/**
* A simple logging mechanism.
*
* Log instances are created for modules, and the logging level can be configured per
* module in a hierarchical fashion.
*
* Typically, you should create a module name based on the full path to a class:
* calling getLog() and passing an object or Class will do this. Alternattely, you
* may create a Log to share in several classes in a package, in which case the
* module name can be like "com.foocorp.games.bunnywar". Finally, you can just
* create made-up module names like "mygame" or "util", but this is not recommended.
* You really should name things based on your packages, and your packages should be
* named according to Sun's recommendations for Java packages.
*
* Typical usage for creating a Log to be used by the entire class would be:
* public class MyClass
* {
* private static const log :Log = Log.getLog(MyClass);
* ...
*
* OR, if you just need a one-off Log:
* protected function doStuff (thingy :Thingy) :void
* {
* if (!isValid(thingy)) {
* Log.getLog(this).warn("Invalid thingy specified", "thingy", thingy);
* ....
*/
public class Log
{
/** Log level constants. */
public static const DEBUG :int = 0;
public static const INFO :int = 1;
public static const WARNING :int = 2;
public static const OFF :int = 3;
// if you add to this, update LEVEL_NAMES and stringToLevel() at the bottom...
/**
* Retrieve a Log for the specified module.
*
* @param moduleSpec can be a String of the module name, or any Object or Class to
* have the module name be the full package and name of the class (recommended).
*/
public static function getLog (moduleSpec :*) :Log
{
const module :String = (moduleSpec is String) ? String(moduleSpec)
: getQualifiedClassName(moduleSpec).replace("::", ".");
return new Log(module);
}
/**
* A convenience function for quickly and easily inserting printy
* statements during application development.
*/
public static function testing (... params) :void
{
var log :Log = new Log("testing");
log.debug.apply(log, params);
}
/**
* A convenience function for quickly printing a stack trace
* to the log, useful for debugging.
*/
public static function dumpStack () :void
{
testing(new Error("dumpStack").getStackTrace());
}
/**
* Add a logging target.
*/
public static function addTarget (target :LogTarget) :void
{
_targets.push(target);
}
/**
* Remove a logging target.
*/
public static function removeTarget (target :LogTarget) :void
{
var dex :int = _targets.indexOf(target);
if (dex != -1) {
_targets.splice(dex, 1);
}
}
/**
* Set the log level for the specified module.
*
* @param module The smallest prefix desired to configure a log level.
* For example, you can set the global level with Log.setLevel("", Log.INFO);
* Then you can Log.setLevel("com.foo.game", Log.DEBUG). Now, everything
* logs at INFO level except for modules within com.foo.game, which is at DEBUG.
*/
public static function setLevel (module :String, level :int) :void
{
_setLevels[module] = level;
_levels = {}; // reset cached levels
}
/**
* Parses a String in the form of ":info;com.foo.game:debug;com.bar.util:warning"
*
* Semicolons separate modules, colons separate a module name from the log level.
* An empty string specifies the top-level (global) module.
*/
public static function setLevels (settingString :String) :void
{
for each (var module :String in settingString.split(";")) {
var setting :Array = module.split(":");
_setLevels[setting[0]] = stringToLevel(String(setting[1]));
}
_levels = {}; // reset cached levels
}
/**
* Use Log.getLog();
*
* @private
*/
public function Log (module :String)
{
if (module == null) module = "";
_module = module;
}
/**
* Log a message with 'debug' priority.
*
* @param args The first argument is the actual message to log. After that, each pair
* of parameters is printed in key/value form, the benefit being that if no log
* message is generated then toString() will not be called on the values.
* A final parameter may be an Error, in which case the stack trace is printed.
*
* @example
* <listing version="3.0">
* log.debug("Message", "key1", value1, "key2", value2, optionalError);
* </listing>
*/
public function debug (... args) :void
{
doLog(DEBUG, args);
}
/**
* Log a message with 'info' priority.
*
* @param args The first argument is the actual message to log. After that, each pair
* of parameters is printed in key/value form, the benefit being that if no log
* message is generated then toString() will not be called on the values.
* A final parameter may be an Error, in which case the stack trace is printed.
*
* @example
* <listing version="3.0">
* log.info("Message", "key1", value1, "key2", value2, optionalError);
* </listing>
*/
public function info (... args) :void
{
doLog(INFO, args);
}
/**
* Log a message with 'warning' priority.
*
* @param args The first argument is the actual message to log. After that, each pair
* of parameters is printed in key/value form, the benefit being that if no log
* message is generated then toString() will not be called on the values.
* A final parameter may be an Error, in which case the stack trace is printed.
*
* @example
* <listing version="3.0">
* log.warning("Message", "key1", value1, "key2", value2, optionalError);
* </listing>
*/
public function warning (... args) :void
{
doLog(WARNING, args);
}
/**
* Log just a stack trace with 'warning' priority.
*/
public function logStackTrace (error :Error) :void
{
warning(error.getStackTrace());
}
protected function doLog (level :int, args :Array) :void
{
if (level < getLevel(_module)) {
return; // we don't want to log it!
}
var logMessage :String = formatMessage(level, args);
trace(logMessage);
// possibly also dispatch to any other log targets.
for each (var target :LogTarget in _targets) {
target.log(logMessage);
}
}
protected function formatMessage (level :int, args :Array) :String
{
var msg :String = getTimeStamp() + " " + LEVEL_NAMES[level] + ": " + _module;
if (args.length > 0) {
msg += " " + String(args[0]); // the primary log message
var err :Error = null;
if (args.length % 2 == 0) { // there's one extra arg
var lastArg :Object = args.pop();
if (lastArg is Error) {
err = lastArg as Error; // ok, it's an error, we like those
} else {
args.push(lastArg, ""); // what? Well, cope by pushing it back with a ""
}
}
if (args.length > 1) {
for (var ii :int = 1; ii < args.length; ii += 2) {
msg += (ii == 1) ? " [" : ", ";
msg += String(args[ii]) + "=" + String(args[ii + 1]);
}
msg += "]";
}
if (err != null) {
msg += "\n" + err.getStackTrace();
}
}
return msg;
}
protected function getTimeStamp () :String
{
var d :Date = new Date();
// return d.toLocaleTimeString();
// format it like the date format in our java logs
return d.fullYear + "/" +
StringUtil.prepad(String(d.month + 1), 2, "0") + "/" +
StringUtil.prepad(String(d.date), 2, "0") + " " +
StringUtil.prepad(String(d.hours), 2, "0") + ":" +
StringUtil.prepad(String(d.minutes), 2, "0") + ":" +
StringUtil.prepad(String(d.seconds), 2, "0") + "," +
StringUtil.prepad(String(d.milliseconds), 3, "0");
}
/**
* Get the logging level for the specified module.
*/
protected static function getLevel (module :String) :int
{
// we probably already have the level cached for this module
var lev :Object = _levels[module];
if (lev == null) {
// cache miss- copy some parent module's level...
var ancestor :String = module;
while (true) {
lev = _setLevels[ancestor];
if (lev != null || ancestor == "") {
// bail if we found a setting or get to the top level,
// but always save the level from _setLevels into _levels
_levels[module] = int(lev); // if lev was null, this will become 0 (DEBUG)
break;
}
var dex :int = ancestor.lastIndexOf(".");
ancestor = (dex == -1) ? "" : ancestor.substring(0, dex);
}
}
return int(lev);
}
protected static function stringToLevel (s :String) :int
{
switch (s.toLowerCase()) {
default: // default to DEBUG
case "debug": return DEBUG;
case "info": return INFO;
case "warning": case "warn": return WARNING;
case "off": return OFF;
}
}
/** The module to which this log instance applies. */
protected var _module :String;
/** Other registered LogTargets, besides the trace log. */
protected static var _targets :Array = [];
/** A cache of log levels, copied from _setLevels. */
protected static var _levels :Object = {};
/** The configured log levels. */
protected static var _setLevels :Object = { "": DEBUG }; // global: debug
/** The outputted names of each level. The last one isn't used, it corresponds with OFF. */
protected static const LEVEL_NAMES :Array = [ "debug", "INFO", "WARNING", false ];
}
}
|
Stop printing square brackets around the log level. Be more like our Java logging.
|
Stop printing square brackets around the log level. Be more like our Java logging.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5394 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
9b6cc5170ba5ee649c287943a934b967817201ad
|
as3-processor/com/mozaic/mozaic.as
|
as3-processor/com/mozaic/mozaic.as
|
package com.mozaic{
public class mozaic {
public function mozaic() {
// constructor code
trace('The work has begun');
}
//do we need this?
public function getCSV(path:String){
//holds the csv data
var details:Object = new Object();
return(details);
}
public function processImage(img_id:String){
}
}
}
|
package com.mozaic{
public class mozaic {
public function mozaic() {
// constructor code
trace('The work has begun');
}
//do we need this?
public function getCSV(path:String){
//holds the csv data
var details:Object = new Object();
return(details);
}
public function processImage(img_id:String){
}
}
}
|
test commit
|
test commit
|
ActionScript
|
mit
|
SpiceDave/homebase-gardening,SpiceDave/homebase-gardening
|
a803cd0a88ee2572f02df69003f8afbd5685bb9c
|
src/org/flintparticles/threeD/emitters/Emitter3D.as
|
src/org/flintparticles/threeD/emitters/Emitter3D.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.threeD.emitters
{
import org.flintparticles.common.emitters.Emitter;
import org.flintparticles.common.particles.Particle;
import org.flintparticles.common.particles.ParticleFactory;
import org.flintparticles.threeD.geom.Quaternion;
import org.flintparticles.threeD.particles.Particle3D;
import org.flintparticles.threeD.particles.ParticleCreator3D;
import flash.geom.Matrix3D;
import flash.geom.Vector3D;
/**
* The Emitter3D class defines an emitter that exists in 3D space. It is the
* main emitter for using Flint in a 3D coordinate system.
*
* <p>This emitter is not constrained to any particular 3D rendering
* environment. The emitter manages the creation and updating of each
* particle's state but does not do any rendering of the particles.
* The rendering is handled by a renderer. Renderer's could be created
* for drawing an emitter's particles on any 3D drawing environment.</p>
*
* <p>This emitter adds 3D specific features to the base emitter class.</p>
*/
public class Emitter3D extends Emitter
{
/**
* @private
*
* default factory to manage the creation, reuse and destruction of particles
*/
protected static var _creator:ParticleCreator3D = new ParticleCreator3D();
/**
* The default particle factory used to manage the creation, reuse and destruction of particles.
*/
public static function get defaultParticleFactory():ParticleFactory
{
return _creator;
}
/**
* @private
*/
protected var _position:Vector3D;
/**
* @private
*/
protected var _rotation:Quaternion;
/**
* @private
*/
protected var _rotationTransform:Matrix3D;
private var _rotTransformRotation:Quaternion;
/**
* Identifies whether the particles should be arranged
* into a spacially sorted array - this speeds up proximity
* testing for those actions that need it.
*/
public var spaceSort:Boolean = false;
/**
* The constructor creates an emitter 3D.
*/
public function Emitter3D()
{
super();
_particleFactory = _creator;
_position = new Vector3D( 0, 0, 0, 1 );
_rotation = Quaternion.IDENTITY.clone();
_rotationTransform = new Matrix3D();
_rotTransformRotation = Quaternion.IDENTITY.clone();
}
/**
* Indicates the position of the Emitter instance relative to
* the local coordinate system of the Renderer.
*/
public function get position():Vector3D
{
return _position;
}
public function set position( value:Vector3D ):void
{
_position = value;
_position.w = 1;
}
/**
* Indicates the rotation of the Emitter instance relative to
* the local coordinate system of the Renderer.
*/
public function get rotation():Quaternion
{
return _rotation;
}
public function set rotation( value:Quaternion ):void
{
_rotation = value;
}
/**
* Indicates the rotation of the Emitter instance relative to
* the local coordinate system of the Renderer, as a matrix
* transformation.
*/
public function get rotationTransform():Matrix3D
{
if( !_rotTransformRotation.equals( _rotation ) )
{
_rotationTransform = _rotation.toMatrixTransformation();
_rotTransformRotation = _rotation.clone();
}
return _rotationTransform;
}
/*
* Used internally to initialize a particle based on the state of the
* emitter. This function sets the particle's position and rotation to
* match the position and rotation of the emitter. After setting this
* default state, the initializer actions will be applied to the particle.
*
* @param particle The particle to initialize.
*/
override protected function initParticle( particle:Particle ):void
{
var p:Particle3D = Particle3D( particle );
p.position = _position.clone();
p.rotation = _rotation.clone();
}
/**
* If the spaceSort property is true, this method creates the spaceSortedX
* array.
*
* @param time The duration, in seconds, of the current frame.
*/
override protected function sortParticles():void
{
if( spaceSort )
{
_particles.sortOn( "x", Array.NUMERIC );
var len:int = _particles.length;
for( var i:int = 0; i < len; ++i )
{
Particle3D( _particles[ i ] ).sortID = i;
}
}
}
}
}
|
/*
* 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.threeD.emitters
{
import org.flintparticles.common.emitters.Emitter;
import org.flintparticles.common.particles.Particle;
import org.flintparticles.common.particles.ParticleFactory;
import org.flintparticles.threeD.geom.Quaternion;
import org.flintparticles.threeD.particles.Particle3D;
import org.flintparticles.threeD.particles.ParticleCreator3D;
import flash.geom.Matrix3D;
import flash.geom.Vector3D;
/**
* The Emitter3D class defines an emitter that exists in 3D space. It is the
* main emitter for using Flint in a 3D coordinate system.
*
* <p>This emitter is not constrained to any particular 3D rendering
* environment. The emitter manages the creation and updating of each
* particle's state but does not do any rendering of the particles.
* The rendering is handled by a renderer. Renderer's could be created
* for drawing an emitter's particles on any 3D drawing environment.</p>
*
* <p>This emitter adds 3D specific features to the base emitter class.</p>
*/
public class Emitter3D extends Emitter
{
/**
* @private
*
* default factory to manage the creation, reuse and destruction of particles
*/
protected static var _creator:ParticleCreator3D = new ParticleCreator3D();
/**
* The default particle factory used to manage the creation, reuse and destruction of particles.
*/
public static function get defaultParticleFactory():ParticleFactory
{
return _creator;
}
/**
* @private
*/
protected var _position:Vector3D;
/**
* @private
*/
protected var _rotation:Quaternion;
/**
* @private
*/
protected var _rotationTransform:Matrix3D;
private var _rotTransformRotation:Quaternion;
/**
* Identifies whether the particles should be arranged
* into a spacially sorted array - this speeds up proximity
* testing for those actions that need it.
*/
public var spaceSort:Boolean = false;
/**
* The constructor creates an emitter 3D.
*/
public function Emitter3D()
{
super();
_particleFactory = _creator;
_position = new Vector3D( 0, 0, 0, 1 );
_rotation = Quaternion.IDENTITY.clone();
_rotationTransform = new Matrix3D();
_rotTransformRotation = Quaternion.IDENTITY.clone();
}
/**
* Indicates the position of the Emitter instance relative to
* the local coordinate system of the Renderer.
*/
public function get position():Vector3D
{
return _position;
}
public function set position( value:Vector3D ):void
{
_position = value;
_position.w = 1;
}
/**
* Indicates the rotation of the Emitter instance relative to
* the local coordinate system of the Renderer.
*/
public function get rotation():Quaternion
{
return _rotation;
}
public function set rotation( value:Quaternion ):void
{
_rotation = value;
}
/**
* Indicates the rotation of the Emitter instance relative to
* the local coordinate system of the Renderer, as a matrix
* transformation.
*/
public function get rotationTransform():Matrix3D
{
if( !_rotTransformRotation.equals( _rotation ) )
{
_rotationTransform = _rotation.toMatrixTransformation();
_rotTransformRotation = _rotation.clone();
}
return _rotationTransform;
}
/*
* Used internally to initialize a particle based on the state of the
* emitter. This function sets the particle's position and rotation to
* match the position and rotation of the emitter. After setting this
* default state, the initializer actions will be applied to the particle.
*
* @param particle The particle to initialize.
*/
override protected function initParticle( particle:Particle ):void
{
var p:Particle3D = Particle3D( particle );
p.position.x = _position.x;
p.position.y = _position.y;
p.position.z = _position.z;
p.rotation.w = _rotation.w;
p.rotation.x = _rotation.x;
p.rotation.y = _rotation.y;
p.rotation.z = _rotation.z;
}
/**
* If the spaceSort property is true, this method creates the spaceSortedX
* array.
*
* @param time The duration, in seconds, of the current frame.
*/
override protected function sortParticles():void
{
if( spaceSort )
{
_particles.sort( sortOnX );
var len:int = _particles.length;
for( var i:int = 0; i < len; ++i )
{
Particle3D( _particles[ i ] ).sortID = i;
}
}
}
private function sortOnX( p1:Particle3D, p2:Particle3D ):int
{
return p1.position.x - p2.position.x;
}
}
}
|
Fix sort error in Emitter3D
|
Fix sort error in Emitter3D
|
ActionScript
|
mit
|
richardlord/Flint
|
e2f5dda9653b3f96d48985af0d263eb2a6200b44
|
index.as
|
index.as
|
// [ ] Variable declaration
let name: type = expression;
// [ ] Basic types (arrow)
/*
byte (8-bit, unsigned)
bool (1-bit[*])
int8
int16
int32
int64
int128
uint8
uint16
uint32
uint64
uint128
intptr (size of a pointer, signed)
uintptr (size of a pointer, unsigned)
char (32-bit, unsigned)
float16
float32
float64
float128
*/
// [ ] Expressions
// [ ] - Add
// [ ] - Subtract
// [ ] - Multiply
// [ ] - Divide
// [ ] - Modulo
// [ ] - Logical And
// [ ] - Logical Or
// [ ] - Logical Not
// [ ] - Relational GT
// [ ] - Relational GE
// [ ] - Relational LT
// [ ] - Relational LE
// [ ] - Relational And
// [ ] - Relational Or
// [ ] - Bitwise And
// [ ] - Bitwise Or
// [ ] - Bitwise Xor
// [ ] - Bitwise Not
// [ ] Pointers
// [ ] - Type
// [ ] - Address Of
// [ ] - Dereference
// [ ] Cast
// [ ] Function declaration
def main() {
}
// [ ] Extern function declaration
extern def puts(s: *byte);
// [ ] Extern function declaration w/ABI
extern "stdcall" def CreateWindowExA();
// [ ] Function call (extern AND local)
main();
puts("Hello");
// [ ] Extern import
extern import "stdint.h";
// [ ] Module (namespace)
module cstdint { extern import "stdint.h"; }
// [ ] c module (built-in)
import "c";
/*
// [ ] Basic types (in C)
c.char
c.uchar
c.schar
c.int
c.uint
c.short
c.ushort
c.long
c.ulong
c.float
c.double
c.ldouble
*/
// [ ] BigInt
int // (∞-bit, signed)
|
Add a roadmap (of sorts)
|
Add a roadmap (of sorts)
|
ActionScript
|
mit
|
arrow-lang/arrow,arrow-lang/arrow,arrow-lang/arrow
|
|
e2a292e0fb4e8bf7f552f59ee858bc41e13fad9a
|
src/as/com/threerings/util/Name.as
|
src/as/com/threerings/util/Name.as
|
package com.threerings.util {
import com.threerings.util.Equalable;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.Streamable;
public class Name extends Object
implements Comparable, Hashable, Streamable
{
public function Name (name :String = "")
{
_name = name;
}
public function getNormal () :String
{
if (_normal == null) {
_normal = normalize(_name);
if (_normal === _name) {
_normal = _name;
}
}
return _normal;
}
public function isValid () :Boolean
{
return !isBlank();
}
public function isBlank () :Boolean
{
return Name.isBlank(this);
}
public function toString () :String
{
return _name;
}
// from interface Hashable
public function equals (other :Object) :Boolean
{
return (ClassUtil.getClass(other) == Name) &&
(getNormal() === (other as Name).getNormal());
}
// from interface Hashable
public function hashCode () :int
{
return StringUtil.hashCode(getNormal());
}
// from interface Comparable
public function compareTo (other :Object) :int
{
var thisNormal :String = getNormal();
var thatNormal :String = (other as Name).getNormal();
if (thisNormal == thatNormal) {
return 0;
} if (thisNormal < thatNormal) {
return -1;
} else {
return 1;
}
}
// from interface Streamable
public function writeObject (out :ObjectOutputStream) :void
//throws IOError
{
out.writeField(_name);
}
// from interface Streamable
public function readObject (ins :ObjectInputStream) :void
//throws IOError
{
_name = (ins.readField(String) as String);
}
protected function normalize (txt :String) :String
{
return txt.toLowerCase();
}
public static function isBlank (name :Name) :Boolean
{
return (name == null || "" === name.toString());
}
/** The raw name text. */
protected var _name :String;
/** The normalized name text. */
protected var _normal :String;
}
}
|
package com.threerings.util {
import com.threerings.util.Equalable;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.Streamable;
public class Name extends Object
implements Comparable, Hashable, Streamable
{
public function Name (name :String = "")
{
_name = name;
}
public function getNormal () :String
{
if (_normal == null) {
_normal = normalize(_name);
if (_normal === _name) {
_normal = _name;
}
}
return _normal;
}
public function isValid () :Boolean
{
return !isBlank();
}
public function isBlank () :Boolean
{
return Name.isBlank(this);
}
public function toString () :String
{
return _name;
}
// from interface Hashable
public function equals (other :Object) :Boolean
{
return (ClassUtil.getClass(other) == Name) &&
(getNormal() === (other as Name).getNormal());
}
// from interface Hashable
public function hashCode () :int
{
return StringUtil.hashCode(getNormal());
}
// from interface Comparable
public function compareTo (other :Object) :int
{
var thisNormal :String = getNormal();
var thatNormal :String = (other as Name).getNormal();
return thisNormal.localeCompare(thatNormal);
}
// from interface Streamable
public function writeObject (out :ObjectOutputStream) :void
//throws IOError
{
out.writeField(_name);
}
// from interface Streamable
public function readObject (ins :ObjectInputStream) :void
//throws IOError
{
_name = (ins.readField(String) as String);
}
protected function normalize (txt :String) :String
{
return txt.toLowerCase();
}
public static function isBlank (name :Name) :Boolean
{
return (name == null || "" === name.toString());
}
/** The raw name text. */
protected var _name :String;
/** The normalized name text. */
protected var _normal :String;
}
}
|
Use localeCompare.
|
Use localeCompare.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4299 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
cae376f14ed94e0a109347e288f524c4f758b417
|
src/aerys/minko/type/loader/TextureLoader.as
|
src/aerys/minko/type/loader/TextureLoader.as
|
package aerys.minko.type.loader
{
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.type.Signal;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.getQualifiedClassName;
public class TextureLoader implements ILoader
{
private static const EMPTY_BITMAPDATA : BitmapData = new BitmapData(1, 1, false, 0);
private var _mipMapping : Boolean;
private var _progress : Signal;
private var _error : Signal;
private var _complete : Signal;
private var _isComplete : Boolean;
protected var _textureResource : TextureResource;
public function get progress() : Signal
{
return _progress;
}
public function get error() : Signal
{
return _error;
}
public function get complete() : Signal
{
return _complete;
}
public function get isComplete() : Boolean
{
return _isComplete;
}
public function get textureResource() : TextureResource
{
return _textureResource;
}
public function TextureLoader(enableMipmapping : Boolean = true)
{
_mipMapping = enableMipmapping;
initialize();
}
private function initialize() : void
{
_textureResource = new TextureResource();
_textureResource.setContentFromBitmapData(EMPTY_BITMAPDATA, _mipMapping);
_isComplete = false;
_error = new Signal('TextureLoader.error');
_progress = new Signal('TextureLoader.progress');
_complete = new Signal('TextureLoader.complete');
}
public function load(request : URLRequest) : void
{
var loader : URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener(ProgressEvent.PROGRESS, loadProgressHandler);
loader.addEventListener(Event.COMPLETE, loadCompleteHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR, loadIoErrorHandler);
loader.load(request);
}
private function loadIoErrorHandler(e : IOErrorEvent) : void
{
_textureResource = null;
_error.execute(this, e.errorID, e.text);
}
private function loadProgressHandler(e : ProgressEvent) : void
{
_progress.execute(this, e.bytesLoaded, e.bytesTotal);
}
private function loadCompleteHandler(e : Event) : void
{
loadBytes(URLLoader(e.currentTarget).data);
}
public function loadClass(classObject : Class) : void
{
var assetObject : Object = new classObject();
if (assetObject is Bitmap || assetObject is BitmapData)
{
var bitmapData : BitmapData = assetObject as BitmapData;
if (bitmapData == null)
bitmapData = Bitmap(assetObject).bitmapData;
_textureResource.setContentFromBitmapData(bitmapData, _mipMapping);
bitmapData.dispose();
_isComplete = true;
_complete.execute(this, _textureResource);
}
else if (assetObject is ByteArray)
{
loadBytes(ByteArray(assetObject));
}
else
{
var className : String = getQualifiedClassName(classObject);
className = className.substr(className.lastIndexOf(':') + 1);
_isComplete = true;
throw new Error('No texture can be created from an object of type \'' + className + '\'');
}
}
public function loadBytes(bytes : ByteArray) : void
{
bytes.position = 0;
if (bytes.readByte() == 'A'.charCodeAt(0) &&
bytes.readByte() == 'T'.charCodeAt(0) &&
bytes.readByte() == 'F'.charCodeAt(0))
{
bytes.position = 0;
_textureResource.setContentFromATF(bytes);
_isComplete = true;
_complete.execute(this, _textureResource);
}
else
{
bytes.position = 0;
var loader : Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadBytesCompleteHandler);
loader.loadBytes(bytes);
}
}
private function loadBytesCompleteHandler(e : Event) : void
{
var displayObject : DisplayObject = LoaderInfo(e.currentTarget).content;
if (displayObject is Bitmap)
{
var bitmapData : BitmapData = Bitmap(displayObject).bitmapData;
_textureResource.setContentFromBitmapData(bitmapData, _mipMapping);
bitmapData.dispose();
_isComplete = true;
_complete.execute(this, _textureResource);
}
else
{
var className : String = getQualifiedClassName(displayObject);
className = className.substr(className.lastIndexOf(':') + 1);
_isComplete = true;
throw new Error(
'No texture can be created from an object of type \'' + className + '\''
);
}
}
public static function loadClass(classObject : Class,
enableMipMapping : Boolean = true) : TextureResource
{
var textureLoader : TextureLoader = new TextureLoader(enableMipMapping);
textureLoader.loadClass(classObject);
return textureLoader.textureResource;
}
public static function load(request : URLRequest,
enableMipMapping : Boolean = true) : TextureResource
{
var textureLoader : TextureLoader = new TextureLoader(enableMipMapping);
textureLoader.load(request);
return textureLoader.textureResource;
}
public static function loadBytes(bytes : ByteArray,
enableMipMapping : Boolean = true) : TextureResource
{
var textureLoader : TextureLoader = new TextureLoader(enableMipMapping);
textureLoader.loadBytes(bytes);
return textureLoader.textureResource;
}
}
}
|
package aerys.minko.type.loader
{
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.type.Signal;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.getQualifiedClassName;
public class TextureLoader implements ILoader
{
private static const EMPTY_BITMAPDATA : BitmapData = new BitmapData(1, 1, false, 0);
private var _mipMapping : Boolean;
private var _progress : Signal;
private var _error : Signal;
private var _complete : Signal;
private var _isComplete : Boolean;
protected var _textureResource : TextureResource;
public function get progress() : Signal
{
return _progress;
}
public function get error() : Signal
{
return _error;
}
public function get complete() : Signal
{
return _complete;
}
public function get isComplete() : Boolean
{
return _isComplete;
}
public function get textureResource() : TextureResource
{
return _textureResource;
}
public function TextureLoader(enableMipmapping : Boolean = true)
{
_mipMapping = enableMipmapping;
initialize();
}
private function initialize() : void
{
_textureResource = new TextureResource();
_textureResource.setContentFromBitmapData(EMPTY_BITMAPDATA, _mipMapping);
_isComplete = false;
_error = new Signal('TextureLoader.error');
_progress = new Signal('TextureLoader.progress');
_complete = new Signal('TextureLoader.complete');
}
public function load(request : URLRequest) : void
{
var loader : URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener(ProgressEvent.PROGRESS, loadProgressHandler);
loader.addEventListener(Event.COMPLETE, loadCompleteHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR, loadIoErrorHandler);
loader.load(request);
}
private function loadIoErrorHandler(e : IOErrorEvent) : void
{
_textureResource = null;
if (_error.numCallbacks == 0)
throw e;
else
_error.execute(this, e.errorID, e.text);
}
private function loadProgressHandler(e : ProgressEvent) : void
{
_progress.execute(this, e.bytesLoaded, e.bytesTotal);
}
private function loadCompleteHandler(e : Event) : void
{
loadBytes(URLLoader(e.currentTarget).data);
}
public function loadClass(classObject : Class) : void
{
var assetObject : Object = new classObject();
if (assetObject is Bitmap || assetObject is BitmapData)
{
var bitmapData : BitmapData = assetObject as BitmapData;
if (bitmapData == null)
bitmapData = Bitmap(assetObject).bitmapData;
_textureResource.setContentFromBitmapData(bitmapData, _mipMapping);
bitmapData.dispose();
_isComplete = true;
_complete.execute(this, _textureResource);
}
else if (assetObject is ByteArray)
{
loadBytes(ByteArray(assetObject));
}
else
{
var className : String = getQualifiedClassName(classObject);
className = className.substr(className.lastIndexOf(':') + 1);
_isComplete = true;
throw new Error('No texture can be created from an object of type \'' + className + '\'');
}
}
public function loadBytes(bytes : ByteArray) : void
{
bytes.position = 0;
if (bytes.readByte() == 'A'.charCodeAt(0) &&
bytes.readByte() == 'T'.charCodeAt(0) &&
bytes.readByte() == 'F'.charCodeAt(0))
{
bytes.position = 0;
_textureResource.setContentFromATF(bytes);
_isComplete = true;
_complete.execute(this, _textureResource);
}
else
{
bytes.position = 0;
var loader : Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadBytesCompleteHandler);
loader.loadBytes(bytes);
}
}
private function loadBytesCompleteHandler(e : Event) : void
{
var displayObject : DisplayObject = LoaderInfo(e.currentTarget).content;
if (displayObject is Bitmap)
{
var bitmapData : BitmapData = Bitmap(displayObject).bitmapData;
_textureResource.setContentFromBitmapData(bitmapData, _mipMapping);
bitmapData.dispose();
_isComplete = true;
_complete.execute(this, _textureResource);
}
else
{
var className : String = getQualifiedClassName(displayObject);
className = className.substr(className.lastIndexOf(':') + 1);
_isComplete = true;
throw new Error(
'No texture can be created from an object of type \'' + className + '\''
);
}
}
public static function loadClass(classObject : Class,
enableMipMapping : Boolean = true) : TextureResource
{
var textureLoader : TextureLoader = new TextureLoader(enableMipMapping);
textureLoader.loadClass(classObject);
return textureLoader.textureResource;
}
public static function load(request : URLRequest,
enableMipMapping : Boolean = true) : TextureResource
{
var textureLoader : TextureLoader = new TextureLoader(enableMipMapping);
textureLoader.load(request);
return textureLoader.textureResource;
}
public static function loadBytes(bytes : ByteArray,
enableMipMapping : Boolean = true) : TextureResource
{
var textureLoader : TextureLoader = new TextureLoader(enableMipMapping);
textureLoader.loadBytes(bytes);
return textureLoader.textureResource;
}
}
}
|
fix TextureLoader.ioErrorHandler() to throw the error if no callback is set for the TextureLoader.error signal
|
fix TextureLoader.ioErrorHandler() to throw the error if no callback is set for the TextureLoader.error signal
|
ActionScript
|
mit
|
aerys/minko-as3
|
c130530c7711390f8641e673b45e9b1c90a01360
|
src/com/axis/mjpegclient/Handle.as
|
src/com/axis/mjpegclient/Handle.as
|
package com.axis.mjpegclient {
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
import com.axis.Logger;
import com.axis.ErrorManager;
import com.axis.http.request;
[Event(name="image",type="flash.events.Event")]
[Event(name="connect",type="flash.events.Event")]
[Event(name="error",type="flash.events.Event")]
public class Handle extends EventDispatcher {
private var urlParsed:Object;
private var socket:Socket = null;
private var buffer:ByteArray = null;
private var dataBuffer:ByteArray = null;
private var url:String = "";
private var params:Object;
private var parseHeaders:Boolean = true;
private var headers:Vector.<String> = new Vector.<String>();
private var clen:int;
private var parseSubheaders:Boolean = true;
public var image:ByteArray = null;
public function Handle(urlParsed:Object) {
this.urlParsed = urlParsed;
this.buffer = new ByteArray();
this.dataBuffer = new ByteArray();
this.socket = new Socket();
this.socket.timeout = 5000;
this.socket.addEventListener(Event.CONNECT, onConnect);
this.socket.addEventListener(Event.CLOSE, onClose);
this.socket.addEventListener(ProgressEvent.SOCKET_DATA, onHttpHeaders);
this.socket.addEventListener(IOErrorEvent.IO_ERROR, onError);
this.socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
}
private function onError(e:ErrorEvent):void {
disconnect();
dispatchEvent(new Event("IOError:" + e.errorID));
}
public function disconnect():void {
if (!socket.connected) {
return;
}
socket.close();
image = null;
buffer = null;
dispatchEvent(new Event("disconnect"));
}
public function stop():void {
disconnect();
}
public function connect():void {
if (socket.connected) {
disconnect();
}
Logger.log('MJPEGClient: connecting to', urlParsed.host + ':' + urlParsed.port);
socket.connect(urlParsed.host, urlParsed.port);
}
private function onConnect(event:Event):void {
buffer = new ByteArray();
dataBuffer = new ByteArray();
headers.length = 0;
parseHeaders = true;
parseSubheaders = true;
socket.writeUTFBytes("GET " + urlParsed.urlpath + " HTTP/1.0\r\n");
socket.writeUTFBytes("Host: " + urlParsed.host + ':' + urlParsed.port + "\r\n");
socket.writeUTFBytes("Accept: multipart/x-mixed-replace\r\n");
socket.writeUTFBytes("User-Agent: Locomote\r\n");
socket.writeUTFBytes("\r\n");
}
private function onClose(e:Event):void {
// Security error is thrown if this line is excluded
socket.close();
}
private function onHttpHeaders(event:ProgressEvent):void {
var parsed:* = request.readHeaders(socket, dataBuffer);
if (false === parsed) {
return;
}
if (200 !== parsed.code) {
ErrorManager.dispatchError(parsed.code);
disconnect();
return;
}
if (!/^multipart\/x-mixed-replace/.test(parsed.headers['content-type'])) {
ErrorManager.dispatchError(829);
disconnect();
return;
}
this.socket.removeEventListener(ProgressEvent.SOCKET_DATA, onHttpHeaders);
this.socket.addEventListener(ProgressEvent.SOCKET_DATA, onImageData);
if (0 < this.dataBuffer.bytesAvailable) {
this.onImageData(event);
}
}
private function onImageData(event:ProgressEvent):void {
socket.readBytes(dataBuffer, dataBuffer.length);
if (parseSubheaders) {
var parsed:* = request.readHeaders(socket, dataBuffer);
if (false === parsed) {
return;
}
this.clen = parsed.headers['content-length'];
parseSubheaders = false;
}
findImage();
if (this.clen < this.dataBuffer.bytesAvailable) {
onImageData(event);
}
};
private function findImage():void {
if (this.dataBuffer.bytesAvailable < this.clen + 2) {
return;
}
image = new ByteArray()
dataBuffer.readBytes(image, 0, clen + 2);
var copy:ByteArray = new ByteArray();
dataBuffer.readBytes(copy, 0);
dataBuffer = copy;
dispatchEvent(new Event("image"));
clen = 0;
parseSubheaders = true;
}
}
}
|
package com.axis.mjpegclient {
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
import com.axis.Logger;
import com.axis.ErrorManager;
import com.axis.http.request;
import com.axis.http.auth;
[Event(name="image",type="flash.events.Event")]
[Event(name="connect",type="flash.events.Event")]
[Event(name="error",type="flash.events.Event")]
public class Handle extends EventDispatcher {
private var urlParsed:Object;
private var socket:Socket = null;
private var buffer:ByteArray = null;
private var dataBuffer:ByteArray = null;
private var url:String = "";
private var params:Object;
private var parseHeaders:Boolean = true;
private var headers:Vector.<String> = new Vector.<String>();
private var clen:int;
private var parseSubheaders:Boolean = true;
private var authState:String = "none";
private var authOpts:Object = {};
private var digestNC:uint = 1;
private var method:String = "";
public var image:ByteArray = null;
public function Handle(urlParsed:Object) {
this.urlParsed = urlParsed;
this.buffer = new ByteArray();
this.dataBuffer = new ByteArray();
this.socket = new Socket();
this.socket.timeout = 5000;
this.socket.addEventListener(Event.CONNECT, onConnect);
this.socket.addEventListener(Event.CLOSE, onClose);
this.socket.addEventListener(ProgressEvent.SOCKET_DATA, onHttpHeaders);
this.socket.addEventListener(IOErrorEvent.IO_ERROR, onError);
this.socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
}
private function onError(e:ErrorEvent):void {
disconnect();
dispatchEvent(new Event("IOError:" + e.errorID));
}
public function disconnect():void {
if (!socket.connected) {
return;
}
socket.close();
image = null;
buffer = null;
dispatchEvent(new Event("disconnect"));
}
public function stop():void {
disconnect();
}
public function connect():void {
if (socket.connected) {
disconnect();
}
Logger.log('MJPEGClient: connecting to', urlParsed.host + ':' + urlParsed.port);
socket.connect(urlParsed.host, urlParsed.port);
}
private function onConnect(event:Event):void {
buffer = new ByteArray();
dataBuffer = new ByteArray();
headers.length = 0;
parseHeaders = true;
parseSubheaders = true;
var authHeader:String =
auth.authorizationHeader(method, authState, authOpts, urlParsed, digestNC++);
socket.writeUTFBytes("GET " + urlParsed.urlpath + " HTTP/1.0\r\n");
socket.writeUTFBytes("Host: " + urlParsed.host + ':' + urlParsed.port + "\r\n");
socket.writeUTFBytes(authHeader);
socket.writeUTFBytes("Accept: multipart/x-mixed-replace\r\n");
socket.writeUTFBytes("User-Agent: Locomote\r\n");
socket.writeUTFBytes("\r\n");
}
private function onClose(e:Event):void {
// Security error is thrown if this line is excluded
socket.close();
}
private function onHttpHeaders(event:ProgressEvent):void {
var parsed:* = request.readHeaders(socket, dataBuffer);
if (false === parsed) {
return;
}
if (401 === parsed.code) {
Logger.log('Unauthorized using auth method: ' + authState);
/* Unauthorized, change authState and (possibly) try again */
authOpts = parsed.headers['www-authenticate'];
var newAuthState:String = auth.nextMethod(authState, authOpts);
if (authState === newAuthState) {
ErrorManager.dispatchError(parsed.code);
return;
}
Logger.log('switching http-authorization from ' + authState + ' to ' + newAuthState);
authState = newAuthState;
connect();
return;
}
if (200 !== parsed.code) {
ErrorManager.dispatchError(parsed.code);
disconnect();
return;
}
if (!/^multipart\/x-mixed-replace/.test(parsed.headers['content-type'])) {
ErrorManager.dispatchError(829);
disconnect();
return;
}
this.socket.removeEventListener(ProgressEvent.SOCKET_DATA, onHttpHeaders);
this.socket.addEventListener(ProgressEvent.SOCKET_DATA, onImageData);
if (0 < this.dataBuffer.bytesAvailable) {
this.onImageData(event);
}
}
private function onImageData(event:ProgressEvent):void {
socket.readBytes(dataBuffer, dataBuffer.length);
if (parseSubheaders) {
var parsed:* = request.readHeaders(socket, dataBuffer);
if (false === parsed) {
return;
}
this.clen = parsed.headers['content-length'];
parseSubheaders = false;
}
findImage();
if (this.clen < this.dataBuffer.bytesAvailable) {
onImageData(event);
}
};
private function findImage():void {
if (this.dataBuffer.bytesAvailable < this.clen + 2) {
return;
}
image = new ByteArray()
dataBuffer.readBytes(image, 0, clen + 2);
var copy:ByteArray = new ByteArray();
dataBuffer.readBytes(copy, 0);
dataBuffer = copy;
dispatchEvent(new Event("image"));
clen = 0;
parseSubheaders = true;
}
}
}
|
Add HTTP Auth support for MJPEG client
|
Add HTTP Auth support for MJPEG client
|
ActionScript
|
bsd-3-clause
|
AxisCommunications/locomote-video-player,gaetancollaud/locomote-video-player
|
bdefaf22505e8b4873fe2eb91baef9db3670cf0e
|
WeaveUI/src/weave/ui/CustomTree.as
|
WeaveUI/src/weave/ui/CustomTree.as
|
/*
Weave (Web-based Analysis and Visualization Environment)
Copyright (C) 2008-2011 University of Massachusetts Lowell
This file is a part of Weave.
Weave is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License, Version 3,
as published by the Free Software Foundation.
Weave is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Weave. If not, see <http://www.gnu.org/licenses/>.
*/
package weave.ui
{
import flash.events.Event;
import mx.collections.IList;
import mx.controls.Tree;
import mx.core.ScrollPolicy;
import mx.core.mx_internal;
import mx.utils.ObjectUtil;
import weave.utils.EventUtils;
/**
* This class features a correctly behaving auto horizontal scroll policy.
* @author adufilie
*/
public class CustomTree extends Tree
{
public function CustomTree()
{
super();
addEventListener("scroll", updateHScrollLater);
}
///////////////////////////////////////////////////////////////////////////////
// solution for automatic maxHorizontalScrollPosition calculation
// modified from http://www.frishy.com/2007/09/autoscrolling-for-flex-tree/
// we need to override maxHorizontalScrollPosition because setting
// Tree's maxHorizontalScrollPosition adds an indent value to it,
// which we don't need as measureWidthOfItems seems to return exactly
// what we need. Not only that, but getIndent() seems to be broken
// anyways (SDK-12578).
// I hate using mx_internal stuff, but we can't do
// super.super.maxHorizontalScrollPosition in AS 3, so we have to
// emulate it.
override public function get maxHorizontalScrollPosition():Number
{
if (isNaN(mx_internal::_maxHorizontalScrollPosition))
return 0;
return mx_internal::_maxHorizontalScrollPosition;
}
override public function set maxHorizontalScrollPosition(value:Number):void
{
if (ObjectUtil.numericCompare(mx_internal::_maxHorizontalScrollPosition, value) != 0)
{
mx_internal::_maxHorizontalScrollPosition = value;
dispatchEvent(new Event("maxHorizontalScrollPositionChanged"));
scrollAreaChanged = true;
invalidateDisplayList();
}
}
private const updateHScrollLater:Function = EventUtils.generateDelayedCallback(this, updateHScrollNow, 0);
private function updateHScrollNow():void
{
// we call measureWidthOfItems to get the max width of the item renderers.
// then we see how much space we need to scroll, setting maxHorizontalScrollPosition appropriately
var widthOfVisibleItems:int = measureWidthOfItems(verticalScrollPosition - offscreenExtraRowsTop, listItems.length);
var maxHSP:Number = widthOfVisibleItems - (unscaledWidth - viewMetrics.left - viewMetrics.right);
var hspolicy:String = ScrollPolicy.ON;
if (maxHSP <= 0)
{
maxHSP = 0;
horizontalScrollPosition = 0;
// horizontal scroll is kept on except when there is no vertical scroll
// this avoids an infinite hide/show loop where hiding/showing the h-scroll bar affects the max h-scroll value
if (maxVerticalScrollPosition == 0)
hspolicy = ScrollPolicy.OFF;
}
maxHorizontalScrollPosition = maxHSP;
if (horizontalScrollPolicy != hspolicy)
horizontalScrollPolicy = hspolicy;
}
///////////////////////////////////////////////////////////////////////////////
// solution for display bugs when hierarchical data changes
private var _dataProvider:Object; // remembers previous value that was passed to "set dataProvider"
override public function set dataProvider(value:Object):void
{
_dataProvider = value;
super.dataProvider = value;
}
/**
* This function must be called whenever the hierarchical data changes.
* Otherwise, the Tree will not display properly.
*/
public function refreshDataProvider():void
{
var _firstVisibleItem:Object = firstVisibleItem;
var _selectedItems:Array = selectedItems;
var _openItems:Array = openItems.concat();
// use value previously passed to "set dataProvider" in order to create a new collection wrapper.
dataProvider = _dataProvider;
// commitProperties() behaves as desired when both dataProvider and openItems are set.
openItems = _openItems;
validateNow(); // necessary in order to select previous items and scroll back to the correct position
// scroll to the previous item, but only if it is within scroll range
var vsp:int = getItemIndex(_firstVisibleItem);
if (vsp >= 0 && vsp <= maxVerticalScrollPosition)
firstVisibleItem = _firstVisibleItem;
// selectedItems must be set last to avoid a bug where the Tree scrolls to the top.
selectedItems = _selectedItems;
}
/**
* This contains a workaround for a problem in List.configureScrollBars relying on a non-working function CursorBookmark.getViewIndex().
* This fixes the bug where the tree would scroll all the way from the bottom to the top when a node is collapsed.
*/
override protected function configureScrollBars():void
{
var rda:Boolean = runningDataEffect;
runningDataEffect = true;
// This is not a perfect scrolling solution. It looks ok when there is a partial row showing at the bottom.
var mvsp:int = Math.max(0, collection.length - listItems.length + 1);
if (verticalScrollPosition > mvsp)
verticalScrollPosition = mvsp;
super.configureScrollBars();
runningDataEffect = rda;
}
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
updateHScrollLater();
// If showRoot is false and root is showing, force commitProperties() to fix the problem.
// This workaround requires that the data descriptor reports that the root item is a branch and it has children, even if it doesn't.
if (!showRoot)
{
var rootItem:Object = dataProvider is IList && (dataProvider as IList).length > 0 ? (dataProvider as IList).getItemAt(0) : null;
if (rootItem && itemToItemRenderer(rootItem))
{
mx_internal::showRootChanged = true;
commitProperties();
}
}
// "iterator" is a HierarchicalViewCursor, and its movePrevious()/moveNext()/seek() functions do not work if "current" is null.
// Calling refreshDataProvider() returns the tree to a working state.
if (iterator && iterator.current == null)
refreshDataProvider();
super.updateDisplayList(unscaledWidth, unscaledHeight);
}
}
}
|
/*
Weave (Web-based Analysis and Visualization Environment)
Copyright (C) 2008-2011 University of Massachusetts Lowell
This file is a part of Weave.
Weave is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License, Version 3,
as published by the Free Software Foundation.
Weave is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Weave. If not, see <http://www.gnu.org/licenses/>.
*/
package weave.ui
{
import flash.events.Event;
import mx.collections.ICollectionView;
import mx.collections.IList;
import mx.collections.IViewCursor;
import mx.controls.Tree;
import mx.core.ScrollPolicy;
import mx.core.mx_internal;
import mx.utils.ObjectUtil;
import weave.utils.EventUtils;
/**
* This class features a correctly behaving auto horizontal scroll policy.
* @author adufilie
*/
public class CustomTree extends Tree
{
public function CustomTree()
{
super();
addEventListener("scroll", updateHScrollLater);
}
///////////////////////////////////////////////////////////////////////////////
// solution for automatic maxHorizontalScrollPosition calculation
// modified from http://www.frishy.com/2007/09/autoscrolling-for-flex-tree/
// we need to override maxHorizontalScrollPosition because setting
// Tree's maxHorizontalScrollPosition adds an indent value to it,
// which we don't need as measureWidthOfItems seems to return exactly
// what we need. Not only that, but getIndent() seems to be broken
// anyways (SDK-12578).
// I hate using mx_internal stuff, but we can't do
// super.super.maxHorizontalScrollPosition in AS 3, so we have to
// emulate it.
override public function get maxHorizontalScrollPosition():Number
{
if (isNaN(mx_internal::_maxHorizontalScrollPosition))
return 0;
return mx_internal::_maxHorizontalScrollPosition;
}
override public function set maxHorizontalScrollPosition(value:Number):void
{
if (ObjectUtil.numericCompare(mx_internal::_maxHorizontalScrollPosition, value) != 0)
{
mx_internal::_maxHorizontalScrollPosition = value;
dispatchEvent(new Event("maxHorizontalScrollPositionChanged"));
scrollAreaChanged = true;
invalidateDisplayList();
}
}
private const updateHScrollLater:Function = EventUtils.generateDelayedCallback(this, updateHScrollNow, 0);
private function updateHScrollNow():void
{
// we call measureWidthOfItems to get the max width of the item renderers.
// then we see how much space we need to scroll, setting maxHorizontalScrollPosition appropriately
var widthOfVisibleItems:int = measureWidthOfItems(verticalScrollPosition - offscreenExtraRowsTop, listItems.length);
var maxHSP:Number = widthOfVisibleItems - (unscaledWidth - viewMetrics.left - viewMetrics.right);
var hspolicy:String = ScrollPolicy.ON;
if (maxHSP <= 0)
{
maxHSP = 0;
horizontalScrollPosition = 0;
// horizontal scroll is kept on except when there is no vertical scroll
// this avoids an infinite hide/show loop where hiding/showing the h-scroll bar affects the max h-scroll value
if (maxVerticalScrollPosition == 0)
hspolicy = ScrollPolicy.OFF;
}
maxHorizontalScrollPosition = maxHSP;
if (horizontalScrollPolicy != hspolicy)
horizontalScrollPolicy = hspolicy;
}
///////////////////////////////////////////////////////////////////////////////
// solution for display bugs when hierarchical data changes
private var _dataProvider:Object; // remembers previous value that was passed to "set dataProvider"
override public function set dataProvider(value:Object):void
{
_dataProvider = value;
super.dataProvider = value;
}
/**
* This function must be called whenever the hierarchical data changes.
* Otherwise, the Tree will not display properly.
*/
public function refreshDataProvider():void
{
var _firstVisibleItem:Object = firstVisibleItem;
var _selectedItems:Array = selectedItems;
var _openItems:Array = openItems.concat();
// use value previously passed to "set dataProvider" in order to create a new collection wrapper.
dataProvider = _dataProvider;
// commitProperties() behaves as desired when both dataProvider and openItems are set.
openItems = _openItems;
validateNow(); // necessary in order to select previous items and scroll back to the correct position
// scroll to the previous item, but only if it is within scroll range
var vsp:int = getItemIndex(_firstVisibleItem);
if (vsp >= 0 && vsp <= maxVerticalScrollPosition)
firstVisibleItem = _firstVisibleItem;
// selectedItems must be set last to avoid a bug where the Tree scrolls to the top.
selectedItems = _selectedItems;
}
/**
* This contains a workaround for a problem in List.configureScrollBars relying on a non-working function CursorBookmark.getViewIndex().
* This fixes the bug where the tree would scroll all the way from the bottom to the top when a node is collapsed.
*/
override protected function configureScrollBars():void
{
var ac:ICollectionView = actualCollection;
var ai:IViewCursor = actualIterator;
var rda:Boolean = runningDataEffect;
runningDataEffect = true;
actualCollection = ac || collection; // avoids null pointer error
actualIterator = ai || iterator;
// This is not a perfect scrolling solution. It looks ok when there is a partial row showing at the bottom.
var mvsp:int = Math.max(0, collection.length - listItems.length + 1);
if (verticalScrollPosition > mvsp)
verticalScrollPosition = mvsp;
super.configureScrollBars();
runningDataEffect = rda;
actualCollection = ac;
actualIterator = ai;
}
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
updateHScrollLater();
// If showRoot is false and root is showing, force commitProperties() to fix the problem.
// This workaround requires that the data descriptor reports that the root item is a branch and it has children, even if it doesn't.
if (!showRoot)
{
var rootItem:Object = dataProvider is IList && (dataProvider as IList).length > 0 ? (dataProvider as IList).getItemAt(0) : null;
if (rootItem && itemToItemRenderer(rootItem))
{
mx_internal::showRootChanged = true;
commitProperties();
}
}
// "iterator" is a HierarchicalViewCursor, and its movePrevious()/moveNext()/seek() functions do not work if "current" is null.
// Calling refreshDataProvider() returns the tree to a working state.
if (iterator && iterator.current == null)
refreshDataProvider();
super.updateDisplayList(unscaledWidth, unscaledHeight);
}
}
}
|
work around null pointer error
|
work around null pointer error
|
ActionScript
|
mpl-2.0
|
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
|
47b600907fdaa9f12d13ee894f2481b9da651520
|
sAS3Cam.as
|
sAS3Cam.as
|
/**
* jQuery AS3 Webcam
*
* Copyright (c) 2012, Sergey Shilko ([email protected])
*
* Date: 08/01/2012
*
* @author Sergey Shilko
* @version 1.0
*
**/
/* SWF external interface:
* webcam.save() - get base64 encoded JPEG image
* webcam.getCameraList() - get list of available cams
* webcam.setCamera(i) - set camera, camera index retrieved with getCameraList
* */
/* External triggers on events:
* webcam.isClientReady() - you respond to SWF with true (by default) meaning javascript is ready to accept callbacks
* webcam.cameraConnected() - camera connected callback from SWF
* webcam.noCameraFound() - SWF response that it cannot find any suitable camera
* webcam.cameraEnabled() - SWF response when camera tracking is enabled (this is called multiple times, use isCameraEnabled flag)
* webcam.cameraDisabled()- SWF response, user denied usage of camera
* webcam.swfApiFail() - Javascript failed to make call to SWF
* webcam.debug() - debug callback used from SWF and can be used from javascript side too
* */
package {
import flash.system.Security;
import flash.system.SecurityPanel;
import flash.external.ExternalInterface;
import flash.display.Sprite;
import flash.media.Camera;
import flash.media.Video;
import flash.display.BitmapData;
import flash.events.*;
import flash.utils.ByteArray;
import flash.utils.Timer;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.display.StageQuality;
import com.adobe.images.JPGEncoder;
import Base64;
public class sAS3Cam extends Sprite {
private var camera:Camera = null;
private var video:Video = null;
private var bmd:BitmapData = null;
private var camBandwidth:int = 0; // Specifies the maximum amount of bandwidth that the current outgoing video feed can use, in bytes per second. To specify that Flash Player video can use as much bandwidth as needed to maintain the value of quality , pass 0 for bandwidth . The default value is 16384.
private var camQuality:int = 100; // this value is 0-100 with 1 being the lowest quality. Pass 0 if you want the quality to vary to keep better framerates
private var camFrameRate:int = 24;
private var camResolution:Array;
private function getCameraResolution():Array {
var resolutionWidth:Number = this.loaderInfo.parameters["resolutionWidth"];
var videoWidth:Number = Math.floor(resolutionWidth);
var resolutionHeight:Number = this.loaderInfo.parameters["resolutionHeight"];
var videoHeight:Number = Math.floor(resolutionHeight);
var serverWidth:Number = Math.floor(stage.stageWidth);
var serverHeight:Number = Math.floor(stage.stageHeight);
var result:Array = [Math.max(videoWidth, serverWidth), Math.max(videoHeight, serverHeight)];
return result;
}
private function setupCamera(useCamera:Camera):void {
useCamera.setMode(camResolution[0],
camResolution[1],
camFrameRate);
useCamera.setQuality(camBandwidth, camQuality);
useCamera.addEventListener(StatusEvent.STATUS, statusHandler);
useCamera.setMotionLevel(100); //disable motion detection
}
private function setVideoCamera(useCamera:Camera):void {
var doSmoothing:Boolean = this.loaderInfo.parameters["smoothing"];
var doDeblocking:Number = this.loaderInfo.parameters["deblocking"];
video = new Video();
video.smoothing = doSmoothing;
video.deblocking = doDeblocking;
video.attachCamera(useCamera);
addChild(video);
}
public function sAS3Cam():void {
flash.system.Security.allowDomain("*");
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.quality = StageQuality.BEST;
stage.align = StageAlign.TOP_LEFT;
camera = Camera.getCamera();
if (null != camera) {
if (ExternalInterface.available) {
camResolution = getCameraResolution();
setupCamera(camera);
setVideoCamera(camera);
bmd = new BitmapData(stage.width, stage.height);
try {
var containerReady:Boolean = isContainerReady();
if (containerReady) {
setupCallbacks();
} else {
var readyTimer:Timer = new Timer(100);
readyTimer.addEventListener(TimerEvent.TIMER, timerHandler);
readyTimer.start();
}
} catch (err:Error) { } finally { }
} else {
}
} else {
extCall('noCameraFound');
}
}
private function statusHandler(event:StatusEvent):void {
if (event.code == "Camera.Unmuted") {
camera.removeEventListener(StatusEvent.STATUS, statusHandler);
extCall('cameraEnabled');
} else {
extCall('cameraDisabled');
}
}
private function extCall(func:String):Boolean {
var target:String = this.loaderInfo.parameters["callTarget"];
return ExternalInterface.call(target + "." + func);
}
private function isContainerReady():Boolean {
var result:Boolean = extCall("isClientReady");
return result;
}
private function setupCallbacks():void {
ExternalInterface.addCallback("save", save);
ExternalInterface.addCallback("setCamera", setCamera);
ExternalInterface.addCallback("getCameraList", getCameraList);
extCall('cameraConnected');
/* when we have pernament accept policy --> */
if (!camera.muted) {
extCall('cameraEnabled');
} else {
Security.showSettings(SecurityPanel.PRIVACY);
}
/* when we have pernament accept policy <-- */
}
private function timerHandler(event:TimerEvent):void {
var isReady:Boolean = isContainerReady();
if (isReady) {
Timer(event.target).stop();
setupCallbacks();
}
}
public function getCameraList():Array {
var list:Array = Camera.names;
list.reverse();
return list;
}
public function setCamera(id:Number):Boolean {
var newcam:Camera = Camera.getCamera(id.toString());
if (newcam) {
camera = newcam;
setupCamera(camera);
setVideoCamera(camera);
return true;
}
return false;
}
public function save():String {
bmd.draw(video);
video.attachCamera(null); //this stops video stream, video will pause on last frame (like a preview)
var quality:Number = 100;
var byteArray:ByteArray = new JPGEncoder(quality).encode(bmd);
var string:String = Base64.encodeByteArray(byteArray);
return string;
}
}
}
|
/**
* jQuery AS3 Webcam
*
* Copyright (c) 2012, Sergey Shilko ([email protected])
*
* Date: 08/01/2012
*
* @author Sergey Shilko
* @version 1.0
*
**/
/* SWF external interface:
* webcam.save() - get base64 encoded JPEG image
* webcam.getCameraList() - get list of available cams
* webcam.setCamera(i) - set camera, camera index retrieved with getCameraList
* */
/* External triggers on events:
* webcam.isClientReady() - you respond to SWF with true (by default) meaning javascript is ready to accept callbacks
* webcam.cameraConnected() - camera connected callback from SWF
* webcam.noCameraFound() - SWF response that it cannot find any suitable camera
* webcam.cameraEnabled() - SWF response when camera tracking is enabled (this is called multiple times, use isCameraEnabled flag)
* webcam.cameraDisabled()- SWF response, user denied usage of camera
* webcam.swfApiFail() - Javascript failed to make call to SWF
* webcam.debug() - debug callback used from SWF and can be used from javascript side too
* */
package {
import flash.system.Security;
import flash.system.SecurityPanel;
import flash.external.ExternalInterface;
import flash.display.Sprite;
import flash.media.Camera;
import flash.media.Video;
import flash.display.BitmapData;
import flash.events.*;
import flash.utils.ByteArray;
import flash.utils.Timer;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.display.StageQuality;
import com.adobe.images.JPGEncoder;
import Base64;
public class sAS3Cam extends Sprite {
private var camera:Camera = null;
private var video:Video = null;
private var bmd:BitmapData = null;
private var camBandwidth:int = 0; // Specifies the maximum amount of bandwidth that the current outgoing video feed can use, in bytes per second. To specify that Flash Player video can use as much bandwidth as needed to maintain the value of quality , pass 0 for bandwidth . The default value is 16384.
private var camQuality:int = 100; // this value is 0-100 with 1 being the lowest quality. Pass 0 if you want the quality to vary to keep better framerates
private var camFrameRate:int = 24;
private var camResolution:Array;
private function getCameraResolution():Array {
var resolutionWidth:Number = this.loaderInfo.parameters["resolutionWidth"];
var videoWidth:Number = Math.floor(resolutionWidth);
var resolutionHeight:Number = this.loaderInfo.parameters["resolutionHeight"];
var videoHeight:Number = Math.floor(resolutionHeight);
var serverWidth:Number = Math.floor(stage.stageWidth);
var serverHeight:Number = Math.floor(stage.stageHeight);
var result:Array = [Math.max(videoWidth, serverWidth), Math.max(videoHeight, serverHeight)];
return result;
}
private function setupCamera(useCamera:Camera):void {
useCamera.setMode(camResolution[0],
camResolution[1],
camFrameRate);
useCamera.setQuality(camBandwidth, camQuality);
useCamera.addEventListener(StatusEvent.STATUS, statusHandler);
useCamera.setMotionLevel(100); //disable motion detection
}
private function setVideoCamera(useCamera:Camera):void {
var doSmoothing:Boolean = this.loaderInfo.parameters["smoothing"];
var doDeblocking:Number = this.loaderInfo.parameters["deblocking"];
video = new Video(camResolution[0],camResolution[1]);
video.smoothing = doSmoothing;
video.deblocking = doDeblocking;
video.attachCamera(useCamera);
addChild(video);
}
public function sAS3Cam():void {
flash.system.Security.allowDomain("*");
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.quality = StageQuality.BEST;
stage.align = StageAlign.TOP_LEFT;
camera = Camera.getCamera();
if (null != camera) {
if (ExternalInterface.available) {
camResolution = getCameraResolution();
setupCamera(camera);
setVideoCamera(camera);
bmd = new BitmapData(stage.width, stage.height);
try {
var containerReady:Boolean = isContainerReady();
if (containerReady) {
setupCallbacks();
} else {
var readyTimer:Timer = new Timer(100);
readyTimer.addEventListener(TimerEvent.TIMER, timerHandler);
readyTimer.start();
}
} catch (err:Error) { } finally { }
} else {
}
} else {
extCall('noCameraFound');
}
}
private function statusHandler(event:StatusEvent):void {
if (event.code == "Camera.Unmuted") {
camera.removeEventListener(StatusEvent.STATUS, statusHandler);
extCall('cameraEnabled');
} else {
extCall('cameraDisabled');
}
}
private function extCall(func:String):Boolean {
var target:String = this.loaderInfo.parameters["callTarget"];
return ExternalInterface.call(target + "." + func);
}
private function isContainerReady():Boolean {
var result:Boolean = extCall("isClientReady");
return result;
}
private function setupCallbacks():void {
ExternalInterface.addCallback("save", save);
ExternalInterface.addCallback("setCamera", setCamera);
ExternalInterface.addCallback("getCameraList", getCameraList);
extCall('cameraConnected');
/* when we have pernament accept policy --> */
if (!camera.muted) {
extCall('cameraEnabled');
} else {
Security.showSettings(SecurityPanel.PRIVACY);
}
/* when we have pernament accept policy <-- */
}
private function timerHandler(event:TimerEvent):void {
var isReady:Boolean = isContainerReady();
if (isReady) {
Timer(event.target).stop();
setupCallbacks();
}
}
public function getCameraList():Array {
var list:Array = Camera.names;
list.reverse();
return list;
}
public function setCamera(id:Number):Boolean {
var newcam:Camera = Camera.getCamera(id.toString());
if (newcam) {
camera = newcam;
setupCamera(camera);
setVideoCamera(camera);
return true;
}
return false;
}
public function save():String {
bmd.draw(video);
video.attachCamera(null); //this stops video stream, video will pause on last frame (like a preview)
var quality:Number = 100;
var byteArray:ByteArray = new JPGEncoder(quality).encode(bmd);
var string:String = Base64.encodeByteArray(byteArray);
return string;
}
}
}
|
Add height and width to Video ctor
|
Add height and width to Video ctor
|
ActionScript
|
mit
|
sshilko/jQuery-AS3-Webcam,sshilko/jQuery-AS3-Webcam,sshilko/jQuery-AS3-Webcam
|
2e3c2f4eca2b15aecd205866cb2c464c05f5584b
|
src/aerys/minko/scene/node/Mesh.as
|
src/aerys/minko/scene/node/Mesh.as
|
package aerys.minko.scene.node
{
import aerys.minko.render.Effect;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.material.Material;
import aerys.minko.render.material.basic.BasicMaterial;
import aerys.minko.render.material.basic.BasicShader;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.controller.mesh.MeshVisibilityController;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.bounding.FrustumCulling;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.math.Ray;
/**
* Mesh objects are a visible instance of a Geometry rendered using a specific
* Effect with specific rendering properties.
*
* <p>
* Those rendering properties are stored in a DataBindings object so they can
* be directly used by the shaders in the rendering API.
* </p>
*
* @author Jean-Marc Le Roux
*
*/
public class Mesh extends AbstractSceneNode
{
public static const DEFAULT_MATERIAL : Effect = new Effect(
new BasicShader()
);
private var _geometry : Geometry = null;
private var _properties : DataProvider = null;
private var _material : Material = null;
private var _bindings : DataBindings = null;
private var _visibility : MeshVisibilityController = new MeshVisibilityController();
private var _frame : uint = 0;
private var _cloned : Signal = new Signal('Mesh.clones');
private var _materialChanged : Signal = new Signal('Mesh.materialChanged');
private var _frameChanged : Signal = new Signal('Mesh.frameChanged');
private var _geometryChanged : Signal = new Signal('Mesh.geometryChanged');
/**
* A DataProvider object already bound to the Mesh bindings.
*
* <pre>
* // set the "diffuseColor" property to 0x0000ffff
* mesh.properties.diffuseColor = 0x0000ffff;
*
* // animate the "diffuseColor" property
* mesh.addController(
* new AnimationController(
* new <ITimeline>[new ColorTimeline(
* "dataProvider.diffuseColor",
* 5000,
* new <uint>[0xffffffff, 0xffffff00, 0xffffffff]
* )]
* )
* );
* </pre>
*
* @return
*
*/
public function get properties() : DataProvider
{
return _properties;
}
public function set properties(value : DataProvider) : void
{
if (_properties != value)
{
if (_properties)
_bindings.removeProvider(_properties);
_properties = value;
if (value)
_bindings.addProvider(value);
}
}
public function get material() : Material
{
return _material;
}
public function set material(value : Material) : void
{
if (_material != value)
{
if (_material)
_bindings.removeProvider(_material);
_material = value;
if (value)
_bindings.addProvider(value);
}
}
/**
* The rendering properties provided to the shaders to customize
* how the mesh will appear on screen.
*
* @return
*
*/
public function get bindings() : DataBindings
{
return _bindings;
}
/**
* The Geometry of the mesh.
* @return
*
*/
public function get geometry() : Geometry
{
return _geometry;
}
public function set geometry(value : Geometry) : void
{
if (_geometry != value)
{
var oldGeometry : Geometry = _geometry;
_geometry = value;
_geometryChanged.execute(this, oldGeometry, value);
}
}
/**
* Whether the mesh is visible or not.
*
* @return
*
*/
public function get visible() : Boolean
{
return _visibility.visible;
}
public function set visible(value : Boolean) : void
{
_visibility.visible = value;
}
public function get frustumCulling() : uint
{
return _visibility.frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
_visibility.frustumCulling = value;
}
public function get cloned() : Signal
{
return _cloned;
}
public function get materialChanged() : Signal
{
return _materialChanged;
}
public function get frameChanged() : Signal
{
return _frameChanged;
}
public function get geometryChanged() : Signal
{
return _geometryChanged;
}
public function get frame() : uint
{
return _frame;
}
public function set frame(value : uint) : void
{
if (_frame != value)
{
var oldFrame : uint = _frame;
_frame = value;
_frameChanged.execute(this, oldFrame, value);
}
}
public function Mesh(geometry : Geometry = null,
material : Material = null,
...controllers)
{
super();
initialize(geometry, material, controllers);
}
private function initialize(geometry : Geometry,
material : Material,
controllers : Array) : void
{
_bindings = new DataBindings(this);
this.properties = new DataProvider(properties, 'meshProperties', DataProviderUsage.EXCLUSIVE);
_geometry = geometry;
this.material = material || new BasicMaterial();
// _visibility.frustumCulling = FrustumCulling.ENABLED;
addController(_visibility);
while (controllers && !(controllers[0] is AbstractController))
controllers = controllers[0];
if (controllers)
for each (var ctrl : AbstractController in controllers)
addController(ctrl);
}
public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY) : Number
{
return _geometry.boundingBox.testRay(
ray,
worldToLocal,
maxDistance
);
}
override public function clone(cloneControllers : Boolean = false) : ISceneNode
{
var clone : Mesh = new Mesh();
clone.copyFrom(this, true, cloneControllers);
return clone;
}
override protected function addedToSceneHandler(child : ISceneNode, scene : Scene) : void
{
super.addedToSceneHandler(child, scene);
if (child === this)
_bindings.addProvider(transformData);
}
override protected function removedFromSceneHandler(child : ISceneNode, scene : Scene) : void
{
super.removedFromSceneHandler(child, scene);
if (child === this)
_bindings.removeProvider(transformData);
}
protected function copyFrom(source : Mesh,
withBindings : Boolean,
cloneControllers : Boolean) : void
{
var numControllers : uint = source.numControllers;
name = source.name;
geometry = source._geometry;
properties = DataProvider(source._properties.clone());
_bindings.copySharedProvidersFrom(source._bindings);
copyControllersFrom(
source, this, cloneControllers, new <AbstractController>[source._visibility]
);
_visibility = source._visibility.clone() as MeshVisibilityController;
addController(_visibility);
transform.copyFrom(source.transform);
material = source._material;
source.cloned.execute(this, source);
}
}
}
|
package aerys.minko.scene.node
{
import aerys.minko.render.Effect;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.material.Material;
import aerys.minko.render.material.basic.BasicMaterial;
import aerys.minko.render.material.basic.BasicShader;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.controller.mesh.MeshVisibilityController;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.bounding.FrustumCulling;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.math.Ray;
/**
* Mesh objects are a visible instance of a Geometry rendered using a specific
* Effect with specific rendering properties.
*
* <p>
* Those rendering properties are stored in a DataBindings object so they can
* be directly used by the shaders in the rendering API.
* </p>
*
* @author Jean-Marc Le Roux
*
*/
public class Mesh extends AbstractSceneNode
{
public static const DEFAULT_MATERIAL : Material = new Material(
new Effect(new BasicShader())
);
private var _geometry : Geometry = null;
private var _properties : DataProvider = null;
private var _material : Material = null;
private var _bindings : DataBindings = null;
private var _visibility : MeshVisibilityController = new MeshVisibilityController();
private var _frame : uint = 0;
private var _cloned : Signal = new Signal('Mesh.clones');
private var _materialChanged : Signal = new Signal('Mesh.materialChanged');
private var _frameChanged : Signal = new Signal('Mesh.frameChanged');
private var _geometryChanged : Signal = new Signal('Mesh.geometryChanged');
/**
* A DataProvider object already bound to the Mesh bindings.
*
* <pre>
* // set the "diffuseColor" property to 0x0000ffff
* mesh.properties.diffuseColor = 0x0000ffff;
*
* // animate the "diffuseColor" property
* mesh.addController(
* new AnimationController(
* new <ITimeline>[new ColorTimeline(
* "dataProvider.diffuseColor",
* 5000,
* new <uint>[0xffffffff, 0xffffff00, 0xffffffff]
* )]
* )
* );
* </pre>
*
* @return
*
*/
public function get properties() : DataProvider
{
return _properties;
}
public function set properties(value : DataProvider) : void
{
if (_properties != value)
{
if (_properties)
_bindings.removeProvider(_properties);
_properties = value;
if (value)
_bindings.addProvider(value);
}
}
public function get material() : Material
{
return _material;
}
public function set material(value : Material) : void
{
if (_material != value)
{
if (_material)
_bindings.removeProvider(_material);
_material = value;
if (value)
_bindings.addProvider(value);
}
}
/**
* The rendering properties provided to the shaders to customize
* how the mesh will appear on screen.
*
* @return
*
*/
public function get bindings() : DataBindings
{
return _bindings;
}
/**
* The Geometry of the mesh.
* @return
*
*/
public function get geometry() : Geometry
{
return _geometry;
}
public function set geometry(value : Geometry) : void
{
if (_geometry != value)
{
var oldGeometry : Geometry = _geometry;
_geometry = value;
_geometryChanged.execute(this, oldGeometry, value);
}
}
/**
* Whether the mesh is visible or not.
*
* @return
*
*/
public function get visible() : Boolean
{
return _visibility.visible;
}
public function set visible(value : Boolean) : void
{
_visibility.visible = value;
}
public function get frustumCulling() : uint
{
return _visibility.frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
_visibility.frustumCulling = value;
}
public function get cloned() : Signal
{
return _cloned;
}
public function get materialChanged() : Signal
{
return _materialChanged;
}
public function get frameChanged() : Signal
{
return _frameChanged;
}
public function get geometryChanged() : Signal
{
return _geometryChanged;
}
public function get frame() : uint
{
return _frame;
}
public function set frame(value : uint) : void
{
if (_frame != value)
{
var oldFrame : uint = _frame;
_frame = value;
_frameChanged.execute(this, oldFrame, value);
}
}
public function Mesh(geometry : Geometry = null,
material : Material = null,
...controllers)
{
super();
initialize(geometry, material, controllers);
}
private function initialize(geometry : Geometry,
material : Material,
controllers : Array) : void
{
_bindings = new DataBindings(this);
this.properties = new DataProvider(properties, 'meshProperties', DataProviderUsage.EXCLUSIVE);
_geometry = geometry;
this.material = material || DEFAULT_MATERIAL;
// _visibility.frustumCulling = FrustumCulling.ENABLED;
addController(_visibility);
while (controllers && !(controllers[0] is AbstractController))
controllers = controllers[0];
if (controllers)
for each (var ctrl : AbstractController in controllers)
addController(ctrl);
}
public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY) : Number
{
return _geometry.boundingBox.testRay(
ray,
worldToLocal,
maxDistance
);
}
override public function clone(cloneControllers : Boolean = false) : ISceneNode
{
var clone : Mesh = new Mesh();
clone.copyFrom(this, true, cloneControllers);
return clone;
}
override protected function addedToSceneHandler(child : ISceneNode, scene : Scene) : void
{
super.addedToSceneHandler(child, scene);
if (child === this)
_bindings.addProvider(transformData);
}
override protected function removedFromSceneHandler(child : ISceneNode, scene : Scene) : void
{
super.removedFromSceneHandler(child, scene);
if (child === this)
_bindings.removeProvider(transformData);
}
protected function copyFrom(source : Mesh,
withBindings : Boolean,
cloneControllers : Boolean) : void
{
var numControllers : uint = source.numControllers;
name = source.name;
geometry = source._geometry;
properties = DataProvider(source._properties.clone());
_bindings.copySharedProvidersFrom(source._bindings);
copyControllersFrom(
source, this, cloneControllers, new <AbstractController>[source._visibility]
);
_visibility = source._visibility.clone() as MeshVisibilityController;
addController(_visibility);
transform.copyFrom(source.transform);
material = source._material;
source.cloned.execute(this, source);
}
}
}
|
fix Mesh.DEFAULT_MATERIAL to be an actual Material object
|
fix Mesh.DEFAULT_MATERIAL to be an actual Material object
|
ActionScript
|
mit
|
aerys/minko-as3
|
662caa83cd1d24020f5e98b8a478f76827ff6f6f
|
dolly-framework/src/test/actionscript/dolly/CloningOfCompositeCloneableClassTest.as
|
dolly-framework/src/test/actionscript/dolly/CloningOfCompositeCloneableClassTest.as
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.CompositeCloneableClass;
import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertFalse;
import org.flexunit.asserts.assertNotNull;
import org.hamcrest.assertThat;
import org.hamcrest.collection.array;
import org.hamcrest.collection.arrayWithSize;
import org.hamcrest.collection.everyItem;
import org.hamcrest.core.isA;
import org.hamcrest.object.equalTo;
use namespace dolly_internal;
public class CloningOfCompositeCloneableClassTest {
private var compositeCloneableClass:CompositeCloneableClass;
private var compositeCloneableClassType:Type;
[Before]
public function before():void {
compositeCloneableClass = new CompositeCloneableClass();
compositeCloneableClass.array = [1, 2, 3, 4, 5];
compositeCloneableClass.arrayList = new ArrayList([1, 2, 3, 4, 5]);
compositeCloneableClass.arrayCollection = new ArrayCollection([1, 2, 3, 4, 5]);
compositeCloneableClassType = Type.forInstance(compositeCloneableClass);
}
[After]
public function after():void {
compositeCloneableClass = null;
compositeCloneableClassType = null;
}
[Test]
public function findingAllWritableFieldsForType():void {
const writableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(compositeCloneableClassType);
assertNotNull(writableFields);
assertEquals(4, writableFields.length);
}
[Test]
public function cloningOfArray():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
assertNotNull(clone.array);
assertThat(clone.array, arrayWithSize(5));
assertThat(clone.array, compositeCloneableClass.array);
assertFalse(clone.array == compositeCloneableClass.array);
assertThat(clone.array, everyItem(isA(Number)));
assertThat(clone.array, array(equalTo(1), equalTo(2), equalTo(3), equalTo(4), equalTo(5)));
}
[Test]
public function cloningOfArrayList():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const arrayList:ArrayList = clone.arrayList;
assertNotNull(arrayList);
assertFalse(clone.arrayList == compositeCloneableClass.arrayList);
assertEquals(arrayList.length, 5);
assertEquals(arrayList.getItemAt(0), 1);
assertEquals(arrayList.getItemAt(1), 2);
assertEquals(arrayList.getItemAt(2), 3);
assertEquals(arrayList.getItemAt(3), 4);
assertEquals(arrayList.getItemAt(4), 5);
}
[Test]
public function cloningOfArrayCollection():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const targetArrayCollection:ArrayCollection = clone.arrayCollection;
assertNotNull(targetArrayCollection);
assertFalse(clone.arrayList == compositeCloneableClass.arrayList);
assertEquals(targetArrayCollection.length, 5);
assertEquals(targetArrayCollection.getItemAt(0), 1);
assertEquals(targetArrayCollection.getItemAt(1), 2);
assertEquals(targetArrayCollection.getItemAt(2), 3);
assertEquals(targetArrayCollection.getItemAt(3), 4);
assertEquals(targetArrayCollection.getItemAt(4), 5);
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.CompositeCloneableClass;
import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertFalse;
import org.flexunit.asserts.assertNotNull;
import org.hamcrest.assertThat;
import org.hamcrest.collection.array;
import org.hamcrest.collection.arrayWithSize;
import org.hamcrest.collection.everyItem;
import org.hamcrest.core.isA;
import org.hamcrest.object.equalTo;
use namespace dolly_internal;
public class CloningOfCompositeCloneableClassTest {
private var compositeCloneableClass:CompositeCloneableClass;
private var compositeCloneableClassType:Type;
[Before]
public function before():void {
compositeCloneableClass = new CompositeCloneableClass();
compositeCloneableClass.array = [1, 2, 3, 4, 5];
compositeCloneableClass.arrayList = new ArrayList([1, 2, 3, 4, 5]);
compositeCloneableClass.arrayCollection = new ArrayCollection([1, 2, 3, 4, 5]);
compositeCloneableClassType = Type.forInstance(compositeCloneableClass);
}
[After]
public function after():void {
compositeCloneableClass = null;
compositeCloneableClassType = null;
}
[Test]
public function findingAllWritableFieldsForType():void {
const writableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(compositeCloneableClassType);
assertNotNull(writableFields);
assertEquals(4, writableFields.length);
}
[Test]
public function cloningOfArray():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
assertNotNull(clone.array);
assertThat(clone.array, arrayWithSize(5));
assertThat(clone.array, compositeCloneableClass.array);
assertFalse(clone.array == compositeCloneableClass.array);
assertThat(clone.array, everyItem(isA(Number)));
assertThat(clone.array, array(equalTo(1), equalTo(2), equalTo(3), equalTo(4), equalTo(5)));
}
[Test]
public function cloningOfArrayList():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const arrayList:ArrayList = clone.arrayList;
assertNotNull(arrayList);
assertFalse(clone.arrayList == compositeCloneableClass.arrayList);
assertEquals(arrayList.length, 5);
assertEquals(arrayList.getItemAt(0), 1);
assertEquals(arrayList.getItemAt(1), 2);
assertEquals(arrayList.getItemAt(2), 3);
assertEquals(arrayList.getItemAt(3), 4);
assertEquals(arrayList.getItemAt(4), 5);
}
[Test]
public function cloningOfArrayCollection():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const targetArrayCollection:ArrayCollection = clone.arrayCollection;
assertNotNull(targetArrayCollection);
assertFalse(clone.arrayCollection == compositeCloneableClass.arrayCollection);
assertEquals(targetArrayCollection.length, 5);
assertEquals(targetArrayCollection.getItemAt(0), 1);
assertEquals(targetArrayCollection.getItemAt(1), 2);
assertEquals(targetArrayCollection.getItemAt(2), 3);
assertEquals(targetArrayCollection.getItemAt(3), 4);
assertEquals(targetArrayCollection.getItemAt(4), 5);
}
}
}
|
Fix typo.
|
Fix typo.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
ccdd6b044a14163a13fd38625d3d39097ff6294c
|
com/segonquart/menuColourIdiomes.as
|
com/segonquart/menuColourIdiomes.as
|
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
class menuColouridiomes extends MoviieClip
{
public var cat, es, en ,fr:MovieClip;
public var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr");
function menuColourIdiomes ():Void
{
this.onRollOver = this.mOver;
this.onRollOut = this.mOut;
this.onRelease =this.mOver;
}
private function mOver()
{
arrayLang_arr[i].colorTo("#95C60D", 0.3, "easeOutCirc");
}
private function mOut()
{
arrayLang_arr[i].colorTo("#010101", 0.3, "easeInCirc");
}
}
|
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
class menuColouridiomes extends MovieClip
{
public var cat, es, en ,fr:MovieClip;
public var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr");
function menuColourIdiomes ():Void
{
this.onRollOver = this.mOver;
this.onRollOut = this.mOut;
this.onRelease =this.mOver;
}
private function mOver()
{
arrayLang_arr[i].colorTo("#95C60D", 0.3, "easeOutCirc");
}
private function mOut()
{
arrayLang_arr[i].colorTo("#010101", 0.3, "easeInCirc");
}
}
|
Update menuColourIdiomes.as
|
Update menuColourIdiomes.as
|
ActionScript
|
bsd-3-clause
|
delfiramirez/web-talking-wear,delfiramirez/web-talking-wear,delfiramirez/web-talking-wear
|
c1d085e9adcd4ccdfcdeaa8e71f258c1b661ae0a
|
src/aerys/minko/scene/node/Mesh.as
|
src/aerys/minko/scene/node/Mesh.as
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.material.Material;
import aerys.minko.render.material.basic.BasicMaterial;
import aerys.minko.scene.controller.mesh.MeshController;
import aerys.minko.scene.controller.mesh.MeshVisibilityController;
import aerys.minko.scene.data.TransformDataProvider;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.enum.FrustumCulling;
import aerys.minko.type.math.Ray;
use namespace minko_scene;
/**
* Mesh objects are a visible instance of a Geometry rendered using a specific
* Effect with specific rendering properties.
*
* <p>
* Those rendering properties are stored in a DataBindings object so they can
* be directly used by the shaders in the rendering API.
* </p>
*
* @author Jean-Marc Le Roux
*
*/
public class Mesh extends AbstractVisibleSceneNode
{
public static const DEFAULT_MATERIAL : Material = new BasicMaterial();
private var _geometry : Geometry;
private var _properties : DataProvider;
private var _material : Material;
private var _bindings : DataBindings;
private var _visibility : MeshVisibilityController;
private var _frame : uint;
private var _cloned : Signal;
private var _materialChanged : Signal;
private var _frameChanged : Signal;
private var _geometryChanged : Signal;
/**
* A DataProvider object already bound to the Mesh bindings.
*
* <pre>
* // set the "diffuseColor" property to 0x0000ffff
* mesh.properties.diffuseColor = 0x0000ffff;
*
* // animate the "diffuseColor" property
* mesh.addController(
* new AnimationController(
* new <ITimeline>[new ColorTimeline(
* "dataProvider.diffuseColor",
* 5000,
* new <uint>[0xffffffff, 0xffffff00, 0xffffffff]
* )]
* )
* );
* </pre>
*
* @return
*
*/
public function get properties() : DataProvider
{
return _properties;
}
public function set properties(value : DataProvider) : void
{
if (_properties != value)
{
if (_properties)
_bindings.removeProvider(_properties);
_properties = value;
if (value)
_bindings.addProvider(value);
}
}
public function get material() : Material
{
return _material;
}
public function set material(value : Material) : void
{
if (_material != value)
{
if (_material)
_bindings.removeProvider(_material);
var oldMaterial : Material = _material;
_material = value;
if (value)
_bindings.addProvider(value);
_materialChanged.execute(this, oldMaterial, value);
}
}
/**
* The rendering properties provided to the shaders to customize
* how the mesh will appear on screen.
*
* @return
*
*/
public function get bindings() : DataBindings
{
return _bindings;
}
/**
* The Geometry of the mesh.
* @return
*
*/
public function get geometry() : Geometry
{
return _geometry;
}
public function set geometry(value : Geometry) : void
{
if (_geometry != value)
{
var oldGeometry : Geometry = _geometry;
if (oldGeometry)
oldGeometry.changed.remove(geometryChangedHandler);
_geometry = value;
if (value)
_geometry.changed.add(geometryChangedHandler);
_geometryChanged.execute(this, oldGeometry, value);
}
}
/**
* Whether the mesh in inside the camera frustum or not.
* @return
*
*/
public function get insideFrustum() : Boolean
{
return _visibility.insideFrustum;
}
override public function get computedVisibility() : Boolean
{
return scene ? _visibility.computedVisibility : super.computedVisibility;
}
public function get frustumCulling() : uint
{
return _visibility.frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
_visibility.frustumCulling = value;
}
public function get cloned() : Signal
{
return _cloned;
}
public function get materialChanged() : Signal
{
return _materialChanged;
}
public function get frameChanged() : Signal
{
return _frameChanged;
}
public function get geometryChanged() : Signal
{
return _geometryChanged;
}
public function get frame() : uint
{
return _frame;
}
public function set frame(value : uint) : void
{
if (_frame != value)
{
var oldFrame : uint = _frame;
_frame = value;
_frameChanged.execute(this, oldFrame, value);
}
}
public function Mesh(geometry : Geometry = null,
material : Material = null,
name : String = null)
{
super();
initializeMesh(geometry, material, name);
}
override protected function initialize() : void
{
_bindings = new DataBindings(this);
this.properties = new DataProvider(
properties,
'meshProperties',
DataProviderUsage.EXCLUSIVE
);
super.initialize();
}
override protected function initializeSignals():void
{
super.initializeSignals();
_cloned = new Signal('Mesh.cloned');
_materialChanged = new Signal('Mesh.materialChanged');
_frameChanged = new Signal('Mesh.frameChanged');
_geometryChanged = new Signal('Mesh.geometryChanged');
}
override protected function initializeContollers():void
{
super.initializeContollers();
addController(new MeshController());
_visibility = new MeshVisibilityController();
_visibility.frustumCulling = FrustumCulling.ENABLED;
addController(_visibility);
}
protected function initializeMesh(geometry : Geometry,
material : Material,
name : String) : void
{
if (name)
this.name = name;
this.geometry = geometry;
this.material = material || DEFAULT_MATERIAL;
}
public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY) : Number
{
return _geometry.boundingBox.testRay(
ray,
getWorldToLocalTransform(),
maxDistance
);
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var clone : Mesh = new Mesh();
clone.name = name;
clone.geometry = _geometry;
clone.properties = DataProvider(_properties.clone());
clone._bindings.copySharedProvidersFrom(_bindings);
clone.transform.copyFrom(transform);
clone.material = _material;
this.cloned.execute(this, clone);
return clone;
}
private function geometryChangedHandler(geometry : Geometry) : void
{
_geometryChanged.execute(this, _geometry, _geometry);
}
}
}
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.material.Material;
import aerys.minko.render.material.basic.BasicMaterial;
import aerys.minko.scene.controller.mesh.MeshController;
import aerys.minko.scene.controller.mesh.MeshVisibilityController;
import aerys.minko.scene.data.TransformDataProvider;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.enum.FrustumCulling;
import aerys.minko.type.math.Ray;
use namespace minko_scene;
/**
* Mesh objects are a visible instance of a Geometry rendered using a specific
* Effect with specific rendering properties.
*
* <p>
* Those rendering properties are stored in a DataBindings object so they can
* be directly used by the shaders in the rendering API.
* </p>
*
* @author Jean-Marc Le Roux
*
*/
public class Mesh extends AbstractVisibleSceneNode
{
public static const DEFAULT_MATERIAL : Material = new BasicMaterial();
private var _geometry : Geometry;
private var _properties : DataProvider;
private var _material : Material;
private var _bindings : DataBindings;
private var _visibility : MeshVisibilityController;
private var _frame : uint;
private var _cloned : Signal;
private var _materialChanged : Signal;
private var _frameChanged : Signal;
private var _geometryChanged : Signal;
/**
* A DataProvider object already bound to the Mesh bindings.
*
* <pre>
* // set the "diffuseColor" property to 0x0000ffff
* mesh.properties.diffuseColor = 0x0000ffff;
*
* // animate the "diffuseColor" property
* mesh.addController(
* new AnimationController(
* new <ITimeline>[new ColorTimeline(
* "dataProvider.diffuseColor",
* 5000,
* new <uint>[0xffffffff, 0xffffff00, 0xffffffff]
* )]
* )
* );
* </pre>
*
* @return
*
*/
public function get properties() : DataProvider
{
return _properties;
}
public function set properties(value : DataProvider) : void
{
if (_properties != value)
{
if (_properties)
_bindings.removeProvider(_properties);
_properties = value;
if (value)
_bindings.addProvider(value);
}
}
public function get material() : Material
{
return _material;
}
public function set material(value : Material) : void
{
if (_material != value)
{
if (_material)
_bindings.removeProvider(_material);
var oldMaterial : Material = _material;
_material = value;
if (value)
_bindings.addProvider(value);
_materialChanged.execute(this, oldMaterial, value);
}
}
/**
* The rendering properties provided to the shaders to customize
* how the mesh will appear on screen.
*
* @return
*
*/
public function get bindings() : DataBindings
{
return _bindings;
}
/**
* The Geometry of the mesh.
* @return
*
*/
public function get geometry() : Geometry
{
return _geometry;
}
public function set geometry(value : Geometry) : void
{
if (_geometry != value)
{
var oldGeometry : Geometry = _geometry;
if (oldGeometry)
oldGeometry.changed.remove(geometryChangedHandler);
_geometry = value;
if (value)
_geometry.changed.add(geometryChangedHandler);
_geometryChanged.execute(this, oldGeometry, value);
}
}
/**
* Whether the mesh in inside the camera frustum or not.
* @return
*
*/
public function get insideFrustum() : Boolean
{
return _visibility.insideFrustum;
}
override public function get computedVisibility() : Boolean
{
return scene
? super.computedVisibility && _visibility.computedVisibility
: super.computedVisibility;
}
public function get frustumCulling() : uint
{
return _visibility.frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
_visibility.frustumCulling = value;
}
public function get cloned() : Signal
{
return _cloned;
}
public function get materialChanged() : Signal
{
return _materialChanged;
}
public function get frameChanged() : Signal
{
return _frameChanged;
}
public function get geometryChanged() : Signal
{
return _geometryChanged;
}
public function get frame() : uint
{
return _frame;
}
public function set frame(value : uint) : void
{
if (_frame != value)
{
var oldFrame : uint = _frame;
_frame = value;
_frameChanged.execute(this, oldFrame, value);
}
}
public function Mesh(geometry : Geometry = null,
material : Material = null,
name : String = null)
{
super();
initializeMesh(geometry, material, name);
}
override protected function initialize() : void
{
_bindings = new DataBindings(this);
this.properties = new DataProvider(
properties,
'meshProperties',
DataProviderUsage.EXCLUSIVE
);
super.initialize();
}
override protected function initializeSignals():void
{
super.initializeSignals();
_cloned = new Signal('Mesh.cloned');
_materialChanged = new Signal('Mesh.materialChanged');
_frameChanged = new Signal('Mesh.frameChanged');
_geometryChanged = new Signal('Mesh.geometryChanged');
}
override protected function initializeContollers():void
{
super.initializeContollers();
addController(new MeshController());
_visibility = new MeshVisibilityController();
_visibility.frustumCulling = FrustumCulling.ENABLED;
addController(_visibility);
}
protected function initializeMesh(geometry : Geometry,
material : Material,
name : String) : void
{
if (name)
this.name = name;
this.geometry = geometry;
this.material = material || DEFAULT_MATERIAL;
}
public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY) : Number
{
return _geometry.boundingBox.testRay(
ray,
getWorldToLocalTransform(),
maxDistance
);
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var clone : Mesh = new Mesh();
clone.name = name;
clone.geometry = _geometry;
clone.properties = DataProvider(_properties.clone());
clone._bindings.copySharedProvidersFrom(_bindings);
clone.transform.copyFrom(transform);
clone.material = _material;
this.cloned.execute(this, clone);
return clone;
}
private function geometryChangedHandler(geometry : Geometry) : void
{
_geometryChanged.execute(this, _geometry, _geometry);
}
}
}
|
fix Mesh.computedVisibility getter to combine frustum culling and parent/self computed visibility properly using super.computedVisibility (github issue #77)
|
fix Mesh.computedVisibility getter to combine frustum culling and parent/self computed visibility properly using super.computedVisibility (github issue #77)
|
ActionScript
|
mit
|
aerys/minko-as3
|
3f1955e356d99ce35b138f438f7ad6330bbbab3b
|
src/aerys/minko/scene/node/Mesh.as
|
src/aerys/minko/scene/node/Mesh.as
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.material.Material;
import aerys.minko.render.material.basic.BasicMaterial;
import aerys.minko.scene.controller.mesh.VisibilityController;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.FrustumCulling;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.math.Ray;
use namespace minko_scene;
/**
* Mesh objects are a visible instance of a Geometry rendered using a specific
* Effect with specific rendering properties.
*
* <p>
* Those rendering properties are stored in a DataBindings object so they can
* be directly used by the shaders in the rendering API.
* </p>
*
* @author Jean-Marc Le Roux
*
*/
public class Mesh extends AbstractSceneNode
{
public static const DEFAULT_MATERIAL : Material = new BasicMaterial();
private var _geometry : Geometry;
private var _properties : DataProvider;
private var _material : Material;
private var _bindings : DataBindings;
private var _visibility : VisibilityController;
private var _frame : uint;
private var _cloned : Signal;
private var _materialChanged : Signal;
private var _frameChanged : Signal;
private var _geometryChanged : Signal;
/**
* A DataProvider object already bound to the Mesh bindings.
*
* <pre>
* // set the "diffuseColor" property to 0x0000ffff
* mesh.properties.diffuseColor = 0x0000ffff;
*
* // animate the "diffuseColor" property
* mesh.addController(
* new AnimationController(
* new <ITimeline>[new ColorTimeline(
* "dataProvider.diffuseColor",
* 5000,
* new <uint>[0xffffffff, 0xffffff00, 0xffffffff]
* )]
* )
* );
* </pre>
*
* @return
*
*/
public function get properties() : DataProvider
{
return _properties;
}
public function set properties(value : DataProvider) : void
{
if (_properties != value)
{
if (_properties)
_bindings.removeProvider(_properties);
_properties = value;
if (value)
_bindings.addProvider(value);
}
}
public function get material() : Material
{
return _material;
}
public function set material(value : Material) : void
{
if (_material != value)
{
if (_material)
_bindings.removeProvider(_material);
var oldMaterial : Material = _material;
_material = value;
if (value)
_bindings.addProvider(value);
_materialChanged.execute(this, oldMaterial, value);
}
}
/**
* The rendering properties provided to the shaders to customize
* how the mesh will appear on screen.
*
* @return
*
*/
public function get bindings() : DataBindings
{
return _bindings;
}
/**
* The Geometry of the mesh.
* @return
*
*/
public function get geometry() : Geometry
{
return _geometry;
}
public function set geometry(value : Geometry) : void
{
if (_geometry != value)
{
var oldGeometry : Geometry = _geometry;
if (oldGeometry)
oldGeometry.changed.remove(geometryChangedHandler);
_geometry = value;
if (value)
_geometry.changed.add(geometryChangedHandler);
_geometryChanged.execute(this, oldGeometry, value);
}
}
/**
* Whether the mesh is visible or not.
*
* @return
*
*/
public function get visible() : Boolean
{
return _visibility.visible;
}
public function set visible(value : Boolean) : void
{
_visibility.visible = value;
}
public function get frustumCulling() : uint
{
return _visibility.frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
_visibility.frustumCulling = value;
}
public function get cloned() : Signal
{
return _cloned;
}
public function get materialChanged() : Signal
{
return _materialChanged;
}
public function get frameChanged() : Signal
{
return _frameChanged;
}
public function get geometryChanged() : Signal
{
return _geometryChanged;
}
public function get frame() : uint
{
return _frame;
}
public function set frame(value : uint) : void
{
if (_frame != value)
{
var oldFrame : uint = _frame;
_frame = value;
_frameChanged.execute(this, oldFrame, value);
}
}
public function Mesh(geometry : Geometry = null,
material : Material = null,
name : String = null)
{
super();
initialize(geometry, material, name);
}
private function initialize(geometry : Geometry,
material : Material,
name : String) : void
{
if (name)
this.name = name;
_cloned = new Signal('Mesh.clones');
_materialChanged = new Signal('Mesh.materialChanged');
_frameChanged = new Signal('Mesh.frameChanged');
_geometryChanged = new Signal('Mesh.geometryChanged');
_bindings = new DataBindings(this);
this.properties = new DataProvider(properties, 'meshProperties', DataProviderUsage.EXCLUSIVE);
this.geometry = geometry;
this.material = material || DEFAULT_MATERIAL;
_visibility = new VisibilityController();
_visibility.frustumCulling = FrustumCulling.ENABLED;
addController(_visibility);
}
public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY) : Number
{
return _geometry.boundingBox.testRay(
ray,
worldToLocal,
maxDistance
);
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var clone : Mesh = new Mesh();
clone.name = name;
clone.geometry = _geometry;
clone.properties = DataProvider(_properties.clone());
clone._bindings.copySharedProvidersFrom(_bindings);
clone.transform.copyFrom(transform);
clone.material = _material;
this.cloned.execute(this, clone);
return clone;
}
private function geometryChangedHandler(geometry : Geometry) : void
{
_geometryChanged.execute(this, _geometry, _geometry);
}
}
}
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.material.Material;
import aerys.minko.render.material.basic.BasicMaterial;
import aerys.minko.scene.controller.mesh.VisibilityController;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.enum.FrustumCulling;
import aerys.minko.type.math.Ray;
use namespace minko_scene;
/**
* Mesh objects are a visible instance of a Geometry rendered using a specific
* Effect with specific rendering properties.
*
* <p>
* Those rendering properties are stored in a DataBindings object so they can
* be directly used by the shaders in the rendering API.
* </p>
*
* @author Jean-Marc Le Roux
*
*/
public class Mesh extends AbstractSceneNode
{
public static const DEFAULT_MATERIAL : Material = new BasicMaterial();
private var _geometry : Geometry;
private var _properties : DataProvider;
private var _material : Material;
private var _bindings : DataBindings;
private var _visibility : VisibilityController;
private var _frame : uint;
private var _cloned : Signal;
private var _materialChanged : Signal;
private var _frameChanged : Signal;
private var _geometryChanged : Signal;
/**
* A DataProvider object already bound to the Mesh bindings.
*
* <pre>
* // set the "diffuseColor" property to 0x0000ffff
* mesh.properties.diffuseColor = 0x0000ffff;
*
* // animate the "diffuseColor" property
* mesh.addController(
* new AnimationController(
* new <ITimeline>[new ColorTimeline(
* "dataProvider.diffuseColor",
* 5000,
* new <uint>[0xffffffff, 0xffffff00, 0xffffffff]
* )]
* )
* );
* </pre>
*
* @return
*
*/
public function get properties() : DataProvider
{
return _properties;
}
public function set properties(value : DataProvider) : void
{
if (_properties != value)
{
if (_properties)
_bindings.removeProvider(_properties);
_properties = value;
if (value)
_bindings.addProvider(value);
}
}
public function get material() : Material
{
return _material;
}
public function set material(value : Material) : void
{
if (_material != value)
{
if (_material)
_bindings.removeProvider(_material);
var oldMaterial : Material = _material;
_material = value;
if (value)
_bindings.addProvider(value);
_materialChanged.execute(this, oldMaterial, value);
}
}
/**
* The rendering properties provided to the shaders to customize
* how the mesh will appear on screen.
*
* @return
*
*/
public function get bindings() : DataBindings
{
return _bindings;
}
/**
* The Geometry of the mesh.
* @return
*
*/
public function get geometry() : Geometry
{
return _geometry;
}
public function set geometry(value : Geometry) : void
{
if (_geometry != value)
{
var oldGeometry : Geometry = _geometry;
if (oldGeometry)
oldGeometry.changed.remove(geometryChangedHandler);
_geometry = value;
if (value)
_geometry.changed.add(geometryChangedHandler);
_geometryChanged.execute(this, oldGeometry, value);
}
}
/**
* Whether the mesh is visible or not.
*
* @return
*
*/
public function get visible() : Boolean
{
return _visibility.visible;
}
public function set visible(value : Boolean) : void
{
_visibility.visible = value;
}
/**
* Whether the mesh in inside the camera frustum or not.
* @return
*
*/
public function get insideFrustum() : Boolean
{
return _visibility.insideFrustum;
}
public function get computedVisibility() : Boolean
{
return _visibility.computedVisibility;
}
public function get frustumCulling() : uint
{
return _visibility.frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
_visibility.frustumCulling = value;
}
public function get cloned() : Signal
{
return _cloned;
}
public function get materialChanged() : Signal
{
return _materialChanged;
}
public function get frameChanged() : Signal
{
return _frameChanged;
}
public function get geometryChanged() : Signal
{
return _geometryChanged;
}
public function get frame() : uint
{
return _frame;
}
public function set frame(value : uint) : void
{
if (_frame != value)
{
var oldFrame : uint = _frame;
_frame = value;
_frameChanged.execute(this, oldFrame, value);
}
}
public function Mesh(geometry : Geometry = null,
material : Material = null,
name : String = null)
{
super();
initialize(geometry, material, name);
}
private function initialize(geometry : Geometry,
material : Material,
name : String) : void
{
if (name)
this.name = name;
_cloned = new Signal('Mesh.clones');
_materialChanged = new Signal('Mesh.materialChanged');
_frameChanged = new Signal('Mesh.frameChanged');
_geometryChanged = new Signal('Mesh.geometryChanged');
_bindings = new DataBindings(this);
this.properties = new DataProvider(properties, 'meshProperties', DataProviderUsage.EXCLUSIVE);
this.geometry = geometry;
this.material = material || DEFAULT_MATERIAL;
_visibility = new VisibilityController();
_visibility.frustumCulling = FrustumCulling.ENABLED;
addController(_visibility);
}
public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY) : Number
{
return _geometry.boundingBox.testRay(
ray,
worldToLocal,
maxDistance
);
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var clone : Mesh = new Mesh();
clone.name = name;
clone.geometry = _geometry;
clone.properties = DataProvider(_properties.clone());
clone._bindings.copySharedProvidersFrom(_bindings);
clone.transform.copyFrom(transform);
clone.material = _material;
this.cloned.execute(this, clone);
return clone;
}
private function geometryChangedHandler(geometry : Geometry) : void
{
_geometryChanged.execute(this, _geometry, _geometry);
}
}
}
|
add Mesh.insideFrustum and Mesh.computedVisibility properties
|
add Mesh.insideFrustum and Mesh.computedVisibility properties
|
ActionScript
|
mit
|
aerys/minko-as3
|
fefdf6ac27345a9ab58314d08f329f267d5b8689
|
ShopbeamWidget.as
|
ShopbeamWidget.as
|
package {
import flash.system.*;
import flash.net.*;
import flash.external.*;
import flash.display.*;
import flash.events.*;
import fl.transitions.easing.*;
import fl.transitions.Tween;
import flash.globalization.CurrencyFormatter;
public class ShopbeamWidget extends MovieClip {
public function ShopbeamWidget() {
brandName.alpha = 0;
productName.alpha = 0;
listPrice.alpha = 0;
salePrice.alpha = 0;
var SHOP_HERE_TWEEN_X: int = 180;
var SHOP_HERE_INITIAL_X: int = hoverMovie.x;
var bagActive: Sprite = hoverMovie.bagActive;
var bagInactive: Sprite = hoverMovie.bagInactive;
function tweenTo(object: DisplayObject, property: String, value: *, duration: int = 30, durationInSeconds: Boolean = false): Tween {
return new Tween(object, property, Strong.easeOut, object[property], value, 30);
}
function tweenAlpha(object: DisplayObject, opacity: Number, duration: int = 30, durationInSeconds: Boolean = false): Tween {
return tweenTo(object, 'alpha', opacity, duration, durationInSeconds);
}
function fadeIn(object: DisplayObject, duration: int = 30, durationInSeconds: Boolean = false): void {
tweenAlpha(object, 1, duration, durationInSeconds)
}
function fadeOut(object: DisplayObject, duration: int = 30, durationInSeconds: Boolean = false): void {
tweenAlpha(object, 0, duration, durationInSeconds)
}
hoverArea.addEventListener(MouseEvent.MOUSE_OVER, function(event:MouseEvent):void {
fadeIn(listPrice);
if (listPrice.text !== salePrice.text) {
fadeIn(strikeThrough);
fadeIn(salePrice);
}
fadeIn(brandName);
fadeIn(productName);
fadeIn(bagActive);
fadeOut(bagInactive);
tweenAlpha(backdrop, 0.6);
tweenTo(hoverMovie, 'x', SHOP_HERE_TWEEN_X);
});
hoverArea.addEventListener(MouseEvent.MOUSE_OUT, function(event:MouseEvent):void {
fadeOut(salePrice);
fadeOut(listPrice);
fadeOut(strikeThrough);
fadeOut(brandName);
fadeOut(productName);
fadeOut(bagActive);
fadeIn(bagInactive);
fadeOut(backdrop);
tweenTo(hoverMovie, 'x', SHOP_HERE_INITIAL_X);
});
function log(): void {
ExternalInterface.call('console.log', arguments.join(' '));
}
function logError(): void {
ExternalInterface.call('console.error', arguments.join(' '));
}
function executeJS(js): void {
var wrapped = 'try {\n' + js + '\n}catch(err){console.error(err);console.error(err.stack);}';
ExternalInterface.call('eval', wrapped);
}
Security.allowDomain('*');
var widgetUuid: String = stage.loaderInfo.parameters.widgetUuid;
var loader: Loader = new Loader();
var widgetData: Object;
ExternalInterface.addCallback('setWidgetData', function setWidgetData(data: String): void {
widgetData = JSON.parse(data);
brandName.text = widgetData.initialProduct.brandName;
productName.text = widgetData.initialProduct.name;
var dollarFormatter: CurrencyFormatter = new CurrencyFormatter('usd');
listPrice.text = dollarFormatter.format((widgetData.initialVariant.listPrice / 100), true);
//strikeThrough.width ...
salePrice.text = dollarFormatter.format((widgetData.initialVariant.salePrice / 100), true);
});
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
var button: Sprite = new Sprite();
button.addChild(loader);
//required for `.useHandCursor` to work
hoverArea.buttonMode = true;
hoverArea.useHandCursor = true;
addChild(button);
setChildIndex(button, 0);
function loadingError(e: IOErrorEvent): void {
logError('widget with id: ' + widgetUuid + ' failed to load image');
}
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loadingError);
function doneLoad(e: Event): void {
loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, doneLoad);
loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, loadingError);
}
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, doneLoad);
function loaderClickHandler(e: Event): void {
log('widgetOpenLightbox' + widgetUuid);
executeJS("Shopbeam.swfOpenLightbox('" + widgetUuid + "')");
}
hoverArea.addEventListener(MouseEvent.CLICK, loaderClickHandler);
log('loading image: ' + stage.loaderInfo.parameters.imageUrl);
loader.load(new URLRequest(stage.loaderInfo.parameters.imageUrl));
}
}
}
|
package {
import flash.system.*;
import flash.net.*;
import flash.external.*;
import flash.display.*;
import flash.events.*;
import fl.transitions.easing.*;
import fl.transitions.Tween;
import flash.globalization.CurrencyFormatter;
public class ShopbeamWidget extends MovieClip {
public function ShopbeamWidget() {
brandName.alpha = 0;
productName.alpha = 0;
listPrice.alpha = 0;
salePrice.alpha = 0;
var SHOP_HERE_TWEEN_X:int = 180;
var SHOP_HERE_INITIAL_X:int = hoverMovie.x;
var bagActive:Sprite = hoverMovie.bagActive;
var bagInactive:Sprite = hoverMovie.bagInactive;
function tweenTo(object:DisplayObject, property:String, value:*, duration:int = 30, durationInSeconds:Boolean = false):Tween {
return new Tween(object, property, Strong.easeOut, object[property], value, 30);
}
function tweenAlpha(object:DisplayObject, opacity:Number, duration:int = 30, durationInSeconds:Boolean = false):Tween {
return tweenTo(object, 'alpha', opacity, duration, durationInSeconds);
}
function fadeIn(object:DisplayObject, duration:int = 30, durationInSeconds:Boolean = false):void {
tweenAlpha(object, 1, duration, durationInSeconds)
}
function fadeOut(object:DisplayObject, duration:int = 30, durationInSeconds:Boolean = false):void {
tweenAlpha(object, 0, duration, durationInSeconds)
}
hoverArea.addEventListener(MouseEvent.MOUSE_OVER, function(event:MouseEvent):void {
fadeIn(listPrice);
if (listPrice.text !== salePrice.text) {
fadeIn(strikeThrough);
fadeIn(salePrice);
}
fadeIn(brandName);
fadeIn(productName);
fadeIn(bagActive);
fadeOut(bagInactive);
tweenAlpha(backdrop, 0.6);
tweenTo(hoverMovie, 'x', SHOP_HERE_TWEEN_X);
});
hoverArea.addEventListener(MouseEvent.MOUSE_OUT, function(event:MouseEvent):void {
fadeOut(salePrice);
fadeOut(listPrice);
fadeOut(strikeThrough);
fadeOut(brandName);
fadeOut(productName);
fadeOut(bagActive);
fadeIn(bagInactive);
fadeOut(backdrop);
tweenTo(hoverMovie, 'x', SHOP_HERE_INITIAL_X);
});
function log():void {
ExternalInterface.call('console.log', arguments.join(' '));
}
function logError():void {
ExternalInterface.call('console.error', arguments.join(' '));
}
function executeJS(js):void {
var wrapped = 'try {\n' + js + '\n}catch(err){console.error(err);console.error(err.stack);}';
ExternalInterface.call('eval', wrapped);
}
Security.allowDomain('*');
var widgetUuid:String = stage.loaderInfo.parameters.widgetUuid;
var loader:Loader = new Loader();
var widgetData:Object;
ExternalInterface.addCallback('setWidgetData', function setWidgetData(data:String):void {
widgetData = JSON.parse(data);
brandName.text = widgetData.initialProduct.brandName;
productName.text = widgetData.initialProduct.name;
var dollarFormatter:CurrencyFormatter = new CurrencyFormatter('usd');
listPrice.text = dollarFormatter.format((widgetData.initialVariant.listPrice / 100), true);
//strikeThrough.width ...
salePrice.text = dollarFormatter.format((widgetData.initialVariant.salePrice / 100), true);
});
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
var button:Sprite = new Sprite();
button.addChild(loader);
//required for `.useHandCursor` to work
hoverArea.buttonMode = true;
hoverArea.useHandCursor = true;
addChild(button);
setChildIndex(button, 0);
function loadingError(e:IOErrorEvent):void {
logError('widget with id: ' + widgetUuid + ' failed to load image');
}
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loadingError);
function doneLoad(e:Event):void {
loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, doneLoad);
loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, loadingError);
}
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, doneLoad);
function loaderClickHandler(e:Event):void {
log('widgetOpenLightbox' + widgetUuid);
executeJS("Shopbeam.swfOpenLightbox('" + widgetUuid + "')");
}
hoverArea.addEventListener(MouseEvent.CLICK, loaderClickHandler);
log('loading image: ' + stage.loaderInfo.parameters.imageUrl);
loader.load(new URLRequest(stage.loaderInfo.parameters.imageUrl));
}
}
}
|
apply webstorm code formatting
|
apply webstorm code formatting
|
ActionScript
|
mit
|
shopbeam/flash-widget-example
|
acee7a5f586a1a0691d3b1b5bdb753148564c8eb
|
src/aerys/minko/type/MouseManager.as
|
src/aerys/minko/type/MouseManager.as
|
package aerys.minko.type
{
import flash.events.IEventDispatcher;
import flash.events.MouseEvent;
import flash.ui.Mouse;
public final class MouseManager
{
private var _x : Number = 0.;
private var _y : Number = 0.;
private var _deltaX : Number = 0.;
private var _deltaY : Number = 0.;
private var _deltaDistance : Number = 0.;
private var _leftButtonDown : Boolean = false;
private var _middleButtonDown : Boolean = false;
private var _rightButtonDown : Boolean = false;
private var _mouseDown : Signal = new Signal("mouseDown");
private var _mouseUp : Signal = new Signal("mouseUp");
private var _cursors : Vector.<String> = new <String>[];
public function get x() : Number
{
return _x;
}
public function get y() : Number
{
return _y;
}
public function get deltaX() : Number
{
return _deltaX;
}
public function get deltaY() : Number
{
return _deltaY;
}
public function get deltaDistance() : Number
{
return _deltaDistance;
}
public function get leftButtonDown() : Boolean
{
return _leftButtonDown;
}
public function get middleButtonDown() : Boolean
{
return _middleButtonDown;
}
public function get rightButtonDown() : Boolean
{
return _rightButtonDown;
}
public function get cursor() : String
{
return Mouse.cursor;
}
public function get mouseDown() : Signal
{
return _mouseDown;
}
public function get mouseUp() : Signal
{
return _mouseUp;
}
public function bind(dispatcher : IEventDispatcher) : void
{
dispatcher.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
dispatcher.addEventListener(MouseEvent.MOUSE_DOWN, mouseLeftDownHandler);
dispatcher.addEventListener(MouseEvent.MOUSE_UP, mouseLeftUpHandler);
if (MouseEvent.RIGHT_CLICK != null)
{
dispatcher.addEventListener(MouseEvent.RIGHT_MOUSE_DOWN, mouseRightDownHandler);
dispatcher.addEventListener(MouseEvent.RIGHT_MOUSE_UP, mouseRightUpHandler);
}
if (MouseEvent.MIDDLE_CLICK != null)
{
dispatcher.addEventListener(MouseEvent.MIDDLE_MOUSE_DOWN, mouseMiddleDownHandler);
dispatcher.addEventListener(MouseEvent.MIDDLE_MOUSE_UP, mouseMiddleUpHandler);
}
}
public function unbind(dispatcher : IEventDispatcher) : void
{
dispatcher.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
dispatcher.removeEventListener(MouseEvent.MOUSE_DOWN, mouseLeftDownHandler);
dispatcher.removeEventListener(MouseEvent.MOUSE_UP, mouseLeftUpHandler);
if (MouseEvent.RIGHT_CLICK != null)
{
dispatcher.removeEventListener(MouseEvent.RIGHT_MOUSE_DOWN, mouseRightDownHandler);
dispatcher.removeEventListener(MouseEvent.RIGHT_MOUSE_UP, mouseRightUpHandler);
}
if (MouseEvent.MIDDLE_CLICK != null)
{
dispatcher.removeEventListener(MouseEvent.MIDDLE_MOUSE_DOWN, mouseMiddleDownHandler);
dispatcher.removeEventListener(MouseEvent.MIDDLE_MOUSE_UP, mouseMiddleUpHandler);
}
}
private function mouseMoveHandler(event : MouseEvent) : void
{
var localX : Number = event.localX;
var localY : Number = event.localY;
_deltaX = localX - _x;
_deltaY = localY - _y;
_deltaDistance = Math.sqrt(_deltaX * deltaX + deltaY * deltaY);
_x = event.localX;
_y = event.localY;
}
private function mouseLeftDownHandler(event : MouseEvent) : void
{
_leftButtonDown = true;
_mouseDown.execute();
}
private function mouseLeftUpHandler(event : MouseEvent) : void
{
_leftButtonDown = false;
_mouseUp.execute();
}
private function mouseMiddleDownHandler(event : MouseEvent) : void
{
_rightButtonDown = true;
}
private function mouseMiddleUpHandler(event : MouseEvent) : void
{
_rightButtonDown = false;
}
private function mouseRightDownHandler(event : MouseEvent) : void
{
_rightButtonDown = true;
}
private function mouseRightUpHandler(event : MouseEvent) : void
{
_rightButtonDown = false;
}
public function pushCursor(cursor : String) : MouseManager
{
_cursors.push(Mouse.cursor);
Mouse.cursor = cursor;
return this;
}
public function popCursor() : MouseManager
{
Mouse.cursor = _cursors.pop();
return this;
}
}
}
|
package aerys.minko.type
{
import flash.events.IEventDispatcher;
import flash.events.MouseEvent;
import flash.ui.Mouse;
public final class MouseManager
{
private var _x : Number = 0.;
private var _y : Number = 0.;
private var _deltaX : Number = 0.;
private var _deltaY : Number = 0.;
private var _deltaDistance : Number = 0.;
private var _leftButtonDown : Boolean = false;
private var _middleButtonDown : Boolean = false;
private var _rightButtonDown : Boolean = false;
private var _mouseDown : Signal = new Signal("mouseDown");
private var _mouseUp : Signal = new Signal("mouseUp");
private var _cursors : Vector.<String> = new <String>[];
public function get x() : Number
{
return _x;
}
public function get y() : Number
{
return _y;
}
public function get deltaX() : Number
{
return _deltaX;
}
public function get deltaY() : Number
{
return _deltaY;
}
public function get deltaDistance() : Number
{
return _deltaDistance;
}
public function get leftButtonDown() : Boolean
{
return _leftButtonDown;
}
public function get middleButtonDown() : Boolean
{
return _middleButtonDown;
}
public function get rightButtonDown() : Boolean
{
return _rightButtonDown;
}
public function get cursor() : String
{
return Mouse.cursor;
}
public function get mouseDown() : Signal
{
return _mouseDown;
}
public function get mouseUp() : Signal
{
return _mouseUp;
}
public function bind(dispatcher : IEventDispatcher) : void
{
dispatcher.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
dispatcher.addEventListener(MouseEvent.MOUSE_DOWN, mouseLeftDownHandler);
dispatcher.addEventListener(MouseEvent.MOUSE_UP, mouseLeftUpHandler);
if (MouseEvent.RIGHT_CLICK != null)
{
dispatcher.addEventListener(MouseEvent.RIGHT_MOUSE_DOWN, mouseRightDownHandler);
dispatcher.addEventListener(MouseEvent.RIGHT_MOUSE_UP, mouseRightUpHandler);
}
if (MouseEvent.MIDDLE_CLICK != null)
{
dispatcher.addEventListener(MouseEvent.MIDDLE_MOUSE_DOWN, mouseMiddleDownHandler);
dispatcher.addEventListener(MouseEvent.MIDDLE_MOUSE_UP, mouseMiddleUpHandler);
}
}
public function unbind(dispatcher : IEventDispatcher) : void
{
dispatcher.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
dispatcher.removeEventListener(MouseEvent.MOUSE_DOWN, mouseLeftDownHandler);
dispatcher.removeEventListener(MouseEvent.MOUSE_UP, mouseLeftUpHandler);
if (MouseEvent.RIGHT_CLICK != null)
{
dispatcher.removeEventListener(MouseEvent.RIGHT_MOUSE_DOWN, mouseRightDownHandler);
dispatcher.removeEventListener(MouseEvent.RIGHT_MOUSE_UP, mouseRightUpHandler);
}
if (MouseEvent.MIDDLE_CLICK != null)
{
dispatcher.removeEventListener(MouseEvent.MIDDLE_MOUSE_DOWN, mouseMiddleDownHandler);
dispatcher.removeEventListener(MouseEvent.MIDDLE_MOUSE_UP, mouseMiddleUpHandler);
}
}
private function mouseMoveHandler(event : MouseEvent) : void
{
var localX : Number = event.localX;
var localY : Number = event.localY;
_deltaX = localX - _x;
_deltaY = localY - _y;
_deltaDistance = Math.sqrt(_deltaX * deltaX + deltaY * deltaY);
_x = event.localX;
_y = event.localY;
}
private function mouseLeftDownHandler(event : MouseEvent) : void
{
_leftButtonDown = true;
_mouseDown.execute();
}
private function mouseLeftUpHandler(event : MouseEvent) : void
{
_leftButtonDown = false;
_mouseUp.execute();
}
private function mouseMiddleDownHandler(event : MouseEvent) : void
{
_middleButtonDown = true;
}
private function mouseMiddleUpHandler(event : MouseEvent) : void
{
_middleButtonDown = false;
}
private function mouseRightDownHandler(event : MouseEvent) : void
{
_rightButtonDown = true;
}
private function mouseRightUpHandler(event : MouseEvent) : void
{
_rightButtonDown = false;
}
public function pushCursor(cursor : String) : MouseManager
{
_cursors.push(Mouse.cursor);
Mouse.cursor = cursor;
return this;
}
public function popCursor() : MouseManager
{
Mouse.cursor = _cursors.pop();
return this;
}
}
}
|
Update src/aerys/minko/type/MouseManager.as
|
Update src/aerys/minko/type/MouseManager.as
Fixed bug in middle mouse button handler.
|
ActionScript
|
mit
|
aerys/minko-as3
|
7ad43b222beddda6f169bb2ffca64977a9b6141d
|
src/goplayer/ConfigurationParser.as
|
src/goplayer/ConfigurationParser.as
|
package goplayer
{
public class ConfigurationParser
{
public static const DEFAULT_API_URL : String
= "http://staging.streamio.com/api"
public static const DEFAULT_SKIN_URL : String = "goplayer-skin.swf"
public static const DEFAULT_TRACKER_ID : String = "global"
public static const VALID_PARAMETERS : Array = [
"api", "tracker", "skin", "video", "bitrate",
"enablertmp", "autoplay", "loop",
"skin:showchrome", "skin:showtitle" ]
private const result : Configuration = new Configuration
private var parameters : Object
private var originalParameterNames : Object
public function ConfigurationParser
(parameters : Object, originalParameterNames : Object)
{
this.parameters = parameters
this.originalParameterNames = originalParameterNames
}
public function execute() : void
{
result.apiURL = getString("api", DEFAULT_API_URL)
result.trackerID = getString("tracker", DEFAULT_TRACKER_ID)
result.skinURL = getString("skin", DEFAULT_SKIN_URL)
result.movieID = getString("video", null)
result.bitratePolicy = getBitratePolicy("bitrate", BitratePolicy.BEST)
result.enableRTMP = getBoolean("enablertmp", true)
result.enableAutoplay = getBoolean("autoplay", false)
result.enableLooping = getBoolean("loop", false)
result.enableChrome = getBoolean("skin:showchrome", true)
result.enableTitle = getBoolean("skin:showtitle", true)
}
public static function parse(parameters : Object) : Configuration
{
const normalizedParameters : Object = {}
const originalParameterNames : Object = {}
for (var name : String in parameters)
if (VALID_PARAMETERS.indexOf(normalize(name)) == -1)
reportUnknownParameter(name)
else
normalizedParameters[normalize(name)] = parameters[name],
originalParameterNames[normalize(name)] = name
const parser : ConfigurationParser = new ConfigurationParser
(normalizedParameters, originalParameterNames)
parser.execute()
return parser.result
}
private static function normalize(name : String) : String
{ return name.toLowerCase().replace(/[^a-z:]/g, "") }
private static function reportUnknownParameter(name : String) : void
{ debug("Error: Unknown parameter: " + name) }
// -----------------------------------------------------
private function getString(name : String, fallback : String) : String
{ return name in parameters ? parameters[name] : fallback }
private function getBoolean
(name : String, fallback : Boolean) : Boolean
{
if (name in parameters)
return $getBoolean(name, parameters[name], fallback)
else
return fallback
}
private function $getBoolean
(name : String, value : String, fallback : Boolean) : Boolean
{
try
{ return $$getBoolean(value) }
catch (error : Error)
{
reportInvalidParameter(name, value, ["true", "false"])
return fallback
}
throw new Error
}
private function $$getBoolean(value : String) : Boolean
{
if (value == "true")
return true
else if (value == "false")
return false
else
throw new Error
}
// -----------------------------------------------------
private function getBitratePolicy
(name : String, fallback : BitratePolicy) : BitratePolicy
{
if (name in parameters)
return $getBitratePolicy(name, parameters[name], fallback)
else
return fallback
}
private function $getBitratePolicy
(name : String, value : String,
fallback : BitratePolicy) : BitratePolicy
{
try
{ return $$getBitratePolicy(value) }
catch (error : Error)
{
reportInvalidParameter(name, value, BITRATE_POLICY_VALUES)
return fallback
}
throw new Error
}
private const BITRATE_POLICY_VALUES : Array =
["<number>kbps", "min", "max", "best"]
private function $$getBitratePolicy(value : String) : BitratePolicy
{
if (value == "max")
return BitratePolicy.MAX
else if (value == "min")
return BitratePolicy.MIN
else if (value == "best")
return BitratePolicy.BEST
else if (Bitrate.parse(value))
return BitratePolicy.specific(Bitrate.parse(value))
else
throw new Error
}
// -----------------------------------------------------
private function reportInvalidParameter
(name : String, value : String, validValues : Array) : void
{
debug("Error: Invalid parameter: " +
"“" + originalParameterNames[name] + "=" + value + "”; " +
getInvalidParameterHint(validValues) + ".")
}
private function getInvalidParameterHint(values : Array) : String
{ return $getInvalidParameterHint(getQuotedValues(values)) }
private function $getInvalidParameterHint(values : Array) : String
{
return "please use " +
"either " + values.slice(0, -1).join(", ") + " " +
"or " + values[values.length - 1]
}
private function getQuotedValues(values : Array) : Array
{
var result : Array = []
for each (var value : String in values)
result.push("“" + value + "”")
return result
}
}
}
|
package goplayer
{
public class ConfigurationParser
{
public static const DEFAULT_STREAMIO_API_URL : String
= "http://staging.streamio.com/api"
public static const DEFAULT_SKIN_URL : String = "goplayer-skin.swf"
public static const DEFAULT_TRACKER_ID : String = "global"
public static const VALID_PARAMETERS : Array = [
"streamio:api", "tracker", "skin", "video", "bitrate",
"enablertmp", "autoplay", "loop",
"skin:showchrome", "skin:showtitle" ]
private const result : Configuration = new Configuration
private var parameters : Object
private var originalParameterNames : Object
public function ConfigurationParser
(parameters : Object, originalParameterNames : Object)
{
this.parameters = parameters
this.originalParameterNames = originalParameterNames
}
public function execute() : void
{
result.apiURL = getString("streamio:api", DEFAULT_STREAMIO_API_URL)
result.trackerID = getString("tracker", DEFAULT_TRACKER_ID)
result.skinURL = getString("skin", DEFAULT_SKIN_URL)
result.movieID = getString("video", null)
result.bitratePolicy = getBitratePolicy("bitrate", BitratePolicy.BEST)
result.enableRTMP = getBoolean("enablertmp", true)
result.enableAutoplay = getBoolean("autoplay", false)
result.enableLooping = getBoolean("loop", false)
result.enableChrome = getBoolean("skin:showchrome", true)
result.enableTitle = getBoolean("skin:showtitle", true)
}
public static function parse(parameters : Object) : Configuration
{
const normalizedParameters : Object = {}
const originalParameterNames : Object = {}
for (var name : String in parameters)
if (VALID_PARAMETERS.indexOf(normalize(name)) == -1)
reportUnknownParameter(name)
else
normalizedParameters[normalize(name)] = parameters[name],
originalParameterNames[normalize(name)] = name
const parser : ConfigurationParser = new ConfigurationParser
(normalizedParameters, originalParameterNames)
parser.execute()
return parser.result
}
private static function normalize(name : String) : String
{ return name.toLowerCase().replace(/[^a-z:]/g, "") }
private static function reportUnknownParameter(name : String) : void
{ debug("Error: Unknown parameter: " + name) }
// -----------------------------------------------------
private function getString(name : String, fallback : String) : String
{ return name in parameters ? parameters[name] : fallback }
private function getBoolean
(name : String, fallback : Boolean) : Boolean
{
if (name in parameters)
return $getBoolean(name, parameters[name], fallback)
else
return fallback
}
private function $getBoolean
(name : String, value : String, fallback : Boolean) : Boolean
{
try
{ return $$getBoolean(value) }
catch (error : Error)
{
reportInvalidParameter(name, value, ["true", "false"])
return fallback
}
throw new Error
}
private function $$getBoolean(value : String) : Boolean
{
if (value == "true")
return true
else if (value == "false")
return false
else
throw new Error
}
// -----------------------------------------------------
private function getBitratePolicy
(name : String, fallback : BitratePolicy) : BitratePolicy
{
if (name in parameters)
return $getBitratePolicy(name, parameters[name], fallback)
else
return fallback
}
private function $getBitratePolicy
(name : String, value : String,
fallback : BitratePolicy) : BitratePolicy
{
try
{ return $$getBitratePolicy(value) }
catch (error : Error)
{
reportInvalidParameter(name, value, BITRATE_POLICY_VALUES)
return fallback
}
throw new Error
}
private const BITRATE_POLICY_VALUES : Array =
["<number>kbps", "min", "max", "best"]
private function $$getBitratePolicy(value : String) : BitratePolicy
{
if (value == "max")
return BitratePolicy.MAX
else if (value == "min")
return BitratePolicy.MIN
else if (value == "best")
return BitratePolicy.BEST
else if (Bitrate.parse(value))
return BitratePolicy.specific(Bitrate.parse(value))
else
throw new Error
}
// -----------------------------------------------------
private function reportInvalidParameter
(name : String, value : String, validValues : Array) : void
{
debug("Error: Invalid parameter: " +
"“" + originalParameterNames[name] + "=" + value + "”; " +
getInvalidParameterHint(validValues) + ".")
}
private function getInvalidParameterHint(values : Array) : String
{ return $getInvalidParameterHint(getQuotedValues(values)) }
private function $getInvalidParameterHint(values : Array) : String
{
return "please use " +
"either " + values.slice(0, -1).join(", ") + " " +
"or " + values[values.length - 1]
}
private function getQuotedValues(values : Array) : Array
{
var result : Array = []
for each (var value : String in values)
result.push("“" + value + "”")
return result
}
}
}
|
Rename `api' parameter to `streamio:api'.
|
Rename `api' parameter to `streamio:api'.
|
ActionScript
|
mit
|
dbrock/goplayer,dbrock/goplayer
|
a515574d2ddb9e061e7f32650999ed7472ec17f1
|
swfcat.as
|
swfcat.as
|
package
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.net.Socket;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.utils.ByteArray;
import flash.utils.setTimeout;
public class swfcat extends Sprite
{
/* David's relay (nickname 3VXRyxz67OeRoqHn) that also serves a
crossdomain policy. */
private const DEFAULT_TOR_ADDR:Object = {
host: "173.255.221.44",
port: 9001
};
// Milliseconds.
private const FACILITATOR_POLL_INTERVAL:int = 1000;
// Socket to facilitator.
private var s_f:Socket;
private var output_text:TextField;
private var fac_addr:Object;
public function puts(s:String):void
{
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
public function swfcat()
{
output_text = new TextField();
output_text.width = 400;
output_text.height = 300;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44CC44;
addChild(output_text);
puts("Starting.");
// Wait until the query string parameters are loaded.
this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
}
private function loaderinfo_complete(e:Event):void
{
var fac_spec:String;
puts("Parameters loaded.");
fac_spec = this.loaderInfo.parameters["facilitator"];
if (!fac_spec) {
puts("Error: no \"facilitator\" specification provided.");
return;
}
puts("Facilitator spec: \"" + fac_spec + "\"");
fac_addr = parse_addr_spec(fac_spec);
if (!fac_addr) {
puts("Error: Facilitator spec must be in the form \"host:port\".");
return;
}
main();
}
/* The main logic begins here, after start-up issues are taken care of. */
private function main():void
{
s_f = new Socket();
s_f.addEventListener(Event.CONNECT, fac_connected);
s_f.addEventListener(Event.CLOSE, function (e:Event):void {
puts("Facilitator: closed connection.");
});
s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
});
s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
});
puts("Facilitator: connecting to " + fac_addr.host + ":" + fac_addr.port + ".");
s_f.connect(fac_addr.host, fac_addr.port);
}
private function fac_connected(e:Event):void
{
puts("Facilitator: connected.");
s_f.addEventListener(ProgressEvent.SOCKET_DATA, fac_data);
s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n");
}
private function fac_data(e:ProgressEvent):void
{
var client_spec:String;
var client_addr:Object;
var proxy_pair:Object;
client_spec = s_f.readMultiByte(e.bytesLoaded, "utf-8");
puts("Facilitator: got \"" + client_spec + "\"");
client_addr = parse_addr_spec(client_spec);
if (!client_addr) {
puts("Error: Client spec must be in the form \"host:port\".");
setTimeout(main, FACILITATOR_POLL_INTERVAL);
return;
}
if (client_addr.host == "0.0.0.0" && client_addr.port == 0) {
puts("Error: Facilitator has no clients.");
setTimeout(main, FACILITATOR_POLL_INTERVAL);
return;
}
proxy_pair = new ProxyPair(this, client_addr, DEFAULT_TOR_ADDR);
proxy_pair.connect();
setTimeout(main, FACILITATOR_POLL_INTERVAL);
}
/* Parse an address in the form "host:port". Returns an Object with
keys "host" (String) and "port" (int). Returns null on error. */
private static function parse_addr_spec(spec:String):Object
{
var parts:Array;
var addr:Object;
parts = spec.split(":", 2);
if (parts.length != 2 || !parseInt(parts[1]))
return null;
addr = {}
addr.host = parts[0];
addr.port = parseInt(parts[1]);
return addr;
}
}
}
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
/* An instance of a client-relay connection. */
class ProxyPair
{
// Address ({host, port}) of client.
private var addr_c:Object;
// Address ({host, port}) of relay.
private var addr_r:Object;
// Socket to client.
private var s_c:Socket;
// Socket to relay.
private var s_r:Socket;
// Parent swfcat, for UI updates.
private var ui:swfcat;
private function log(msg:String):void
{
ui.puts(id() + ": " + msg)
}
// String describing this pair for output.
private function id():String
{
return "<" + this.addr_c.host + ":" + this.addr_c.port +
"," + this.addr_r.host + ":" + this.addr_r.port + ">";
}
public function ProxyPair(ui:swfcat, addr_c:Object, addr_r:Object)
{
this.ui = ui;
this.addr_c = addr_c;
this.addr_r = addr_r;
}
public function connect():void
{
s_r = new Socket();
s_r.addEventListener(Event.CONNECT, tor_connected);
s_r.addEventListener(Event.CLOSE, function (e:Event):void {
log("Tor: closed.");
if (s_c.connected)
s_c.close();
});
s_r.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Tor: I/O error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
s_r.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Tor: security error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
log("Tor: connecting to " + addr_r.host + ":" + addr_r.port + ".");
s_r.connect(addr_r.host, addr_r.port);
}
private function tor_connected(e:Event):void
{
log("Tor: connected.");
s_c = new Socket();
s_c.addEventListener(Event.CONNECT, client_connected);
s_c.addEventListener(Event.CLOSE, function (e:Event):void {
log("Client: closed.");
if (s_r.connected)
s_r.close();
});
s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Client: I/O error: " + e.text + ".");
if (s_r.connected)
s_r.close();
});
s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Client: security error: " + e.text + ".");
if (s_r.connected)
s_r.close();
});
log("Client: connecting to " + addr_c.host + ":" + addr_c.port + ".");
s_c.connect(addr_c.host, addr_c.port);
}
private function client_connected(e:Event):void
{
log("Client: connected.");
s_r.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_r.readBytes(bytes, 0, e.bytesLoaded);
log("Tor: read " + bytes.length + ".");
s_c.writeBytes(bytes);
});
s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_c.readBytes(bytes, 0, e.bytesLoaded);
log("Client: read " + bytes.length + ".");
s_r.writeBytes(bytes);
});
}
}
|
package
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.net.Socket;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.utils.ByteArray;
import flash.utils.setTimeout;
public class swfcat extends Sprite
{
/* David's relay (nickname 3VXRyxz67OeRoqHn) that also serves a
crossdomain policy. */
private const DEFAULT_TOR_ADDR:Object = {
host: "173.255.221.44",
port: 9001
};
// Milliseconds.
private const FACILITATOR_POLL_INTERVAL:int = 1000;
// Socket to facilitator.
private var s_f:Socket;
private var output_text:TextField;
private var fac_addr:Object;
public function puts(s:String):void
{
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
public function swfcat()
{
output_text = new TextField();
output_text.width = 400;
output_text.height = 300;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44CC44;
addChild(output_text);
puts("Starting.");
// Wait until the query string parameters are loaded.
this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
}
private function loaderinfo_complete(e:Event):void
{
var fac_spec:String;
puts("Parameters loaded.");
fac_spec = this.loaderInfo.parameters["facilitator"];
if (!fac_spec) {
puts("Error: no \"facilitator\" specification provided.");
return;
}
puts("Facilitator spec: \"" + fac_spec + "\"");
fac_addr = parse_addr_spec(fac_spec);
if (!fac_addr) {
puts("Error: Facilitator spec must be in the form \"host:port\".");
return;
}
main();
}
/* The main logic begins here, after start-up issues are taken care of. */
private function main():void
{
s_f = new Socket();
s_f.addEventListener(Event.CONNECT, fac_connected);
s_f.addEventListener(Event.CLOSE, function (e:Event):void {
puts("Facilitator: closed connection.");
setTimeout(main, FACILITATOR_POLL_INTERVAL);
});
s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
});
s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
});
puts("Facilitator: connecting to " + fac_addr.host + ":" + fac_addr.port + ".");
s_f.connect(fac_addr.host, fac_addr.port);
}
private function fac_connected(e:Event):void
{
puts("Facilitator: connected.");
s_f.addEventListener(ProgressEvent.SOCKET_DATA, fac_data);
s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n");
}
private function fac_data(e:ProgressEvent):void
{
var client_spec:String;
var client_addr:Object;
var proxy_pair:Object;
client_spec = s_f.readMultiByte(e.bytesLoaded, "utf-8");
puts("Facilitator: got \"" + client_spec + "\"");
client_addr = parse_addr_spec(client_spec);
if (!client_addr) {
puts("Error: Client spec must be in the form \"host:port\".");
return;
}
if (client_addr.host == "0.0.0.0" && client_addr.port == 0) {
puts("Error: Facilitator has no clients.");
return;
}
proxy_pair = new ProxyPair(this, client_addr, DEFAULT_TOR_ADDR);
proxy_pair.connect();
}
/* Parse an address in the form "host:port". Returns an Object with
keys "host" (String) and "port" (int). Returns null on error. */
private static function parse_addr_spec(spec:String):Object
{
var parts:Array;
var addr:Object;
parts = spec.split(":", 2);
if (parts.length != 2 || !parseInt(parts[1]))
return null;
addr = {}
addr.host = parts[0];
addr.port = parseInt(parts[1]);
return addr;
}
}
}
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
/* An instance of a client-relay connection. */
class ProxyPair
{
// Address ({host, port}) of client.
private var addr_c:Object;
// Address ({host, port}) of relay.
private var addr_r:Object;
// Socket to client.
private var s_c:Socket;
// Socket to relay.
private var s_r:Socket;
// Parent swfcat, for UI updates.
private var ui:swfcat;
private function log(msg:String):void
{
ui.puts(id() + ": " + msg)
}
// String describing this pair for output.
private function id():String
{
return "<" + this.addr_c.host + ":" + this.addr_c.port +
"," + this.addr_r.host + ":" + this.addr_r.port + ">";
}
public function ProxyPair(ui:swfcat, addr_c:Object, addr_r:Object)
{
this.ui = ui;
this.addr_c = addr_c;
this.addr_r = addr_r;
}
public function connect():void
{
s_r = new Socket();
s_r.addEventListener(Event.CONNECT, tor_connected);
s_r.addEventListener(Event.CLOSE, function (e:Event):void {
log("Tor: closed.");
if (s_c.connected)
s_c.close();
});
s_r.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Tor: I/O error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
s_r.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Tor: security error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
log("Tor: connecting to " + addr_r.host + ":" + addr_r.port + ".");
s_r.connect(addr_r.host, addr_r.port);
}
private function tor_connected(e:Event):void
{
log("Tor: connected.");
s_c = new Socket();
s_c.addEventListener(Event.CONNECT, client_connected);
s_c.addEventListener(Event.CLOSE, function (e:Event):void {
log("Client: closed.");
if (s_r.connected)
s_r.close();
});
s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Client: I/O error: " + e.text + ".");
if (s_r.connected)
s_r.close();
});
s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Client: security error: " + e.text + ".");
if (s_r.connected)
s_r.close();
});
log("Client: connecting to " + addr_c.host + ":" + addr_c.port + ".");
s_c.connect(addr_c.host, addr_c.port);
}
private function client_connected(e:Event):void
{
log("Client: connected.");
s_r.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_r.readBytes(bytes, 0, e.bytesLoaded);
log("Tor: read " + bytes.length + ".");
s_c.writeBytes(bytes);
});
s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_c.readBytes(bytes, 0, e.bytesLoaded);
log("Client: read " + bytes.length + ".");
s_r.writeBytes(bytes);
});
}
}
|
Reschedule a facilitator connection upon close, not upon data read.
|
Reschedule a facilitator connection upon close, not upon data read.
|
ActionScript
|
mit
|
infinity0/flashproxy,infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,infinity0/flashproxy,glamrock/flashproxy,glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,glamrock/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,infinity0/flashproxy
|
6315f2931c58267c48c46e861addde40dc7ed3e3
|
source/com/kemsky/support/StreamError.as
|
source/com/kemsky/support/StreamError.as
|
/*
* Copyright: (c) 2015. Turtsevich Alexander
*
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.html
*/
package com.kemsky.support
{
/**
* Stream error class
*/
public class StreamError extends Error
{
/**
* @inheritDoc
*/
public function StreamError(message:String = null, errorID:int = 0)
{
super(message, errorID);
}
}
}
|
/*
* Copyright: (c) 2015. Turtsevich Alexander
*
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.html
*/
package com.kemsky.support
{
/**
* Stream error class
*/
public class StreamError extends Error
{
/**
* Constructor.
* @param message error description.
* @param errorID error number.
*/
public function StreamError(message:String = null, errorID:int = 0)
{
super(message, errorID);
}
}
}
|
clean up
|
clean up
|
ActionScript
|
mit
|
kemsky/stream
|
2fe5a1994c464ab2cabcc0ef2b46bdb3a9616749
|
WeaveUI/src/weave/menus/ExportMenu.as
|
WeaveUI/src/weave/menus/ExportMenu.as
|
/* ***** BEGIN LICENSE BLOCK *****
*
* This file is part of Weave.
*
* The Initial Developer of Weave is the Institute for Visualization
* and Perception Research at the University of Massachusetts Lowell.
* Portions created by the Initial Developer are Copyright (C) 2008-2015
* the Initial Developer. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* ***** END LICENSE BLOCK ***** */
package weave.menus
{
import weave.Weave;
import weave.compiler.Compiler;
import weave.core.LinkableCallbackScript;
import weave.core.LinkableFunction;
import weave.visualization.tools.ExternalTool;
public class ExportMenu extends WeaveMenuItem
{
public function ExportMenu()
{
super({
shown: function():Boolean { return shown; },
label: lang("Weave 2.0"),
children: [
{
label: lang("Export to HTML5"),
click: export
},
{
enabled: function():Boolean { return exported; },
label: lang("Copy layout from HTML5"),
click: function():void {
JavaScript.exec(
jsVars(false),
'var obj = window[WEAVE_EXTERNAL_TOOLS][windowName];',
'this.path("Layout").request("FlexibleLayout").state(obj.window.weave.path("Layout").getState())'
);
}
}
]
});
}
private static const windowName:String = ExternalTool.generateWindowName();
public static function get shown():Boolean
{
return Weave.properties.version.value == 'Custom';
}
private static function jsVars(catchErrors:Boolean):Object
{
return {
WEAVE_EXTERNAL_TOOLS: ExternalTool.WEAVE_EXTERNAL_TOOLS,
'windowName': windowName,
'catch': catchErrors && function():*{}
};
}
public static function get exported():Boolean
{
return JavaScript.exec(
jsVars(true),
'var obj = window[WEAVE_EXTERNAL_TOOLS][windowName];',
'return !!obj.window.weave;'
);
}
public static var url:String = "/weave-html5/";
public static function export():void
{
ExternalTool.launch(WeaveAPI.globalHashMap, url, windowName);
}
public static function disableScripts(exportUrl:String = null):void
{
LinkableFunction.enabled = false;
LinkableCallbackScript.enabled = false;
if (exportUrl)
ExportMenu.url = exportUrl;
else
exportUrl = ExportMenu.url;
var names:Array = WeaveAPI.globalHashMap.getNames();
var lcs:LinkableCallbackScript = WeaveAPI.globalHashMap.requestObject("_disableFlashScripts", LinkableCallbackScript, false);
// put new script first
WeaveAPI.globalHashMap.setNameOrder(names);
lcs.groupedCallback.value = false;
lcs.script.value = "if (typeof ExportMenu != 'undefined') {\n" +
"\tExportMenu.disableScripts(" + Compiler.stringify(exportUrl) + ");\n" +
"\tExportMenu.export();\n" +
"\tSessionStateEditor.openDefaultEditor();\n" +
"}";
}
/*
public static function flush():void
{
if (!exported)
{
export();
return;
}
JavaScript.exec(
jsVars(false),
<![CDATA[
var obj = window[WEAVE_EXTERNAL_TOOLS][windowName];
var content = atob(obj.path.getValue('btoa(Weave.createWeaveFileContent())'));
obj.window.weavejs.core.WeaveArchive.loadFileContent(obj.window.weave, content);
]]>
);
}
*/
}
}
|
/* ***** BEGIN LICENSE BLOCK *****
*
* This file is part of Weave.
*
* The Initial Developer of Weave is the Institute for Visualization
* and Perception Research at the University of Massachusetts Lowell.
* Portions created by the Initial Developer are Copyright (C) 2008-2015
* the Initial Developer. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* ***** END LICENSE BLOCK ***** */
package weave.menus
{
import weave.Weave;
import weave.compiler.Compiler;
import weave.core.LinkableCallbackScript;
import weave.core.LinkableFunction;
import weave.visualization.tools.ExternalTool;
public class ExportMenu extends WeaveMenuItem
{
public function ExportMenu()
{
super({
shown: function():Boolean { return ExportMenu.shown; },
label: lang("Weave 2.0"),
children: [
{
label: lang("Export to HTML5"),
click: export
},
{
enabled: function():Boolean { return exported; },
label: lang("Copy layout from HTML5"),
click: function():void {
JavaScript.exec(
jsVars(false),
'var obj = window[WEAVE_EXTERNAL_TOOLS][windowName];',
'this.path("Layout").request("FlexibleLayout").state(obj.window.weave.path("Layout").getState())'
);
}
}
]
});
}
private static const windowName:String = ExternalTool.generateWindowName();
public static function get shown():Boolean
{
return Weave.properties.version.value == 'Custom';
}
private static function jsVars(catchErrors:Boolean):Object
{
return {
WEAVE_EXTERNAL_TOOLS: ExternalTool.WEAVE_EXTERNAL_TOOLS,
'windowName': windowName,
'catch': catchErrors && function():*{}
};
}
public static function get exported():Boolean
{
return JavaScript.exec(
jsVars(true),
'var obj = window[WEAVE_EXTERNAL_TOOLS][windowName];',
'return !!obj.window.weave;'
);
}
public static var url:String = "/weave-html5/";
public static function export():void
{
ExternalTool.launch(WeaveAPI.globalHashMap, url, windowName);
}
public static function disableScripts(exportUrl:String = null):void
{
LinkableFunction.enabled = false;
LinkableCallbackScript.enabled = false;
if (exportUrl)
ExportMenu.url = exportUrl;
else
exportUrl = ExportMenu.url;
var names:Array = WeaveAPI.globalHashMap.getNames();
var lcs:LinkableCallbackScript = WeaveAPI.globalHashMap.requestObject("_disableFlashScripts", LinkableCallbackScript, false);
// put new script first
WeaveAPI.globalHashMap.setNameOrder(names);
lcs.groupedCallback.value = false;
lcs.script.value = "if (typeof ExportMenu != 'undefined') {\n" +
"\tExportMenu.disableScripts(" + Compiler.stringify(exportUrl) + ");\n" +
"\tExportMenu.export();\n" +
"\tSessionStateEditor.openDefaultEditor();\n" +
"}";
}
/*
public static function flush():void
{
if (!exported)
{
export();
return;
}
JavaScript.exec(
jsVars(false),
<![CDATA[
var obj = window[WEAVE_EXTERNAL_TOOLS][windowName];
var content = atob(obj.path.getValue('btoa(Weave.createWeaveFileContent())'));
obj.window.weavejs.core.WeaveArchive.loadFileContent(obj.window.weave, content);
]]>
);
}
*/
}
}
|
fix for ExportMenu shown property.
|
fix for ExportMenu shown property.
|
ActionScript
|
mpl-2.0
|
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
|
274250b02149a31c32abb4dabfa021034f12da5b
|
src/org/mangui/HLS/parsing/Manifest.as
|
src/org/mangui/HLS/parsing/Manifest.as
|
package org.mangui.HLS.parsing {
import flash.events.*;
import flash.net.*;
import org.mangui.HLS.utils.*;
/** Helpers for parsing M3U8 files. **/
public class Manifest {
/** Starttag for a fragment. **/
public static const FRAGMENT:String = '#EXTINF:';
/** Header tag that must be at the first line. **/
public static const HEADER:String = '#EXTM3U';
/** Starttag for a level. **/
public static const LEVEL:String = '#EXT-X-STREAM-INF:';
/** Tag that delimits the end of a playlist. **/
public static const ENDLIST:String = '#EXT-X-ENDLIST';
/** Tag that provides the sequence number. **/
private static const SEQNUM:String = '#EXT-X-MEDIA-SEQUENCE:';
/** Tag that provides the target duration for each segment. **/
private static const TARGETDURATION:String = '#EXT-X-TARGETDURATION:';
/** Tag that indicates discontinuity in the stream */
private static const DISCONTINUITY:String = '#EXT-X-DISCONTINUITY';
/** Tag that provides date/time information */
private static const PROGRAMDATETIME:String = '#EXT-X-PROGRAM-DATE-TIME';
/** Index in the array with levels. **/
private var _index:Number;
/** URLLoader instance. **/
private var _urlloader:URLLoader;
/** Function to callback loading to. **/
private var _success:Function;
/** URL of an M3U8 playlist. **/
private var _url:String;
/** Load a playlist M3U8 file. **/
public function loadPlaylist(url:String,success:Function,error:Function,index:Number):void {
_url = url;
_success = success;
_index = index;
_urlloader = new URLLoader();
_urlloader.addEventListener(Event.COMPLETE,_loaderHandler);
_urlloader.addEventListener(IOErrorEvent.IO_ERROR,error);
_urlloader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,error);
_urlloader.load(new URLRequest(url));
};
/** The M3U8 playlist was loaded. **/
private function _loaderHandler(event:Event):void {
_success(String(event.target.data),_url,_index);
};
/** Extract fragments from playlist data. **/
public static function getFragments(data:String,base:String=''):Array {
var fragments:Array = [];
var lines:Array = data.split("\n");
//fragment seqnum
var seqnum:Number = 0;
// fragment start time (in sec)
var start_time:Number = 0;
var program_date:Number=0;
// fragment continuity index incremented at each discontinuity
var continuity_index:Number = 0;
var i:Number = 0;
// first look for sequence number
while (i < lines.length) {
if(lines[i].indexOf(Manifest.SEQNUM) == 0) {
seqnum = Number(lines[i].substr(Manifest.SEQNUM.length));
break;
}
i++;
}
i = 0;
while (i < lines.length) {
if(lines[i].indexOf(Manifest.PROGRAMDATETIME) == 0) {
//Log.txt(lines[i]);
var year:Number = lines[i].substr(25,4);
var month:Number = lines[i].substr(30,2);
var day:Number = lines[i].substr(33,2);
var hour:Number = lines[i].substr(36,2);
var minutes:Number = lines[i].substr(39,2);
var seconds:Number = lines[i].substr(42,2);
program_date = new Date(year,month,day,hour,minutes,seconds).getTime();
} else if(lines[i].indexOf(Manifest.FRAGMENT) == 0) {
var comma_position:Number = lines[i].indexOf(',');
var duration:Number = (comma_position == -1) ? lines[i].substr(Manifest.FRAGMENT.length) : lines[i].substr(Manifest.FRAGMENT.length,comma_position-Manifest.FRAGMENT.length);
// Look for next non-blank line, for url
i++;
while(lines[i].match(/^\s*$/)) {
i++;
}
var url:String = Manifest._extractURL(lines[i],base);
fragments.push(new Fragment(url,duration,seqnum++,start_time,continuity_index,program_date));
start_time+=duration;
program_date = 0;
} else if(lines[i].indexOf(Manifest.DISCONTINUITY) == 0) {
continuity_index++;
Log.txt("discontinuity found at seqnum " + seqnum);
}
i++;
}
if(fragments.length == 0) {
//throw new Error("No TS fragments found in " + base);
Log.txt("No TS fragments found in " + base);
}
return fragments;
};
/** Extract levels from manifest data. **/
public static function extractLevels(data:String,base:String=''):Array {
var levels:Array = [];
var lines:Array = data.split("\n");
var i:Number = 0;
while (i<lines.length) {
if(lines[i].indexOf(Manifest.LEVEL) == 0) {
var level:Level = new Level();
var params:Array = lines[i].substr(Manifest.LEVEL.length).split(',');
for(var j:Number = 0; j<params.length; j++) {
if(params[j].indexOf('BANDWIDTH') > -1) {
level.bitrate = params[j].split('=')[1];
if(level.bitrate < 150000) {
level.audio = true;
}
} else if (params[j].indexOf('RESOLUTION') > -1) {
level.height = params[j].split('=')[1].split('x')[1];
level.width = params[j].split('=')[1].split('x')[0];
} else if (params[j].indexOf('CODECS') > -1 && lines[i].indexOf('avc1') == -1) {
level.audio = true;
}
}
// Look for next non-blank line, for url
i++;
while(lines[i].match(/^\s*$/)) {
i++;
}
level.url = Manifest._extractURL(lines[i],base);
levels.push(level);
}
i++;
}
if(levels.length == 0) {
throw new Error("No playlists found in Manifest: " + base);
}
levels.start_seqnum = -1;
levels.end_seqnum = -1;
levels.sortOn('bitrate',Array.NUMERIC);
return levels;
};
/** Extract whether the stream is live or ondemand. **/
public static function hasEndlist(data:String):Boolean {
if(data.indexOf(Manifest.ENDLIST) > 0) {
return true;
} else {
return false;
}
};
public static function getTargetDuration(data:String):Number {
var lines:Array = data.split("\n");
var i:Number = 0;
var targetduration:Number = 0;
// first look for target duration
while (i < lines.length) {
if(lines[i].indexOf(Manifest.TARGETDURATION) == 0) {
targetduration = Number(lines[i].substr(Manifest.TARGETDURATION.length));
break;
}
i++;
}
return targetduration;
}
/** Extract URL (check if absolute or not). **/
private static function _extractURL(path:String,base:String):String {
var _prefix:String = null;
var _suffix:String = null;
if(path.substr(0,7) == 'http://' || path.substr(0,8) == 'https://') {
return path;
} else {
// Remove querystring
if(base.indexOf('?') > -1) {
base = base.substr(0,base.indexOf('?'));
}
// domain-absolute
if(path.substr(0,1) == '/') {
// base = http[s]://domain/subdomain:1234/otherstuff
// prefix = http[s]://
// suffix = domain/subdomain:1234/otherstuff
_prefix=base.substr(0,base.indexOf("//")+2);
_suffix=base.substr(base.indexOf("//")+2);
// return http[s]://domain/subdomain:1234/path
return _prefix+_suffix.substr(0,_suffix.indexOf("/"))+path;
} else {
return base.substr(0,base.lastIndexOf('/') + 1) + path;
}
}
};
}
}
|
package org.mangui.HLS.parsing {
import flash.events.*;
import flash.net.*;
import org.mangui.HLS.utils.*;
/** Helpers for parsing M3U8 files. **/
public class Manifest {
/** Starttag for a fragment. **/
public static const FRAGMENT:String = '#EXTINF:';
/** Header tag that must be at the first line. **/
public static const HEADER:String = '#EXTM3U';
/** Starttag for a level. **/
public static const LEVEL:String = '#EXT-X-STREAM-INF:';
/** Tag that delimits the end of a playlist. **/
public static const ENDLIST:String = '#EXT-X-ENDLIST';
/** Tag that provides the sequence number. **/
private static const SEQNUM:String = '#EXT-X-MEDIA-SEQUENCE:';
/** Tag that provides the target duration for each segment. **/
private static const TARGETDURATION:String = '#EXT-X-TARGETDURATION:';
/** Tag that indicates discontinuity in the stream */
private static const DISCONTINUITY:String = '#EXT-X-DISCONTINUITY';
/** Tag that provides date/time information */
private static const PROGRAMDATETIME:String = '#EXT-X-PROGRAM-DATE-TIME';
/** Index in the array with levels. **/
private var _index:Number;
/** URLLoader instance. **/
private var _urlloader:URLLoader;
/** Function to callback loading to. **/
private var _success:Function;
/** URL of an M3U8 playlist. **/
private var _url:String;
/** Load a playlist M3U8 file. **/
public function loadPlaylist(url:String,success:Function,error:Function,index:Number):void {
_url = url;
_success = success;
_index = index;
_urlloader = new URLLoader();
_urlloader.addEventListener(Event.COMPLETE,_loaderHandler);
_urlloader.addEventListener(IOErrorEvent.IO_ERROR,error);
_urlloader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,error);
_urlloader.load(new URLRequest(url));
};
/** The M3U8 playlist was loaded. **/
private function _loaderHandler(event:Event):void {
_success(String(event.target.data),_url,_index);
};
/** Extract fragments from playlist data. **/
public static function getFragments(data:String,base:String=''):Array {
var fragments:Array = [];
var lines:Array = data.split("\n");
//fragment seqnum
var seqnum:Number = 0;
// fragment start time (in sec)
var start_time:Number = 0;
var program_date:Number=0;
// fragment continuity index incremented at each discontinuity
var continuity_index:Number = 0;
var i:Number = 0;
// first look for sequence number
while (i < lines.length) {
if(lines[i].indexOf(Manifest.SEQNUM) == 0) {
seqnum = Number(lines[i].substr(Manifest.SEQNUM.length));
break;
}
i++;
}
i = 0;
while (i < lines.length) {
if(lines[i].indexOf(Manifest.PROGRAMDATETIME) == 0) {
//Log.txt(lines[i]);
var year:Number = lines[i].substr(25,4);
var month:Number = lines[i].substr(30,2);
var day:Number = lines[i].substr(33,2);
var hour:Number = lines[i].substr(36,2);
var minutes:Number = lines[i].substr(39,2);
var seconds:Number = lines[i].substr(42,2);
program_date = new Date(year,month,day,hour,minutes,seconds).getTime();
} else if(lines[i].indexOf(Manifest.FRAGMENT) == 0) {
var comma_position:Number = lines[i].indexOf(',');
var duration:Number = (comma_position == -1) ? lines[i].substr(Manifest.FRAGMENT.length) : lines[i].substr(Manifest.FRAGMENT.length,comma_position-Manifest.FRAGMENT.length);
// Look for next non-blank line, for url
i++;
while(lines[i].match(/^\s*$/)) {
i++;
}
var url:String = Manifest._extractURL(lines[i],base);
fragments.push(new Fragment(url,duration,seqnum++,start_time,continuity_index,program_date));
start_time+=duration;
program_date = 0;
} else if(lines[i].indexOf(Manifest.DISCONTINUITY) == 0) {
continuity_index++;
Log.txt("discontinuity found at seqnum " + seqnum);
}
i++;
}
if(fragments.length == 0) {
//throw new Error("No TS fragments found in " + base);
Log.txt("No TS fragments found in " + base);
}
return fragments;
};
/** Extract levels from manifest data. **/
public static function extractLevels(data:String,base:String=''):Array {
var levels:Array = [];
var lines:Array = data.split("\n");
var i:Number = 0;
while (i<lines.length) {
if(lines[i].indexOf(Manifest.LEVEL) == 0) {
var level:Level = new Level();
var params:Array = lines[i].substr(Manifest.LEVEL.length).split(',');
for(var j:Number = 0; j<params.length; j++) {
if(params[j].indexOf('BANDWIDTH') > -1) {
level.bitrate = params[j].split('=')[1];
} else if (params[j].indexOf('RESOLUTION') > -1) {
level.height = params[j].split('=')[1].split('x')[1];
level.width = params[j].split('=')[1].split('x')[0];
} else if (params[j].indexOf('CODECS') > -1 && lines[i].indexOf('avc1') == -1) {
level.audio = true;
}
}
// Look for next non-blank line, for url
i++;
while(lines[i].match(/^\s*$/)) {
i++;
}
level.url = Manifest._extractURL(lines[i],base);
levels.push(level);
}
i++;
}
if(levels.length == 0) {
throw new Error("No playlists found in Manifest: " + base);
}
levels.start_seqnum = -1;
levels.end_seqnum = -1;
levels.sortOn('bitrate',Array.NUMERIC);
return levels;
};
/** Extract whether the stream is live or ondemand. **/
public static function hasEndlist(data:String):Boolean {
if(data.indexOf(Manifest.ENDLIST) > 0) {
return true;
} else {
return false;
}
};
public static function getTargetDuration(data:String):Number {
var lines:Array = data.split("\n");
var i:Number = 0;
var targetduration:Number = 0;
// first look for target duration
while (i < lines.length) {
if(lines[i].indexOf(Manifest.TARGETDURATION) == 0) {
targetduration = Number(lines[i].substr(Manifest.TARGETDURATION.length));
break;
}
i++;
}
return targetduration;
}
/** Extract URL (check if absolute or not). **/
private static function _extractURL(path:String,base:String):String {
var _prefix:String = null;
var _suffix:String = null;
if(path.substr(0,7) == 'http://' || path.substr(0,8) == 'https://') {
return path;
} else {
// Remove querystring
if(base.indexOf('?') > -1) {
base = base.substr(0,base.indexOf('?'));
}
// domain-absolute
if(path.substr(0,1) == '/') {
// base = http[s]://domain/subdomain:1234/otherstuff
// prefix = http[s]://
// suffix = domain/subdomain:1234/otherstuff
_prefix=base.substr(0,base.indexOf("//")+2);
_suffix=base.substr(base.indexOf("//")+2);
// return http[s]://domain/subdomain:1234/path
return _prefix+_suffix.substr(0,_suffix.indexOf("/"))+path;
} else {
return base.substr(0,base.lastIndexOf('/') + 1) + path;
}
}
};
}
}
|
remove implicit rules that force playlist to be audio only
|
remove implicit rules that force playlist to be audio only
|
ActionScript
|
mpl-2.0
|
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
|
9938bb4b3084f4b054d31c046a5928a0ddea75e3
|
sdk-remote/src/tests/bin/liburbi-check.as
|
sdk-remote/src/tests/bin/liburbi-check.as
|
m4_pattern_allow([^URBI_(PATH|SERVER)$]) -*- shell-script -*-
URBI_INIT
# Avoid zombies and preserve debugging information.
cleanup ()
{
exit_status=$?
# We can be killed even before children are spawned.
test -n "$children" ||
exit $exit_status
# In case we were caught by set -e, kill the children.
children_kill
children_harvest
children_report
children_sta=$(children_status remote)
# Don't clean before calling children_status...
test x$VERBOSE != x || children_clean
case $exit_status:$children_sta in
(0:0) ;;
(0:*) # Maybe a children exited for SKIP etc.
exit $children_sta;;
(*:*) # If the checker failed, there is a big problem.
error SOFTWARE "$0 itself failed with $exit_status";;
esac
# rst_expect sets exit=false if it saw a failure.
$exit
}
trap cleanup 0
# Overriden to include the test name.
stderr ()
{
echo >&2 "$(basename $0): $me: $@"
echo >&2
}
# Sleep some time, but taking into account the fact that
# instrumentation slows down a lot.
my_sleep ()
{
if $INSTRUMENT; then
sleep $(($1 * 5))
else
sleep $1
fi
}
## -------------- ##
## Main program. ##
## -------------- ##
exec 3>&2
check_dir abs_builddir bin/liburbi-check
# Make it absolute.
chk=$(absolute "$1")
if test ! -f "$chk.cc"; then
fatal "no such file: $chk.cc"
fi
# ./../../../tests/2.x/andexp-pipeexp.chk -> 2.x
medir=$(basename $(dirname "$chk"))
# ./../../../tests/2.x/andexp-pipeexp.chk -> 2.x/andexp-pipeexp
me=$medir/$(basename "$chk" ".cc")
# ./../../../tests/2.x/andexp-pipeexp.chk -> andexp-pipeexp
meraw=$(basename $me) # MERAW!
srcdir=$(absolute $srcdir)
export srcdir
# Move to a private dir.
mkcd $me.dir
# Help debugging
set | rst_pre "$me variables"
# Leaves trailing files, so run it in subdir.
find_urbi_server
# Compute expected output.
sed -n -e 's,//= ,,p' $chk.cc >output.exp
touch error.exp
echo 0 >status.exp
# Start it.
spawn_urbi_server
# Start the test.
valgrind=$(instrument "remote.val")
cmd="$valgrind ../../bin/tests$EXEEXT --port-file server.port $meraw"
echo "$cmd" >remote.cmd
$cmd >remote.out.raw 2>remote.err &
children_register remote
# Let some time to run the tests.
children_wait 10
# Ignore the "client errors".
sed -e '/^E client error/d' remote.out.raw >remote.out.eff
# Compare expected output with actual output.
rst_expect output remote.out
rst_pre "Error output" remote.err
# Display Valgrind report.
rst_pre "Valgrind" remote.val
# Exit with success: liburbi-check made its job. But now clean (on
# trap 0) will check $exit to see if there is a failure in the tests
# and adjust the exit status accordingly.
exit 0
|
m4_pattern_allow([^URBI_(PATH|SERVER)$]) -*- shell-script -*-
URBI_INIT
# Avoid zombies and preserve debugging information.
cleanup ()
{
exit_status=$?
# We can be killed even before children are spawned.
test -n "$children" ||
exit $exit_status
# In case we were caught by set -e, kill the children.
children_kill
children_harvest
children_report
children_sta=$(children_status remote)
# Don't clean before calling children_status...
test x$VERBOSE != x || children_clean
case $exit_status:$children_sta in
(0:0) ;;
(0:*) # Maybe a children exited for SKIP etc.
exit $children_sta;;
(*:*) # If the checker failed, there is a big problem.
error SOFTWARE "$0 itself failed with $exit_status";;
esac
# rst_expect sets exit=false if it saw a failure.
$exit
}
trap cleanup 0
# Overriden to include the test name.
stderr ()
{
local i
for i
do
echo >&2 "$(basename $0): $me: $i"
done
echo >&2
}
# Sleep some time, but taking into account the fact that
# instrumentation slows down a lot.
my_sleep ()
{
if $INSTRUMENT; then
sleep $(($1 * 5))
else
sleep $1
fi
}
## -------------- ##
## Main program. ##
## -------------- ##
exec 3>&2
check_dir abs_builddir bin/liburbi-check
# Make it absolute.
chk=$(absolute "$1")
if test ! -f "$chk.cc"; then
fatal "no such file: $chk.cc"
fi
# ./../../../tests/2.x/andexp-pipeexp.chk -> 2.x
medir=$(basename $(dirname "$chk"))
# ./../../../tests/2.x/andexp-pipeexp.chk -> 2.x/andexp-pipeexp
me=$medir/$(basename "$chk" ".cc")
# ./../../../tests/2.x/andexp-pipeexp.chk -> andexp-pipeexp
meraw=$(basename $me) # MERAW!
srcdir=$(absolute $srcdir)
export srcdir
# Move to a private dir.
mkcd $me.dir
# Help debugging
set | rst_pre "$me variables"
# Leaves trailing files, so run it in subdir.
find_urbi_server
# Compute expected output.
sed -n -e 's,//= ,,p' $chk.cc >output.exp
touch error.exp
echo 0 >status.exp
# Start it.
spawn_urbi_server
# Start the test.
valgrind=$(instrument "remote.val")
cmd="$valgrind ../../bin/tests$EXEEXT --port-file server.port $meraw"
echo "$cmd" >remote.cmd
$cmd >remote.out.raw 2>remote.err &
children_register remote
# Let some time to run the tests.
children_wait 10
# Ignore the "client errors".
sed -e '/^E client error/d' remote.out.raw >remote.out.eff
# Compare expected output with actual output.
rst_expect output remote.out
rst_pre "Error output" remote.err
# Display Valgrind report.
rst_pre "Valgrind" remote.val
# Exit with success: liburbi-check made its job. But now clean (on
# trap 0) will check $exit to see if there is a failure in the tests
# and adjust the exit status accordingly.
exit 0
|
Fix stderr().
|
Fix stderr().
* src/tests/bin/liburbi-check.as: Output should be on several lines.
|
ActionScript
|
bsd-3-clause
|
aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.