CombinedText stringlengths 4 3.42M |
|---|
package laya.ui {
import laya.events.Event;
import laya.net.Loader;
import laya.resource.Texture;
import laya.utils.Handler;
import laya.utils.Utils;
import laya.utils.WeakObject;
/**
* 图片加载完成后调度。
* @eventType Event.LOADED
*/
[Event(name = "loaded", type = "laya.events.Event")]
/**
* 当前帧发生变化后调度。
* @eventType laya.events.Event
*/
[Event(name = "change", type = "laya.events.Event")]
/**
* <p> <code>Clip</code> 类是位图切片动画。</p>
* <p> <code>Clip</code> 可将一张图片,按横向分割数量 <code>clipX</code> 、竖向分割数量 <code>clipY</code> ,
* 或横向分割每个切片的宽度 <code>clipWidth</code> 、竖向分割每个切片的高度 <code>clipHeight</code> ,
* 从左向右,从上到下,分割组合为一个切片动画。</p>
* Image和Clip组件是唯一支持异步加载的两个组件,比如clip.skin = "abc/xxx.png",其他UI组件均不支持异步加载。
*
* @example <caption>以下示例代码,创建了一个 <code>Clip</code> 实例。</caption>
* package
* {
* import laya.ui.Clip;
* public class Clip_Example
* {
* private var clip:Clip;
* public function Clip_Example()
* {
* Laya.init(640, 800);//设置游戏画布宽高。
* Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。
* onInit();
* }
* private function onInit():void
* {
* clip = new Clip("resource/ui/clip_num.png", 10, 1);//创建一个 Clip 类的实例对象 clip ,传入它的皮肤skin和横向分割数量、竖向分割数量。
* clip.autoPlay = true;//设置 clip 动画自动播放。
* clip.interval = 100;//设置 clip 动画的播放时间间隔。
* clip.x = 100;//设置 clip 对象的属性 x 的值,用于控制 clip 对象的显示位置。
* clip.y = 100;//设置 clip 对象的属性 y 的值,用于控制 clip 对象的显示位置。
* clip.on(Event.CLICK, this, onClick);//给 clip 添加点击事件函数侦听。
* Laya.stage.addChild(clip);//将此 clip 对象添加到显示列表。
* }
* private function onClick():void
* {
* trace("clip 的点击事件侦听处理函数。clip.total="+ clip.total);
* if (clip.isPlaying == true)
* {
* clip.stop();//停止动画。
* }else {
* clip.play();//播放动画。
* }
* }
* }
* }
* @example
* Laya.init(640, 800);//设置游戏画布宽高
* Laya.stage.bgColor = "#efefef";//设置画布的背景颜色
* var clip;
* Laya.loader.load("resource/ui/clip_num.png",laya.utils.Handler.create(this,loadComplete));//加载资源
* function loadComplete() {
* console.log("资源加载完成!");
* clip = new laya.ui.Clip("resource/ui/clip_num.png",10,1);//创建一个 Clip 类的实例对象 clip ,传入它的皮肤skin和横向分割数量、竖向分割数量。
* clip.autoPlay = true;//设置 clip 动画自动播放。
* clip.interval = 100;//设置 clip 动画的播放时间间隔。
* clip.x =100;//设置 clip 对象的属性 x 的值,用于控制 clip 对象的显示位置。
* clip.y =100;//设置 clip 对象的属性 y 的值,用于控制 clip 对象的显示位置。
* clip.on(Event.CLICK,this,onClick);//给 clip 添加点击事件函数侦听。
* Laya.stage.addChild(clip);//将此 clip 对象添加到显示列表。
* }
* function onClick()
* {
* console.log("clip 的点击事件侦听处理函数。");
* if(clip.isPlaying == true)
* {
* clip.stop();
* }else {
* clip.play();
* }
* }
* @example
* import Clip = laya.ui.Clip;
* import Handler = laya.utils.Handler;
* class Clip_Example {
* private clip: Clip;
* constructor() {
* Laya.init(640, 800);//设置游戏画布宽高。
* Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。
* this.onInit();
* }
* private onInit(): void {
* this.clip = new Clip("resource/ui/clip_num.png", 10, 1);//创建一个 Clip 类的实例对象 clip ,传入它的皮肤skin和横向分割数量、竖向分割数量。
* this.clip.autoPlay = true;//设置 clip 动画自动播放。
* this.clip.interval = 100;//设置 clip 动画的播放时间间隔。
* this.clip.x = 100;//设置 clip 对象的属性 x 的值,用于控制 clip 对象的显示位置。
* this.clip.y = 100;//设置 clip 对象的属性 y 的值,用于控制 clip 对象的显示位置。
* this.clip.on(laya.events.Event.CLICK, this, this.onClick);//给 clip 添加点击事件函数侦听。
* Laya.stage.addChild(this.clip);//将此 clip 对象添加到显示列表。
* }
* private onClick(): void {
* console.log("clip 的点击事件侦听处理函数。clip.total=" + this.clip.total);
* if (this.clip.isPlaying == true) {
* this.clip.stop();//停止动画。
* } else {
* this.clip.play();//播放动画。
* }
* }
* }
*
*/
public class Clip extends Component {
/**@private */
protected var _sources:Array;
/**@private */
protected var _bitmap:AutoBitmap;
/**@private */
protected var _skin:String;
/**@private */
protected var _clipX:int = 1;
/**@private */
protected var _clipY:int = 1;
/**@private */
protected var _clipWidth:Number = 0;
/**@private */
protected var _clipHeight:Number = 0;
/**@private */
protected var _autoPlay:Boolean;
/**@private */
protected var _interval:int = 50;
/**@private */
protected var _complete:Handler;
/**@private */
protected var _isPlaying:Boolean;
/**@private */
protected var _index:int = 0;
/**@private */
protected var _clipChanged:Boolean;
/**@private */
protected var _group:String;
/**@private */
protected var _toIndex:int = -1;
/**
* 创建一个新的 <code>Clip</code> 示例。
* @param url 资源类库名或者地址
* @param clipX x方向分割个数
* @param clipY y方向分割个数
*/
public function Clip(url:String = null, clipX:int = 1, clipY:int = 1) {
_clipX = clipX;
_clipY = clipY;
this.skin = url;
}
/**@inheritDoc */
override public function destroy(destroyChild:Boolean = true):void {
super.destroy(true);
_bitmap && _bitmap.destroy();
_bitmap = null;
_sources = null;
}
/**
* 销毁对象并释放加载的皮肤资源。
*/
public function dispose():void {
destroy(true);
Laya.loader.clearRes(_skin);
}
/**@inheritDoc */
override protected function createChildren():void {
graphics = _bitmap = new AutoBitmap();
}
/**@private */
protected function _onDisplay(e:Event = null):void {
if (_isPlaying) {
if (_displayedInStage) play();
else stop();
} else if (_autoPlay) {
play();
}
}
/**
* @copy laya.ui.Image#skin
*/
public function get skin():String {
return _skin;
}
public function set skin(value:String):void {
if (_skin != value) {
_skin = value;
if (value) {
_setClipChanged()
} else {
_bitmap.source = null;
}
}
}
/**X轴(横向)切片数量。*/
public function get clipX():int {
return _clipX;
}
public function set clipX(value:int):void {
_clipX = value || 1;
_setClipChanged()
}
/**Y轴(竖向)切片数量。*/
public function get clipY():int {
return _clipY;
}
public function set clipY(value:int):void {
_clipY = value || 1;
_setClipChanged()
}
/**
* 横向分割时每个切片的宽度,与 <code>clipX</code> 同时设置时优先级高于 <code>clipX</code> 。
*/
public function get clipWidth():Number {
return _clipWidth;
}
public function set clipWidth(value:Number):void {
_clipWidth = value;
_setClipChanged()
}
/**
* 竖向分割时每个切片的高度,与 <code>clipY</code> 同时设置时优先级高于 <code>clipY</code> 。
*/
public function get clipHeight():Number {
return _clipHeight;
}
public function set clipHeight(value:Number):void {
_clipHeight = value;
_setClipChanged()
}
/**
* @private
* 改变切片的资源、切片的大小。
*/
protected function changeClip():void {
_clipChanged = false;
if (!_skin) return;
var img:* = Loader.getRes(_skin);
if (img) {
loadComplete(_skin, img);
} else {
Laya.loader.load(_skin, Handler.create(this, loadComplete, [_skin]));
}
}
/**
* @private
* 加载切片图片资源完成函数。
* @param url 资源地址。
* @param img 纹理。
*/
protected function loadComplete(url:String, img:Texture):void {
if (url === _skin && img) {
var w:Number = _clipWidth || Math.ceil(img.sourceWidth / _clipX);
var h:Number = _clipHeight || Math.ceil(img.sourceHeight / _clipY);
var key:String = _skin + w + h;
var clips:Array = WeakObject.I.get(key);
if (!Utils.isOkTextureList(clips))
{
clips = null;
}
if (clips) _sources = clips;
else {
_sources = [];
for (var i:int = 0; i < _clipY; i++) {
for (var j:int = 0; j < _clipX; j++) {
_sources.push(Texture.createFromTexture(img, w * j, h * i, w, h));
}
}
WeakObject.I.set(key, _sources);
}
index = _index;
event(Event.LOADED);
onCompResize();
}
}
/**
* 源数据。
*/
public function get sources():Array {
return _sources;
}
public function set sources(value:Array):void {
_sources = value;
index = _index;
event(Event.LOADED);
}
/**
* 资源分组。
*/
public function get group():String {
return _group;
}
public function set group(value:String):void {
if (value && _skin) Loader.setGroup(_skin, value);
_group = value;
}
/**@inheritDoc */
override public function set width(value:Number):void {
super.width = value;
_bitmap.width = value;
}
/**@inheritDoc */
override public function set height(value:Number):void {
super.height = value;
_bitmap.height = value;
}
/**@inheritDoc */
override protected function get measureWidth():Number {
runCallLater(changeClip);
return _bitmap.width;
}
/**@inheritDoc */
override protected function get measureHeight():Number {
runCallLater(changeClip);
return _bitmap.height;
}
/**
* <p>当前实例的位图 <code>AutoImage</code> 实例的有效缩放网格数据。</p>
* <p>数据格式:"上边距,右边距,下边距,左边距,是否重复填充(值为0:不重复填充,1:重复填充)",以逗号分隔。
* <ul><li>例如:"4,4,4,4,1"</li></ul></p>
* @see laya.ui.AutoBitmap.sizeGrid
*/
public function get sizeGrid():String {
if (_bitmap.sizeGrid) return _bitmap.sizeGrid.join(",");
return null;
}
public function set sizeGrid(value:String):void {
_bitmap.sizeGrid = UIUtils.fillArray(Styles.defaultSizeGrid, value, Number);
}
/**
* 当前帧索引。
*/
public function get index():int {
return _index;
}
public function set index(value:int):void {
_index = value;
_bitmap && _sources && (_bitmap.source = _sources[value]);
event(Event.CHANGE);
}
/**
* 切片动画的总帧数。
*/
public function get total():int {
runCallLater(changeClip);
return _sources ? _sources.length : 0;
}
/**
* 表示是否自动播放动画,若自动播放值为true,否则值为false;
* <p>可控制切片动画的播放、停止。</p>
*/
public function get autoPlay():Boolean {
return _autoPlay;
}
public function set autoPlay(value:Boolean):void {
if (_autoPlay != value) {
_autoPlay = value;
value ? play() : stop();
}
}
/**
* 表示动画播放间隔时间(以毫秒为单位)。
*/
public function get interval():int {
return _interval;
}
public function set interval(value:int):void {
if (_interval != value) {
_interval = value;
if (_isPlaying) play();
}
}
/**
* 表示动画的当前播放状态。
* 如果动画正在播放中,则为true,否则为flash。
*/
public function get isPlaying():Boolean {
return _isPlaying;
}
public function set isPlaying(value:Boolean):void {
_isPlaying = value;
}
/**
* 播放动画。
* @param from 开始索引
* @param to 结束索引,-1为不限制
*/
public function play(from:int = 0, to:int = -1):void {
_isPlaying = true;
this.index = from;
this._toIndex = to;
this._index++;
Laya.timer.loop(this.interval, this, _loop);
on(Event.DISPLAY, this, _onDisplay);
on(Event.UNDISPLAY, this, _onDisplay);
}
/**
* @private
*/
protected function _loop():void {
if (_style.visible && this._sources) {
_index++;
if (_toIndex > -1 && _index >= _toIndex) stop();
else if (this._index >= this._sources.length) this._index = 0;
this.index = _index;
}
}
/**
* 停止动画。
*/
public function stop():void {
this._isPlaying = false;
Laya.timer.clear(this, _loop);
event(Event.COMPLETE);
}
/**@inheritDoc */
override public function set dataSource(value:*):void {
_dataSource = value;
if (value is int || value is String) index = parseInt(value);
else super.dataSource = value;
}
/**
* <code>AutoBitmap</code> 位图实例。
*/
public function get bitmap():AutoBitmap {
return _bitmap;
}
/**@private */
protected function _setClipChanged():void {
if (!_clipChanged) {
_clipChanged = true;
callLater(changeClip);
}
}
}
} |
/**
* Copyright (C) 2010 Rafał Szemraj.
*
* 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.puremvc.as3.multicore.utilities.fabrication.logging {
/**
* LogLevel class holds info about log level hierarchy in logging api. Each logged message
* is logged at individual level which improve filtering abilities.
* @author Rafał Szemraj
*/
public class LogLevel {
private var _level:uint;
private var _name:String;
/**
* DEFAULT log level ( same as DEBUG )
*/
public static const DEFAULT:LogLevel = new LogLevel(50, "DEBUG");
/**
* DEBUG log level
*/
public static const DEBUG:LogLevel = new LogLevel(50, "DEBUG");
/**
* INFO log level
*/
public static const INFO:LogLevel = new LogLevel(40, "INFO");
/**
* WARN log level
*/
public static const WARN:LogLevel = new LogLevel(30, "WARN");
/**
* ERROR log level
*/
public static const ERROR:LogLevel = new LogLevel(20, "ERROR");
/**
* FATAL log level
*/
public static const FATAL:LogLevel = new LogLevel(10, "FATAL");
/**
* NONE log level ( logging is blocked )
*/
public static const NONE:LogLevel = new LogLevel(0, "NONE");
/**
* Creates LogLevel instance for given levelName
* @param levelName String
* @return LogLevel instance
*/
public static function fromLogLevelName(levelName:String):LogLevel
{
levelName = levelName.toUpperCase();
var logLevel:LogLevel;
switch (levelName) {
case LogLevel.INFO.getName() :
logLevel = LogLevel.INFO;
break;
case LogLevel.DEBUG.getName() :
logLevel = LogLevel.DEBUG;
break;
case LogLevel.WARN.getName() :
logLevel = LogLevel.WARN;
break;
case LogLevel.ERROR.getName() :
logLevel = LogLevel.ERROR;
break;
case LogLevel.FATAL.getName() :
logLevel = LogLevel.FATAL;
break;
default:
logLevel = LogLevel.DEFAULT;
}
return logLevel;
}
public function LogLevel(level:uint = 50, name:String = "DEBUG")
{
_level = level;
_name = name;
}
/**
* Compares current log level with another one
* @param logLevel another logLevel instance
* @return <strong>true</strong> if passed in logLevel is higher in log hierarchy,
* otherwise returns <strong>false</strong>
*/
public function isGreaterOrEqual(logLevel:LogLevel):Boolean
{
return _level >= logLevel._level;
}
/**
* Returns value of logLevel
* @return value of logLevel
*/
public function getValue():uint
{
return _level;
}
/**
* Returns name of logLevel
* @return name of logLevel
*/
public function getName():String
{
return _name;
}
}
}
|
//
// $Id$
//
// Treasure Chest - a piece of furni for Whirled
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.display.DisplayObject;
import flash.display.MovieClip;
import flash.geom.ColorTransform;
import com.whirled.FurniControl;
import com.whirled.ControlEvent;
import com.whirled.EntityControl;
import com.whirled.DataPack;
/**
* Treasure Chest is the coolest piece of Furni ever.
*/
[SWF(width="200", height="300")]
public class EnchantedDoor extends Sprite
{
public static const OPEN_DOOR_SIGNAL :String = "dj_tutorial_complete";
public function EnchantedDoor ()
{
// instantiate and wire up our control
_control = new FurniControl(this);
// listen for an unload event
_control.addEventListener(Event.UNLOAD, handleUnload);
DataPack.load(_control.getDefaultDataPack(), gotPack);
}
protected function gotPack (result:Object) : void
{
if (result is DataPack) {
speed = result.getNumber("TransitionSpeed");
result.getDisplayObjects({open:"DoorImage", shadow:"DoorImage"}, gotDisplayObject);
} else {
speed = 10;
gotDisplayObject(null);
}
}
protected function gotDisplayObject(result:Object) : void {
if (result) {
openImage = result.open;
shadowLayer = result.shadow;
} else {
openImage = new OPEN() as DisplayObject;
shadowLayer = new OPEN() as DisplayObject;
}
openImage.y = 300 - openImage.height;
openImage.x = (200 - openImage.width) / 2;
openImage.alpha = 0;
shadowLayer.y = 300 - openImage.height;
shadowLayer.x = (200 - openImage.width) / 2;
var transform:ColorTransform = new ColorTransform;
transform.color = 0x000000;
shadowLayer.transform.colorTransform = transform;
shadowLayer.alpha = .5;
maskLayer = new MASK() as DisplayObject;
maskLayer.width = openImage.width;
maskLayer.height = openImage.height;
maskLayer.x = openImage.x;
maskLayer.y = openImage.y;
doorContainer = new Sprite;
doorContainer.addChild(shadowLayer);
doorContainer.addChild(maskLayer);
shadowLayer.mask = maskLayer;
shadowLayer.y = maskLayer.y + maskLayer.height;
addChild(doorContainer);
//addChild(openImage);
state = _control.getMemory("state", "closed") as String;
if (state == "closed") {
// Do nothing
} else if (state == "open") {
handleMsgReceived({name:"open"});
} else {
trace("[EnchantedDoor] Error: Invalid state::" + state);
}
_control.addEventListener(ControlEvent.MESSAGE_RECEIVED, handleMsgReceived);
_control.addEventListener(ControlEvent.SIGNAL_RECEIVED, handleSignal);
}
protected function handleMsgReceived(event: Object) : void
{
switch (event.name) {
case "open":
state = "open";
_control.setMemory("state", state);
addEventListener(Event.ENTER_FRAME, frameHandler);
break;
case "close":
state = "closed";
_control.setMemory("state", "closed");
addEventListener(Event.ENTER_FRAME, frameHandler);
break;
}
}
protected function handleSignal(event:ControlEvent) : void {
if (event.name == OPEN_DOOR_SIGNAL) {
if (state == "closed") {
_control.sendMessage("open");
}
}
}
protected function frameHandler(event:Event) : void {
if (state == "open") {
shadowLayer.y -= speed;
if (shadowLayer.y <= maskLayer.y) {
// Done Raising Shadow
shadowLayer.y = maskLayer.y
if (!this.contains(openImage)) {
this.addChild(openImage);
}
openImage.alpha += speed * .025;
if (openImage.alpha >= 1) {
openImage.alpha = 1;
removeEventListener(Event.ENTER_FRAME, frameHandler);
}
}
} else if (state == "closed") {
openImage.alpha -= speed * .025;
if (openImage.alpha <= 0) {
openImage.alpha = 0;
if (this.contains(openImage)) {
this.removeChild(openImage);
}
shadowLayer.y += speed;
if (shadowLayer.y >= maskLayer.y + maskLayer.height) {
// Done closing
shadowLayer.y = maskLayer.y + maskLayer.height;
removeEventListener(Event.ENTER_FRAME, frameHandler);
}
}
}
}
/**
* This is called when your furni is unloaded.
*/
protected function handleUnload (event :Event) :void
{
// stop any sounds, clean up any resources that need it. This specifically includes
// unregistering listeners to any events - especially Event.ENTER_FRAME
if (hasEventListener(Event.ENTER_FRAME)) {
removeEventListener(Event.ENTER_FRAME, frameHandler);
}
}
protected var openImage:*;
protected var closedImage:*;
protected var state:String;
protected var speed:int = 10;
protected var _control :FurniControl;
protected var doorContainer:Sprite;
protected var maskLayer:DisplayObject;
protected var shadowLayer:*;
[Embed(source="door.swf")]
protected static const OPEN:Class;
[Embed(source="mask.png")]
protected static const MASK:Class;
}
}
|
/*
* Scratch Project Editor and Player
* Copyright (C) 2014 Massachusetts Institute of Technology
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/*
John:
[x] cursors for select and stamp mode
[x] deactivate when media library showing (so cursor doesn't disappear)
[ ] snap costume center to grid
[ ] allow larger pens (make size slider be non-linear)
[ ] when converting stage from bitmap to vector, trim white area (?)
[ ] minor: small shift when baking in after moving selection
[ ] add readout for pen size
[ ] add readout for zoom
*/
package svgeditor {
import flash.display.*;
import flash.events.*;
import flash.geom.*;
import scratch.ScratchCostume;
import svgeditor.objs.*;
import svgeditor.tools.*;
import svgutils.SVGElement;
import ui.parts.*;
import uiwidgets.*;
public class BitmapEdit extends ImageEdit {
public var stampMode:Boolean;
public static const bitmapTools:Array = [
{ name: 'bitmapBrush', desc: 'Brush' },
{ name: 'line', desc: 'Line' },
{ name: 'rect', desc: 'Rectangle', shiftDesc: 'Square' },
{ name: 'ellipse', desc: 'Ellipse', shiftDesc: 'Circle' },
{ name: 'text', desc: 'Text' },
{ name: 'paintbucket', desc: 'Fill with color' },
{ name: 'bitmapEraser', desc: 'Erase' },
{ name: 'bitmapSelect', desc: 'Select' },
];
private var offscreenBM:BitmapData;
public function BitmapEdit(app:Scratch, imagesPart:ImagesPart) {
super(app, imagesPart);
addStampTool();
setToolMode('bitmapBrush');
}
protected override function getToolDefs():Array { return bitmapTools }
protected override function onColorChange(e:Event):void {
var pencilTool:BitmapPencilTool = currentTool as BitmapPencilTool;
if (pencilTool) pencilTool.updateProperties();
super.onColorChange(e);
}
public override function shutdown():void {
super.shutdown();
// Bake and save costume
bakeIntoBitmap();
saveToCostume();
}
// -----------------------------
// Bitmap selection support
//------------------------------
public override function snapToGrid(toolsP:Point):Point {
var toolsLayer:Sprite = getToolsLayer();
var contentLayer:Sprite = workArea.getContentLayer();
var p:Point = contentLayer.globalToLocal(toolsLayer.localToGlobal(toolsP));
var roundedP:Point = workArea.getScale() == 1 ? new Point(Math.round(p.x), Math.round(p.y)) : new Point(Math.round(p.x * 2) / 2, Math.round(p.y * 2) / 2);
return toolsLayer.globalToLocal(contentLayer.localToGlobal(roundedP));
}
public function getSelection(r:Rectangle):SVGBitmap {
var bm:BitmapData = workArea.getBitmap().bitmapData;
r = r.intersection(bm.rect); // constrain selection to bitmap content
if ((r.width < 1) || (r.height < 1)) return null; // empty rectangle
var selectionBM:BitmapData = new BitmapData(r.width, r.height, true, 0);
selectionBM.copyPixels(bm, r, new Point(0, 0));
if (stampMode) {
highlightTool('bitmapSelect');
} else {
bm.fillRect(r, bgColor()); // cut out the selection
}
if (isScene) removeWhiteAroundSelection(selectionBM);
var el:SVGElement = SVGElement.makeBitmapEl(selectionBM, 0.5);
var result:SVGBitmap = new SVGBitmap(el, el.bitmap);
result.redraw();
result.x = r.x / 2;
result.y = r.y / 2;
workArea.getContentLayer().addChild(result);
return result;
}
private function removeWhiteAroundSelection(bm:BitmapData):void {
// Clear extra white pixels around the actual content when editing on the stage.
// Find the box around the non-white pixels
var r:Rectangle = bm.getColorBoundsRect(0xFFFFFFFF, 0xFFFFFFFF, false);
if ((r.width == 0) || (r.height == 0)) return; // if all white, do nothing
r.inflate(1, 1);
const corners:Array = [
new Point(r.x, r.y),
new Point(r.right, 0),
new Point(0, r.bottom),
new Point(r.right, r.bottom)
];
for each (var p:Point in corners) {
if (bm.getPixel(p.x, p.y) == 0xFFFFFF) bm.floodFill(p.x, p.y, 0);
}
}
protected override function selectHandler(evt:Event = null):void {
if ((currentTool is ObjectTransformer && !(currentTool as ObjectTransformer).getSelection())) {
// User clicked away from the object transformer, so bake it in.
bakeIntoBitmap();
saveToCostume();
}
var cropToolEnabled:Boolean = (currentTool is ObjectTransformer && !!(currentTool as ObjectTransformer).getSelection());
imagesPart.setCanCrop(cropToolEnabled);
}
public function cropToSelection():void {
var sel:Selection;
var transformTool:ObjectTransformer = currentTool as ObjectTransformer;
if (transformTool) {
sel = transformTool.getSelection();
}
if (sel) {
var bm:BitmapData = workArea.getBitmap().bitmapData;
bm.fillRect(bm.rect, 0);
app.runtime.shiftIsDown = false;
bakeIntoBitmap(false);
}
}
public function deletingSelection():void {
if (app.runtime.shiftIsDown) {
cropToSelection();
}
}
// -----------------------------
// Load and Save Costume
//------------------------------
protected override function loadCostume(c:ScratchCostume):void {
var bm:BitmapData = workArea.getBitmap().bitmapData;
bm.fillRect(bm.rect, bgColor()); // clear
var scale:Number = 2 / c.bitmapResolution;
var costumeBM:BitmapData = c.bitmapForEditor(isScene);
var destP:Point = isScene ?
new Point(0, 0) :
new Point(480 - (scale * c.rotationCenterX), 360 - (scale * c.rotationCenterY));
bm.copyPixels(costumeBM, costumeBM.rect, destP);
if (c.undoList.length == 0) {
recordForUndo(costumeBM, (scale * c.rotationCenterX), (scale * c.rotationCenterY));
}
}
public override function addCostume(c:ScratchCostume, destP:Point):void {
var el:SVGElement = SVGElement.makeBitmapEl(c.bitmapForEditor(isScene), 0.5);
var sel:SVGBitmap = new SVGBitmap(el, el.bitmap);
sel.redraw();
sel.x = destP.x - c.width() / 2;
sel.y = destP.y - c.height() / 2;
workArea.getContentLayer().addChild(sel);
setToolMode('bitmapSelect');
(currentTool as ObjectTransformer).select(new Selection([sel]));
}
public override function saveContent(evt:Event = null):void {
// Note: Don't save when there is an active selection or in text entry mode.
if (currentTool is ObjectTransformer) return;
if (currentTool is TextTool) return; // should select the text so it can be manipulated
bakeIntoBitmap();
saveToCostume();
}
private function saveToCostume():void {
// Note: Although the bitmap is double resolution, the rotation center is not doubled,
// since it is applied to the costume after the bitmap has been scaled down.
var c:ScratchCostume = targetCostume;
var bm:BitmapData = workArea.getBitmap().bitmapData;
if (isScene) {
c.setBitmapData(bm.clone(), bm.width / 2, bm.height / 2);
} else {
var r:Rectangle = bm.getColorBoundsRect(0xFF000000, 0, false);
var newBM:BitmapData;
if (r.width >= 1 && r.height >= 1) {
newBM = new BitmapData(r.width, r.height, true, 0);
newBM.copyPixels(bm, r, new Point(0, 0));
c.setBitmapData(newBM, Math.floor(480 - r.x), Math.floor(360 - r.y));
} else {
newBM = new BitmapData(2, 2, true, 0); // empty bitmap
c.setBitmapData(newBM, 0, 0);
}
}
recordForUndo(c.baseLayerBitmap.clone(), c.rotationCenterX, c.rotationCenterY);
Scratch.app.setSaveNeeded();
}
override public function setToolMode(newMode:String, bForce:Boolean = false, fromButton:Boolean = false):void {
imagesPart.setCanCrop(false);
highlightTool('none');
var obj:ISVGEditable = null;
if ((bForce || newMode != toolMode) && currentTool is SVGEditTool)
obj = (currentTool as SVGEditTool).getObject();
var prevToolMode:String = toolMode;
super.setToolMode(newMode, bForce, fromButton);
if (obj) {
if (!(currentTool is ObjectTransformer)) {
// User was editing an object and switched tools, bake the object
bakeIntoBitmap();
saveToCostume();
}
}
}
private function createdObjectIsEmpty():Boolean {
// Return true if the created object is empty (i.e. the user clicked without moving the mouse).
var content:Sprite = workArea.getContentLayer();
if (content.numChildren == 1) {
var svgShape:SVGShape = content.getChildAt(0) as SVGShape;
if (svgShape) {
var el:SVGElement = svgShape.getElement();
var attr:Object = el.attributes;
if (el.tag == 'ellipse') {
if (!attr.rx || (attr.rx < 1)) return true;
if (!attr.ry || (attr.ry < 1)) return true;
}
if (el.tag == 'rect') {
if (!attr.width || (attr.width < 1)) return true;
if (!attr.height || (attr.height < 1)) return true;
}
}
}
return false;
}
private function bakeIntoBitmap(doClear:Boolean = true):void {
// Render any content objects (text, circle, rectangle, line) into my bitmap.
// Note: Must do this at low quality setting to avoid antialiasing.
var content:Sprite = workArea.getContentLayer();
if (content.numChildren == 0) return; // nothing to bake in
var bm:BitmapData = workArea.getBitmap().bitmapData;
if (bm && (content.numChildren > 0)) {
var m:Matrix = new Matrix();
m = content.getChildAt(0).transform.matrix.clone();
m.scale(2, 2);
var oldQuality:String = stage.quality;
if (!Scratch.app.runtime.shiftIsDown) stage.quality = StageQuality.LOW;
for (var i:int = 0; i < content.numChildren; i++) {
var el:DisplayObject = content.getChildAt(i) as DisplayObject;
var textEl:SVGTextField = el as SVGTextField;
if (textEl && !Scratch.app.runtime.shiftIsDown) {
// Even in LOW quality mode, text is anti-aliased.
// This code forces it to have sharp edges for ease of using the paint bucket.
const threshold:int = 0x60 << 24;
var c:int = 0xFF000000 | textEl.textColor;
clearOffscreenBM();
offscreenBM.draw(el, m, null, null, null, true);
// force pixels above threshold to be text color, alpha 1.0
offscreenBM.threshold(
offscreenBM, offscreenBM.rect, new Point(0, 0),
'>', threshold, c, 0xFF000000, false);
// force pixels below threshold to be transparent
offscreenBM.threshold(
offscreenBM, offscreenBM.rect, new Point(0, 0),
'<=', threshold, 0, 0xFF000000, false);
// copy result into work bitmap
bm.draw(offscreenBM);
} else {
bm.draw(el, m, null, null, null, true);
}
}
stage.quality = oldQuality;
}
if (doClear) workArea.clearContent();
stampMode = false;
}
private function clearOffscreenBM():void {
var bm:BitmapData = workArea.getBitmap().bitmapData;
if (!offscreenBM ||
(offscreenBM.width != bm.width) ||
(offscreenBM.height != bm.height)) {
offscreenBM = new BitmapData(bm.width, bm.height, true, 0);
return;
}
offscreenBM.fillRect(offscreenBM.rect, 0);
}
// -----------------------------
// Set costume center support
//------------------------------
public override function translateContents(x:Number, y:Number):void {
var bm:BitmapData = workArea.getBitmap().bitmapData;
var newBM:BitmapData = new BitmapData(bm.width, bm.height, true, 0);
newBM.copyPixels(bm, bm.rect, new Point(Math.round(2 * x), Math.round(2 * y)));
workArea.getBitmap().bitmapData = newBM;
}
// -----------------------------
// Stamp and Flips
//------------------------------
private function addStampTool():void {
const buttonSize:Point = new Point(37, 33);
var lastTool:DisplayObject = toolButtonsLayer.getChildAt(toolButtonsLayer.numChildren - 1);
var btn:IconButton = new IconButton(
stampBitmap,
SoundsPart.makeButtonImg('bitmapStamp', true, buttonSize),
SoundsPart.makeButtonImg('bitmapStamp', false, buttonSize));
btn.x = 0;
btn.y = lastTool.y + lastTool.height + 4;
SimpleTooltips.add(btn, {text: 'Select and duplicate', direction: 'right'});
registerToolButton('bitmapStamp', btn);
toolButtonsLayer.addChild(btn);
}
private function stampBitmap(ignore:*):void {
setToolMode('bitmapBrush');
setToolMode('bitmapSelect');
highlightTool('bitmapStamp');
stampMode = true;
}
protected override function flipAll(vertical:Boolean):void {
var oldBM:BitmapData = workArea.getBitmap().bitmapData;
var newBM:BitmapData = new BitmapData(oldBM.width, oldBM.height, true, 0);
var m:Matrix = new Matrix();
if (vertical) {
m.scale(1, -1);
m.translate(0, oldBM.height);
} else {
m.scale(-1, 1);
m.translate(oldBM.width, 0);
}
newBM.draw(oldBM, m);
workArea.getBitmap().bitmapData = newBM;
saveToCostume();
}
private function getBitmapSelection():SVGBitmap {
var content:Sprite = workArea.getContentLayer();
for (var i:int = 0; i < content.numChildren; i++) {
var svgBM:SVGBitmap = content.getChildAt(i) as SVGBitmap;
if (svgBM) return svgBM;
}
return null;
}
// -----------------------------
// Grow/Shrink Tool Support
//------------------------------
public function scaleAll(scale:Number):void {
var bm:BitmapData = workArea.getBitmap().bitmapData;
var r:Rectangle = isScene ?
bm.getColorBoundsRect(0xFFFFFFFF, 0xFFFFFFFF, false) :
bm.getColorBoundsRect(0xFF000000, 0, false);
var newBM:BitmapData = new BitmapData(Math.max(1, r.width * scale), Math.max(1, r.height * scale), true, bgColor());
var m:Matrix = new Matrix();
m.translate(-r.x, -r.y);
m.scale(scale, scale);
newBM.draw(bm, m);
var destP:Point = new Point(r.x - ((r.width * (scale - 1)) / 2), r.y - ((r.height * (scale - 1)) / 2));
bm.fillRect(bm.rect, bgColor());
bm.copyPixels(newBM, newBM.rect, destP);
saveToCostume();
}
// -----------------------------
// Clear/Undo/Redo
//------------------------------
override protected function clearSelection():void {
// Re-activate the tool that (looks like) it's currently active
// If there's an uncommitted action, this will commit it in the same way that changing the tool would.
setToolMode(lastToolMode ? lastToolMode : toolMode, true);
}
public override function canClearCanvas():Boolean {
// True if canvas has any marks.
var bm:BitmapData = workArea.getBitmap().bitmapData;
var r:Rectangle = bm.getColorBoundsRect(0xFFFFFFFF, bgColor(), false);
return (r.width > 0) && (r.height > 0);
}
public override function clearCanvas(ignore:* = null):void {
setToolMode('bitmapBrush');
var bm:BitmapData = workArea.getBitmap().bitmapData;
bm.fillRect(bm.rect, bgColor());
super.clearCanvas();
}
private function bgColor():int { return isScene ? 0xFFFFFFFF : 0 }
protected override function restoreUndoState(undoRec:Array):void {
var c:ScratchCostume = targetCostume;
c.setBitmapData(undoRec[0], undoRec[1], undoRec[2]);
loadCostume(c);
}
}}
|
package kabam.rotmg.protip.view {
import com.gskinner.motion.GTween;
import flash.display.Sprite;
import flash.filters.GlowFilter;
public class ProTipView extends Sprite {
public function ProTipView() {
super();
this.text = new ProTipText();
this.text.x = 300;
this.text.y = 125;
addChild(this.text);
filters = [new GlowFilter(0, 1, 3, 3, 2, 1)];
mouseEnabled = false;
mouseChildren = false;
}
private var text:ProTipText;
public function setTip(param1:String):void {
this.text.setTip(param1);
var _loc2_:GTween = new GTween(this, 5, {"alpha": 0});
_loc2_.delay = 5;
_loc2_.onComplete = this.removeSelf;
}
private function removeSelf(param1:GTween):void {
}
}
}
|
package test {
public class ASCompleteTest {
public function ASCompleteTest(v:String) {
(v is String).$(EntryPoint)
}
}
} |
package kabam.rotmg.startup.model.impl {
import kabam.lib.tasks.Task;
import kabam.rotmg.startup.model.api.StartupDelegate;
import org.swiftsuspenders.Injector;
public class TaskDelegate implements StartupDelegate {
public var injector:Injector;
public var taskClass:Class;
public var priority:int;
public function getPriority():int {
return (this.priority);
}
public function make():Task {
return (this.injector.getInstance(this.taskClass));
}
}
}
|
package com.playfab
{
import com.playfab.ExperimentationModels.*;
public class PlayFabExperimentationAPI
{
public static function CreateExperiment(request:CreateExperimentRequest, onComplete:Function, onError:Function):void
{
if (PlayFabSettings.EntityToken == null) throw new Error("Must call GetEntityToken to call this method");
var requetJson:String = JSON.stringify( request );
var onPostComplete:Function = function(resultData:Object, error:PlayFabError):void
{
if(error)
{
if(onError != null)
onError(error);
if(PlayFabSettings.GlobalErrorHandler != null)
PlayFabSettings.GlobalErrorHandler(error);
}
else
{
var result:CreateExperimentResult = new CreateExperimentResult(resultData);
if(onComplete != null)
onComplete(result);
}
}
PlayFabHTTP.post(PlayFabSettings.GetURL("/Experimentation/CreateExperiment"), requetJson, "X-EntityToken", PlayFabSettings.EntityToken, onPostComplete);
}
public static function DeleteExperiment(request:DeleteExperimentRequest, onComplete:Function, onError:Function):void
{
if (PlayFabSettings.EntityToken == null) throw new Error("Must call GetEntityToken to call this method");
var requetJson:String = JSON.stringify( request );
var onPostComplete:Function = function(resultData:Object, error:PlayFabError):void
{
if(error)
{
if(onError != null)
onError(error);
if(PlayFabSettings.GlobalErrorHandler != null)
PlayFabSettings.GlobalErrorHandler(error);
}
else
{
var result:EmptyResponse = new EmptyResponse(resultData);
if(onComplete != null)
onComplete(result);
}
}
PlayFabHTTP.post(PlayFabSettings.GetURL("/Experimentation/DeleteExperiment"), requetJson, "X-EntityToken", PlayFabSettings.EntityToken, onPostComplete);
}
public static function GetExperiments(request:GetExperimentsRequest, onComplete:Function, onError:Function):void
{
if (PlayFabSettings.EntityToken == null) throw new Error("Must call GetEntityToken to call this method");
var requetJson:String = JSON.stringify( request );
var onPostComplete:Function = function(resultData:Object, error:PlayFabError):void
{
if(error)
{
if(onError != null)
onError(error);
if(PlayFabSettings.GlobalErrorHandler != null)
PlayFabSettings.GlobalErrorHandler(error);
}
else
{
var result:GetExperimentsResult = new GetExperimentsResult(resultData);
if(onComplete != null)
onComplete(result);
}
}
PlayFabHTTP.post(PlayFabSettings.GetURL("/Experimentation/GetExperiments"), requetJson, "X-EntityToken", PlayFabSettings.EntityToken, onPostComplete);
}
public static function GetLatestScorecard(request:GetLatestScorecardRequest, onComplete:Function, onError:Function):void
{
if (PlayFabSettings.EntityToken == null) throw new Error("Must call GetEntityToken to call this method");
var requetJson:String = JSON.stringify( request );
var onPostComplete:Function = function(resultData:Object, error:PlayFabError):void
{
if(error)
{
if(onError != null)
onError(error);
if(PlayFabSettings.GlobalErrorHandler != null)
PlayFabSettings.GlobalErrorHandler(error);
}
else
{
var result:GetLatestScorecardResult = new GetLatestScorecardResult(resultData);
if(onComplete != null)
onComplete(result);
}
}
PlayFabHTTP.post(PlayFabSettings.GetURL("/Experimentation/GetLatestScorecard"), requetJson, "X-EntityToken", PlayFabSettings.EntityToken, onPostComplete);
}
public static function GetTreatmentAssignment(request:GetTreatmentAssignmentRequest, onComplete:Function, onError:Function):void
{
if (PlayFabSettings.EntityToken == null) throw new Error("Must call GetEntityToken to call this method");
var requetJson:String = JSON.stringify( request );
var onPostComplete:Function = function(resultData:Object, error:PlayFabError):void
{
if(error)
{
if(onError != null)
onError(error);
if(PlayFabSettings.GlobalErrorHandler != null)
PlayFabSettings.GlobalErrorHandler(error);
}
else
{
var result:GetTreatmentAssignmentResult = new GetTreatmentAssignmentResult(resultData);
if(onComplete != null)
onComplete(result);
}
}
PlayFabHTTP.post(PlayFabSettings.GetURL("/Experimentation/GetTreatmentAssignment"), requetJson, "X-EntityToken", PlayFabSettings.EntityToken, onPostComplete);
}
public static function StartExperiment(request:StartExperimentRequest, onComplete:Function, onError:Function):void
{
if (PlayFabSettings.EntityToken == null) throw new Error("Must call GetEntityToken to call this method");
var requetJson:String = JSON.stringify( request );
var onPostComplete:Function = function(resultData:Object, error:PlayFabError):void
{
if(error)
{
if(onError != null)
onError(error);
if(PlayFabSettings.GlobalErrorHandler != null)
PlayFabSettings.GlobalErrorHandler(error);
}
else
{
var result:EmptyResponse = new EmptyResponse(resultData);
if(onComplete != null)
onComplete(result);
}
}
PlayFabHTTP.post(PlayFabSettings.GetURL("/Experimentation/StartExperiment"), requetJson, "X-EntityToken", PlayFabSettings.EntityToken, onPostComplete);
}
public static function StopExperiment(request:StopExperimentRequest, onComplete:Function, onError:Function):void
{
if (PlayFabSettings.EntityToken == null) throw new Error("Must call GetEntityToken to call this method");
var requetJson:String = JSON.stringify( request );
var onPostComplete:Function = function(resultData:Object, error:PlayFabError):void
{
if(error)
{
if(onError != null)
onError(error);
if(PlayFabSettings.GlobalErrorHandler != null)
PlayFabSettings.GlobalErrorHandler(error);
}
else
{
var result:EmptyResponse = new EmptyResponse(resultData);
if(onComplete != null)
onComplete(result);
}
}
PlayFabHTTP.post(PlayFabSettings.GetURL("/Experimentation/StopExperiment"), requetJson, "X-EntityToken", PlayFabSettings.EntityToken, onPostComplete);
}
public static function UpdateExperiment(request:UpdateExperimentRequest, onComplete:Function, onError:Function):void
{
if (PlayFabSettings.EntityToken == null) throw new Error("Must call GetEntityToken to call this method");
var requetJson:String = JSON.stringify( request );
var onPostComplete:Function = function(resultData:Object, error:PlayFabError):void
{
if(error)
{
if(onError != null)
onError(error);
if(PlayFabSettings.GlobalErrorHandler != null)
PlayFabSettings.GlobalErrorHandler(error);
}
else
{
var result:EmptyResponse = new EmptyResponse(resultData);
if(onComplete != null)
onComplete(result);
}
}
PlayFabHTTP.post(PlayFabSettings.GetURL("/Experimentation/UpdateExperiment"), requetJson, "X-EntityToken", PlayFabSettings.EntityToken, onPostComplete);
}
}
}
|
/* 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/. */
// imports must be first statments
import DefaultClass.*;
import com.adobe.test.Assert;
// var SECTION = "Definitions"; // provide a document reference (ie, ECMA section)
// var VERSION = "AS 3.0"; // Version of JavaScript or ECMA
// var TITLE = "public extend Default Class"; // Provide ECMA section title or a description
var BUGNUMBER = "";
/**
* Calls to Assert.expectEq here. Assert.expectEq is a function that is defined
* in shell.js and takes three arguments:
* - a string representation of what is being tested
* - the expected result
* - the actual result
*
* For example, a test might look like this:
*
* var helloWorld = "Hello World";
*
* Assert.expectEq(
* "var helloWorld = 'Hello World'", // description of the test
* "Hello World", // expected result
* helloWorld ); // actual result
*
*/
arr = new Array(1, 2, 3);
//*******************************************
// access public static method of parent
// class from outside of class
//*******************************************
Assert.expectEq( "*** Public Static Methods and Public Static properites ***", 1, 1 );
//Assert.expectEq( "PubExtDefaultClassPubStat.setStatArray(arr), PubExtDefaultClassPubStat.statArray", arr,
// (PubExtDefaultClassPubStat.setStatArray(arr), PubExtDefaultClassPubStat.statArray) );
// ********************************************
// access public static method from a default
// method of a sub class
//
// ********************************************
EXTDCLASS = new PubExtDefaultClassPubStat();
Assert.expectEq( "*** Access public static method from default method of sub class ***", 1, 1 );
Assert.expectEq( "EXTDCLASS.subSetArray(arr), EXTDCLASS.subGetArray()", arr, EXTDCLASS.testSubGetSetArray(arr) );
// <TODO> fill in the rest of the cases here
// ********************************************
// access public static method from a public
// method of a sub class
//
// ********************************************
EXTDCLASS = new PubExtDefaultClassPubStat();
Assert.expectEq( "*** Access public static method from public method of sub class ***", 1, 1 );
Assert.expectEq( "EXTDCLASS.pubSubSetArray(arr), EXTDCLASS.pubSubGetArray()", arr, (EXTDCLASS.pubSubSetArray(arr), EXTDCLASS.pubSubGetArray()) );
// <TODO> fill in the rest of the cases here
// ********************************************
// access public static method from a private
// method of a sub class
//
// ********************************************
EXTDCLASS = new PubExtDefaultClassPubStat();
Assert.expectEq( "*** Access public static method from private method of sub class ***", 1, 1 );
Assert.expectEq( "EXTDCLASS.testPrivSubArray(arr)", arr, EXTDCLASS.testPrivSubArray(arr) );
// <TODO> fill in the rest of the cases here
// ********************************************
// access public static method from a final
// method of a sub class
//
// ********************************************
EXTDCLASS = new PubExtDefaultClassPubStat();
Assert.expectEq( "*** Access public static method from final method of sub class ***", 1, 1 );
Assert.expectEq( "EXTDCLASS.testFinSubArray(arr)", arr, EXTDCLASS.testFinSubArray(arr) );
// ********************************************
// access public static method from a static
// method of a sub class
//
// ********************************************
Assert.expectEq( "*** Access public static method from static method of sub class ***", 1, 1 );
Assert.expectEq( "PubExtDefaultClassPubStat.testStatSubArray(arr)", arr, PubExtDefaultClassPubStat.testStatSubArray(arr));
// <TODO> fill in the rest of the cases here
// ********************************************
// access public static method from a public static
// method of a sub class
//
// ********************************************
Assert.expectEq( "*** Access public static method from public static method of sub class ***", 1, 1 );
Assert.expectEq( "PubExtDefaultClassPubStat.pubStatSubSetArray(arr), PubExtDefaultClassPubStat.pubStatSubGetArray()", arr,
(PubExtDefaultClassPubStat.pubStatSubSetArray(arr), PubExtDefaultClassPubStat.pubStatSubGetArray()) );
// <TODO> fill in the rest of the cases here
// ********************************************
// access public static method from a private static
// method of a sub class
//
// ********************************************
Assert.expectEq( "*** Access public static method from private static method of sub class ***", 1, 1 );
Assert.expectEq( "PubExtDefaultClassPubStat.testPrivStatSubArray(arr)", arr, PubExtDefaultClassPubStat.testPrivStatSubArray(arr) );
// <TODO> fill in the rest of the cases here
// ********************************************
// access public static property from
// default method in sub class
// ********************************************
EXTDCLASS = new PubExtDefaultClassPubStat();
Assert.expectEq( "*** Access public static property from default method in sub class ***", 1, 1 );
Assert.expectEq( "EXTDCLASS.subSetDPArray(arr), EXTDCLASS.subGetDPArray()", arr, EXTDCLASS.testSubGetSetDPArray(arr) );
// <TODO> fill in the rest of the cases here
// ********************************************
// access public static property from
// public method in sub class
// ********************************************
EXTDCLASS = new PubExtDefaultClassPubStat();
Assert.expectEq( "*** Access public static property from public method in sub class ***", 1, 1 );
Assert.expectEq( "EXTDCLASS.pubSubSetDPArray(arr), EXTDCLASS.pubSubGetDPArray()", arr, (EXTDCLASS.pubSubSetDPArray(arr), EXTDCLASS.pubSubGetDPArray()) );
// <TODO> fill in the rest of the cases here
// ********************************************
// access public static property from
// private method in sub class
// ********************************************
EXTDCLASS = new PubExtDefaultClassPubStat();
Assert.expectEq( "*** Access public static property from private method in sub class ***", 1, 1 );
Assert.expectEq( "EXTDCLASS.privSubSetDPArray(arr), EXTDCLASS.privSubGetDPArray()", arr, EXTDCLASS.testPrivSubDPArray(arr) );
// <TODO> fill in the rest of the cases here
// ********************************************
// access public static property from
// final method in sub class
// ********************************************
EXTDCLASS = new PubExtDefaultClassPubStat();
Assert.expectEq( "*** Access public static property from final method in sub class ***", 1, 1 );
Assert.expectEq( "EXTDCLASS.finSubSetDPArray(arr), EXTDCLASS.finSubGetDPArray()", arr, EXTDCLASS.testFinSubDPArray(arr) );
// ********************************************
// access public static property from
// static method in sub class
// ********************************************
Assert.expectEq( "*** Access public static property from static method in sub class ***", 1, 1 );
Assert.expectEq( "PubExtDefaultClassPubStat.statSubSetSPArray(arr), PubExtDefaultClassPubStat.statSubGetSPArray()", arr,PubExtDefaultClassPubStat.testStatSubSPArray(arr) );
// ********************************************
// access public static property from
// public static method in sub class
// ********************************************
Assert.expectEq( "*** Access public static property from public static method in sub class ***", 1, 1 );
Assert.expectEq( "PubExtDefaultClassPubStat.pubStatSubSetSPArray(arr), PubExtDefaultClassPubStat.pubStatSubGetSPArray()", arr,
(PubExtDefaultClassPubStat.pubStatSubSetSPArray(arr), PubExtDefaultClassPubStat.pubStatSubGetSPArray()) );
// ********************************************
// access public static property from
// private static method in sub class
// ********************************************
Assert.expectEq( "*** Access public static property from private static method in sub class ***", 1, 1 );
Assert.expectEq( "PubExtDefaultClassPubStat.testPrivStatSubPArray(arr)", arr, PubExtDefaultClassPubStat.testPrivStatSubPArray(arr));
// <TODO> fill in the rest of the cases here
// displays results.
|
/* Copyright (c) 2006-2013 Regents of the University of Minnesota.
For licensing terms, see the file LICENSE. */
// A Set class.
//
// NOTE: Set is a Dictionary that maintains itself as this[x] = x. This means
// that both types of for loops can be used (for-in and for-each).
// The for-in will not have the proper types because it loops over the
// stringified keys of the Set. It is highly recommended to use
// for-each for performance, and parity with Array.
//
// for-in can be used if tampering is done with the value stored in
// the Set for each key (i.e. see Update_Base).
//
// WARNING: While use of square brackets on Sets will compile, do not use
// them. It will screw up the length value.
//
// WARNING: This class still have some weird shit going on so use with caution.
// In particular, you can't put strings or ints in it (!!!), and
// members are compared with the strict equality operator (===). [rp]
// 2010.09.01: Declaring this class dynamic should solve [rp]'s problem. [lb]
//
// NOTE: This class must be declared dynamic for the [] operator to work right.
package utils.misc {
import flash.utils.Dictionary;
import mx.utils.UIDUtil;
// NOTE: This class is dynamic because that's what you do when you extend
// Dictionary or Array.
public dynamic class Set_UUID extends Dictionary {
// *** Class attributes
protected static var log:Logging = Logging.get_logger('Set_UUID__');
// *** Instance variables
protected var length_:int; // number of items in the set
// *** Constructor
public function Set_UUID(members:Array=null)
{
var obj:Object;
super();
this.length_ = 0;
if (members !== null) {
for each (obj in members) {
this.add(obj);
}
}
}
// *** Getters and setters
//
public function get empty() :Boolean
{
return (this.length_ == 0);
}
//
public function get length() :int
{
return this.length_;
}
// *** Instance methods
//
public function add(x:*) :String
{
// Flex is weird. If you getUID on an Array, the UID becomes part
// of any 'for' or 'for each' loop. And -- to boot -- the Array
// length remains unchanged. [lb] is surprised not to find this topic
// Googleable, but cursory debugging showed it to be true.
m4_ASSERT(!(x is Array));
// The solution is probably to implement the IUID interface and
// return one's own UID. See: mx_internal_uid.
// http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/core/IUID.html
var uuid:String = UIDUtil.getUID(x);
if (!(uuid in this)) {
// Add an entry to the database.
// NOTE: We used to not care about the value we set, so it used to
// be null. Now, it's set to the object itself, such that we
// can iterate over the Set using for-each, which is quicker
// and easier to work with than for-in-ing.
this[uuid] = x;
this.length_++;
}
return uuid;
}
//
/*
public function add(x:Object) :void
{
var s:String;
var obj:*;
if (x is String) {
s = x as String;
if (!(s in this)) {
this[s] = 1;
this.length_++;
}
}
else {
//obj = x as *;
obj = x;
if (!(obj in this)) {
this[obj] = 1;
this.length_++;
}
}
}
*/
//
public function add_all(a:*) :void
{
var obj:Object;
if (a !== null) {
for each (obj in a) {
this.add(obj);
}
}
}
// Return an array containing my members.
public function as_Array() :Array
{
var a:Array = new Array();
var obj:Object;
for each (obj in this) {
a.push(obj);
}
return a;
}
//
public function clear() :void
{
var clone:Set_UUID = this.clone();
var obj:Object;
for each (obj in clone) {
this.remove(obj);
}
}
// Return a shallow copy of myself.
public function clone() :Set_UUID
{
var s:Set_UUID = new Set_UUID();
var obj:Object;
for each (obj in this) {
s.add(obj);
}
return s;
}
// Returns true if item is in the set.
public function contains(item:Object) :Boolean
{
return this.is_member(item);
}
// Returns true if at all items in itms are in the set.
public function contains_all(itms:*) :Boolean
{
var contains_all:Boolean = true;
for each (var item:Object in itms) {
if (!this.is_member(item)) {
contains_all = false;
break;
}
}
return contains_all;
}
// Returns true if at least one item in itms is in the set.
public function contains_any(itms:*) :Boolean
{
var contains_at_least_one:Boolean = false;
for each (var item:Object in itms) {
if (this.is_member(item)) {
contains_at_least_one = true;
break;
}
}
return contains_at_least_one;
}
// How Python defines difference:
// "Return a new set with elements in the set that are not in others."
public function difference(...others) :Set_UUID
{
var the_diff:Set_UUID = this.clone();
var obj:Object;
var another_set:Set_UUID;
if (others[0] is Array) {
m4_ASSERT(others.length == 1);
others = others[0];
}
for each (another_set in others) {
for each (obj in another_set) {
the_diff.remove(obj);
}
}
return the_diff;
}
// NOTE: The name and info of this fcn. ripped off of Python's set().
// "Return a new set with elements in either the set or other but not
// both."
public function equals(other:Set_UUID) :Boolean
{
var is_equal:Boolean = (this.length == other.length);
var obj:Object;
var uuid:String;
if (is_equal) {
for each (obj in this) {
uuid = UIDUtil.getUID(obj);
if (!(uuid in other)) {
// m4_DEBUG('equals: no: !(obj in other):', obj);
is_equal = false;
break;
}
}
}
if (is_equal) {
for each (obj in other) {
uuid = UIDUtil.getUID(obj);
if (!(uuid in this)) {
// m4_DEBUG('equals: no: !(obj in this):', obj);
is_equal = false;
break;
}
}
}
return is_equal;
}
// "Executes a test function on each item in the array until an item is
// reached that returns false for the specified function."
// [C.f. Flex Array documentation.]
public function every(callback:Function, thisObject:*=null) :Boolean
{
var result:Boolean = true;
var obj:Object;
for each (obj in this) {
result = callback(obj, this);
if (!result) {
break;
}
}
return result;
}
//
public function extend(a:*) :void
{
this.add_all(a);
}
// Returns true if item is in the set.
public function is_member(item:Object) :Boolean
{
var uuid:String = UIDUtil.getUID(item);
return (uuid in this);
}
// Return an arbitrary member of myself. Behavior undefined if I have no
// members.
public function item_get_random() :Object
{
var obj:Object = null;
if (this.length > 0) {
for each (obj in this) {
break; // just grab the first one
}
}
return obj;
}
// If the Set_UUID has just zero or one member(s), returns null or the
// member. If the Set_UUID contains two or more members, throws an error.
public function one() :Object
{
//trace('Set_UUID: one: this.length:', this.length);
m4_ASSERT(this.length < 2);
return this.item_get_random();
}
//
public function remove(x:*) :void
{
var uuid:String = UIDUtil.getUID(x);
if (uuid in this) {
this.length_--;
delete this[uuid];
}
}
//
public function toString(use_newlines:Boolean=false) :String
{
var key_uuid:String;
var set_contents:String = '';
// NOTE: Not 'for each'
for (key_uuid in this) {
if (set_contents != '') {
if (!use_newlines) {
set_contents += ', ';
}
else {
set_contents += '\n';
}
}
set_contents += this[key_uuid];
}
return set_contents;
}
//
public function union(...others) :Set_UUID
{
var the_union:Set_UUID = this.clone();
var obj:Object;
var another_set:Set_UUID;
if (others[0] is Array) {
m4_ASSERT(others.length == 1);
others = others[0];
}
for each (another_set in others) {
for each (obj in another_set) {
the_union.add(obj);
}
}
return the_union;
}
}
}
|
package com.ixiyou.speUI.mcontrols
{
import com.ixiyou.speUI.collections.skins.ProgressBarSkin;
import com.ixiyou.speUI.core.ISkinComponent;
import com.ixiyou.speUI.collections.MSprite;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.Loader
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.text.TextField;
import flash.utils.getTimer;
[Event(name="complete",type="flash.events.Event")]
[Event(name="io_error",type="flash.events.IOErrorEvent")]
/**
* 进度条组件
* @author spe
*/
public class MProgressBar extends MSprite implements ISkinComponent
{
//加载对象
protected var _target:EventDispatcher;
protected var startTime:int;
protected var _bytesLoaded:int;
protected var _bytesTotal:int;
//进度条皮肤
protected var _skin:*
protected var _progerss:MovieClip
protected var _text:TextField
//文本显示模式
public var mode:uint=1
public function MProgressBar(config:*=null)
{
super(config)
if (config) {
if (config.skin != null) skin = config.skin
if(config.mode!=null)mode=config.mode
if(config.target != null)target=config.target
}
if(skin==null )skin=null
}
/**设置组件皮肤*/
public function get skin():*{return _skin}
public function set skin(value:*):void {
if (value is Sprite) {
try {
var _skinSpr:Sprite
if(_skin&&this.contains(_skin as Sprite))removeChild(_skin as Sprite)
_skinSpr=_skin = value as Sprite;
_skinSpr.x = _skinSpr.y = 0;
addChild(_skinSpr);
if (_skinSpr.getChildByName('_text'))_text = _skinSpr.getChildByName('_text') as TextField;
if (_skinSpr.getChildByName('_progerss'))_progerss = _skinSpr.getChildByName('_progerss') as MovieClip
_progerss.stop()
setSize(_skinSpr.width,_skinSpr.height)
//upSize()
}catch (e:TypeError) {
skin=new ProgressBarSkin()
}
}else if (value == null){skin=new ProgressBarSkin()}
}
/**
* 大小更新
*/
override public function upSize():void {
trace('MProgressBar', width, height);
}
/**
* 设置进度条目标。请在load方法执行前设置。
*
* @return
*
*/
public function get target():EventDispatcher{return _target;}
public function set target(value:EventDispatcher):void
{
if (_target == value) return;
removeEvents()
_target = value
_target.addEventListener(Event.OPEN,openHandler);
_target.addEventListener(ProgressEvent.PROGRESS,progressHandler);
_target.addEventListener(Event.COMPLETE,completeHandler);
_target.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
startTime = getTimer()
}
/**
* 开始加载
* @param event
*/
private function openHandler(event:Event):void
{
startTime = getTimer();
}
/**
* 加载进度
* @param event
*/
private function progressHandler(event:ProgressEvent):void
{
_bytesLoaded = event.bytesLoaded;
_bytesTotal = event.bytesTotal;
var str:String
if (_text) {
if (mode == 1) {
str=(loadPercent * 100).toFixed(1) + "%"
}else if (mode == 2) {
str=bytesLoaded + "/" + bytesTotal
}else {
str= (loadPercent * 100).toFixed(1) + "%" +
"(" + bytesLoaded + "/" + bytesTotal + ")";
str += "\n已用时:" + progressTimeString +
"\n预计剩余时间:" + progressNeedTimeString;
}
_text.text=str
}
if (_progerss) {
_progerss.gotoAndStop((event.bytesLoaded/event.bytesTotal* 100)>>0)
}
this.dispatchEvent(event);
}
/**
* 加载完成
* @param event
*/
private function completeHandler(event:Event):void
{
//"加载完成";
if (_progerss) _progerss.gotoAndStop(100)
if (_text)_text.text="加载完成"
removeEvents();
this.dispatchEvent(event);
}
/**
* 加载出现错误
* @param event
*/
private function ioErrorHandler(event:IOErrorEvent):void
{
//"加载失败";
if (_text)_text.text="加载失败"
removeEvents();
this.dispatchEvent(event);
}
/**
* 删除事件
*/
private function removeEvents():void
{
if (target)
{
target.removeEventListener(Event.OPEN,openHandler);
target.removeEventListener(ProgressEvent.PROGRESS,progressHandler);
target.removeEventListener(Event.COMPLETE,completeHandler);
target.removeEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
}
}
/**
* 已加载的字节数
*
* @return
*
*/
public function get bytesLoaded():int{return _bytesLoaded;}
/**
* 总字节数
*
* @return
*
*/
public function get bytesTotal():int{ return _bytesTotal;}
/**
* 当前进度百分比
*/
public function get loadPercent():Number
{
return bytesLoaded/bytesTotal;
}
/**
* 加载已经用的时间
*
* @return
*
*/
public function get progressTime():int { return getTimer() - startTime; }
public function get progressTimeString():String{ return timeToString(progressTime)}
/**
* 预计还需要的时间
*
* @return
*
*/
public function get progressNeedTime():int{return progressTime * (1 / loadPercent - 1);}
public function get progressNeedTimeString():String{return timeToString(progressNeedTime)}
/**
* 把时间转换成格式化得样式
* @param t
* @return
*/
private function timeToString(t:int):String
{
t /= 1000;
var min:int = int(t / 60);
var sec:int = t % 60;
return (min>0)?(min.toString()+"分"):""+sec.toString()+"秒";
}
/**
* 摧毁
*/
override public function destory():void
{
super.destory();
removeEvents();
}
}
} |
package com.gestureworks.cml.elements
{
import com.gestureworks.cml.events.StateEvent;
import com.gestureworks.cml.utils.Waveform;
import com.adobe.xmp.core.XMPConst;
import com.adobe.xmp.core.XMPMeta;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.SampleDataEvent;
import flash.events.TimerEvent;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundTransform;
import flash.net.URLLoader;
import flash.net.URLStream;
import flash.utils.ByteArray;
import flash.net.URLRequest;
import flash.utils.Endian;
import flash.utils.Timer;
import flash.net.URLLoaderDataFormat;
/**
* The WAV element is an AIR required element that loads in a .WAV file and plays it, with the options to pause, stop, and resume play. The WAV element will automatically load any XMP data
* if it is present. The WAV element also provides the option of a graphical waveform by setting the display property to "waveform", otherwise "none". The waveform's color can be set.
*
* <p>To use the WavElement, it absolutely MUST be compiled in an AIR project.</p>
*
* <codeblock xml:space="preserve" class="+ topic/pre pr-d/codeblock ">
*
var wavElement:WavElement = new WavElement();
wavElement.open("FDR-Infamy.wav");
wavElement.autoplay = true;
wavElement.display = "waveform";
wavElement.volume = 0.5;
addChild(wavElement);
wavElement.init();
*
* </codeblock>
* @author Ideum
*/
public class WAV extends TouchContainer
{
private var urlLoader:URLLoader;
private var waveSound:flash.media.Sound;
private var channel:SoundChannel;
private var soundTrans:SoundTransform;
private var Position:uint;
private var loading:Boolean = false;
private var waveForm:Waveform;
private var _loaded:Boolean;
private var bgGraphic:Sprite;
private var bytes:ByteArray;
private var _invalidError:Error;
// update timer
private var _timerFormated:String = "00:00";
public static var TIME:String = "Time";
public var timer:Timer;
/**
* Cue start byte position
* @default null
*/
private var _cueStreamStart:Number;
/**
* Constructor
*/
public function WAV()
{
super();
mouseChildren = true;
//propertyDefaults();
_averageGain = new Array();
}
private var _channels:uint = 0;
/**
* Number of audio channels
* @default 0
*/
public function get channels():uint { return _channels; }
private var _printData:Boolean;
/**
* print data
*/
public function get printData():Boolean { return _printData; }
public function set printData(val:Boolean):void { _printData = val; }
private var _cueStart:Number = 0;
/**
* Cue start point in milliseconds
* @default 0
*/
public function get cueStart():Number { return _cueStart; }
public function set cueStart(val:Number):void { _cueStart = val; }
private var _byteRate:uint = 0;
/**
* Audio byte rate (bytes per second)
* @default 0
*/
public function get byteRate():uint { return _byteRate; }
private var _bufferSize:uint = 2048;
/**
* Audio buffer size
* @default 2048
*/
public function get bufferSize():uint { return _bufferSize; }
public function set bufferSize(val:uint):void {
if (val == 2048 || val == 4096 || val == 8192)
_bufferSize = val;
else
throw new Error("Buffer size must be a power of two. (Use: 2048, 4096, or 8192)");
}
private var _backgroundColor:uint = 0x333333;
/**
* Sets the background color
* @default 0x333333
*/
public function get backgroundColor():uint {return _backgroundColor;}
public function set backgroundColor(value:uint):void
{
_backgroundColor = value;
}
private var _backgroundAlpha:Number = 1.0;
/**
* Sets the background alpha
* @default 1.0
*/
public function get backgroundAlpha():Number{ return _backgroundAlpha;}
public function set backgroundAlpha(value:Number):void
{
_backgroundAlpha = value;
}
private var _waveColor:uint = 0xFFFFFF;
/**
* Sets the color of the waveform
* @default 0xFFFFFF
*/
public function get waveColor():uint{ return _waveColor;}
public function set waveColor(value:uint):void
{
_waveColor = value;
}
private var _autoLoad:Boolean = true;
[Deprecated(replacement = "preload")]
/**
* Indicates whether the wav file is autoloaded
*/
public function get autoLoad():Boolean { return _preload; }
public function set autoLoad(value:Boolean):void
{
_preload = value;
}
private var _preload:Boolean = false;
/**
* Indicates whether the wav file is preloaded by the cml parser
* @default true
*/
public function get preload():Boolean { return _preload; }
public function set preload(value:Boolean):void
{
_preload = value;
}
private var _autoplay:Boolean = false;
/**
* Indicates whether the wav file plays upon load
* @default true
*/
public function get autoplay():Boolean { return _autoplay; }
public function set autoplay(value:Boolean):void
{
_autoplay = value;
}
private var _loop:Boolean = false;
/**
* Specifies wether the wav file will to loop to the beginning and continue playing upon completion
* @default false
*/
public function get loop():Boolean { return _loop; }
public function set loop(value:Boolean):void { _loop = value; }
private var _src:String;
/**
* Sets the wav file path
* @default
*/
public function get src():String{ return _src;}
public function set src(value:String):void
{
if (src == value) return;
_src = value;
}
private var _volume:Number = 1;
/**
* Sets the volume
* @default 1
*/
public function get volume():Number {return _volume;}
public function set volume(value:Number):void
{
if (value < 0.0) _volume = 0.0;
else if (value > 1.0) _volume = 1.0;
else _volume = value;
}
private var _pan:Number = 0;
/**
* Sets the audio pannning ( -1 = left, 0 = center, 1 = right )
* @default 0
*/
public function get pan():Number {return _pan;}
public function set pan(value:Number):void
{
if (value < -1.0) _pan = -1.0;
else if (value > 1.0) _pan = 1.0;
else _pan = value;
}
private var _display:String = "waveform";
/**
* Visualization display type, choose waveform or none
* @default waveform
*/
public function get display():String {return _display;}
public function set display(value:String):void
{
_display = value;
//if (preload)
//load();
}
// READ ONLY //
private var _bitDepth:uint;
/**
* depth of wav file
*/
public function get bitDepth():uint { return _bitDepth; }
private var _wavLength:uint;
/**
* length of wav file
*/
public function get wavLength():uint { return _wavLength; }
private var _duration:Number = 0;
/**
* Total duration
* @default 0
*/
public function get duration():Number { return _duration; }
private var _percentLoaded:Number = 0;
/**
* Percent of file loaded
* @default 0
*/
public function get percentLoaded():Number { return _percentLoaded; }
private var _playhead:Number = 0;
/**
* Playhead position in ms
* @default 0
*/
public function get playhead():Number { return _playhead; }
private var _isPlaying:Boolean = false;
/**
* Sets video playing status
* @default false
*/
public function get isPlaying():Boolean { return _isPlaying; }
private var _paused:Boolean = false;
/**
* specifies whether the wav file is paused or not
* @default false
*/
public function get paused():Boolean { return _paused; }
/**
* Array of average gain values
* @default null
*/
private var _averageGain:Array;
public function get averageGain():Array { return _averageGain; }
private var _sampleRate:uint = 0;
public function get sampleRate():uint { return _sampleRate; }
// PROTECTED //
/**
* Byte position in file stream which indicates the beginning of audio data
* @default 0
*/
protected var _audioStreamStart:Number = 0;
/**
* Byte position in file stream which indicates the beginning of audio data
* default = 0
*/
protected var _audioStreamEnd:Number = 0;
/**
* Current audio data byte position in the file stream
* @default 0
*/
protected var _audioStreamPosition:Number = 0;
/**
* Number of audio data bytes available in file stream
* @default 0
*/
protected var _audioStreamAvailable:Number = 0;
/**
* Total size in bytes of audio data in file stream
* default = 0
*/
protected var _audioStreamSize:Number = 0;
/**
* Byte rate in milliseconds
* default = 0
*/
protected var _msByteRate:uint = 0;
protected var _stream:FileStream;
private var _file:File;
// XMP DATA //
/**
* XMP metadata object
* @default null
*/
private var _xmp:XMPMeta;
public function get xmp():XMPMeta { return _xmp; }
/**
* XMP (dublin core) title metadata
* @default null
*/
private var _title:String;
public function get title():String { return _title; }
/**
* XMP artist metadata
* @default null
*/
private var _artist:String;
public function get artist():String { return _artist; }
/**
* XMP album metadata
* @default null
*/
private var _album:String;
public function get album():String { return _album; }
/**
* XMP album metadata
* @default null
*/
private var _date:String;
public function get date():String { return _date; }
/**
* XMP album metadata
* @default null
*/
private var _publisher:String;
public function get publisher():String { return _publisher; }
/**
* XMP comment metadata
* @default null
*/
private var _comment:String;
public function get comment():String { return _comment; }
/**
* Variable audio buffer size (might be smaller than audio buffer size near the end of file)
* @default null
*/
private var _varBufferSize:Number;
/**
* Audio block align (bytes per sample)
* @default 0
*/
private var _blockAlign:uint = 0;
public function get blockAlign():uint { return _blockAlign; }
private var _fileSize:uint;
public function get fileSize():uint { return _fileSize; }
// PUBLIC METHODS //
/**
* Initialisation method
*/
override public function init():void
{
load();
}
/**
* Sets the src property from the argument and loads the wav file
* @param file Full path and file name of wav file
*/
public function open(file:String):void
{
src = file;
load();
}
/**
* closes wav file
*/
public function close():void
{
channel.stop();
waveSound.removeEventListener(SampleDataEvent.SAMPLE_DATA, readAudioData);
_isPlaying = false;
_paused = false;
visible = false;
timer.stop();
}
/**
* plays wav file
*/
public function play():void {
if (_isPlaying == false) {
//if not paused, start from defined cue
if(!_paused) {
//skip to audio data + cue start point
_cueStreamStart = _cueStart * byteRate / 1000 + _audioStreamStart;
//make sure number is equally divisible by the block align
var err:Number = _cueStreamStart % blockAlign;
_cueStreamStart = _cueStreamStart - err;
//set stream position
_stream.position = _cueStreamStart;
}
//add SampleDataEvent listener (runs at the audio rate, currently flash only supports 44.1 Hz)
waveSound.addEventListener(SampleDataEvent.SAMPLE_DATA, readAudioData);
timer.start();
//play the sound file through sound object, leave cue and loop properties at zero (handled differently)
waveSound.play();
_isPlaying = true;
}
}
/**
* pauses the wav file
*/
public function pause():void {
//stop playback and set pause to true
waveSound.removeEventListener(SampleDataEvent.SAMPLE_DATA, readAudioData);
timer.stop();
_isPlaying = false;
_paused = true;
}
/**
* seek method
* @param pos
*/
public function seek(pos:Number):void
{
pause();
//set stream position
_stream.position = pos;
play();
dispatchEvent(new StateEvent(StateEvent.CHANGE, this.id, "Position" , _stream.position));
}
/**
* stops wav file
*/
public function stop():void {
//stop playback
waveSound.removeEventListener(SampleDataEvent.SAMPLE_DATA, readAudioData);
timer.stop();
_isPlaying = false;
}
// PRIVATE //
//load
private function load():void
{
loading = true;;
waveSound = new flash.media.Sound();
channel = new SoundChannel();
soundTrans = new SoundTransform();
//sound.addEventListener(Event.COMPLETE, soundLoaded);
if (display == "waveform")
{
bgGraphic = new Sprite;
bgGraphic.graphics.beginFill(backgroundColor, backgroundAlpha);
bgGraphic.graphics.drawRect(0, 0, width, height);
bgGraphic.graphics.endFill();
addChild(bgGraphic);
waveForm = new Waveform();
waveForm.waveColor = _waveColor;
waveForm.waveWidth = width;
waveForm.waveHeight = height;
addChild(waveForm);
}
//update timer
timer = new Timer(10);
timer.addEventListener(TimerEvent.TIMER, updateDisplay);
//sound
soundTrans.volume = _volume;
soundTrans.pan = _pan;
_isPlaying = false;
Position = 0;
//audio
_file = File.applicationDirectory.resolvePath(_src);
_stream = new FileStream();
_stream.open(_file, FileMode.READ);
_fileSize = _stream.bytesAvailable;
traverseFile();
}
/**
* Reads through the audio data at the audio rate; Event handler for SampleDataEvent
* @param SampleDataEvent
* @return none
*/
private function readAudioData(e:SampleDataEvent):void {
var j:uint = 0;
//read through the data at the audio rate
for (var i:int=0; i<_varBufferSize; i++) {
var leftAmp:Number = _stream.readShort() / 32767 * _volume * (1 - _pan * .5);
e.data.writeFloat(leftAmp);
if (channels == 2) {
var rightAmp:Number = _stream.readShort() / 32767 * _volume * (1 + _pan * .5);
e.data.writeFloat(rightAmp);
}
//update audio stream position
_audioStreamPosition = _stream.position - _audioStreamStart;
//compute the amount of audio data remaining
_audioStreamAvailable = _audioStreamSize - _audioStreamPosition;
//if there is less than one sample per channel, loop
if ((_audioStreamAvailable < blockAlign) && (_loop)) {
_varBufferSize = bufferSize;
_stream.position = _cueStreamStart;
}
//currently use to create graphical waveform
_averageGain[j] = leftAmp + rightAmp * .5;
j++
}
//if smaller than current buffer size, compute the new buffer size
if (_audioStreamAvailable < _varBufferSize * blockAlign)
_varBufferSize = _audioStreamAvailable / blockAlign;
//if end of audio data reached, reset buffer size and stop playback
if (_audioStreamAvailable == 0) {
_varBufferSize = _bufferSize;
stop();
}
}
//timer methods
private function updateDisplay(event:TimerEvent):void
{
var string:String=formatTime(channel.position);
sendUpdate(string);
if (display == "waveform") {
waveForm.averageGain = _averageGain;
waveForm.draw();
}
}
private function sendUpdate(string:String):void
{
_timerFormated = string;
}
private function formatTime(t:int):String
{
var s:int=Math.round(t/1000);
var m:int=0;
if (s>0)
{
while (s > 59)
{
m++;
s-=60;
}
return String((m < 10 ? "0" : "") + m + ":" + (s < 10 ? "0" : "") + s);
}
else return "00:00";
}
private function traverseFile():void {
//reset byte position
_stream.position = 0;
//loop index
var i:int;
/* RIFF chunk */
//read chunk id (4 bytes)
_stream.endian = Endian.BIG_ENDIAN;
var chunkId:String = _stream.readUTFBytes(4);
if (_printData)
trace ('Chunk Id = ' + chunkId);
if (chunkId != 'RIFF')
throw _invalidError;
//read chunk size (4 bytes - little endian)
_stream.endian = Endian.LITTLE_ENDIAN;
var chunkSize:uint;
for (i=0; i<4; i++)
chunkSize += _stream.readUnsignedByte() * int(Math.pow(256,i));
if (_printData)
trace ('Chunk Size = ' + chunkSize + ' bytes');
//read format (4 bytes - big endian)
_stream.endian = Endian.BIG_ENDIAN;
var format:String = _stream.readUTFBytes(4)
if (_printData)
trace ('Format = ' + format);
if (format != 'WAVE')
throw _invalidError;
/* subchunk1 (fmt) */
//read subchunk1 id (4 bytes - big endian)
var subchunk1Id:String = _stream.readUTFBytes(4)
if (_printData)
trace ('Subchunk1 Id = ' + subchunk1Id);
if (subchunk1Id != 'fmt ')
throw _invalidError;
//read subchunk1 size (4 bytes - little endian)
_stream.endian = Endian.LITTLE_ENDIAN;
var fmtChunkSize:uint;
for (i=0; i<4; i++)
fmtChunkSize += _stream.readUnsignedByte() * int(Math.pow(256,i));
if (_printData)
trace ('Subchunk1 Size = ' + fmtChunkSize + ' bytes');
//record start position of fmt chunk data
var fmtChunkStart:uint = _stream.position;
//read audio format (2 bytes - little endian)
var audioFormat:uint = _stream.readUnsignedByte();
_stream.readUnsignedByte();
if (_printData)
trace('Audio Format = uncompressed PCM');
if (audioFormat != 1)
throw _invalidError;
//read number of channels (2 bytes - little endian)
_channels = _stream.readUnsignedByte();
_stream.readUnsignedByte();
if (_printData)
trace('Channels = ' + channels);
if (channels > 2)
throw new Error("More than two channels are not supported");
//read sample rate (4 bytes - little endian)
for (i=0; i<4; i++)
_sampleRate += _stream.readUnsignedByte() * int(Math.pow(256,i));
if (_printData)
trace("Sample Rate = " + sampleRate);
if (_sampleRate != 44100)
throw new Error("Sample rate not supported; 44100 Hz required");
//read byte rate (4 bytes - little endian)
for (i=0; i<4; i++)
_byteRate += _stream.readUnsignedByte() * int(Math.pow(256,i));
_msByteRate = _byteRate / 1000;
if (_printData)
trace("Byte Rate = " + byteRate);
//read block align (2 bytes - little endian)
for (i=0; i<2; i++)
_blockAlign += _stream.readUnsignedByte() * int(Math.pow(256,i));
if (_printData)
trace("Block Align = " + _blockAlign);
//read bits per sample (2 bytes - little endian)
_bitDepth = _stream.readUnsignedByte();
_stream.readUnsignedByte();
if (_printData)
trace("Bit Depth = " + bitDepth);
if (bitDepth != 16)
throw new Error("Bit depth is not supported; Must be 16 bits");
//read compression parameter (2 bytes - little endian) - doesn't exist if PCM
if (audioFormat != 1)
_stream.position +=2;
//read any extra paramerters
var fmtPosition:uint = _stream.position - fmtChunkStart;
while (fmtPosition != fmtChunkSize)
_stream.position++;
//traverse subchunks
parseSubChunk();
//read sub chunk (look for audio 'DATA' chunk and '_PMX' xmp metadata chunk)
function parseSubChunk():void {
//read subchunk id (4 bytes - big endian)
_stream.endian = Endian.BIG_ENDIAN;
var subChunkId:String = _stream.readUTFBytes(4);
if (_printData)
trace ('Subchunk Id = ' + subChunkId);
//read subchunk size (4 bytes - little endian)
_stream.endian = Endian.LITTLE_ENDIAN;
var subChunkSize:uint = 0;
for (i=0; i<4; i++)
subChunkSize += _stream.readUnsignedByte() * int(Math.pow(256,i));
if (_printData)
trace ('Subchunk Size = ' + subChunkSize)
//read xmp metadata
if (subChunkId == '_PMX') {
//read xmp data as a string
var str:String = _stream.readUTFBytes(subChunkSize);
//create xmp objects
_xmp = new XMPMeta(str);
var xmpDM:Namespace = XMPConst.xmpDM;
var dc:Namespace = XMPConst.dc;
//assign targeted data
if (_xmp.dc::title)
_title = xmp.dc::title[1]
if (_xmp.xmpDM::artist)
_artist = xmp.xmpDM::artist;
if (_xmp.xmpDM::album)
_album = xmp.xmpDM::album;
if (_xmp.xmpDM::shotDay)
_date = xmp.xmpDM::shotDay;
if (_xmp.dc::publisher)
_publisher = xmp.dc::publisher[1]
if (_xmp.xmpDM::comment)
_comment= xmp.xmpDM::comment;
if (_printData)
trace('XMP = ' + str);
//free memory
str = null;
}
else {
//if audio data chunk, mark location, size, and length
if (subChunkId == 'data') {
_audioStreamSize = subChunkSize;
_audioStreamStart = _stream.position;
_audioStreamEnd = _audioStreamStart + _audioStreamSize;
_wavLength = _audioStreamSize / byteRate * 1000;
}
_stream.position += subChunkSize;
}
//if end of file, exit recursive function
if (_stream.bytesAvailable == 0)
fileTraversalComplete();
//else, read another sub chunk
else
parseSubChunk();
}
}
private function fileTraversalComplete():void {
if (_printData)
trace('File traversal complete');
_loaded = true;
_varBufferSize = bufferSize;
//Dispatch event, file is loaded, ready to play.
dispatchEvent(new StateEvent(StateEvent.CHANGE, this.id, "loaded", _loaded));
if (_autoplay)
play();
}
/**
* @inheritDoc
*/
override public function dispose():void {
super.dispose();
_averageGain = null;
_xmp = null;
_file = null;
_stream = null;
_invalidError = null;
waveForm = null;
soundTrans = null;
urlLoader = null;
bgGraphic = null;
bytes = null;
if (timer) {
timer.stop();
timer.removeEventListener(TimerEvent.TIMER, updateDisplay);
timer = null;
}
if (channel)
{
channel.stop();
channel = null;
}
if (waveSound) {
waveSound.removeEventListener(SampleDataEvent.SAMPLE_DATA, readAudioData);
waveSound = null;
}
}
}
} |
package flare.query
{
/**
* Expression operator that tests if a value is within a given range.
* Implemented as an <code>And</code> of <code>Comparison</code>
* expressions.
*/
public class Range extends And
{
/** Sub-expression for the minimum value of the range. */
public function get min():Expression { return _children[0].left; }
public function set min(e:*):void {
_children[0].left = Expression.expr(e);
}
/** Sub-expression for the maximum value of the range. */
public function get max():Expression { return _children[1].right; }
public function set max(e:*):void {
_children[1].right = Expression.expr(e);
}
/** Sub-expression for the value to test for range inclusion. */
public function get val():Expression { return _children[0].right; }
public function set val(e:*):void {
var expr:Expression = Expression.expr(e);
_children[0].right = expr;
_children[1].left = expr;
}
/**
* Create a new Range operator.
* @param min sub-expression for the minimum value of the range
* @param max sub-expression for the maximum value of the range
* @param val sub-expression for the value to test for range inclusion
*/
public function Range(min:*=null, max:*=null, val:*=null)
{
addChild(new Comparison(Comparison.LTEQ));
addChild(new Comparison(Comparison.LTEQ));
if(min)this.min = min;
if(max)this.max = max;
if(val)this.val = val;
}
/**
* @inheritDoc
*/
public override function clone():Expression
{
return new Range(min.clone(), max.clone(), val.clone());
}
} // end of class RangePredicate
} |
/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */
/* vi: set ts=4 sw=4 expandtab: (add to ~/.vimrc: set modeline modelines=5) */
/* 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/. */
import avmplus.System;
import avmplus.File;
import flash.utils.ByteArray;
import flash.system.Worker;
import flash.system.PromiseChannel;
function makeCode(name) {
return File.readByteArray(name);
}
var blob = makeCode("receiver.abc");
var p = new Worker([blob]);
var m1 = new PromiseChannel(Worker.current, p);
var m2 = new PromiseChannel(Worker.current, p);
var m3 = new PromiseChannel(p, Worker.current);
p.startWithChannels([m1, m2, m3]);
class Foo {
var x:int = 10;
};
dynamic class Bar extends Foo {
var y:int = 12;
}
class Baz extends Bar {
var w:int = 100;
}
m1.send(new Foo());
var bar1 = new Bar();
bar1.z = 15;
m1.send(bar1);
var baz1 = new Baz();
//(baz1 as Bar).z = -1;
m1.send(baz1);
/*
dynamic class FunnyArray extends Array {
//var funnyLength:int = 42;
};
var funnyArray1 = new FunnyArray();
funnyArray1[4] = 10;
m1.send(funnyArray1);
*/
m1.send(<foo><bar></bar></foo>);
m1.send(new Date());
m1.send(p);
var ch = new PromiseChannel(Worker.current, p);
m1.send(ch);
ch.send(10);
m1.send(blob);
m1.send(10);
m2.send(true);
m1.send(undefined);
m1.send({x:1});
function build(i) {
if (i > 0)
return { array: [1,2,3,4], f: 1.2, label: "hey", rest: build(i - 1) }
else
return null;
}
var t0,t1;
print('iterating sending big data');
for (var i = 0; i < 5; i++) {
var bigdata = build(1000);
t0 = System.getTimer();
m1.send(bigdata);
t1 = m3.receive();
}
print('time', t1 - t0);
Worker.current.stop();
|
//----------------------------------------------------------------------------------------------------
// Standard MIDI File class
// modified by keim.
// This soruce code is distributed under BSD-style license (see org.si.license.txt).
//
// Original code
// url; http://wonderfl.net/code/0aad6e9c1c5f5a983c6fce1516ea501f7ea7dfaa
// Copyright (c) 2010 nemu90kWw All rights reserved.
// The original code is distributed under MIT license.
// (see http://www.opensource.org/licenses/mit-license.php).
//----------------------------------------------------------------------------------------------------
package org.si.sion.midi {
import flash.utils.ByteArray;
import flash.net.*;
import flash.events.*;
/** Standard MIDI File class */
public class SMFData extends EventDispatcher
{
// variables
//--------------------------------------------------------------------------------
/** Standard MIDI file format (0,1 o 2) */
public var format:int;
/** track count */
public var numTracks:int;
/** resolution [ticks/whole tone] */
public var resolution:int;
/** initial tempo */
public var bpm:int = 0;
/** text information */
public var text:String = "";
/** title string */
public var title:String = null;
/** author infomation */
public var author:String = null;
/** numerator of signiture */
public var signature_n:int = 0;
/** denominator of signiture */
public var signature_d:int = 0;
/** song length [measures] */
public var measures:Number = 0;
/** SMF tracks */
public var tracks:Vector.<SMFTrack> = new Vector.<SMFTrack>();
private var _urlLoader:URLLoader;
// properties
//--------------------------------------------------------------------------------
/** Is avaiblable ? */
public function isAvailable() : Boolean { return (numTracks > 0); }
/** to string. */
override public function toString():String
{
var text:String = "";
text += "format : SMF" + format + "\n";
text += "numTracks : " + numTracks + "\n";
text += "resolution : " + (resolution>>2) + "\n";
text += "title : " + title + "\n";
text += "author : " + author + "\n";
text += "signature : " + signature_n + "/" + signature_d + "\n";
text += "BPM : " + bpm + "\n";
return text;
}
// constructor
//--------------------------------------------------------------------------------
/** constructor */
function SMFData()
{
clear();
}
// operations
//--------------------------------------------------------------------------------
/** Clear. */
public function clear() : SMFData
{
format = 0;
numTracks = 0;
resolution = 0;
bpm = 0;
text = null;
title = null;
author = null;
signature_n = 0;
signature_d = 0;
measures = 0;
tracks.length = 0;
return this;
}
/** Load SMF file. This function dispatches Event.COPMLETE when finish loading
* @param url URL of SMF file
*/
public function load(url:URLRequest) : void
{
var byteArray:ByteArray = new ByteArray();
_urlLoader = new URLLoader();
_urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
_urlLoader.addEventListener(Event.COMPLETE, _onComplete);
_urlLoader.addEventListener(ProgressEvent.PROGRESS, _onProgress);
_urlLoader.addEventListener(IOErrorEvent.IO_ERROR, _onError);
_urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, _onError);
_urlLoader.load(url);
}
/** Load SMF data from byteArray. This function dispatches Event.COPMLETE but returns data immediately.
* @param bytes SMF file binary
*/
public function loadBytes(bytes:ByteArray) : SMFData
{
bytes.position = 0;
clear();
var tr:int, len:uint, temp:ByteArray = new ByteArray();
while (bytes.bytesAvailable > 0) {
var type:String = bytes.readMultiByte(4, "us-ascii");
switch(type) {
case "MThd":
bytes.position += 4;
format = bytes.readUnsignedShort();
numTracks = bytes.readUnsignedShort();
resolution = bytes.readUnsignedShort() << 2;
break;
case "MTrk":
len = bytes.readUnsignedInt();
bytes.readBytes(temp, 0, len);
tracks.push(new SMFTrack(this, tracks.length, temp));
break;
default:
len = bytes.readUnsignedInt();
bytes.position += len;
break;
}
}
if (text == null) text = "";
if (title == null) title = "";
if (author == null) author = "";
if (resolution > 0) {
len = 0;
for (tr=0; tr<tracks.length; tr++) {
if (len < tracks[tr].totalTime) len = tracks[tr].totalTime;
}
measures = len / resolution;
}
dispatchEvent(new Event(Event.COMPLETE));
return this;
}
// internal use
//--------------------------------------------------
private function _onProgress(e:ProgressEvent) : void
{
dispatchEvent(e.clone());
}
private function _onComplete(e:Event) : void
{
_removeAllListeners();
loadBytes(_urlLoader.data);
}
private function _onError(e:ErrorEvent) : void
{
_removeAllListeners();
dispatchEvent(e.clone());
}
private function _removeAllListeners() : void
{
_urlLoader.removeEventListener(Event.COMPLETE, _onComplete);
_urlLoader.removeEventListener(ProgressEvent.PROGRESS, _onProgress);
_urlLoader.removeEventListener(IOErrorEvent.IO_ERROR, _onError);
_urlLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, _onError);
}
}
}
|
package PeekAttack.FB
{
import flash.events.NetStatusEvent;
import flash.events.TimerEvent;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.net.sendToURL;
import flash.utils.Timer;
import flash.utils.clearTimeout;
import flash.utils.setTimeout;
public class StratusConnection extends StreamEventDispatcher
{
//############### Private Fields ##################
private const DeveloperKey :String = "04e5d33437110ee0363288f5-91187653a6fc";
private const connectUrl :String = "rtmfp://stratus.adobe.com";
private var NumberOfFailedConnections :int = 0;
private const connectionName :String = "StratusConnection";
private var outgoingStream :NetStream;
private var incomingStream :NetStream;
//'''''''''' Stream Messaging Functions '''''''''''''''
private const ON_RECEIVE_DEFINITELY :String = "ON_RECEIVE_DEFINITELY";
private const ON_RECEIVED :String = "ON_RECEIVED";
private const RTMP_SAMPLE_ACCESS :String = "|RtmpSampleAccess";
//'''''''''' Messaging '''''''''''''''
[Bindable] public var numberPendingMessages :int = 0;
private var pendingMessages :Array;
//private
[Bindable] public var currentMessageID :int=0;
public var receivedMessageIDs :Object;
private var sendingTimer :Timer;
private var timeoutId:uint;
//############### Constructor ##################
public function StratusConnection()
{
pendingMessages = new Array;
receivedMessageIDs = new Object;
addEventListener(NetStatusEvent.NET_STATUS,netConnectionHandler);
connectWithTimeout();
sendingTimer = new Timer(500,0);
sendingTimer.addEventListener(TimerEvent.TIMER,sendingTimerEventHandler);
}
private function connectWithTimeout():void
{
if(timeoutId)
clearTimeout(timeoutId);
connect(connectUrl+"/"+DeveloperKey);
timeoutId = setTimeout(dispatchEvent,4000,
new NetStatusEvent(NetStatusEvent.NET_STATUS,false,false,
{'code':NETCONNECTION_CONNECT_FAILED}));
}
//############### METHODS ##################
private function netConnectionHandler(event:NetStatusEvent):void
{
//Nicht einfach so den status zumüllen, sondern dafür sorgen, dass
//Event eine sinnvolle message produziert
//status("NetConnection event: " + event.info.code);
switch (event.info.code)
{
//##################### CONNECT ############################
case NETCONNECTION_CONNECT_SUCCESS:
clearTimeout(timeoutId);
status("Successfully connected to "+ connectUrl);
dispatchStreamEvent(StreamEvent.STRATUS_CONNECTION_ESTABLISHED);
break;
case NETCONNECTION_CONNECT_CLOSED:
case NETCONNECTION_CONNECT_APPSHUTDOWN:
break;
case NETCONNECTION_CONNECT_REJECTED:
case NETCONNECTION_CONNECT_FAILED:
status(event.info.code);
status("Failed to register to " + connectUrl+ "NumberOfFailedConnections "+NumberOfFailedConnections);
if(NumberOfFailedConnections>3)
{
status("Abandoning stratus");
dispatchStreamEvent(StreamEvent.STRATUS_CONNECTION_REJECTED);
close();
}else
{
status("Trying to register again ...");
NumberOfFailedConnections++;
setTimeout(connectWithTimeout,500);
}
break;
//The specified application is shutting down.
//TODO reconnect to both Stratus and rmtp?
status(connectionName+ " Nicht behandeltes Event from:" +event.info.code);
break;
//##################### CALL ############################
case NETCONNECTION_CALL_FAILED:
//The NetConnection.call method was not able to invoke the server-side method or command.
case NETCONNECTION_CALL_PROHIBITED:
//An Action Message Format (AMF) operation is prevented for security reasons. Either the AMF URL is not in the same domain as the file containing the code calling the NetConnection.call() method, or the AMF server does not have a policy file that trusts the domain of the the file containing the code calling the NetConnection.call() method.
case NETCONNECTION_CALL_BADVERSION:
//Packet encoded in an unidentified format.
status("Nicht behandeltes Event from "+connectUrl+":" +event.info.code);
break;
//##################### SHARED OBJECTS ############################
/*
"SharedObject.Flush.Success" "status" The "pending" status is resolved and the SharedObject.flush() call succeeded.
"SharedObject.Flush.Failed" "error" The "pending" status is resolved, but the SharedObject.flush() failed.
"SharedObject.BadPersistence" "error" A request was made for a shared object with persistence flags, but the request cannot be granted because the object has already been created with different flags.
"SharedObject.UriMismatch" "error" An attempt was made to connect to a NetConnection object that has a different URI (URL) than the shared object.
*/
default:
dispatchStreamEvent(event.info.code,event.info.stream || "");
}
}
public function sendDefinitely(handlerName:String, msg:Object ):void
{
//status(handlerName+"\n");
//delete stop on new conection
pendingMessages[currentMessageID]=[handlerName,msg];
outgoingStream.send(ON_RECEIVE_DEFINITELY,currentMessageID,handlerName,msg);
currentMessageID++;
numberPendingMessages++;
if(!sendingTimer.running)
sendingTimer.start();
}
private function sendingTimerEventHandler(e:TimerEvent=null):void
{
if(outgoingStream!=null)
for (var ID:String in pendingMessages)
if(pendingMessages[ID])
outgoingStream.send(ON_RECEIVE_DEFINITELY,ID,pendingMessages[ID][0],pendingMessages[ID][1]);
}
public function rtmpSampleAccess(number:Number,delay:Number):void
{
if(number>0)
{
outgoingStream.send(RTMP_SAMPLE_ACCESS,true,true);
setTimeout(rtmpSampleAccess,delay,number-1,delay);
}
}
public function createStratusMessagingSystem( incomingStream :NetStream,
outgoingStream :NetStream):void
{
//Emtpy Array fo received messages
receivedMessageIDs=new Object;
pendingMessages = new Array;
this.outgoingStream=outgoingStream;
this.incomingStream=incomingStream;
incomingStream.client = new Object();
outgoingStream.client = new Object();
incomingStream.client.ON_RECEIVE_DEFINITELY = function ( ID:String,
handlerName:String,
msg:Object) :void{
if(receivedMessageIDs[ID]==null)
{
receivedMessageIDs[ID]="1";
incomingStream.client[handlerName](msg);
}
outgoingStream.send(ON_RECEIVED,ID);
}
incomingStream.client.ON_RECEIVED = function (ID:String):void{
if(pendingMessages[ID])
{
pendingMessages[ID]=null;
numberPendingMessages--;
if(numberPendingMessages==0)
sendingTimer.stop();
}
}
setTimeout(sendingTimerEventHandler,0);
}
}
} |
; second pass test 2
.entry LIST
.extern W
MAIN: add r3, LIST
LOOP: prn #48
lea W, r6
inc r6
mov r3, K
sub r1, r4
bne END
cmp K, #-6
bne %W
dec W
.entry MAIN
jmp %LOOP
add L3, L3
END: stop
STR: .string "abcd"
LIST: .data 6, -9
.data -100
K: .data 31
|
/*
* =BEGIN CLOSED LICENSE
*
* Copyright (c) 2013-2014 Andras Csizmadia
* http://www.vpmedia.eu
*
* For information about the licensing and copyright please
* contact Andras Csizmadia at andras@vpmedia.eu
*
* 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.
*
* =END CLOSED LICENSE
*/
package hu.vpmedia.blitting {
import flash.display.BitmapData;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.TimerEvent;
import flash.filters.ColorMatrixFilter;
import flash.geom.ColorTransform;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.media.Camera;
import flash.media.Video;
import flash.net.NetStream;
import flash.utils.Timer;
import flash.utils.setTimeout;
[Event(name="Event.RENDER", type="flash.events.Event")]
/**
* TBD
*/
public class BitmapVideo extends EventDispatcher {
/**
* @private
*/
public var bitmapData:BitmapData;
/**
* @private
*/
protected var _width:int;
/**
* @private
*/
protected var _height:int;
/**
* @private
*/
protected var _active:Boolean;
/**
* @private
*/
protected var _video:Video;
/**
* @private
*/
protected var _refreshRate:int;
/**
* @private
*/
protected var _timer:Timer;
/**
* @private
*/
protected var _paintMatrix:Matrix;
/**
* @private
*/
protected var _smooth:Boolean;
/**
* @private
*/
protected var _colorTransform:ColorTransform;
/**
* @private
*/
protected var _colorMatrix:Array;
/**
* @private
*/
protected var _colorMatrixFilter:ColorMatrixFilter = new ColorMatrixFilter();
/**
* @private
*/
protected const origin:Point = new Point();
/**
* @private
*/
protected var _camera:Camera;
/**
* @private
*/
protected var _netStream:NetStream;
/**
* @private
*/
protected const INIT_DELAY:int = 100;
/**
* @private
*/
protected var _isMirror:Boolean;
/**
* @private
*/
public function BitmapVideo(width:int, height:int, refreshRate:int = 15, mirror:Boolean = true) {
_isMirror = mirror;
_width = width;
_height = height;
_refreshRate = refreshRate;
initialize();
}
/**
* @private
*/
private function initialize():void {
bitmapData = new BitmapData(_width, _height, false, 0);
_timer = new Timer(1000 / _refreshRate);
_timer.addEventListener(TimerEvent.TIMER, draw, false, 0, true);
// sharpen video
/*
var filter = new flash.filters.ConvolutionFilter();
filter.matrixX = 3;
filter.matrixY = 3;
filter.matrix = [-1, 0, -1, 0, 8, 0, -1, 0, -1];
filter.bias = 0;
filter.divisor = 4;
_video.filters = [filter];
*/
_paintMatrix = new Matrix(_width / _width, 0, 0, _height / _height, 0, 0);
if (_isMirror) {
_paintMatrix.scale(-1, 1);
_paintMatrix.tx = _width;
}
_smooth = _paintMatrix.a != 1 || _paintMatrix.d != 1;
}
/**
* TBD
*/
public function close():void {
active = false;
if (_camera) {
_video.attachCamera(null);
_camera = null;
}
if (_netStream) {
_video.attachNetStream(null);
_netStream = null;
}
_video = null;
}
/**
* TBD
*/
public function attachCamera(camera:Camera):void {
if (!camera) {
close();
return;
}
_camera = camera;
setTimeout(attachSource, INIT_DELAY);
}
/**
* @private
*/
protected function attachSource():void {
if (_camera) {
_video = new Video(_camera.width, _camera.height);
_video.attachCamera(_camera);
}
else if (_netStream) {
_video = new Video(_width, _height);
_video.attachNetStream(_netStream);
}
}
/**
* TBD
*/
public function attachNetStream(netStream:NetStream):void {
if (!netStream) {
close();
return;
}
_netStream = netStream;
setTimeout(attachSource, INIT_DELAY);
}
/**
* TBD
*/
public function set active(value:Boolean):void {
_active = value;
if (_active) _timer.start() else _timer.stop();
}
/**
* TBD
*/
public function set refreshRate(value:int):void {
_refreshRate = value;
_timer.delay = 1000 / _refreshRate;
}
/**
* TBD
*/
public function set colorTransform(value:ColorTransform):void {
_colorTransform = value;
}
/**
* TBD
*/
public function set colorMatrix(value:Array):void {
_colorMatrixFilter.matrix = _colorMatrix = value;
}
/**
* @private
*/
protected function draw(event:TimerEvent = null):void {
if (!_active) {
return;
}
try {
bitmapData.lock();
bitmapData.draw(_video, _paintMatrix, _colorTransform, "normal", null, _smooth);
if (_colorMatrix != null) {
bitmapData.applyFilter(bitmapData, bitmapData.rect, origin, _colorMatrixFilter);
}
bitmapData.unlock();
} catch (e:Error) {
}
dispatchEvent(new Event(Event.RENDER));
}
}
} |
package age.data.objectStates
{
import age.data.ObjectInfo;
/**
* 空闲状态
* @author zhanghaocong
*
*/
public class IdleState extends AbstractObjectState
{
/**
* constructor
*
*/
public function IdleState(info:ObjectInfo)
{
super(info);
}
/**
* @inheritDoc
*
*/
override public function apply():void
{
info.actionName = "idle";
stop();
}
}
}
|
package feathers.tests
{
import feathers.controls.Button;
import feathers.controls.Slider;
import flash.geom.Point;
import org.flexunit.Assert;
import starling.display.DisplayObject;
import starling.display.Quad;
import starling.events.Event;
import starling.events.Touch;
import starling.events.TouchEvent;
import starling.events.TouchPhase;
public class SliderHorizontalTests
{
private static const THUMB_NAME:String = "thumb";
private static const TRACK_NAME:String = "track";
private static const TRACK_WIDTH:Number = 200;
private static const TRACK_HEIGHT:Number = 20;
private static const THUMB_WIDTH:Number = 20;
private static const THUMB_HEIGHT:Number = 20;
private var _slider:Slider;
[Before]
public function prepare():void
{
this._slider = new Slider();
this._slider.direction = Slider.DIRECTION_HORIZONTAL;
this._slider.trackLayoutMode = Slider.TRACK_LAYOUT_MODE_SINGLE;
this._slider.minimumTrackFactory = function():Button
{
var track:Button = new Button();
track.name = TRACK_NAME;
track.defaultSkin = new Quad(TRACK_WIDTH, TRACK_HEIGHT);
return track;
};
this._slider.thumbFactory = function():Button
{
var thumb:Button = new Button();
thumb.name = THUMB_NAME;
thumb.defaultSkin = new Quad(THUMB_WIDTH, THUMB_HEIGHT);
return thumb;
};
TestFeathers.starlingRoot.addChild(this._slider);
this._slider.validate();
}
[After]
public function cleanup():void
{
this._slider.removeFromParent(true);
this._slider = null;
Assert.assertStrictlyEquals("Child not removed from Starling root on cleanup.", 0, TestFeathers.starlingRoot.numChildren);
}
[Test]
public function testSingleTrackAutoSize():void
{
Assert.assertStrictlyEquals("The width of the slider was not calculated correctly.",
TRACK_WIDTH, this._slider.width);
Assert.assertStrictlyEquals("The height of the slider was not calculated correctly.",
TRACK_HEIGHT, this._slider.height);
}
[Test]
public function testProgrammaticSelectionChange():void
{
this._slider.minimum = 0;
this._slider.maximum = 10;
this._slider.value = 5;
var hasChanged:Boolean = false;
this._slider.addEventListener(Event.CHANGE, function(event:Event):void
{
hasChanged = true;
});
this._slider.value = 6;
Assert.assertTrue("Event.CHANGE was not dispatched", hasChanged);
}
[Test]
public function testInteractiveSelectionChangeWithDraggingThumb():void
{
var beforeValue:Number = 5;
this._slider.minimum = 0;
this._slider.maximum = 10;
this._slider.value = beforeValue;
//validate to position the thumb correctly.
this._slider.validate();
var hasChanged:Boolean = false;
this._slider.addEventListener(Event.CHANGE, function(event:Event):void
{
hasChanged = true;
});
var position:Point = new Point(TRACK_WIDTH / 2, THUMB_HEIGHT / 2);
var target:DisplayObject = this._slider.stage.hitTest(position, true);
Assert.assertStrictlyEquals("The hit test did not return the slider's thumb",
this._slider.getChildByName(THUMB_NAME).name, target.name);
var touch:Touch = new Touch(0);
touch.target = target;
touch.phase = TouchPhase.BEGAN;
touch.globalX = position.x;
touch.globalY = position.y;
var touches:Vector.<Touch> = new <Touch>[touch];
target.dispatchEvent(new TouchEvent(TouchEvent.TOUCH, touches));
touch.phase = TouchPhase.MOVED;
touch.globalX = position.x + THUMB_WIDTH * 2;
target.dispatchEvent(new TouchEvent(TouchEvent.TOUCH, touches));
touch.phase = TouchPhase.ENDED;
target.dispatchEvent(new TouchEvent(TouchEvent.TOUCH, touches));
Assert.assertTrue("Event.CHANGE was not dispatched", hasChanged);
Assert.assertTrue("The value property was not changed to a greater value",
beforeValue < this._slider.value);
}
[Test]
public function testInteractiveSelectionChangeWithDraggingThumbBeyondRightEdgeOfTrack():void
{
var beforeValue:Number = 5;
this._slider.minimum = 0;
this._slider.maximum = 10;
this._slider.value = beforeValue;
//validate to position the thumb correctly.
this._slider.validate();
var hasChanged:Boolean = false;
this._slider.addEventListener(Event.CHANGE, function(event:Event):void
{
hasChanged = true;
});
var position:Point = new Point(TRACK_WIDTH / 2, THUMB_HEIGHT / 2);
var target:DisplayObject = this._slider.stage.hitTest(position, true);
Assert.assertStrictlyEquals("The hit test did not return the slider's thumb",
this._slider.getChildByName(THUMB_NAME).name, target.name);
var touch:Touch = new Touch(0);
touch.target = target;
touch.phase = TouchPhase.BEGAN;
touch.globalX = position.x;
touch.globalY = position.y;
var touches:Vector.<Touch> = new <Touch>[touch];
target.dispatchEvent(new TouchEvent(TouchEvent.TOUCH, touches));
touch.phase = TouchPhase.MOVED;
touch.globalX = position.x + TRACK_WIDTH;
target.dispatchEvent(new TouchEvent(TouchEvent.TOUCH, touches));
touch.phase = TouchPhase.ENDED;
target.dispatchEvent(new TouchEvent(TouchEvent.TOUCH, touches));
Assert.assertTrue("Event.CHANGE was not dispatched", hasChanged);
Assert.assertStrictlyEquals("The value property was not equal to the maximum value",
this._slider.maximum, this._slider.value);
}
[Test]
public function testInteractiveSelectionChangeWithDraggingThumbBeyondLeftEdgeOfTrack():void
{
var beforeValue:Number = 5;
this._slider.minimum = 0;
this._slider.maximum = 10;
this._slider.value = beforeValue;
//validate to position the thumb correctly.
this._slider.validate();
var hasChanged:Boolean = false;
this._slider.addEventListener(Event.CHANGE, function(event:Event):void
{
hasChanged = true;
});
var position:Point = new Point(TRACK_WIDTH / 2, THUMB_HEIGHT / 2);
var target:DisplayObject = this._slider.stage.hitTest(position, true);
Assert.assertStrictlyEquals("The hit test did not return the slider's thumb",
this._slider.getChildByName(THUMB_NAME).name, target.name);
var touch:Touch = new Touch(0);
touch.target = target;
touch.phase = TouchPhase.BEGAN;
touch.globalX = position.x;
touch.globalY = position.y;
var touches:Vector.<Touch> = new <Touch>[touch];
target.dispatchEvent(new TouchEvent(TouchEvent.TOUCH, touches));
touch.phase = TouchPhase.MOVED;
touch.globalX = position.x - TRACK_WIDTH;
target.dispatchEvent(new TouchEvent(TouchEvent.TOUCH, touches));
touch.phase = TouchPhase.ENDED;
target.dispatchEvent(new TouchEvent(TouchEvent.TOUCH, touches));
Assert.assertTrue("Event.CHANGE was not dispatched", hasChanged);
Assert.assertStrictlyEquals("The value property was not equal to the minimum value",
this._slider.minimum, this._slider.value);
}
[Test]
public function testInteractiveSelectionChangeWithTouchToLeftOfThumb():void
{
var beforeValue:Number = 5;
this._slider.minimum = 0;
this._slider.maximum = 10;
this._slider.value = beforeValue;
//validate to position the thumb correctly.
this._slider.validate();
var hasChanged:Boolean = false;
this._slider.addEventListener(Event.CHANGE, function(event:Event):void
{
hasChanged = true;
});
var position:Point = new Point(TRACK_WIDTH / 3, THUMB_HEIGHT / 2);
var target:DisplayObject = this._slider.stage.hitTest(position, true);
Assert.assertStrictlyEquals("The hit test did not return the slider's track",
this._slider.getChildByName(TRACK_NAME).name, target.name);
var touch:Touch = new Touch(0);
touch.target = target;
touch.phase = TouchPhase.BEGAN;
touch.globalX = position.x;
touch.globalY = position.y;
var touches:Vector.<Touch> = new <Touch>[touch];
target.dispatchEvent(new TouchEvent(TouchEvent.TOUCH, touches));
touch.phase = TouchPhase.ENDED;
target.dispatchEvent(new TouchEvent(TouchEvent.TOUCH, touches));
Assert.assertTrue("Event.CHANGE was not dispatched", hasChanged);
Assert.assertTrue("The value property was not less than the previous value",
beforeValue > this._slider.value);
}
[Test]
public function testInteractiveSelectionChangeWithTouchToRightOfThumb():void
{
var beforeValue:Number = 5;
this._slider.minimum = 0;
this._slider.maximum = 10;
this._slider.value = beforeValue;
//validate to position the thumb correctly.
this._slider.validate();
var hasChanged:Boolean = false;
this._slider.addEventListener(Event.CHANGE, function(event:Event):void
{
hasChanged = true;
});
var position:Point = new Point(2 * TRACK_WIDTH / 3, THUMB_HEIGHT / 2);
var target:DisplayObject = this._slider.stage.hitTest(position, true);
Assert.assertStrictlyEquals("The hit test did not return the slider's track",
this._slider.getChildByName(TRACK_NAME).name, target.name);
var touch:Touch = new Touch(0);
touch.target = target;
touch.phase = TouchPhase.BEGAN;
touch.globalX = position.x;
touch.globalY = position.y;
var touches:Vector.<Touch> = new <Touch>[touch];
target.dispatchEvent(new TouchEvent(TouchEvent.TOUCH, touches));
touch.phase = TouchPhase.ENDED;
target.dispatchEvent(new TouchEvent(TouchEvent.TOUCH, touches));
Assert.assertTrue("Event.CHANGE was not dispatched", hasChanged);
Assert.assertTrue("The value property was not greater than the previous value",
beforeValue < this._slider.value);
}
}
}
|
package logic
{
import mx.collections.ArrayCollection;
public class AttributeExplorer
{
public function AttributeExplorer()
{
}
// gets an object set
public function getExtent(A:Array, objects: Array, data: ArrayCollection): Array
{
var B: Array = new Array();
var i: int = 0;
var j: int = 0;
for (i = 0; i < objects.length; ++i) // for all objects
{
for (j = 0; j < A.length; ++j) // for all attributes
{
if (!data[i][A[j]])
{
break;
}
}
if (j == A.length)
{
B.push(i);
}
}
return B;
}
public function fromBitSetToAttributeSet(A: Array, attributes: Array): Array
{
var i: int = 0;
var attrSet: Array = new Array();
for (i = 0; i < A.length; ++i)
{
if (A[i])
{
attrSet.push(i);
}
}
return attrSet;
}
public function fromAttributeSetToBitSet(A: Array, attributes: Array): Array
{
var i: int = 0;
var bitSet: Array = new Array();
for (i = 0; i < attributes.length; ++i)
{
bitSet.push(false);
}
for (i = 0; i < A.length; ++i)
{
bitSet[A[i]] = true;
}
return bitSet;
}
public function getIntent(B:Array, attributes: Array, data: ArrayCollection): Array
{
var A: Array = new Array();
var i: int = 0;
var j: int = 0;
for (j = 0; j < attributes.length; ++j) // for all attributes
{
for (i = 0; i < B.length; ++i) // for all objects
{
if (!data[B[i]][j])
{
break;
}
}
if (i == B.length)
{
A.push(j);
}
}
return A;
}
// B - A
public function getBitSetDifference(A: Array, B: Array): Array
{
var C: Array = new Array();
var i: int;
for (i = 0; i < A.length; ++i)
{
if (A[i] == B[i])
{
C.push(false);
}
else
{
C.push(B[i]);
}
}
return C;
}
public function getAttrSetAsString(A: Array, attributes:Array): String
{
var s:String = "";
var i: int = 0;
var sA: Array = new Array();
for (i = 0; i < A.length; ++i)
{
sA.push("<b>" + attributes[A[i]] + "</b>");
}
s = sA.join(", ");
if (s == "")
{
s = "<i>no</i>";
}
return s;
}
public var sPremise: ArrayCollection = new ArrayCollection();
public var sConclusion: ArrayCollection = new ArrayCollection();
// A is included in X
private function Included(bsA: Array, bsX: Array): Boolean
{
var i: int = 0;
for (i = 0; i < bsA.length; ++i)
{
if (bsA[i])
{
if (!bsX[i])
{
break;
}
}
}
return (i == bsA.length);
}
// A <iPos B
private function Smaller(bsA: Array, bsB: Array, iPos: int): Boolean
{
var i: int = 0;
for (i = 0; i < bsA.length; ++i)
{
if (bsA[i] != bsB[i])
{
break;
}
}
if (i < iPos)
{
return false;
}
// i >= iPos
return (bsB[i]);
}
private function Alpha(bsA: Array): Array
{
var i: int = 0;
var bsAlpha: Array = new Array();
for (i = 0; i < bsA.length; ++i)
{
bsAlpha.push(bsA[i]); // copy values
}
for (i = 0; i < sPremise.length; ++i)
{
if (Included(sPremise[i], bsA))
{
var j: int = 0;
for (j = 0; j < sConclusion[i].length; ++j)
{
if (sConclusion[i][j])
{
bsAlpha[j] = true;
}
}
}
}
return bsAlpha;
}
public function FirstClosure(objects: Array, attributes: Array, data: ArrayCollection): Array
{
var bsA: Array = new Array();
var i: int = 0;
for (i = 0; i < attributes.length; ++i)
{
bsA.push(false);
}
var bsADeriv: Array = fromAttributeSetToBitSet(
getIntent(
getExtent(
fromBitSetToAttributeSet(bsA, attributes),
objects, data),
attributes, data),
attributes);
sPremise.addItem(bsA);
sConclusion.addItem(bsADeriv);
return bsA;
}
public function NextClosure(bsA: Array, objects: Array, attributes: Array, data: ArrayCollection): Array
{
var i: int = attributes.length;
var bsIA: Array = new Array(); // bsA without modifications
for (i = 0; i < bsA.length; ++i)
{
bsIA.push(bsA[i]);
}
var success: Boolean = false;
do
{
var j: int = 0;
i = i - 1;
if (bsA[i] == false)
{
bsA[i] = true;
// bsA is now a valid A . i
var bsAlpha: Array = Alpha(bsA);
// bsAlpha is now Alpha(A . i)
if (Smaller(bsIA, bsAlpha, i))
{
var bsAlphaDeriv: Array = fromAttributeSetToBitSet(
getIntent(
getExtent(
fromBitSetToAttributeSet(bsAlpha, attributes),
objects, data),
attributes, data),
attributes);
sPremise.addItem(bsAlpha);
sConclusion.addItem(bsAlphaDeriv);
success = true;
}
else
{
bsA[i] = false;
}
}
else
{
bsA[i] = false;
}
} while ((success == false) && (i > 0))
return bsAlpha;
}
}
} |
package ru.codestage.xfltool.ui.controls.log
{
import com.bit101.components.Panel;
import com.bit101.components.ScrollPane;
import com.bit101.components.Style;
import com.bit101.components.TextArea;
import com.junkbyte.console.Cc;
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.AntiAliasType;
import flash.text.StyleSheet;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.utils.setTimeout;
import ru.codestage.utils.string.StrUtil;
import ru.codestage.xfltool.Main;
import ru.codestage.xfltool.ui.controls.customized.ScrollPaneNoHScroll;
import ru.codestage.xfltool.ui.controls.customized.TextAreaHTML;
import ru.codestage.xfltool.ui.locale.LocaleManager;
/**
* ...
* @author Dmitriy [focus] Yukhanov
*/
public final class LogArea extends TextAreaHTML
{
private var _currentLogIndex:uint;
//private var items:Vector.<LogAreaItem> = new Vector.<LogAreaItem>();
private var totalHints:Vector.<String> = new Vector.<String>();
//private var _locked:Boolean = false;
public function LogArea(parent:DisplayObjectContainer = null, xpos:Number = 0, ypos:Number = 0, text:String="")
{
super(parent, xpos, ypos, text);
_init();
}
private function _init():void
{
_currentLogIndex = 0;
this.addEventListener(MouseEvent.MOUSE_WHEEL, this_mouseWheel);
this.autoHideScrollBar = true;
this.mouseEnabled = false;
this.html = true;
this.editable = false;
this.selectable = true;
textField.defaultTextFormat = new TextFormat(Style.fontName, 14, Style.LABEL_TEXT);
textField.styleSheet = Main.instance.logStyle.styleSheet;
}
private function this_mouseWheel(e:MouseEvent):void
{
_scrollbar.value -= e.delta*10;
}
public function add(newLogLines:String, type:String = null, hint:String = null):void
{
if (type != null)
{
text += "<span class='" + type + "'>" + newLogLines + "</span><span class='line'> <br> </span><br>";
}
else
{
text += "<span class='body'>" + newLogLines + "</span><span class='line'> <br> </span><br>";
}
_scrollDownRequestsCounter++;
if (hint)
{
hint = "<span class='" + type + "'>" + LocaleManager.getString(LocaleManager.LOG_HINT) + "</span><i>" + hint + "</i>";
if (totalHints.indexOf(hint) == -1)
{
totalHints[totalHints.length] = hint;
}
}
}
public function addTotalHints():void
{
var len:uint = totalHints.length;
var i:uint = 0;
for (i; i < len; i++ )
{
add(totalHints[i], LogStyle.TYPE_CONTEXT_HINT);
}
totalHints.length = 0;
}
public function clear():void
{
_currentLogIndex = 0;
text = "";
totalHints.length = 0;
draw();
}
public function getRawText():String
{
/*var result:String = "";
var len:uint = items.length;
var i:uint = 0;
for (i; i < len; i++ )
{
result += items[i].getRawText() + "\n==========================================================================\n";
}*/
return _tf.text;
}
/*public function lock():void
{
_locked = true;
}
public function unlock():void
{
setTimeout(_afterUnlock, 500);
}*/
}
} |
package {
import openfl.display.Stage;
public class Main {
public function Main () {
var stage:Stage = new Stage (550, 400, 0xFFFFFF, App);
document.body.appendChild (stage.element);
}
}
} |
/**
* Copyright (C) 2008 Darshan Sawardekar.
*
* 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.puremvc.as3.multicore.utilities.fabrication.events.test {
import org.puremvc.as3.multicore.utilities.fabrication.addons.BaseTestCase;
import org.puremvc.as3.multicore.utilities.fabrication.events.*;
import org.puremvc.as3.multicore.utilities.fabrication.interfaces.IDisposable;
/**
* @author Darshan Sawardekar
*/
public class FabricatorEventTest extends BaseTestCase {
private var fabricatorEvent:FabricatorEvent;
[Before]
public function setUp():void
{
fabricatorEvent = new FabricatorEvent(FabricatorEvent.FABRICATION_CREATED);
}
[After]
public function tearDown():void
{
fabricatorEvent.dispose();
fabricatorEvent = null;
}
[Test]
public function testInstantiation():void
{
assertType(FabricatorEvent, fabricatorEvent);
}
[Test]
public function testFabricatorEventHasCreatedType():void
{
assertNotNull(FabricatorEvent.FABRICATION_CREATED);
}
[Test]
public function testFabricatorEventHasRemovedType():void
{
assertNotNull(FabricatorEvent.FABRICATION_REMOVED);
}
[Test]
public function testFabricatorEventStoresCreatedType():void
{
var event:FabricatorEvent = new FabricatorEvent(FabricatorEvent.FABRICATION_CREATED);
assertEquals(FabricatorEvent.FABRICATION_CREATED, event.type);
}
[Test]
public function fabricatorEventStoresRemovedType():void
{
var event:FabricatorEvent = new FabricatorEvent(FabricatorEvent.FABRICATION_REMOVED);
assertEquals(FabricatorEvent.FABRICATION_REMOVED, event.type);
}
public function fabricatorEventIsDisposable():void
{
assertType(IDisposable, fabricatorEvent);
}
}
}
|
/*
* Copyright 2011 the original author or authors.
*
* 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.spicefactory.parsley.command.impl {
import org.spicefactory.lib.command.CommandResult;
import org.spicefactory.lib.command.data.CommandData;
import org.spicefactory.lib.command.lifecycle.DefaultCommandLifecycle;
import org.spicefactory.lib.command.proxy.CommandProxy;
import org.spicefactory.lib.reflect.ClassInfo;
import org.spicefactory.parsley.core.command.ManagedCommandProxy;
import org.spicefactory.parsley.core.command.ObservableCommand;
import org.spicefactory.parsley.core.context.Context;
import org.spicefactory.parsley.core.context.DynamicObject;
import org.spicefactory.parsley.core.messaging.Message;
import org.spicefactory.parsley.core.state.GlobalState;
import flash.utils.Dictionary;
/**
* Extension of the standalone CommandLifecycle from Spicelib that deals with
* adding and removing commands to/from the Context during execution and passing
* them to the CommandManager.
*
* @author Jens Halm
*/
public class ManagedCommandLifecycle extends DefaultCommandLifecycle {
private var context:Context;
private var _trigger:Message;
private var nextId:String;
private var root:Boolean = true;
private var observables:Dictionary = new Dictionary();
/**
* Creates a new instance.
*
* @param context the Context all commands should be added to during execution
* @param root the root command this lifecycle gets applied to
* @param trigger the message that triggered the command (if any)
*/
function ManagedCommandLifecycle (context:Context, root:ManagedCommandProxy, trigger:Message = null) {
super(context.domain);
this.context = context;
this.nextId = root.id;
this._trigger = trigger;
}
/**
* The message that triggered the command.
* This property is null when the command was started programmatically.
*/
public function get trigger (): Message {
return _trigger;
}
/**
* @private
*/
public override function beforeExecution (command:Object, data:CommandData) : void {
if (isObservableTarget(command)) {
var dynamicObject:DynamicObject;
if (!GlobalState.objects.isManaged(command)) {
dynamicObject = context.addDynamicObject(command);
dynamicObject.instance; // force immediate addition to Context
}
var targetContext: Context = (trigger) ? trigger.senderContext : context;
targetContext.scopeManager.observeCommand(createObservableCommand(command, dynamicObject));
}
else if (command is ManagedCommandProxy) {
nextId = ManagedCommandProxy(command).id;
}
}
/**
* @private
*/
public override function afterCompletion (command:Object, result:CommandResult) : void {
if (observables[command]) {
var observable:ObservableCommandImpl = observables[command];
observable.setResult(result);
}
}
private function isObservableTarget (command:Object) : Boolean {
return (!(command is CommandProxy));
}
private function createObservableCommand (command:Object, dynamicObject:DynamicObject) : ObservableCommand {
var type:ClassInfo = ClassInfo.forInstance(command, context.domain);
var observable:ObservableCommand = new ObservableCommandImpl(command, type, dynamicObject, nextId, trigger, root);
root = false;
nextId = null;
observables[command] = observable;
return observable;
}
}
}
import org.spicefactory.lib.command.CommandResult;
import org.spicefactory.lib.reflect.ClassInfo;
import org.spicefactory.parsley.core.command.CommandStatus;
import org.spicefactory.parsley.core.command.ObservableCommand;
import org.spicefactory.parsley.core.context.DynamicObject;
import org.spicefactory.parsley.core.messaging.Message;
class ObservableCommandImpl implements ObservableCommand {
private var dynamicObject:DynamicObject;
private var _command:Object;
private var _type:ClassInfo;
private var _trigger:Message;
private var _id:String;
private var _status:CommandStatus;
private var _result:Object;
private var _root:Boolean;
private var callbacks:Array = [];
function ObservableCommandImpl (command:Object, type:ClassInfo, dynamicObject:DynamicObject = null,
id:String = null, trigger:Message = null, root:Boolean = false) {
this.dynamicObject = dynamicObject;
_command = command;
_type = type;
_id = id;
_trigger = trigger;
_root = root;
_status = CommandStatus.EXECUTE;
}
public function get trigger () : Message {
return _trigger;
}
public function get id () : String {
return _id;
}
public function get command () : Object {
return _command;
}
public function get type () : ClassInfo {
return _type;
}
public function get result () : Object {
return _result;
}
public function get status () : CommandStatus {
return _status;
}
public function get root () : Boolean {
return _root;
}
public function observe (callback:Function) : void {
callbacks.push(callback);
}
public function setResult (result:CommandResult) : void {
_status =
(result.complete) ? CommandStatus.COMPLETE
: (result.value) ? CommandStatus.ERROR : CommandStatus.CANCEL;
_result = result.value;
for each (var callback:Function in callbacks) {
callback(this);
}
callbacks = [];
if (dynamicObject) {
dynamicObject.remove();
dynamicObject = null;
}
}
}
|
package org.flexlite.domUI.skins.vector
{
import org.flexlite.domUI.components.Button;
import org.flexlite.domUI.components.UIAsset;
import org.flexlite.domCore.dx_internal;
import org.flexlite.domUI.skins.VectorSkin;
use namespace dx_internal;
/**
* 水平滑块默认皮肤
* @author DOM
*/
public class HSliderSkin extends VectorSkin
{
public function HSliderSkin()
{
super();
this.minWidth = 50;
this.minHeight = 11;
}
public var thumb:Button;
public var track:Button;
public var trackHighlight:UIAsset;
/**
* @inheritDoc
*/
override protected function createChildren():void
{
super.createChildren();
track = new Button;
track.left = 0;
track.right = 0;
track.top = 0;
track.bottom = 0;
track.minWidth = 33;
track.width = 100;
track.tabEnabled = false;
track.skinName = HSliderTrackSkin;
addElement(track);
trackHighlight = new UIAsset;
trackHighlight.top = 0;
trackHighlight.bottom = 0;
trackHighlight.minWidth = 33;
trackHighlight.width = 100;
trackHighlight.tabEnabled = false;
trackHighlight.skinName = HSliderTrackHighlightSkin;
addElement(trackHighlight);
thumb = new Button();
thumb.top = 0;
thumb.bottom = 0;
thumb.width = 11;
thumb.height = 11;
thumb.tabEnabled = false;
thumb.skinName = SliderThumbSkin;
addElement(thumb);
}
/**
* @inheritDoc
*/
override protected function updateDisplayList(w:Number,h:Number):void
{
super.updateDisplayList(w,h);
this.alpha = currentState=="disabled"?0.5:1;
}
}
} |
/*
* Class: Accessibility
* @author Ryan C. Knaggs
* @since 1.0
* @version 1.0 - RCK
* @date 12/03/2009
* @description: This class object is designed to
* allow a user to interact with this
* application by using the keyboard
*/
package models
{
import communication.WebServices;
import controller.MenuController;
import flash.accessibility.*;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.external.ExternalInterface;
import flash.utils.*;
import flash.utils.Timer;
import libs.utils.ExtendedChars;
import libs.vo.EventVO;
import libs.vo.GlobalsVO;
import mx.controls.Label;
import mx.core.*;
import mxml.CategoryItem;
import mxml.Menu;
import mxml.MenuItem;
public class Accessibility_Model
{
private var loop:Timer; // Focus iterator
private var _menuController:MenuController; // Menu controller
private var _currentMenuContainer:Menu; // Current menu container that is displayed
private var _currentMenuItems:Array; // Current menuitems that exist inside the menu container
private var _currentTabbedSelection:Object = new Object();
// Is menu open Flag
private var _isOpen:Boolean = false;
// Is menu Flag
private var _isMenu_F:Boolean = false;
// Categories
private var _maxCategories:int;
private var _categoryIndex:int;
// Menu Items
private var _menuItemIndex:int;
private var _maxMenuItems:int;
private var _forceShowMenuItem:Boolean = false; // When user select SHIFT+TAB to advance back
private var _tabIndex:int;
private var _tabList:Array;
private var _tabIsFwd:Boolean = true;
private var _space_F:Boolean = true;
private var _currentInstanceObject:Object;
// Alias
private const MCR:String = "MenuController";
/**
* Constructor
*/
public function Accessibility_Model() {
_tabIndex = -1;
resetMenu();
}
/**
* Keyboard behavior
* @param key:Object
* @see JSInterface
*/
public function keySelect(key:Object):void {
/* This class object MUST be referenced after
* Everything has initialized. Don't place this
* in the constructor of this class object
* otherwise it will be null */
if(this._menuController == null) {
//trace("get tablist");
_tabList = GlobalsVO.accessableTabList;
// Get MenuController
_menuController = MenuController(GlobalsVO.getGlobal(MCR));
/* Setup Listener on menu controller
* when a new menu has invoked */
try {
_menuController.addEventListener(EventVO.NEWMENU,onMenuController);
} catch(e:Error) {
return;
}
/* Set the max number of menu
* categories to work with */
try {
_maxCategories = _menuController.createMenuBar.getCategories().length;
} catch(e:Error) {
_maxCategories = 0
}
}
/* Determine what key from
* keyboard was pressed */
switch(key.keyCode) {
// Tab key
case 9:
_tabIsFwd = !key.isShift
onTab();
break;
// Spacebar
case 32:
navigateURL();
break;
// Left Arrow
case 37:
_menuItemIndex = -1;
onCategory(false);
break;
// Up Arrow
case 38:
onMenuItem(false);
break;
// Right Arrow
case 39:
_menuItemIndex = -1;
onCategory(true);
break;
// Down Arrow
case 40:
onMenuItem(true);
break;
}
}
/**
* Menu controller available
* @param e
*/
public function onMenuController(e:Event):void {
/* If the Menu Controller dispatched
* then setup a listener for a new menu
* This is needed to access all then resources
* for the new created menu */
if(e.currentTarget is MenuController) {
_currentMenuContainer = e.currentTarget._childObject as Menu;
_currentMenuContainer.addEventListener(EventVO.ONMENULOAD,onNewMenu);
}
}
/**
* If the user selected the TAB key
* @param _tabIsFwd
*/
private function onTab():void {
// If menu not opened
if(!_isMenu_F) {
_tabIndex += _tabIsFwd ? 1 : -1;
}
if(_tabIndex >= GlobalsVO.INIT_TAB_MENUBAR && _maxCategories > 0) {
_isMenu_F = true;
unFocusHeader();
onTabMenu(_tabIsFwd);
} else {
if(_isOpen) {
resetMenu();
}
focus();
}
}
/**
* Initialize the Menu
* for positioning purposes
*/
private function resetMenu():void {
_categoryIndex = -1;
_menuItemIndex = -1;
try {
_menuController.deleteChildrenObjects();
_isOpen = false;
} catch(e:Error){}
}
/**
* After the menu is finished being constructed
* and is ready, then you can get reference to
* all of the menu's public accessed objects
* @param e:Event - Current menu reference of the
* newly created menu that has displayed on the stage
*/
public function onNewMenu(e:Event):void {
/* If new menu selected, then set this flag
* Needed for onTab method */
_isOpen = true;
/* At this point, you have all references to
* all public object that are inside the
* Menu.mxml object.
* The menuInitializer holds on to all of the
* menuitems that are inside the current menu
* container
* @see view.InitializeMenu_View.as */
// Menu Items Array Reference
_currentMenuItems = e.currentTarget.menuInitializer.menuItemArr;
// Max Number of Menu Items
_maxMenuItems = _currentMenuItems.length;
// Clean Up
_currentMenuContainer.removeEventListener(EventVO.ONMENULOAD,onNewMenu);
/* If the user selects SHIFT+TAB while
* using the menu and the menu is about to
* go to the previous category */
if(_forceShowMenuItem) {
_forceShowMenuItem = false;
_menuItemIndex = _maxMenuItems-1;
menuItemSelect();
}
}
/**
* Required to fix a bug with Flex focus to
* properly focus on the correct asset
*/
private function focus():void {
if(loop != null) {
loop.stop();
loop = null;
}
if(loop == null) {
loop = new Timer(10,1);
loop.addEventListener(TimerEvent.TIMER,onHeaderFocus);
loop.start();
}
}
/**
* Verify if the next item to tab
* exists. If not the check to see
* if the next or previous one exists
* @return:Object - Display Object
* to set focus
*/
private function validateTab():Object {
var i:int;
var instance:Object;
_currentInstanceObject = instance = getTabObjectByPriority(_tabIndex);
//trace("\n\n_currentInstanceObject: "+_currentInstanceObject);
/* If the Flex components want to respond based on focus
* such as a button and you do not wish for that class
* to react, then you need to set something in the class
to respond or not */
if(instance == null) {
// Check if no more items in header to tab through
if(_tabIndex >= _tabList.length) {
_tabIndex == GlobalsVO.INIT_TAB_MENUBAR;
if(_maxCategories <=0) {
exitFocus();
} else {
onTab();
}
}
// Tab is forward
if(_tabIsFwd) {
for(i=_tabIndex;i<_tabList.length;++i) {
_tabIndex++;
instance = getTabObjectByPriority(_tabIndex);
//trace("3 loop validateTab: "+_tabIndex);
if(instance != null) {
return instance;
}
}
// Otherwise Backwards
} else {
for(i=_tabList.length;i>0;--i) {
_tabIndex--;
instance = getTabObjectByPriority(_tabIndex);
if(instance != null) {
return instance;
}
}
}
}
return instance;
}
/**
* Navigate to the current selection
* from one of the items in the header
* or the menu
*/
private function navigateURL():void {
/* If user is focued on the search field
* and presses the space bar while entering
* in a word, skip navigateURL */
if(_currentInstanceObject.toString().toLowerCase().indexOf("searchfield") > -1) return;
if(_currentTabbedSelection.value == null || _currentTabbedSelection.value == undefined) return;
//trace("Selected URL: "+_currentTabbedSelection.value,_currentTabbedSelection.target);
WebServices.navigateToUrl(_currentTabbedSelection.value,_currentTabbedSelection.target);
}
/**
* Set focus on an asset only for header
* @param e
*/
private function onHeaderFocus(e:TimerEvent):void {
var instance:Object = validateTab();
try {
instance.setFocus();
instance.drawFocus(true);
talk(instance.parentDocument.getDataByAccessibility(instance));
} catch(e:Error) {}
}
/**
* Converts HTML stuff back to a talkable word
* such as &
* @param str
* @return
*/
private function convertHTMLtoWord(str:String):String {
return new ExtendedChars().convertWord(str);
}
private function talk(valueObj:Object=null):void {
//trace("talk: "+valueObj);
/* for(var i:Object in valueObj) {
trace("i: "+i+" valueObj[i]: "+valueObj[i]);
} */
var vo:String = new String();
try {
vo = valueObj.component.toString();
} catch(e:Error) {
vo = "";
}
trace("\n####################vo: "+vo);
if(vo.indexOf("searchField") > -1) {
//trace("######## 1");
ExternalInterface.call("focusMe",1);
} else {
//trace("######## 0");
ExternalInterface.call("focusMe",0);
}
GlobalsVO.getGlobal(GlobalsVO.JSINTERFACE).talk(convertHTMLtoWord(valueObj.name));
/* Set current URL when the user selects
* the spacebar */
_currentTabbedSelection = valueObj;
}
/**
* Get the displayObject based on the index
* @param index
* @return
*/
private function getTabObjectByPriority(index:int):* {
for(var i:int=0; i<_tabList.length; ++i) {
try{
if(_tabList[i].tabOrder == index) {
return _tabList[i].displayObject;
}
} catch(e:Error) {}
}
return null;
}
/**
* Stop showing focus on items
* in the header bar
*/
private function unFocusHeader():void {
for(var i:int = 0; i< GlobalsVO.INIT_TAB_MENUBAR; ++i) {
try {
getTabObjectByPriority(i).drawFocus(false);
} catch(e:Error) {}
}
/* The last option is the search button
* the setfocus needs to stop focusing on the
* search button, if the user decides to tab
* to the menu categories and menuitems.
* You simply can't unfocus from the current focused
* object. Instead, you need to focus on a new object*/
var label:Label = new Label();
var instance:Object = FlexGlobals.topLevelApplication.addChild(label);
label.setFocus();
FlexGlobals.topLevelApplication.removeChild(instance);
}
/**
* If the "Tab" key was selected
* @param isForward:Boolean
*/
private function onTabMenu(isForward:Boolean):void {
// Tab key advance by one
if(isForward) {
// If menu is open
if(_isOpen) {
/* If the menu item index exceeds max menuitems
* for the current menu container */
if(_menuItemIndex >=_maxMenuItems-1) {
onCategory(true);
} else {
// Tab forward and go to the next menuitem below
onMenuItem(true);
}
} else {
// If first time menu open from tab key
onCategory(true);
}
} else {
// If menu is open
if(_isOpen) {
// If menu item index is at the top
if(_menuItemIndex <=0) {
/* If the first category is displayed
* SHIFT+TAB was selected
* then go back to the header */
if(_categoryIndex <= 0) {
_isMenu_F = false;
resetMenu();
_tabIsFwd = false;
onTab();
return;
}
// Display Menu item in last row for previous menu show
_forceShowMenuItem = true;
onCategory(false);
} else {
onMenuItem(false);
}
} else {
onCategory(false); // If first time menu open from tab key
}
}
}
/**
* Advance new category
* @param isRight
*/
private function onCategory(isRight:Boolean):void {
// If the menubar is blank
if(_maxCategories <= 0) exitFocus();
// Assume that the menu is closed
_isOpen = false;
// If Left or Right Arrow key
if(isRight) {
_categoryIndex++;
_menuItemIndex = -1;
} else {
_categoryIndex--;
}
if(_categoryIndex == -1) {
_categoryIndex = 0;
}
// If last category reach, then repeat
if(_categoryIndex >= _maxCategories) {
exitFocus();
_categoryIndex = 0;
return;
}
var instance:CategoryItem = _menuController.createMenuBar.getCategoryRef(_categoryIndex) as CategoryItem;
_menuController.newCategory(null,instance);
talk(instance.getDataByAccessibility(instance));
}
/**
* Select the current menuitem from the
* current menu container
*/
private function menuItemSelect():void {
// Call the Menu.mxml container and select a menuitem
var instance:MenuItem = _currentMenuItems[_menuItemIndex] as MenuItem;
_currentMenuContainer.selectMenuItem(null,instance);
talk(instance.getDataByAccessibility(instance));
}
/**
* Send focus back to the JS container
*/
public function exitFocus():void {
//trace("exitFocus");
resetMenu();
try {
GlobalsVO.getGlobal(GlobalsVO.JSINTERFACE).tabOut();
} catch (e:Error) {}
}
/**
* Advance the menuitem
* @param isDown:Boolean
*/
private function onMenuItem(isDown:Boolean):void {
// If menu is not open then ignore
if(!_isOpen) return;
// If isDown then advance down
isDown ? _menuItemIndex++ : _menuItemIndex--;
// If first menuitem and up then goto the last menuitem
if(_menuItemIndex < 0) _menuItemIndex = _maxMenuItems-1;
// If the last menuitem and down then goto the first menuitem
if(_menuItemIndex >= _maxMenuItems) _menuItemIndex = 0;
menuItemSelect();
}
}
} |
// Rotator script object class. Script objects to be added to a scene node must implement the empty ScriptObject interface
class Checkpoint : ScriptObject
{
Vector3 scale;
void Start()
{
// Subscribe physics collisions that concern this scene node
SubscribeToEvent(node, "NodeCollisionStart", "HandleNodeCollision");
scale = node.scale;
}
void HandleNodeCollision(StringHash eventType, VariantMap& eventData)
{
// Get the other colliding body, make sure it is moving (has nonzero mass)
RigidBody@ otherBody = eventData["OtherBody"].GetPtr();
if (otherBody.mass > 0.0f)
{
if (otherBody.node.vars.Contains("Player")) {
VariantMap data;
data["Score"] = 2;
otherBody.node.SendEvent("PlayerScoreAdd", data);
SendEvent("CheckpointReached");
data["Type"] = SOUND_EFFECT;
data["SoundFile"] = "Data/Sounds/checkpoint.wav";
SendEvent("PlaySound", data);
node.Remove();
}
}
}
// Update is called during the variable timestep scene update
void Update(float timeStep)
{
node.Rotate(Quaternion(0, timeStep * 10, 0));
Vector3 newScale = scale + scale * Sin(time.elapsedTime * 200.0f) * 0.1f;
newScale.y = scale.y;
node.scale = newScale;
}
}
|
/*
* PROJECT: FLARToolKit
* --------------------------------------------------------------------------------
* This work is based on the FLARToolKit developed by
* R.Iizuka (nyatla)
* http://nyatla.jp/nyatoolkit/
*
* The FLARToolKit is ActionScript 3.0 version ARToolkit class library.
* Copyright (C)2008 Saqoosha
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* For further information please contact.
* http://www.libspark.org/wiki/saqoosha/FLARToolKit
* <saq(at)saqoosha.net>
*
*/
package org.libspark.flartoolkit.markersystem.utils
{
import org.libspark.flartoolkit.core.*;
import org.libspark.flartoolkit.core.match.*;
/**
* このクラスは、ARマーカの検出結果を保存するデータクラスです。
*/
public class ARMarkerList_Item extends TMarkerData
{
/** MK_ARの情報。比較のための、ARToolKitマーカを格納します。*/
public var matchpatt:FLARMatchPatt_Color_WITHOUT_PCA;
/** MK_ARの情報。検出した矩形の格納変数。マーカの一致度を格納します。*/
public var cf:Number;
public var patt_w:int;
public var patt_h:int;
/** MK_ARの情報。パターンのエッジ割合。*/
public var patt_edge_percentage:int;
/** */
public function ARMarkerList_Item(i_patt:FLARCode,i_patt_edge_percentage:int,i_patt_size:Number)
{
super();
this.matchpatt=new FLARMatchPatt_Color_WITHOUT_PCA(i_patt);
this.patt_edge_percentage=i_patt_edge_percentage;
this.marker_offset.setSquare(i_patt_size);
this.patt_w=i_patt.getWidth();
this.patt_h=i_patt.getHeight();
return;
}
}
} |
/**
* Copyright (c) 2012 - 2100 Sindney
*
* 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 bloom.brushes
{
import flash.text.TextFormat;
import bloom.events.BrushEvent;
/**
* Dispatched when redraw is needed.
* @eventType bloom.events.BrushEvent
*/
[BrushEvent(name = "redraw", type = "bloom.events.BrushEvent")]
/**
* TextBrush
*
* @author sindney
*/
public class TextBrush extends Brush {
private var _textFormat:TextFormat;
public function TextBrush(font:String = "Verdana", size:int = 12, color:uint = 0x000000, bold:Boolean = false, italic:Boolean = false, underline:Boolean = false) {
super();
_textFormat = new TextFormat(font, size, color, bold, italic, underline);
}
/**
* Use this to make your changes up to date.
*/
override public function update():void {
dispatchEvent(new BrushEvent("redraw"));
}
override public function clone():Brush {
return new TextBrush(_textFormat.font, int(_textFormat.size), uint(_textFormat.color), Boolean(_textFormat.bold), Boolean(_textFormat.italic), Boolean(_textFormat.underline));
}
override public function destroy():void {
_textFormat = null;
}
///////////////////////////////////
// getter/setters
///////////////////////////////////
public function get textFormat():TextFormat {
return _textFormat;
}
///////////////////////////////////
// toString
///////////////////////////////////
public override function toString():String {
return "[bloom.brushes.TextBrush]";
}
}
} |
//THIS FILE IS AUTO GENERATED, DO NOT MODIFY!!
//THIS FILE IS AUTO GENERATED, DO NOT MODIFY!!
//THIS FILE IS AUTO GENERATED, DO NOT MODIFY!!
package com.gamesparks.api.messages
{
import com.gamesparks.api.types.*;
import com.gamesparks.*;
/**
* A message sent to sockets when disconnectOthers() has been called.
*/
public class SessionTerminatedMessage extends GSResponse
{
public static var MESSAGE_TYPE:String = ".SessionTerminatedMessage";
public function SessionTerminatedMessage(data : Object)
{
super(data);
}
/**
* Used to automatically re-authenticate a client during socket connect.
*/
public function getAuthToken() : String
{
if(data.authToken != null)
{
return data.authToken;
}
return null;
}
}
}
|
package org.openapitools.client.model {
import org.openapitools.common.ListWrapper;
public class RequestedPageDetailsList implements ListWrapper {
// This declaration below of _RequestedPageDetails_obj_class is to force flash compiler to include this class
private var _requestedPageDetails_obj_class: org.openapitools.client.model.RequestedPageDetails = null;
[XmlElements(name="requestedPageDetails", type="org.openapitools.client.model.RequestedPageDetails")]
public var requestedPageDetails: Array = new Array();
public function getList(): Array{
return requestedPageDetails;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package spark.automation.delegates.components.supportClasses
{
import flash.display.DisplayObject;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.ui.Keyboard;
import mx.automation.Automation;
import mx.automation.events.AutomationRecordEvent;
import mx.core.EventPriority;
import mx.core.mx_internal;
import spark.components.supportClasses.ButtonBarBase;
import spark.events.IndexChangeEvent;
use namespace mx_internal;
[Mixin]
/**
*
* Defines methods and properties required to perform instrumentation for the
* ButtonBarBase control.
*
* @see spark.components.supportClasses.ButtonBarBase
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*
*/
public class SparkButtonBarBaseAutomationImpl extends SparkListBaseAutomationImpl
{
include "../../../../core/Version.as";
//--------------------------------------------------------------------------
//
// Class methods
//
//--------------------------------------------------------------------------
/**
* Registers the delegate class for a component class with automation manager.
*
* @param root The SystemManger of the application.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public static function init(root:DisplayObject):void
{
Automation.registerDelegateClass(spark.components.supportClasses.ButtonBarBase, SparkButtonBarBaseAutomationImpl);
}
/**
* Constructor.
* @param obj ButtonBarBase object to be automated.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function SparkButtonBarBaseAutomationImpl(obj:spark.components.supportClasses.ButtonBarBase)
{
super(obj);
recordClick = false;
obj.addEventListener(AutomationRecordEvent.RECORD, automationRecordHandler, false, EventPriority.DEFAULT+1, true);
obj.addEventListener(spark.events.IndexChangeEvent.CHANGE, itemClickHandler, false, 0, true);
}
/**
* @private
*/
private function automationRecordHandler(event:AutomationRecordEvent):void
{
if (event.replayableEvent.type == MouseEvent.CLICK)
event.stopImmediatePropagation();
}
/**
* @private
*/
protected function itemClickHandler(event:spark.events.IndexChangeEvent):void
{
}
//--------------------------------------------------------------------------
//
// Event handlers
//
//--------------------------------------------------------------------------
/**
* @private
*/
override protected function keyDownHandler(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.DOWN:
case Keyboard.RIGHT:
case Keyboard.UP:
case Keyboard.LEFT:
recordAutomatableEvent(event);
break;
}
}
}
}
|
package dragonBones.objects
{
/**
* @private
*/
public class FFDTimelineData extends TimelineData
{
public var skin:SkinData;
public var slot:SkinSlotData;
public var display:DisplayData;
public function FFDTimelineData()
{
super(this);
}
override protected function _onClear():void
{
super._onClear();
skin = null;
slot = null;
display = null;
}
}
} |
package com.gestureworks.cml.elements
{
import com.modestmaps.geo.Location;
/**
* A ModestMapMarker is primarily a container for graphic objects that gives the latitude and longitude of map.
* It has following parameters: longitude and longitude.
*
* @author Ideum
* @see ModestMap
*/
public class ModestMapMarker extends TouchContainer
{
/**
* Constructor
*/
public function ModestMapMarker()
{
super();
mouseChildren = true;
}
private var _longitude:Number;
/**
* Specifies the longitude of map
*/
public function get longitude():Number { return _longitude; }
public function set longitude(value:Number):void {
_longitude = value;
}
private var _latitude:Number;
/**
* Specifies the latitude of map
*/
public function get latitude():Number { return _latitude; }
public function set latitude(value:Number):void {
_latitude = value;
}
/**
* @inheritDoc
*/
override public function dispose():void {
super.dispose();
}
/**
* Initialisation method
*/
override public function init():void {}
}
} |
/*
The MIT License (MIT)
Copyright (c) 2013-2014 winlin
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
{
import flash.events.NetStatusEvent;
import flash.external.ExternalInterface;
import flash.net.NetConnection;
import flash.net.ObjectEncoding;
import flash.utils.clearTimeout;
import flash.utils.setTimeout;
/**
* SRS bandwidth check/test library,
* user can copy this file and use it directly,
* this library will export as callback functions, and js callback functions.
*
* Usage:
* var bandwidth:SrsBandwidth = new SrsBandwidth();
* bandwidth.initialize(......); // required
* bandwidth.check_bandwidth(......); // required
* bandwidth.stop(); // optional
*
* @remark we donot use event, but use callback functions set by initialize.
*/
public class SrsBandwidth
{
/**
* server notice client to do the downloading/play bandwidth test.
*/
public static const StatusSrsBwtcPlayStart:String = "srs.bwtc.play.start";
/**
* server notice client to complete the downloading/play bandwidth test.
*/
public static const StatusSrsBwtcPlayStop:String = "srs.bwtc.play.stop";
/**
* server notice client to do the uploading/publish bandwidth test.
*/
public static const StatusSrsBwtcPublishStart:String = "srs.bwtc.publish.start";
/**
* server notice client to complete the uploading/publish bandwidth test.
*/
public static const StatusSrsBwtcPublishStop:String = "srs.bwtc.publish.stop";
/**
* constructor, do nothing
*/
public function SrsBandwidth()
{
}
/**
* initialize the bandwidth test tool, the callbacks. null to ignore.
*
* the as callbacks.
* @param as_on_ready, function():void, callback when bandwidth tool is ready to run.
* @param as_on_status_change, function(code:String, data:String):void, where:
* code can be:
* "NetConnection.Connect.Failed", see NetStatusEvent(evt.info.code).
* "NetConnection.Connect.Rejected", see NetStatusEvent(evt.info.code).
* "NetConnection.Connect.Success", see NetStatusEvent(evt.info.code).
* "NetConnection.Connect.Closed", see NetStatusEvent(evt.info.code).
* SrsBandwidth.StatusSrsBwtcPlayStart, "srs.bwtc.play.start", when srs start test play bandwidth.
* SrsBandwidth.StatusSrsBwtcPlayStop, "srs.bwtc.play.stop", when srs complete test play bandwidth.
* SrsBandwidth.StatusSrsBwtcPublishStart, "srs.bwtc.publish.start", when srs start test publish bandwidth.
* SrsBandwidth.StatusSrsBwtcPublishStop, "srs.bwtc.publish.stop", when srs complete test publish bandwidth.
* data is extra parameter:
* kbps, for code is SrsBandwidth.StatusSrsBwtcPlayStop or SrsBandwidth.StatusSrsBwtcPublishStop.
* "", otherwise empty string.
* @param as_on_progress_change, function(percent:Number):void, where:
* percent, the progress percent, 0 means 0%, 100 means 100%.
* @param as_on_srs_info, function(srs_server:String, srs_primary_authors:String, srs_id:String, srs_pid:String, srs_server_ip:String):void, where:
* srs_server: the srs server info.
* srs_primary_authors: the srs version info.
* srs_id: the tracable log id, to direclty grep the log..
* srs_pid: the srs process id, to direclty grep the log.
* srs_server_ip: the srs server ip, where client connected at.
* @param as_on_complete, function(start_time:Number, end_time:Number, play_kbps:Number, publish_kbps:Number, play_bytes:Number, publish_bytes:Number, play_time:Number, publish_time:Number):void, where
* start_time, the start timestamp, in ms.
* end_time, the finish timestamp, in ms.
* play_kbps, the play/downloading kbps.
* publish_kbps, the publish/uploading kbps.
* play_bytes, the bytes play/download from server, in bytes.
* publish_bytes, the bytes publish/upload to server, in bytes.
* play_time, the play/download duration time, in ms.
* publish_time, the publish/upload duration time, in ms.
*
* the js callback id.
* @param js_id, specifies the id of swfobject, used to identify the bandwidth object.
* for all js callback, the first param always be the js_id, to identify the callback object.
*
* the js callbacks.
* @param js_on_ready, function(js_id:String):void, callback when bandwidth tool is ready to run.
* @param js_on_status_change, function(js_id:String, code:String, data:String):void
* @param as_on_progress_change, function(js_id:String, percent:Number):void
* @param as_on_srs_info, function(js_id:String, srs_server:String, srs_primary_authors:String, srs_id:String, srs_pid:String, srs_server_ip:String):void
* @param as_on_complete, function(js_id:String, start_time:Number, end_time:Number, play_kbps:Number, publish_kbps:Number, play_bytes:Number, publish_bytes:Number, play_time:Number, publish_time:Number):void
*
* the js export functions.
* @param js_export_check_bandwidth, function(url:String):void, for js to start bandwidth check, @see: check_bandwidth(url:String):void
* @param js_export_stop, function():void, for js to stop bandwidth check, @see: stop():void
*
* @remark, all parameters can be null.
* @remark, as and js callback use same parameter, except that the js calblack first parameter is js_id:String.
*/
public function initialize(
as_on_ready:Function, as_on_status_change:Function, as_on_progress_change:Function, as_on_srs_info:Function, as_on_complete:Function,
js_id:String, js_on_ready:String, js_on_status_change:String, js_on_progress_change:String, js_on_srs_info:String, js_on_complete:String,
js_export_check_bandwidth:String, js_export_stop:String
):void {
this.as_on_ready = as_on_ready;
this.as_on_srs_info = as_on_srs_info;
this.as_on_status_change = as_on_status_change;
this.as_on_progress_change = as_on_progress_change;
this.as_on_complete = as_on_complete;
this.js_id = js_id;
this.js_on_srs_info = js_on_srs_info;
this.js_on_ready = js_on_ready;
this.js_on_status_change = js_on_status_change;
this.js_on_progress_change = js_on_progress_change;
this.js_on_complete = js_on_complete;
this.js_export_check_bandwidth = js_export_check_bandwidth;
this.js_export_stop = js_export_stop;
flash.utils.setTimeout(this.system_on_js_ready, 0);
}
/**
* start check bandwidth.
* @param url, a String indicates the url to check bandwidth,
* format as: rtmp://server:port/app?key=xxx&&vhost=xxx
* for example, rtmp://dev:1935/app?key=35c9b402c12a7246868752e2878f7e0e&vhost=bandcheck.srs.com
* where the key and vhost must be config in SRS, like:
* vhost bandcheck.srs.com {
* enabled on;
* chunk_size 65000;
* bandcheck {
* enabled on;
* key "35c9b402c12a7246868752e2878f7e0e";
* interval 30;
* limit_kbps 4000;
* }
* }
*
* @remark user must invoke this as method, or js exported method.
*/
public function check_bandwidth(url:String):void {
this.js_call_check_bandwidth(url);
}
/**
* stop check bancwidth.
* @remark it's optional, however, user can abort the bandwidth check.
*/
public function stop():void {
this.js_call_stop();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////// ///////////////////////////////
////////////////////////// ///////////////////////////////
////////////////////////// ///////////////////////////////
////////////////////////// ///////////////////////////////
////////////////////////// Private Section, ignore please. ///////////////////////////////
////////////////////////// ///////////////////////////////
////////////////////////// ///////////////////////////////
////////////////////////// ///////////////////////////////
////////////////////////// ///////////////////////////////
////////////////////////// ///////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* ***********************************************************************
* private section, including private fields, method and embeded classes.
* ***********************************************************************
*/
/**
* as callback.
*/
private var as_on_ready:Function;
private var as_on_srs_info:Function;
private var as_on_status_change:Function;
private var as_on_progress_change:Function;
private var as_on_complete:Function;
/**
* js callback.
*/
private var js_id:String;
private var js_on_ready:String;
private var js_on_srs_info:String;
private var js_on_status_change:String;
private var js_on_progress_change:String;
private var js_on_complete:String;
/**
* js export functions.
*/
private var js_export_check_bandwidth:String;
private var js_export_stop:String;
/**
* srs debug infos
*/
private var srs_server:String = null;
private var srs_primary_authors:String = null;
private var srs_id:String = null;
private var srs_pid:String = null;
private var srs_server_ip:String = null;
/**
* the underlayer connection, to send call message to do the bandwidth
* check/test with server.
*/
private var connection:NetConnection = null;
/**
* use timeout to sendout publish call packets.
* when got stop publish packet from server, stop publish call loop.
*/
private var publish_timeout_handler:uint = 0;
/**
* system callack event, when js ready, register callback for js.
* the actual main function.
*/
private function system_on_js_ready():void {
if (!flash.external.ExternalInterface.available) {
trace("js not ready, try later.");
flash.utils.setTimeout(this.system_on_js_ready, 100);
return;
}
if (this.js_export_check_bandwidth != null) {
flash.external.ExternalInterface.addCallback(this.js_export_check_bandwidth, this.js_call_check_bandwidth);
}
if (this.js_export_stop != null) {
flash.external.ExternalInterface.addCallback(this.js_export_stop, this.js_call_stop);
}
if (as_on_ready != null) {
as_on_ready();
}
if (js_on_ready != null) {
flash.external.ExternalInterface.call(this.js_on_ready, this.js_id);
}
}
private function js_call_check_bandwidth(url:String):void {
js_call_stop();
__on_progress_change(0);
// init connection
connection = new NetConnection;
connection.objectEncoding = ObjectEncoding.AMF0;
connection.client = {
onStatus: onStatus,
// play
onSrsBandCheckStartPlayBytes: onSrsBandCheckStartPlayBytes,
onSrsBandCheckPlaying: onSrsBandCheckPlaying,
onSrsBandCheckStopPlayBytes: onSrsBandCheckStopPlayBytes,
// publish
onSrsBandCheckStartPublishBytes: onSrsBandCheckStartPublishBytes,
onSrsBandCheckStopPublishBytes: onSrsBandCheckStopPublishBytes,
onSrsBandCheckFinished: onSrsBandCheckFinished
};
connection.addEventListener(NetStatusEvent.NET_STATUS, onStatus);
connection.connect(url);
__on_progress_change(3);
}
private function js_call_stop():void {
if (connection) {
connection.close();
connection = null;
}
}
/**
* NetConnection callback this function, when recv server call "onSrsBandCheckStartPlayBytes"
* then start @updatePlayProgressTimer for updating the progressbar
* */
private function onSrsBandCheckStartPlayBytes(evt:Object):void{
var duration_ms:Number = evt.duration_ms;
var interval_ms:Number = evt.interval_ms;
trace("start play test, duration=" + duration_ms + ", interval=" + interval_ms);
connection.call("onSrsBandCheckStartingPlayBytes", null);
__on_status_change(SrsBandwidth.StatusSrsBwtcPlayStart);
__on_progress_change(10);
}
private function onSrsBandCheckPlaying(evt:Object):void{
}
private function onSrsBandCheckStopPlayBytes(evt:Object):void{
var duration_ms:Number = evt.duration_ms;
var interval_ms:Number = evt.interval_ms;
var duration_delta:Number = evt.duration_delta;
var bytes_delta:Number = evt.bytes_delta;
var kbps:Number = 0;
if(duration_delta > 0){
kbps = bytes_delta * 8.0 / duration_delta; // b/ms == kbps
}
kbps = (int(kbps * 10))/10.0;
flash.utils.setTimeout(stopPlayTest, 0);
__on_status_change(SrsBandwidth.StatusSrsBwtcPlayStop, String(kbps));
__on_progress_change(40);
}
private function stopPlayTest():void{
connection.call("onSrsBandCheckStoppedPlayBytes", null);
}
/**
* publishing methods.
*/
private function onSrsBandCheckStartPublishBytes(evt:Object):void{
var duration_ms:Number = evt.duration_ms;
var interval_ms:Number = evt.interval_ms;
connection.call("onSrsBandCheckStartingPublishBytes", null);
flash.utils.setTimeout(publisher, 0);
__on_status_change(SrsBandwidth.StatusSrsBwtcPublishStart);
__on_progress_change(60);
}
private function publisher():void{
var data:Array = new Array();
/**
* the data size cannot too large, it will increase the test time.
* server need atleast got one packet, then timeout to stop the publish.
*
* cannot too small neither, it will limit the max publish kbps.
*
* the test values:
* test_s test_s
* data_size max_publish_kbps (no limit) (limit upload to 5KBps)
* 100 2116 6.5 7.3
* 200 4071 6.5 7.7
* 300 6438 6.5 10.3
* 400 9328 6.5 10.2
* 500 10377 6.5 10.0
* 600 13737 6.5 10.8
* 700 15635 6.5 12.0
* 800 18103 6.5 14.0
* 900 20484 6.5 14.2
* 1000 21447 6.5 16.8
*/
var data_size:int = 900;
for(var i:int; i < data_size; i++) {
data.push("SrS band check data from client's publishing......");
}
connection.call("onSrsBandCheckPublishing", null, data);
publish_timeout_handler = flash.utils.setTimeout(publisher, 0);
}
private function onSrsBandCheckStopPublishBytes(evt:Object):void{
var duration_ms:Number = evt.duration_ms;
var interval_ms:Number = evt.interval_ms;
var duration_delta:Number = evt.duration_delta;
var bytes_delta:Number = evt.bytes_delta;
var kbps:Number = 0;
if(duration_delta > 0){
kbps = bytes_delta * 8.0 / duration_delta; // b/ms == kbps
}
kbps = (int(kbps * 10))/10.0;
stopPublishTest();
__on_progress_change(90);
}
private function stopPublishTest():void{
// the stop publish response packet can not send out, for the queue is full.
//connection.call("onSrsBandCheckStoppedPublishBytes", null);
// clear the timeout to stop the send loop.
if (publish_timeout_handler > 0) {
flash.utils.clearTimeout(publish_timeout_handler);
publish_timeout_handler = 0;
}
}
private function onSrsBandCheckFinished(evt:Object):void{
var start_time:Number = evt.start_time;
var end_time:Number = evt.end_time;
var play_kbps:Number = evt.play_kbps;
var publish_kbps:Number = evt.publish_kbps;
var play_bytes:Number = evt.play_bytes;
var play_time:Number = evt.play_time;
var publish_bytes:Number = evt.publish_bytes;
var publish_time:Number = evt.publish_time;
if (this.as_on_complete != null) {
this.as_on_complete(start_time, end_time, play_kbps, publish_kbps, play_bytes, publish_bytes, play_time, publish_time);
}
if (this.js_on_complete != null) {
flash.external.ExternalInterface.call(this.js_on_complete, this.js_id,
start_time, end_time, play_kbps, publish_kbps, play_bytes, publish_bytes, play_time, publish_time);
}
__on_progress_change(100);
// when got finish packet, directly close connection.
js_call_stop();
// the last final packet can not send out, for the queue is full.
//connection.call("finalClientPacket", null);
}
/**
* get NetConnection NetStatusEvent
*/
private function onStatus(evt:NetStatusEvent): void {
trace(evt.info.code);
if (evt.info.hasOwnProperty("data") && evt.info.data) {
if (evt.info.data.hasOwnProperty("srs_server")) {
srs_server = evt.info.data.srs_server;
}
if (evt.info.data.hasOwnProperty("srs_primary_authors")) {
srs_primary_authors = evt.info.data.srs_primary_authors;
}
if (evt.info.data.hasOwnProperty("srs_id")) {
srs_id = evt.info.data.srs_id;
}
if (evt.info.data.hasOwnProperty("srs_pid")) {
srs_pid = evt.info.data.srs_pid;
}
if (evt.info.data.hasOwnProperty("srs_server_ip")) {
srs_server_ip = evt.info.data.srs_server_ip;
}
if (this.as_on_srs_info != null) {
this.as_on_srs_info(srs_server, srs_primary_authors, srs_id, srs_pid, srs_server_ip);
}
if (this.js_on_srs_info != null) {
flash.external.ExternalInterface.call(this.js_on_srs_info, this.js_id,
srs_server, srs_primary_authors, srs_id, srs_pid, srs_server_ip);
}
}
if (evt.info.code) {
__on_status_change(evt.info.code);
}
switch(evt.info.code){
case "NetConnection.Connect.Success":
__on_progress_change(8);
break;
}
}
/**
* invoke the callback.
*/
private function __on_progress_change(percent:Number):void {
if (this.as_on_progress_change != null) {
this.as_on_progress_change(percent);
}
if (this.js_on_progress_change != null) {
flash.external.ExternalInterface.call(this.js_on_progress_change, this.js_id,
percent);
}
}
private function __on_status_change(code:String, data:String=""):void {
if (this.as_on_status_change != null) {
this.as_on_status_change(code, data);
}
if (this.js_on_status_change != null) {
flash.external.ExternalInterface.call(this.js_on_status_change, this.js_id,
code, data);
}
}
}
} |
/* See LICENSE for copyright and terms of use */
import org.actionstep.NSAnimation;
import org.actionstep.constants.NSAnimationCurve;
/**
* <p>Invokes the method <code>animationDidAdvance</code>, which frees the delegate
* from specifiying a large number of progress marks for a smooth animation. This is
* also an alternative to the Cocoa-recommended subclassing of <code>NSAnimation</code>.
* </p>
*
* @author Tay Ray Chuan
*/
class org.actionstep.ASAnimation extends NSAnimation {
private var m_start:Number;
private var m_range:Number;
//******************************************************
//* Construction
//******************************************************
/**
* Creates a new instance of the <code>ASAnimation</code> class.
*/
public function ASAnimation() {
m_start = 0;
m_range = 1;
}
/**
* Initializes the animation.
*/
public function initWithDurationAnimationCurve(time:Number, curve:NSAnimationCurve):ASAnimation {
return ASAnimation(super.initWithDurationAnimationCurve(time, curve));
}
//******************************************************
//* Setting end points and progress
//******************************************************
/**
* Sets the points the animation interpolates between.
*
* The defaults are 0 and 1.
*/
public function setEndPoints(start:Number, end:Number):Void {
m_start = start;
m_range = end - start;
}
/**
* Overridden to call a special delegate method, and to transform the
* progress into a value between the animation's endpoints.
*/
public function setCurrentProgress(n:Number):Void {
super.setCurrentProgress(n);
var prog:Number = currentProgress() * m_range + m_start;
m_delegate["animationDidAdvance"].call(m_delegate, this, prog);
}
} |
//Created by Action Script Viewer - http://www.buraks.com/asv
package com.company.rotmg.graphics {
import flash.display.MovieClip;
[Embed(source="FullCharBoxGraphic.swf", symbol="com.company.rotmg.graphics.FullCharBoxGraphic")]
public dynamic class FullCharBoxGraphic extends MovieClip {
public function FullCharBoxGraphic() {
super();
}
}
}//package com.company.rotmg.graphics
|
////////////////////////////////////////////////////////////////////////////////
//
// ADOBE SYSTEMS INCORPORATED
// Copyright 2003-2007 Adobe Systems Incorporated
// All Rights Reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
package flexlib.baseClasses
{
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.FocusEvent;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.geom.Rectangle;
import flash.ui.Keyboard;
import mx.automation.IAutomationObject;
import flexlib.containers.accordionClasses.AccordionHeader;
import mx.controls.Button;
import mx.core.ClassFactory;
import mx.core.ComponentDescriptor;
import mx.core.Container;
import mx.core.ContainerCreationPolicy;
import mx.core.EdgeMetrics;
import mx.core.FlexGlobals;
import mx.core.FlexVersion;
import mx.core.IDataRenderer;
import mx.core.IFactory;
import mx.managers.IFocusManagerComponent;
import mx.managers.IHistoryManagerClient;
import mx.core.IInvalidating;
import mx.core.IUIComponent;
import mx.core.ScrollPolicy;
import mx.core.UIComponent;
import mx.core.mx_internal;
import mx.effects.Effect;
import mx.effects.Tween;
import mx.events.ChildExistenceChangedEvent;
import mx.events.FlexEvent;
import mx.events.IndexChangedEvent;
import mx.geom.RoundedRectangle;
import mx.managers.HistoryManager;
import mx.styles.CSSStyleDeclaration;
use namespace mx_internal;
[RequiresDataBinding(true)]
//[IconFile("Accordion.png")]
/**
* Dispatched when the selected child container changes.
*
* @eventType mx.events.IndexChangedEvent.CHANGE
* @helpid 3012
* @tiptext change event
*/
[Event(name="change", type="mx.events.IndexChangedEvent")]
//--------------------------------------
// Styles
//--------------------------------------
/**
* Specifies the alpha transparency values used for the background fill of components.
* You should set this to an Array of either two or four numbers.
* Elements 0 and 1 specify the start and end values for
* an alpha gradient.
* If elements 2 and 3 exist, they are used instead of elements 0 and 1
* when the component is in a mouse-over state.
* The global default value is <code>[ 0.60, 0.40, 0.75, 0.65 ]</code>.
* Some components, such as the ApplicationControlBar container,
* have a different default value. For the ApplicationControlBar container,
* the default value is <code>[ 0.0, 0.0 ]</code>.
*/
[Style(name="fillAlphas", type="Array", arrayType="Number", inherit="no", deprecatedReplacement="headerStyleName",
deprecatedSince="3.0")]
/**
* Specifies the colors used to tint the background fill of the component.
* You should set this to an Array of either two or four uint values
* that specify RGB colors.
* Elements 0 and 1 specify the start and end values for
* a color gradient.
* If elements 2 and 3 exist, they are used instead of elements 0 and 1
* when the component is in a mouse-over state.
* For a flat-looking control, set the same color for elements 0 and 1
* and for elements 2 and 3,
* The default value is
* <code>[ 0xFFFFFF, 0xCCCCCC, 0xFFFFFF, 0xEEEEEE ]</code>.
* <p>Some components, such as the ApplicationControlBar container,
* have a different default value. For the ApplicationControlBar container,
* the default value is <code>[ 0xFFFFFF, 0xFFFFFF ]</code>.</p>
*/
[Style(name="fillColors", type="Array", arrayType="uint", format="Color", inherit="no", deprecatedReplacement="headerStyleName",
deprecatedSince="3.0")]
/**
* Specifies the alpha transparency value of the focus skin.
*
* @default 0.4
*/
[Style(name="focusAlpha", type="Number", inherit="no", deprecatedReplacement="headerStyleName", deprecatedSince="3.0")]
/**
* Specifies which corners of the focus rectangle should be rounded.
* This value is a space-separated String that can contain any
* combination of <code>"tl"</code>, <code>"tr"</code>, <code>"bl"</code>
* and <code>"br"</code>.
* For example, to specify that the right side corners should be rounded,
* but the left side corners should be square, use <code>"tr br"</code>.
* The <code>cornerRadius</code> style property specifies
* the radius of the rounded corners.
* The default value depends on the component class; if not overridden for
* the class, default value is <code>"tl tr bl br"</code>.
*
*/
[Style(name="focusRoundedCorners", type="String", inherit="no", deprecatedReplacement="headerStyleName",
deprecatedSince="3.0")]
/**
* Skin used to draw the focus rectangle.
*
* @default mx.skins.halo.HaloFocusRect
*/
[Style(name="focusSkin", type="Class", inherit="no", deprecatedReplacement="headerStyleName", deprecatedSince="3.0")]
/**
* Thickness, in pixels, of the focus rectangle outline.
*
* @default 2
*/
[Style(name="focusThickness", type="Number", format="Length", inherit="no", deprecatedReplacement="headerStyleName",
deprecatedSince="3.0")]
/**
* Name of the CSS style declaration that specifies styles for the accordion
* headers (tabs).
*
* <p>You can use this class selector to set the values of all the style properties
* of the AccordionHeader class, including <code>fillAlphas</code>, <code>fillColors</code>,
* <code>focusAlpha</code>, <code>focusRounderCorners</code>,
* <code>focusSkin</code>, <code>focusThickness</code>, and <code>selectedFillColors</code>.</p>
*/
[Style(name="headerStyleName", type="String", inherit="no")]
/**
* Number of pixels between children in the horizontal direction.
* The default value is 8.
*/
[Style(name="horizontalGap", type="Number", format="Length", inherit="no")]
/**
* Height of each accordion header, in pixels.
* The default value is automatically calculated based on the font styles for
* the header.
*/
[Style(name="headerHeight", type="Number", format="Length", inherit="no")]
/**
* Duration, in milliseconds, of the animation from one child to another.
* The default value is 250.
*/
[Style(name="openDuration", type="Number", format="Time", inherit="no")]
/**
* Tweening function used by the animation from one child to another.
*/
[Style(name="openEasingFunction", type="Function", inherit="no")]
/**
* Number of pixels between the container's bottom border and its content area.
* The default value is -1, so the bottom border of the last header
* overlaps the Accordion container's bottom border.
*/
[Style(name="paddingBottom", type="Number", format="Length", inherit="no")]
/**
* Number of pixels between the container's top border and its content area.
* The default value is -1, so the top border of the first header
* overlaps the Accordion container's top border.
*/
[Style(name="paddingTop", type="Number", format="Length", inherit="no")]
/**
* The two colors used to tint the background of the component
* when in its selected state.
* Pass the same color for both values for "flat" looking control.
* The default value is <code>undefined</code>, which means the colors
* are derived from <code>themeColor</code>.
*/
[Style(name="selectedFillColors", type="Array", arrayType="uint", format="Color", inherit="no", deprecatedReplacement="headerStyleName",
deprecatedSince="3.0")]
/**
* Color of header text when rolled over.
* The default value is 0x2B333C.
*/
[Style(name="textRollOverColor", type="uint", format="Color", inherit="yes")]
/**
* Color of selected text.
* The default value is 0x2B333C.
*/
[Style(name="textSelectedColor", type="uint", format="Color", inherit="yes")]
/**
* Number of pixels between children in the vertical direction.
* The default value is -1, so the top and bottom borders
* of adjacent headers overlap.
*/
[Style(name="verticalGap", type="Number", format="Length", inherit="no")]
//--------------------------------------
// Excluded APIs
//--------------------------------------
[Exclude(name="autoLayout", kind="property")]
[Exclude(name="clipContent", kind="property")]
[Exclude(name="defaultButton", kind="property")]
[Exclude(name="horizontalLineScrollSize", kind="property")]
[Exclude(name="horizontalPageScrollSize", kind="property")]
[Exclude(name="horizontalScrollBar", kind="property")]
[Exclude(name="horizontalScrollPolicy", kind="property")]
[Exclude(name="horizontalScrollPosition", kind="property")]
[Exclude(name="maxHorizontalScrollPosition", kind="property")]
[Exclude(name="maxVerticalScrollPosition", kind="property")]
[Exclude(name="verticalLineScrollSize", kind="property")]
[Exclude(name="verticalPageScrollSize", kind="property")]
[Exclude(name="verticalScrollBar", kind="property")]
[Exclude(name="verticalScrollPolicy", kind="property")]
[Exclude(name="verticalScrollPosition", kind="property")]
[Exclude(name="scroll", kind="event")]
/*
[Exclude(name="focusBlendMode", kind="style")]
[Exclude(name="focusSkin", kind="style")]
[Exclude(name="focusThickness", kind="style")]
*/
[Exclude(name="horizontalScrollBarStyleName", kind="style")]
[Exclude(name="verticalScrollBarStyleName", kind="style")]
//--------------------------------------
// Other metadata
//--------------------------------------
[DefaultBindingProperty(source="selectedIndex", destination="selectedIndex")]
[DefaultTriggerEvent("change")]
/**
* AccordionBase is a copy/paste version of the original Accordion class in the Flex framework.
*
* <p>The only modifications made to this class were to change some properties and
* methods from private to protected so we can override them in a subclass.</p>
*
* <p>An Accordion navigator container has a collection of child containers,
* but only one of them at a time is visible.
* It creates and manages navigator buttons (accordion headers), which you use
* to navigate between the children.
* There is one navigator button associated with each child container,
* and each navigator button belongs to the Accordion container, not to the child.
* When the user clicks a navigator button, the associated child container
* is displayed.
* The transition to the new child uses an animation to make it clear to
* the user that one child is disappearing and a different one is appearing.</p>
*
* <p>The Accordion container does not extend the ViewStack container,
* but it implements all the properties, methods, styles, and events
* of the ViewStack container, such as <code>selectedIndex</code>
* and <code>selectedChild</code>.</p>
*
* <p>An Accordion container has the following default sizing characteristics:</p>
* <table class="innertable">
* <tr>
* <th>Characteristic</th>
* <th>Description</th>
* </tr>
* <tr>
* <td>Default size</td>
* <td>The width and height of the currently active child.</td>
* </tr>
* <tr>
* <td>Container resizing rules</td>
* <td>Accordion containers are only sized once to fit the size of the first child container by default.
* They do not resize when you navigate to other child containers by default.
* To force Accordion containers to resize when you navigate to a different child container,
* set the resizeToContent property to true.</td>
* </tr>
* <tr>
* <td>Child sizing rules</td>
* <td>Children are sized to their default size. The child is clipped if it is larger than the Accordion container.
* If the child is smaller than the Accordion container, it is aligned to the upper-left corner of the
* Accordion container.</td>
* </tr>
* <tr>
* <td>Default padding</td>
* <td>-1 pixel for the top, bottom, left, and right values.</td>
* </tr>
* </table>
*
* @mxml
*
* <p>The <code><mx:Accordion></code> tag inherits all of the
* tag attributes of its superclass, with the exception of scrolling-related
* attributes, and adds the following tag attributes:</p>
*
* <pre>
* <mx:Accordion
* <strong>Properties</strong>
* headerRenderer="<i>IFactory</i>"
* historyManagementEnabled="true|false"
* resizeToContent="false|true"
* selectedIndex="undefined"
*
* <strong>Styles</strong>
* headerHeight="depends on header font styles"
* headerStyleName="<i>No default</i>"
* horizontalGap="8"
* openDuration="250"
* openEasingFunction="undefined"
* paddingBottom="-1"
* paddingTop="-1"
* textRollOverColor="0xB333C"
* textSelectedColor="0xB333C"
* verticalGap="-1"
*
* <strong>Events</strong>
* change="<i>No default</i>"
* >
* ...
* <i>child tags</i>
* ...
* </mx:Accordion>
* </pre>
*
*
*
* @see mx.containers.accordionClasses.AccordionHeader
*
* @tiptext Accordion allows for navigation between different child views
* @helpid 3013
*/
public class AccordionBase extends Container implements IHistoryManagerClient, IFocusManagerComponent
{
//include "../core/Version.as";
//--------------------------------------------------------------------------
//
// Class constants
//
//--------------------------------------------------------------------------
/**
* @private
* Base for all header names (_header0 - _headerN).
*/
private static const HEADER_NAME_BASE:String = "_header";
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*/
public function AccordionBase()
{
super();
headerRenderer = new ClassFactory(AccordionHeader);
// Most views can't take focus, but an accordion can.
// However, it draws its own focus indicator on the
// header for the currently selected child view.
// Container() has set tabEnabled false, so we
// have to set it back to true.
tabEnabled = true;
// Accordion always clips content, it just handles it by itself
super.clipContent = false;
addEventListener(ChildExistenceChangedEvent.CHILD_ADD, childAddHandler);
addEventListener(ChildExistenceChangedEvent.CHILD_REMOVE, childRemoveHandler);
showInAutomationHierarchy = true;
}
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
/**
* @private
* Is the accordian currently sliding between views?
*/
protected var bSliding:Boolean = false;
/**
* @private
*/
private var initialSelectedIndex:int = -1;
/**
* @private
* If true, call HistoryManager.save() when setting currentIndex.
*/
private var bSaveState:Boolean = false;
/**
* @private
*/
private var bInLoadState:Boolean = false;
/**
* @private
*/
private var firstTime:Boolean = true;
/**
* @private
*/
protected var showFocusIndicator:Boolean = false;
/**
* @private
* Cached tween properties to speed up tweening calculations.
*/
protected var tweenViewMetrics:EdgeMetrics;
protected var tweenContentWidth:Number;
protected var tweenContentHeight:Number;
protected var tweenOldSelectedIndex:int;
protected var tweenNewSelectedIndex:int;
protected var tween:Tween;
/**
* @private
* We'll measure ourselves once and then store the results here
* for the lifetime of the ViewStack.
*/
protected var accMinWidth:Number;
protected var accMinHeight:Number;
protected var accPreferredWidth:Number;
protected var accPreferredHeight:Number;
/**
* @private
* When a child is added or removed, this flag is set true
* and it causes a re-measure.
*/
private var childAddedOrRemoved:Boolean = false;
/**
* @private
* Remember which child has an overlay mask, if any.
*/
private var overlayChild:IUIComponent;
/**
* @private
* Keep track of the overlay's targetArea
*/
private var overlayTargetArea:RoundedRectangle;
/**
* @private
*/
protected var layoutStyleChanged:Boolean = false;
/**
* @private
*/
protected var currentDissolveEffect:Effect;
//--------------------------------------------------------------------------
//
// Overridden properties
//
//--------------------------------------------------------------------------
//----------------------------------
// autoLayout
//----------------------------------
// Don't allow user to set autoLayout because
// there are problems if deferred instantiation
// runs at the same time as an effect. (Bug 79174)
[Inspectable(environment="none")]
/**
* @private
*/
override public function get autoLayout():Boolean
{
return true;
}
/**
* @private
*/
override public function set autoLayout(value:Boolean):void
{
}
//----------------------------------
// baselinePosition
//----------------------------------
/**
* @private
* The baselinePosition of an Accordion is calculated
* for the label of the first header.
* If there are no children, a child is temporarily added
* to do the computation.
*/
override public function get baselinePosition():Number
{
if (FlexVersion.compatibilityVersion < FlexVersion.VERSION_3_0)
return super.baselinePosition;
if (!validateBaselinePosition())
return NaN;
var isEmpty:Boolean = numChildren == 0;
if (isEmpty)
{
var child0:Container = new Container();
addChild(child0);
validateNow();
}
var header0:Button = getHeaderAt(0);
var result:Number = header0.y + header0.baselinePosition;
if (isEmpty)
{
removeChildAt(0);
validateNow();
}
return result;
}
//----------------------------------
// clipContent
//----------------------------------
// We still need to ensure the clip mask is *never* created for an
// Accordion.
[Inspectable(environment="none")]
/**
* @private
*/
override public function get clipContent():Boolean
{
return true; // Accordion does clip, it just does it itself
}
/**
* @private
*/
override public function set clipContent(value:Boolean):void
{
}
//----------------------------------
// horizontalScrollPolicy
//----------------------------------
[Inspectable(environment="none")]
/**
* @private
*/
override public function get horizontalScrollPolicy():String
{
return ScrollPolicy.OFF;
}
/**
* @private
*/
override public function set horizontalScrollPolicy(value:String):void
{
}
//----------------------------------
// verticalScrollPolicy
//----------------------------------
[Inspectable(environment="none")]
/**
* @private
*/
override public function get verticalScrollPolicy():String
{
return ScrollPolicy.OFF;
}
/**
* @private
*/
override public function set verticalScrollPolicy(value:String):void
{
}
//--------------------------------------------------------------------------
//
// Public properties
//
//--------------------------------------------------------------------------
/**
* @private
*/
private var _focusedIndex:int = -1;
/**
* @private
*/
mx_internal function get focusedIndex():int
{
return _focusedIndex;
}
//----------------------------------
// contentHeight
//----------------------------------
/**
* The height of the area, in pixels, in which content is displayed.
* You can override this getter if your content
* does not occupy the entire area of the container.
*/
protected function get contentHeight():Number
{
// Start with the height of the entire accordion.
var contentHeight:Number = unscaledHeight;
// Subtract the heights of the top and bottom borders.
var vm:EdgeMetrics = viewMetricsAndPadding;
contentHeight -= vm.top + vm.bottom;
// Subtract the header heights.
var verticalGap:Number = getStyle("verticalGap");
var n:int = numChildren;
for (var i:int = 0; i < n; i++)
{
contentHeight -= getHeaderAt(i).height;
if (i > 0)
contentHeight -= verticalGap;
}
return contentHeight;
}
//----------------------------------
// contentWidth
//----------------------------------
/**
* The width of the area, in pixels, in which content is displayed.
* You can override this getter if your content
* does not occupy the entire area of the container.
*/
protected function get contentWidth():Number
{
// Start with the width of the entire accordion.
var contentWidth:Number = unscaledWidth;
// Subtract the widths of the left and right borders.
var vm:EdgeMetrics = viewMetricsAndPadding;
contentWidth -= vm.left + vm.right;
contentWidth -= getStyle("paddingLeft") +
getStyle("paddingRight");
return contentWidth;
}
//----------------------------------
// headerRenderer
//----------------------------------
/**
* @private
* Storage for the headerRenderer property.
*/
private var _headerRenderer:IFactory;
[Bindable("headerRendererChanged")]
/**
* A factory used to create the navigation buttons for each child.
* The default value is a factory which creates a
* <code>mx.containers.accordionClasses.AccordionHeader</code>. The
* created object must be a subclass of Button and implement the
* <code>mx.core.IDataRenderer</code> interface. The <code>data</code>
* property is set to the content associated with the header.
*
* @see mx.containers.accordionClasses.AccordionHeader
*/
public function get headerRenderer():IFactory
{
return _headerRenderer;
}
/**
* @private
*/
public function set headerRenderer(value:IFactory):void
{
_headerRenderer = value;
dispatchEvent(new Event("headerRendererChanged"));
}
//----------------------------------
// historyManagementEnabled
//----------------------------------
/**
* @private
* Storage for historyManagementEnabled property.
*/
private var _historyManagementEnabled:Boolean = true;
/**
* @private
*/
private var historyManagementEnabledChanged:Boolean = false;
[Inspectable(defaultValue="true")]
/**
* If set to <code>true</code>, this property enables history management
* within this Accordion container.
* As the user navigates from one child to another,
* the browser remembers which children were visited.
* The user can then click the browser's Back and Forward buttons
* to move through this navigation history.
*
* @default true
*
* @see mx.managers.HistoryManager
*/
public function get historyManagementEnabled():Boolean
{
return _historyManagementEnabled;
}
/**
* @private
*/
public function set historyManagementEnabled(value:Boolean):void
{
if (value != _historyManagementEnabled)
{
_historyManagementEnabled = value;
historyManagementEnabledChanged = true;
invalidateProperties();
}
}
//----------------------------------
// resizeToContent
//----------------------------------
/**
* @private
* Storage for the resizeToContent property.
*/
protected var _resizeToContent:Boolean = false;
[Inspectable(defaultValue="false")]
/**
* If set to <code>true</code>, this Accordion automatically resizes to
* the size of its current child.
*
* @default false
*/
public function get resizeToContent():Boolean
{
return _resizeToContent;
}
/**
* @private
*/
public function set resizeToContent(value:Boolean):void
{
if (value != _resizeToContent)
{
_resizeToContent = value;
if (value)
invalidateSize();
}
}
//----------------------------------
// selectedChild
//----------------------------------
[Bindable("valueCommit")]
/**
* A reference to the currently visible child container.
* The default value is a reference to the first child.
* If there are no children, this property is <code>null</code>.
*
* <p><b>Note:</b> You can only set this property in an ActionScript statement,
* not in MXML.</p>
*
* @tiptext Specifies the child view that is currently displayed
* @helpid 3401
*/
public function get selectedChild():Container
{
if (selectedIndex == -1)
return null;
return Container(getChildAt(selectedIndex));
}
/**
* @private
*/
public function set selectedChild(value:Container):void
{
var newIndex:int = getChildIndex(DisplayObject(value));
if (newIndex >= 0 && newIndex < numChildren)
selectedIndex = newIndex;
}
//----------------------------------
// selectedIndex
//----------------------------------
/**
* @private
* Storage for the selectedIndex and selectedChild properties.
*/
private var _selectedIndex:int = -1;
/**
* @private
*/
private var proposedSelectedIndex:int = -1;
[Bindable("valueCommit")]
[Inspectable(category="General", defaultValue="0")]
/**
* The zero-based index of the currently visible child container.
* Child indexes are in the range 0, 1, 2, ..., n - 1, where n is the number
* of children.
* The default value is 0, corresponding to the first child.
* If there are no children, this property is <code>-1</code>.
*
* @default 0
*
* @tiptext Specifies the index of the child view that is currently displayed
* @helpid 3402
*/
public function get selectedIndex():int
{
if (proposedSelectedIndex != -1)
return proposedSelectedIndex;
return _selectedIndex;
}
/**
* @private
*/
public function set selectedIndex(value:int):void
{
// Bail if new index isn't a number.
if (value == -1)
return;
// Bail if the index isn't changing.
if (value == _selectedIndex)
return;
// Propose the specified value as the new value for selectedIndex.
// It gets applied later when commitProperties() calls commitSelectedIndex().
// The proposed value can be "out of range", because the children
// may not have been created yet, so the range check is handled
// in commitSelectedIndex(), not here. Other calls to this setter
// can change the proposed index before it is committed. Also,
// childAddHandler() proposes a value of 0 when it creates the first
// child, if no value has yet been proposed.
proposedSelectedIndex = value;
invalidateProperties();
// Set a flag which will cause the History Manager to save state
// the next time measure() is called.
if (historyManagementEnabled && _selectedIndex != -1 && !bInLoadState)
bSaveState = true;
dispatchEvent(new FlexEvent(FlexEvent.VALUE_COMMIT));
}
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
override public function createComponentsFromDescriptors(
recurse:Boolean=true):void
{
// The easiest way to handle the ContainerCreationPolicy.ALL policy is to let
// Container's implementation of createComponents handle it.
if (actualCreationPolicy == ContainerCreationPolicy.ALL)
{
super.createComponentsFromDescriptors();
return;
}
// If the policy is ContainerCreationPolicy.AUTO, Accordion instantiates its children
// immediately, but not any grandchildren. The children of
// the selected child will get created in instantiateSelectedChild().
// Why not create the grandchildren of the selected child by calling
// createComponentFromDescriptor(childDescriptors[i], i == selectedIndex);
// in the loop below? Because one of this Accordion's childDescriptors
// may be for a Repeater, in which case the following loop over the
// childDescriptors is not the same as a loop over the children.
// In particular, selectedIndex is supposed to specify the nth
// child, not the nth childDescriptor, and the 2nd parameter of
// createComponentFromDescriptor() should make the recursion happen
// on the nth child, not the nth childDescriptor.
var numChildrenBefore:int = numChildren;
if (childDescriptors)
{
var n:int = childDescriptors.length;
for (var i:int = 0; i < n; i++)
{
var descriptor:ComponentDescriptor =
ComponentDescriptor(childDescriptors[i]);
createComponentFromDescriptor(descriptor, false);
}
}
numChildrenCreated = numChildren - numChildrenBefore;
processedDescriptors = true;
}
/**
* @private
*/
override public function setChildIndex(child:DisplayObject,
newIndex:int):void
{
var oldIndex:int = getChildIndex(child);
// Check boundary conditions first
if (oldIndex == -1 || newIndex < 0)
return;
var nChildren:int = numChildren;
if (newIndex >= nChildren)
newIndex = nChildren - 1;
// Next, check for no move
if (newIndex == oldIndex)
return;
// De-select the old selected index header
var oldSelectedHeader:Button = getHeaderAt(selectedIndex);
if (oldSelectedHeader)
{
oldSelectedHeader.selected = false;
drawHeaderFocus(_focusedIndex, false);
}
// Adjust the depths and _childN references of the affected children.
super.setChildIndex(child, newIndex);
// Shuffle the headers
shuffleHeaders(oldIndex, newIndex);
// Select the new selected index header
var newSelectedHeader:Button = getHeaderAt(selectedIndex);
if (newSelectedHeader)
{
newSelectedHeader.selected = true;
drawHeaderFocus(_focusedIndex, showFocusIndicator);
}
// Make sure the new selected child is instantiated
instantiateChild(selectedChild);
}
/**
* @private
*/
private function shuffleHeaders(oldIndex:int, newIndex:int):void
{
var i:int;
// Adjust the _headerN references of the affected headers.
// Note: Algorithm is the same as Container.setChildIndex().
var header:Button = getHeaderAt(oldIndex);
if (newIndex < oldIndex)
{
for (i = oldIndex; i > newIndex; i--)
{
getHeaderAt(i - 1).name = HEADER_NAME_BASE + i;
}
}
else
{
for (i = oldIndex; i < newIndex; i++)
{
getHeaderAt(i + 1).name = HEADER_NAME_BASE + i;
}
}
header.name = HEADER_NAME_BASE + newIndex;
}
/**
* @private
*/
override protected function commitProperties():void
{
super.commitProperties();
if (historyManagementEnabledChanged)
{
if (historyManagementEnabled)
HistoryManager.register(this);
else
HistoryManager.unregister(this);
historyManagementEnabledChanged = false;
}
commitSelectedIndex();
if (firstTime)
{
firstTime = false;
// Add "addedToStage" and "removedFromStage" listeners so we can
// register/un-register from the history manager when this component
// is added or removed from the display list.
addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler, false, 0, true);
addEventListener(Event.REMOVED_FROM_STAGE, removedFromStageHandler, false, 0, true);
}
}
/**
* @private
*/
override protected function measure():void
{
super.measure();
/* measure() gets implemented by a subclass, either HAccordion or VAccordion */
/**
var minWidth:Number = 0;
var minHeight:Number = 0;
var preferredWidth:Number = 0;
var preferredHeight:Number = 0;
var paddingLeft:Number = getStyle("paddingLeft");
var paddingRight:Number = getStyle("paddingRight");
var headerHeight:Number = getHeaderHeight();
// In general, we only measure once and thereafter use cached values.
// There are three exceptions: when resizeToContent is true,
// when a layout style like headerHeight changes,
// and when a child is added or removed.
//
// We need to copy the cached values into the measured fields
// again to handle the case where scaleX or scaleY is not 1.0.
// When the Accordion is zoomed, code in UIComponent.measureSizes
// scales the measuredWidth/Height values every time that
// measureSizes is called. (bug 100749)
if (accPreferredWidth && !_resizeToContent &&
!layoutStyleChanged && !childAddedOrRemoved)
{
measuredMinWidth = accMinWidth;
measuredMinHeight = accMinHeight;
measuredWidth = accPreferredWidth;
measuredHeight = accPreferredHeight;
return;
}
layoutStyleChanged = false;
childAddedOrRemoved = false;
var n:int = numChildren;
for (var i:int = 0; i < n; i++)
{
var button:Button = getHeaderAt(i);
var child:IUIComponent = IUIComponent(getChildAt(i));
minWidth = Math.max(minWidth, button.minWidth);
minHeight += headerHeight;
preferredWidth = Math.max(preferredWidth, minWidth);
preferredHeight += headerHeight;
// The headers preferredWidth is messing up the accordion measurement. This may not
// be needed anyway because we're still using the headers minWidth to determine our overall
// minWidth.
if (i == selectedIndex)
{
preferredWidth = Math.max(preferredWidth, child.getExplicitOrMeasuredWidth());
preferredHeight += child.getExplicitOrMeasuredHeight();
minWidth = Math.max(minWidth, child.minWidth);
minHeight += child.minHeight;
}
}
// Add space for borders and margins
var vm:EdgeMetrics = viewMetricsAndPadding;
var widthPadding:Number = vm.left + vm.right;
var heightPadding:Number = vm.top + vm.bottom;
// Need to adjust the widthPadding if paddingLeft and paddingRight are negative numbers
// (see explanation in updateDisplayList())
if (paddingLeft < 0)
widthPadding -= paddingLeft;
if (paddingRight < 0)
widthPadding -= paddingRight;
minWidth += widthPadding;
preferredWidth += widthPadding;
minHeight += heightPadding;
preferredHeight += heightPadding;
measuredMinWidth = minWidth;
measuredMinHeight = minHeight;
measuredWidth = preferredWidth;
measuredHeight = preferredHeight;
// If we're called before instantiateSelectedChild, then bail.
// We'll be called again later (instantiateSelectedChild calls
// invalidateSize), and we don't want to load values into the
// cache until we're fully initialized. (bug 102639)
// This check was moved from the beginning of this function to
// here to fix bugs 103665/104213.
if (selectedChild && Container(selectedChild).numChildrenCreated == -1)
return;
// Don't remember sizes if we don't have any children
if (numChildren == 0)
return;
accMinWidth = minWidth;
accMinHeight = minHeight;
accPreferredWidth = preferredWidth;
accPreferredHeight = preferredHeight;
**/
}
/**
* @private
* Arranges the layout of the accordion contents.
*
* @tiptext Arranges the layout of the Accordion's contents
* @helpid 3017
*/
override protected function updateDisplayList(unscaledWidth:Number,
unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
/* updateDisplayList() gets implemented by a subclass, either HAccordion or VAccordion */
/**
// Don't do layout if we're tweening because the tweening
// code is handling it.
if (tween)
return;
// Measure the border.
var bm:EdgeMetrics = borderMetrics;
var paddingLeft:Number = getStyle("paddingLeft");
var paddingRight:Number = getStyle("paddingRight");
var paddingTop:Number = getStyle("paddingTop");
var verticalGap:Number = getStyle("verticalGap");
// Determine the width and height of the content area.
var localContentWidth:Number = calcContentWidth();
var localContentHeight:Number = calcContentHeight();
// Arrange the headers, the content clips,
// based on selectedIndex.
var x:Number = bm.left + paddingLeft;
var y:Number = bm.top + paddingTop;
// Adjustments. These are required since the default halo
// appearance has verticalGap and all margins set to -1
// so the edges of the headers overlap each other and the
// border of the accordion. These overlaps cause problems with
// the content area clipping, so we adjust for them here.
var contentX:Number = x;
var adjContentWidth:Number = localContentWidth;
var headerHeight:Number = getHeaderHeight();
if (paddingLeft < 0)
{
contentX -= paddingLeft;
adjContentWidth += paddingLeft;
}
if (paddingRight < 0)
adjContentWidth += paddingRight;
var n:int = numChildren;
for (var i:int = 0; i < n; i++)
{
var header:Button = getHeaderAt(i);
var content:IUIComponent = IUIComponent(getChildAt(i));
header.move(x, y);
header.setActualSize(localContentWidth, headerHeight);
y += headerHeight;
if (i == selectedIndex)
{
content.move(contentX, y);
content.visible = true;
var contentW:Number = adjContentWidth;
var contentH:Number = localContentHeight;
if (!isNaN(content.percentWidth))
{
if (contentW > content.maxWidth)
contentW = content.maxWidth;
}
else
{
if (contentW > content.getExplicitOrMeasuredWidth())
contentW = content.getExplicitOrMeasuredWidth();
}
if (!isNaN(content.percentHeight))
{
if (contentH > content.maxHeight)
contentH = content.maxHeight;
}
else
{
if (contentH > content.getExplicitOrMeasuredHeight())
contentH = content.getExplicitOrMeasuredHeight();
}
if (content.width != contentW ||
content.height != contentH)
{
content.setActualSize(contentW, contentH);
}
y += localContentHeight;
}
else
{
content.move(contentX, i < selectedIndex
? y : y - localContentHeight);
content.visible = false;
}
y += verticalGap;
}
// Make sure blocker is in front
if (blocker)
rawChildren.setChildIndex(blocker, numChildren - 1);
// refresh the focus rect, the dimensions might have changed.
drawHeaderFocus(_focusedIndex, showFocusIndicator);
*/
}
/**
* @private
*/
override mx_internal function setActualCreationPolicies(policy:String):void
{
super.setActualCreationPolicies(policy);
// If the creation policy is switched to ContainerCreationPolicy.ALL and our createComponents
// function has already been called (we've created our children but not
// all our grandchildren), then create all our grandchildren now (bug 99160).
if (policy == ContainerCreationPolicy.ALL && numChildren > 0)
{
var n:int = numChildren;
for (var i:int = 0; i < n; i++)
{
Container(getChildAt(i)).createComponentsFromDescriptors();
}
}
}
/**
* @private
*/
override protected function focusInHandler(event:FocusEvent):void
{
super.focusInHandler(event);
showFocusIndicator = focusManager.showFocusIndicator;
// When the accordion has focus, the Focus Manager
// should not treat the Enter key as a click on
// the default pushbutton.
if (event.target == this)
focusManager.defaultButtonEnabled = false;
}
/**
* @private
*/
override protected function focusOutHandler(event:FocusEvent):void
{
super.focusOutHandler(event);
showFocusIndicator = false;
if (focusManager && event.target == this)
focusManager.defaultButtonEnabled = true;
}
/**
* @private
*/
override public function drawFocus(isFocused:Boolean):void
{
drawHeaderFocus(_focusedIndex, isFocused);
}
/**
* @private
*/
override public function styleChanged(styleProp:String):void
{
super.styleChanged(styleProp);
if (!styleProp ||
styleProp == "headerStyleName" ||
styleProp == "styleName")
{
var headerStyleName:Object = getStyle("headerStyleName");
var header:Button;
if (headerStyleName)
{
if (FlexVersion.compatibilityVersion < FlexVersion.VERSION_3_0)
{
var headerStyleDecl:CSSStyleDeclaration =
FlexGlobals.topLevelApplication.styleManager.getStyleDeclaration("." + headerStyleName);
if (headerStyleDecl)
{
// Need to reset the header style declaration and
// regenerate their style cache
for (var i:int = 0; i < numChildren; i++)
{
header = getHeaderAt(i);
if (header)
{
header.styleDeclaration = headerStyleDecl;
header.regenerateStyleCache(true);
header.styleChanged(null);
}
}
}
}
else
{
for (var j:int = 0; j < numChildren; j++)
{
header = getHeaderAt(j);
if (header)
{
header.styleName = headerStyleName;
}
}
}
}
}
else if (FlexGlobals.topLevelApplication.styleManager.isSizeInvalidatingStyle(styleProp))
{
layoutStyleChanged = true;
}
}
/**
* @private
* When asked to create an overlay mask, create it on the selected child
* instead. That way, the chrome around the edge of the Accordion (e.g. the
* header buttons) is not occluded by the overlay mask (bug 99029).
*/
override mx_internal function addOverlay(color:uint, targetArea:RoundedRectangle=null):void
{
// As we're switching the currently-selected child, don't
// allow two children to both have an overlay at the same time.
// This is done because it makes accounting a headache. If there's
// a legitimate reason why two children both need overlays, this
// restriction could be relaxed.
if (overlayChild)
removeOverlay();
// Remember which child has an overlay, so that we don't inadvertently
// create an overlay on one child and later try to remove the overlay
// of another child. (bug 100731)
overlayChild = selectedChild as IUIComponent;
if (!overlayChild)
return;
effectOverlayColor = color;
overlayTargetArea = targetArea;
if (selectedChild && selectedChild.numChildrenCreated == -1) // No children have been created
{
// Wait for the childrenCreated event before creating the overlay
selectedChild.addEventListener(FlexEvent.INITIALIZE,
initializeHandler);
}
else // Children already exist
{
initializeHandler(null);
}
}
/**
* @private
* Called when we are running a Dissolve effect
* and the initialize event has been dispatched
* or the children already exist
*/
private function initializeHandler(event:FlexEvent):void
{
UIComponent(overlayChild).addOverlay(effectOverlayColor, overlayTargetArea);
}
/**
* @private
* Handle key down events
*/
override mx_internal function removeOverlay():void
{
if (overlayChild)
{
UIComponent(overlayChild).removeOverlay();
overlayChild = null;
}
}
// -------------------------------------------------------------------------
// StateInterface
// -------------------------------------------------------------------------
/**
* @copy mx.managers.IHistoryManagerClient#saveState()
*/
public function saveState():Object
{
var index:int = _selectedIndex == -1 ? 0 : _selectedIndex;
return {selectedIndex: index};
}
/**
* @copy mx.managers.IHistoryManagerClient#loadState()
*/
public function loadState(state:Object):void
{
var newIndex:int = state ? int(state.selectedIndex) : 0;
if (newIndex == -1)
newIndex = initialSelectedIndex;
if (newIndex == -1)
newIndex = 0;
if (newIndex != _selectedIndex)
{
// When loading a new state, we don't want to
// save our current state in the history stack.
bInLoadState = true;
selectedIndex = newIndex;
bInLoadState = false;
}
}
//--------------------------------------------------------------------------
//
// Public methods
//
//--------------------------------------------------------------------------
/**
* Returns a reference to the navigator button for a child container.
*
* @param index Zero-based index of the child.
*
* @return Button object representing the navigator button.
*/
public function getHeaderAt(index:int):Button
{
return Button(rawChildren.getChildByName(HEADER_NAME_BASE + index));
}
/**
* @private
* Returns the height of the header control. All header controls are the same
* height.
*/
protected function getHeaderHeight():Number
{
var headerHeight:Number = getStyle("headerHeight");
if (isNaN(headerHeight))
{
headerHeight = 0;
if (numChildren > 0)
headerHeight = getHeaderAt(0).measuredHeight;
}
return headerHeight;
}
/**
* @private
* Returns the width of the header control. All header controls are the same
* width.
*/
protected function getHeaderWidth():Number
{
var headerWidth:Number = getStyle("headerWidth");
if (isNaN(headerWidth))
{
headerWidth = 0;
if (numChildren > 0)
headerWidth = getHeaderAt(0).measuredHeight;
}
return headerWidth;
}
//--------------------------------------------------------------------------
//
// Private methods
//
//--------------------------------------------------------------------------
/**
* @private
* Utility method to create the segment header
*/
private function createHeader(content:DisplayObject, i:int):void
{
// Before creating the header, un-select the currently selected
// header. We will be selecting the correct header below.
if (selectedIndex != -1 && getHeaderAt(selectedIndex))
getHeaderAt(selectedIndex).selected = false;
// Create the header.
// Notes:
// 1) An accordion maintains a reference to
// the header for its Nth child as _headerN. These references are
// juggled when children and their headers are re-indexed or
// removed, to ensure that _headerN is always a reference the
// header for the Nth child.
// 2) Always create the header with the index of the last item.
// If needed, the headers will be shuffled below.
var header:Button = Button(headerRenderer.newInstance());
header.name = HEADER_NAME_BASE + (numChildren - 1);
if (FlexVersion.compatibilityVersion < FlexVersion.VERSION_3_0)
{
header.styleName = this;
}
var headerStyleName:String = getStyle("headerStyleName");
if (headerStyleName)
{
if (FlexVersion.compatibilityVersion < FlexVersion.VERSION_3_0)
{
var headerStyleDecl:CSSStyleDeclaration = FlexGlobals.topLevelApplication.styleManager.getStyleDeclaration("." + headerStyleName);
if (headerStyleDecl)
header.styleDeclaration = headerStyleDecl;
}
else
{
header.styleName = headerStyleName;
}
}
header.addEventListener(MouseEvent.CLICK, headerClickHandler);
IDataRenderer(header).data = content;
if (content is Container)
{
var contentContainer:Container = Container(content);
header.label = contentContainer.label;
if (contentContainer.icon)
header.setStyle("icon", contentContainer.icon);
// If the child has a toolTip, transfer it to the header.
var toolTip:String = contentContainer.toolTip;
if (toolTip && toolTip != "")
{
header.toolTip = toolTip;
contentContainer.toolTip = null;
}
}
rawChildren.addChild(header);
// If the newly added child isn't at the end of our child list, shuffle
// the headers accordingly.
if (i != numChildren - 1)
shuffleHeaders(numChildren - 1, i);
// Make sure the correct header is selected
if (selectedIndex != -1 && getHeaderAt(selectedIndex))
getHeaderAt(selectedIndex).selected = true;
}
/**
* @private
*/
protected function calcContentWidth():Number
{
// Start with the width of the entire accordion.
var contentWidth:Number = unscaledWidth;
// Subtract the widths of the left and right borders.
var vm:EdgeMetrics = viewMetricsAndPadding;
contentWidth -= vm.left + vm.right;
return contentWidth;
}
/**
* @private
*/
protected function calcContentHeight():Number
{
// Start with the height of the entire accordion.
var contentHeight:Number = unscaledHeight;
// Subtract the heights of the top and bottom borders.
var vm:EdgeMetrics = viewMetricsAndPadding;
contentHeight -= vm.top + vm.bottom;
// Subtract the header heights.
var verticalGap:Number = getStyle("verticalGap");
var headerHeight:Number = getHeaderHeight();
var n:int = numChildren;
for (var i:int = 0; i < n; i++)
{
contentHeight -= headerHeight;
if (i > 0)
contentHeight -= verticalGap;
}
return contentHeight;
}
/**
* @private
*/
protected function drawHeaderFocus(headerIndex:int, isFocused:Boolean):void
{
if (headerIndex != -1)
getHeaderAt(headerIndex).drawFocus(isFocused);
}
/**
* @private
*/
private function headerClickHandler(event:Event):void
{
var header:Button = Button(event.currentTarget);
var oldIndex:int = selectedIndex;
// content is placed onto the button so we have to access it via []
selectedChild = Container(IDataRenderer(header).data);
var newIndex:int = selectedIndex;
if (oldIndex != newIndex)
dispatchChangeEvent(oldIndex, newIndex, event);
}
/**
* @private
*/
private function commitSelectedIndex():void
{
if (proposedSelectedIndex == -1)
return;
var newIndex:int = proposedSelectedIndex;
proposedSelectedIndex = -1;
// The selectedIndex must be undefined if there are no children,
// even if a selectedIndex has been proposed.
if (numChildren == 0)
{
_selectedIndex = -1;
return;
}
// Ensure that the new index is in bounds.
if (newIndex < 0)
newIndex = 0;
else if (newIndex > numChildren - 1)
newIndex = numChildren - 1;
// Remember the old index.
var oldIndex:int = _selectedIndex;
// Bail if the index isn't changing.
if (newIndex == oldIndex)
return;
// If we are currently playing a Dissolve effect, end it and restart it again
currentDissolveEffect = null;
if (isEffectStarted)
{
var dissolveInstanceClass:Class = Class(systemManager.getDefinitionByName("mx.effects.effectClasses.DissolveInstance"));
for (var i:int = 0; i < _effectsStarted.length; i++)
{
// Avoid referencing the DissolveInstance class directly, so that
// we don't create an unwanted linker dependency.
if (dissolveInstanceClass && _effectsStarted[i] is dissolveInstanceClass)
{
// If we find the dissolve, save a pointer to the parent effect and end the instance
currentDissolveEffect = _effectsStarted[i].effect;
_effectsStarted[i].end();
break;
}
}
}
// Unfocus the old header.
if (_focusedIndex != newIndex)
drawHeaderFocus(_focusedIndex, false);
// Deselect the old header.
if (oldIndex != -1)
getHeaderAt(oldIndex).selected = false;
// Commit the new index.
_selectedIndex = newIndex;
// Remember our initial selected index so we can
// restore to our default state when the history
// manager requests it.
if (initialSelectedIndex == -1)
initialSelectedIndex = _selectedIndex;
// Select the new header.
getHeaderAt(newIndex).selected = true;
if (_focusedIndex != newIndex)
{
// Focus the new header.
_focusedIndex = newIndex;
drawHeaderFocus(_focusedIndex, showFocusIndicator);
}
if (bSaveState)
{
HistoryManager.save();
bSaveState = false;
}
if (getStyle("openDuration") == 0 || oldIndex == -1)
{
// Need to set the new index to be visible here
// in order for effects to work.
Container(getChildAt(newIndex)).setVisible(true);
// Now that the effects have been triggered, we can hide the
// current view until it is properly sized and positioned below.
Container(getChildAt(newIndex)).setVisible(false, true);
if (oldIndex != -1)
Container(getChildAt(oldIndex)).setVisible(false);
instantiateChild(selectedChild);
}
else
{
if (tween)
tween.endTween();
startTween(oldIndex, newIndex);
}
}
/**
* @private
*/
protected function instantiateChild(child:Container):void
{
// fix for bug#137430
// when the selectedChild index is -1 (invalid value due to any reason)
// selectedContainer will not be valid. Before we proceed
// we need to make sure of its validity.
if (!child)
return;
// Performance optimization: don't call createComponents if we know
// that createComponents has already been called.
if (child && child.numChildrenCreated == -1)
child.createComponentsFromDescriptors();
// Do the initial measurement/layout pass for the newly-instantiated
// descendants.
invalidateSize();
invalidateDisplayList();
if (child is IInvalidating)
IInvalidating(child).invalidateSize();
}
/**
* @private
*/
private function dispatchChangeEvent(oldIndex:int,
newIndex:int,
cause:Event=null):void
{
var indexChangeEvent:IndexChangedEvent =
new IndexChangedEvent(IndexChangedEvent.CHANGE);
indexChangeEvent.oldIndex = oldIndex;
indexChangeEvent.newIndex = newIndex;
indexChangeEvent.relatedObject = getChildAt(newIndex);
indexChangeEvent.triggerEvent = cause;
dispatchEvent(indexChangeEvent);
}
/**
* @private
*/
protected function startTween(oldSelectedIndex:int, newSelectedIndex:int):void
{
bSliding = true;
// To improve the animation performance, we set up some invariants
// used in onTweenUpdate. (Some of these, like contentHeight, are
// too slow to recalculate at every tween step.)
tweenViewMetrics = viewMetricsAndPadding;
tweenContentWidth = calcContentWidth();
tweenContentHeight = calcContentHeight();
tweenOldSelectedIndex = oldSelectedIndex;
tweenNewSelectedIndex = newSelectedIndex;
// A single instance of Tween drives the animation.
var openDuration:Number = getStyle("openDuration");
tween = new Tween(this, 0, tweenContentHeight, openDuration);
var easingFunction:Function = getStyle("openEasingFunction") as Function;
if (easingFunction != null)
tween.easingFunction = easingFunction;
// Ideally, all tweening should be managed by the EffectManager. Since
// this tween isn't managed by the EffectManager, we need this alternate
// mechanism to tell the EffectManager that we're tweening. Otherwise, the
// EffectManager might try to play another effect that animates the same
// properties.
if (oldSelectedIndex != -1)
Container(getChildAt(oldSelectedIndex)).tweeningProperties = ["x", "y", "width", "height"];
Container(getChildAt(newSelectedIndex)).tweeningProperties = ["x", "y", "width", "height"];
// If the content of the new child hasn't been created yet, set the new child
// to the content width/height. This way any background color will show up
// properly during the animation.
var newSelectedChild:Container = Container(getChildAt(newSelectedIndex));
if (newSelectedChild.numChildren == 0)
{
var paddingLeft:Number = getStyle("paddingLeft");
var contentX:Number = borderMetrics.left + (paddingLeft > 0 ? paddingLeft : 0);
newSelectedChild.move(contentX, newSelectedChild.y);
newSelectedChild.setActualSize(tweenContentWidth, tweenContentHeight);
}
UIComponent.suspendBackgroundProcessing();
}
/**
* @private
*/
mx_internal function onTweenUpdate(value:Number):void
{
// Fetch the tween invariants we set up in startTween.
var vm:EdgeMetrics = tweenViewMetrics;
var contentWidth:Number = tweenContentWidth;
var contentHeight:Number = tweenContentHeight;
var oldSelectedIndex:int = tweenOldSelectedIndex;
var newSelectedIndex:int = tweenNewSelectedIndex;
// The tweened value is the height of the new content area, which varies
// from 0 to the contentHeight. As the new content area grows, the
// old content area shrinks.
var newContentHeight:Number = value;
var oldContentHeight:Number = contentHeight - value;
// These offsets for the Y position of the content clips make the content
// clips appear to be pushed up and pulled down.
var oldOffset:Number = oldSelectedIndex < newSelectedIndex ?
-newContentHeight :
newContentHeight;
var newOffset:Number = newSelectedIndex > oldSelectedIndex ?
oldContentHeight :
-oldContentHeight;
// Loop over all the headers to arrange them vertically.
// The loop is intentionally over ALL the headers, not just the ones that
// need to move; this makes the animation look equally smooth
// regardless of how many headers are moving.
// We also reposition the two visible content clips.
var y:Number = vm.top;
var verticalGap:Number = getStyle("verticalGap");
var n:int = numChildren;
for (var i:int = 0; i < n; i++)
{
var header:Button = getHeaderAt(i);
var content:Container = Container(getChildAt(i));
header.$y = y;
y += header.height;
if (i == oldSelectedIndex)
{
content.cacheAsBitmap = true;
content.scrollRect = new Rectangle(0, -oldOffset,
contentWidth, contentHeight);
content.visible = true;
y += oldContentHeight;
}
else if (i == newSelectedIndex)
{
content.cacheAsBitmap = true;
content.scrollRect = new Rectangle(0, -newOffset,
contentWidth, contentHeight);
content.visible = true;
y += newContentHeight;
}
y += verticalGap;
}
}
/**
* @private
*/
mx_internal function onTweenEnd(value:Number):void
{
bSliding = false;
var oldSelectedIndex:int = tweenOldSelectedIndex;
var vm:EdgeMetrics = tweenViewMetrics;
var verticalGap:Number = getStyle("verticalGap");
var headerHeight:Number = getHeaderHeight();
var localContentWidth:Number = calcContentWidth();
var localContentHeight:Number = calcContentHeight();
var y:Number = vm.top;
var content:Container;
var n:int = numChildren;
for (var i:int = 0; i < n; i++)
{
var header:Button = getHeaderAt(i);
header.$y = y;
y += headerHeight;
if (i == selectedIndex)
{
content = Container(getChildAt(i));
content.cacheAsBitmap = false;
content.scrollRect = null;
content.visible = true;
y += localContentHeight;
}
y += verticalGap;
}
if (oldSelectedIndex != -1)
{
content = Container(getChildAt(oldSelectedIndex));
content.cacheAsBitmap = false;
content.scrollRect = null;
content.visible = false;
content.tweeningProperties = null;
}
// Delete the temporary tween invariants we set up in startTween.
tweenViewMetrics = null;
tweenContentWidth = NaN;
tweenContentHeight = NaN;
tweenOldSelectedIndex = 0;
tweenNewSelectedIndex = 0;
tween = null;
UIComponent.resumeBackgroundProcessing();
Container(getChildAt(selectedIndex)).tweeningProperties = null;
// If we interrupted a Dissolve effect, restart it here
if (currentDissolveEffect)
{
if (currentDissolveEffect.target != null)
{
currentDissolveEffect.play();
}
else
{
currentDissolveEffect.play([this]);
}
}
// Let the screen render the last frame of the animation before
// we begin instantiating the new child.
callLater(instantiateChild, [selectedChild]);
}
//--------------------------------------------------------------------------
//
// Overridden event handlers
//
//--------------------------------------------------------------------------
/**
* @private
* Handles "keyDown" event.
*/
override protected function keyDownHandler(event:KeyboardEvent):void
{
// Only listen for events that have come from the accordion itself.
if (event.target != this)
return;
var prevValue:int = selectedIndex;
switch (event.keyCode)
{
case Keyboard.PAGE_DOWN:
{
drawHeaderFocus(_focusedIndex, false);
_focusedIndex = selectedIndex = (selectedIndex < numChildren - 1
? selectedIndex + 1
: 0);
drawHeaderFocus(_focusedIndex, true);
event.stopPropagation();
dispatchChangeEvent(prevValue, selectedIndex, event);
break;
}
case Keyboard.PAGE_UP:
{
drawHeaderFocus(_focusedIndex, false);
_focusedIndex = selectedIndex = (selectedIndex > 0 ?
selectedIndex - 1 :
numChildren - 1);
drawHeaderFocus(_focusedIndex, true);
event.stopPropagation();
dispatchChangeEvent(prevValue, selectedIndex, event);
break;
}
case Keyboard.HOME:
{
drawHeaderFocus(_focusedIndex, false);
_focusedIndex = selectedIndex = 0;
drawHeaderFocus(_focusedIndex, true);
event.stopPropagation();
dispatchChangeEvent(prevValue, selectedIndex, event);
break;
}
case Keyboard.END:
{
drawHeaderFocus(_focusedIndex, false);
_focusedIndex = selectedIndex = numChildren - 1;
drawHeaderFocus(_focusedIndex, true);
event.stopPropagation();
dispatchChangeEvent(prevValue, selectedIndex, event);
break;
}
case Keyboard.DOWN:
case Keyboard.RIGHT:
{
drawHeaderFocus(_focusedIndex, false);
_focusedIndex = (_focusedIndex < numChildren - 1
? _focusedIndex + 1
: 0);
drawHeaderFocus(_focusedIndex, true);
event.stopPropagation();
break;
}
case Keyboard.UP:
case Keyboard.LEFT:
{
drawHeaderFocus(_focusedIndex, false);
_focusedIndex = (_focusedIndex > 0 ?
_focusedIndex - 1 :
numChildren - 1);
drawHeaderFocus(_focusedIndex, true);
event.stopPropagation();
break;
}
case Keyboard.SPACE:
case Keyboard.ENTER:
{
event.stopPropagation();
if (_focusedIndex != selectedIndex)
{
selectedIndex = _focusedIndex;
dispatchChangeEvent(prevValue, selectedIndex, event);
}
break;
}
}
}
//--------------------------------------------------------------------------
//
// Event handlers
//
//--------------------------------------------------------------------------
/**
* @private
* Handles "addedToStage" event
*/
private function addedToStageHandler(event:Event):void
{
if (historyManagementEnabled)
HistoryManager.register(this);
}
/**
* @private
* Handles "removedFromStage" event
*/
private function removedFromStageHandler(event:Event):void
{
HistoryManager.unregister(this);
}
/**
* @private
*/
private function childAddHandler(event:ChildExistenceChangedEvent):void
{
childAddedOrRemoved = true;
var child:DisplayObject = event.relatedObject;
// Accordion creates all of its children initially invisible.
// They are made as they become the selected child.
child.visible = false;
// Create the header associated with this child.
createHeader(child, getChildIndex(child));
// If the child's label or icon changes, Accordion needs to know so that
// the header label can be updated. This event is handled by
// labelChanged().
// note: weak listeners
child.addEventListener("labelChanged", labelChangedHandler, false, 0, true);
child.addEventListener("iconChanged", iconChangedHandler, false, 0, true);
// If we just created the first child and no selected index has
// been proposed, then propose this child to be selected.
if (numChildren == 1 && proposedSelectedIndex == -1)
{
selectedIndex = 0;
// Select the new header.
var newHeader:Button = getHeaderAt(0);
newHeader.selected = true;
// Focus the new header.
_focusedIndex = 0;
drawHeaderFocus(_focusedIndex, showFocusIndicator);
}
if (child as IAutomationObject)
{
IAutomationObject(child).showInAutomationHierarchy = true;
}
}
/**
* @private
*/
private function childRemoveHandler(event:ChildExistenceChangedEvent):void
{
childAddedOrRemoved = true;
if (numChildren == 0)
return;
var child:DisplayObject = event.relatedObject;
var oldIndex:int = selectedIndex;
var newIndex:int;
var index:int = getChildIndex(child);
// Remove Event Listeners, in case children are referenced elsewhere.
child.removeEventListener("labelChanged", labelChangedHandler);
child.removeEventListener("iconChanged", iconChangedHandler);
var nChildren:int = numChildren - 1;
// number of children remaining after child has been removed
rawChildren.removeChild(getHeaderAt(index));
// Shuffle all higher numbered headers down.
for (var i:int = index; i < nChildren; i++)
{
getHeaderAt(i + 1).name = HEADER_NAME_BASE + i;
}
// If we just deleted the only child, the accordion is now empty,
// and no child is now selected.
if (nChildren == 0)
{
// There's no need to go through all of commitSelectedIndex(),
// and it wouldn't do the right thing, anyway, because
// it bails immediately if numChildren is 0.
newIndex = _focusedIndex = -1;
}
else if (index > selectedIndex)
{
return;
}
// If we deleted a child before the selected child, the
// index of that selected child is now 1 less than it was,
// but the selected child itself hasn't changed.
else if (index < selectedIndex)
{
newIndex = oldIndex - 1;
}
// Now handle the case that we deleted the selected child
// and there is another child that we must select.
else if (index == selectedIndex)
{
// If it was the last child, select the previous one.
// Otherwise, select the next one. This next child now
// has the same index as the one we just deleted,
if (index == nChildren)
{
newIndex = oldIndex - 1;
// if something's selected, instantiate it
if (newIndex != -1)
instantiateChild(Container(getChildAt(newIndex)));
}
else
{
newIndex = oldIndex;
// can't do selectedChild because we need to actually do
// newIndex + 1 because currently that's what the index
// of the child is (SDK-12622) since this one isn't
// actually removed from the display list yet
instantiateChild(Container(getChildAt(newIndex + 1)));
}
// Select the new selected index header.
var newHeader:Button = getHeaderAt(newIndex);
newHeader.selected = true;
}
if (_focusedIndex > index)
{
_focusedIndex--;
drawHeaderFocus(_focusedIndex, showFocusIndicator);
}
else if (_focusedIndex == index)
{
if (index == nChildren)
_focusedIndex--;
drawHeaderFocus(_focusedIndex, showFocusIndicator);
}
_selectedIndex = newIndex;
dispatchEvent(new FlexEvent(FlexEvent.VALUE_COMMIT));
}
/**
* @private
* Handles "labelChanged" event.
*/
private function labelChangedHandler(event:Event):void
{
var child:DisplayObject = DisplayObject(event.target);
var childIndex:int = getChildIndex(child);
var header:Button = getHeaderAt(childIndex);
header.label = Container(event.target).label;
}
/**
* @private
* Handles "iconChanged" event.
*/
private function iconChangedHandler(event:Event):void
{
var child:DisplayObject = DisplayObject(event.target);
var childIndex:int = getChildIndex(child);
var header:Button = getHeaderAt(childIndex);
header.setStyle("icon", Container(event.target).icon);
//header.icon = Container(event.target).icon;
}
}
}
|
/* 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/. */
import com.adobe.test.Assert;
import com.adobe.test.Utils;
// var SECTION = "15.2.3.1-3";
// var VERSION = "ECMA_1";
// var TITLE = "Object.prototype";
var testcases = getTestCases();
// TODO: REVIEW AS4 CONVERSION ISSUE
// Adding this function getJSClass directly to file rather than in Utils
function getJSClass(obj)
{
if (isObject(obj))
return findClass(findType(obj));
return cnNoObject;
}
function isObject(obj)
{
return obj instanceof Object;
}
function findType(obj)
{
var cnObjectToString = Object.prototype.toString;
return cnObjectToString.apply(obj);
}
// given '[object Number]', return 'Number'
function findClass(sType)
{
var re = /^\[.*\s+(\w+)\s*\]$/;
var a = sType.match(re);
if (a && a[1])
return a[1];
return cnNoClass;
}
function getTestCases() {
var array = new Array();
var item = 0;
var thisError="no exception thrown";
try{
// save
var origPrototype = Object.prototype;
Object.prototype = null;
// restore
Object.prototype = origPrototype;
} catch (e:ReferenceError) {
thisError=e.toString();
} finally {
array[item++] = Assert.expectEq( "Object.prototype = null; Object.prototype",
"ReferenceError: Error #1074",
Utils.referenceError(thisError)
);
}
return ( array );
}
|
package net.manaca.events
{
import flash.events.Event;
public class PlayerEvent extends Event
{
/**
* Dispatched when the play state chenged.
* @eventType playStateChange
*/
static public const PLAY_STATE_CHANGE:String = "playStateChange";
/**
* Dispatched when the play progress chenged.
* @eventType playStateChange
*/
static public const PROGRESS_CHANGE:String = "progressChange";
/**
*
* @param type
* @param bubbles
* @param cancelable
*
*/
public function PlayerEvent(type:String,
bubbles:Boolean = false,
cancelable:Boolean = false)
{
super(type, bubbles, cancelable);
}
//==========================================================================
// Methods
//==========================================================================
/**
* @inheritDoc
*/
override public function clone():Event
{
return new PlayerEvent(type, bubbles, cancelable);
}
}
} |
/*
* Tangible User Interfacer (former TouchAll) demo code.
*
* Copyright 2016 Gonçalo Amador <g.n.p.amador@gmail.com>
*
* 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 touchAll.demos.multimediaTouchDemo
{
import flash.ui.*;
import flash.display.*;
import flash.events.Event;
import touchAll.*;
import touchAll.multimedia.Multimedia;
/**
* @author Gonçalo Amador
*/
[SWF(width="1280", height="720", frameRate="60", backgroundColor="#ffffff")]
public class MultimediaTouchDemo extends MovieClip
{
/* global variables */
private var tAll:TouchAll = new TouchAll(stage);
//private var tAll:TouchAll = new TouchAll(stage, 1280, 720, 0x000000, true, true);
//private var tAll:TouchAll = new TouchAll(stage,1280,720, 0x000000, true, false, false, false, true, "10.0.4.145", 3000);
private var multimedia:Multimedia = new Multimedia(stage);
public function MultimediaTouchDemo():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
/* LOAD STAGE CONTENT */
tAll.backgroundLoader();
multimedia.backgroundMultimediaEventListenersLoader();
/* load images */
multimedia.addImage("resources/summer.jpg");
multimedia.addImage("resources/palacio.jpg");
multimedia.addImage("resources/lake.jpg");
multimedia.addImage("resources/forest.jpg");
//multimedia.addImage("file:///G:/touch/Source%20Code/TouchProject/bin/resources/forest.jpg");
/* load an SWF */
//multimedia.addSWF("resources/test.swf");
/* load an MP4 and FLV */
multimedia.addVideo("resources/Asus Xtion Pro test using OpenNI & OpenCV.mp4");
multimedia.addVideo("resources/Asus Xtion Pro test using OpenNI & OpenCV.flv");
/* stage set up */
tAll.stageLoader();
tAll.stageEventListenersLoader();
/* tuio set up */
tAll.tuioLoader();
}
}
}
|
/*
* 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.flexunit.listeners
{
import org.flexunit.runner.IDescription;
import org.flexunit.runner.Result;
import org.flexunit.runner.notification.Failure;
import org.flexunit.runner.notification.IRunListener;
import org.flexunit.runner.notification.ITemporalRunListener;
[Deprecated(replacement="TestRunnerBase can be used directly now.", since="4.1")]
public class UIListener implements ITemporalRunListener
{
private var uiListener : ITemporalRunListener;
public function UIListener( uiListener : ITemporalRunListener )
{
super();
this.uiListener = uiListener;
}
public function testRunStarted( description:IDescription ):void {
this.uiListener.testRunStarted( description );
}
public function testRunFinished( result:Result ):void {
this.uiListener.testRunFinished( result );
}
public function testStarted( description:IDescription ):void {
this.uiListener.testStarted(description );
}
public function testFinished( description:IDescription ):void {
this.uiListener.testFinished( description );
}
public function testFailure( failure:Failure ):void {
this.uiListener.testFailure( failure );
}
public function testAssumptionFailure( failure:Failure ):void {
this.uiListener.testAssumptionFailure( failure );
}
public function testIgnored( description:IDescription ):void {
this.uiListener.testIgnored( description );
}
public function testTimed( description:IDescription, runTime:Number ):void {
this.uiListener.testTimed( description, runTime );
}
}
} |
package com.ankamagames.dofus.network.messages.game.guild
{
import com.ankamagames.dofus.network.ProtocolTypeManager;
import com.ankamagames.dofus.network.types.game.social.GuildVersatileInformations;
import com.ankamagames.jerakine.network.CustomDataWrapper;
import com.ankamagames.jerakine.network.ICustomDataInput;
import com.ankamagames.jerakine.network.ICustomDataOutput;
import com.ankamagames.jerakine.network.INetworkMessage;
import com.ankamagames.jerakine.network.NetworkMessage;
import com.ankamagames.jerakine.network.utils.FuncTree;
import flash.utils.ByteArray;
public class GuildVersatileInfoListMessage extends NetworkMessage implements INetworkMessage
{
public static const protocolId:uint = 7464;
private var _isInitialized:Boolean = false;
public var guilds:Vector.<GuildVersatileInformations>;
private var _guildstree:FuncTree;
public function GuildVersatileInfoListMessage()
{
this.guilds = new Vector.<GuildVersatileInformations>();
super();
}
override public function get isInitialized() : Boolean
{
return this._isInitialized;
}
override public function getMessageId() : uint
{
return 7464;
}
public function initGuildVersatileInfoListMessage(guilds:Vector.<GuildVersatileInformations> = null) : GuildVersatileInfoListMessage
{
this.guilds = guilds;
this._isInitialized = true;
return this;
}
override public function reset() : void
{
this.guilds = new Vector.<GuildVersatileInformations>();
this._isInitialized = false;
}
override public function pack(output:ICustomDataOutput) : void
{
var data:ByteArray = new ByteArray();
this.serialize(new CustomDataWrapper(data));
writePacket(output,this.getMessageId(),data);
}
override public function unpack(input:ICustomDataInput, length:uint) : void
{
this.deserialize(input);
}
override public function unpackAsync(input:ICustomDataInput, length:uint) : FuncTree
{
var tree:FuncTree = new FuncTree();
tree.setRoot(input);
this.deserializeAsync(tree);
return tree;
}
public function serialize(output:ICustomDataOutput) : void
{
this.serializeAs_GuildVersatileInfoListMessage(output);
}
public function serializeAs_GuildVersatileInfoListMessage(output:ICustomDataOutput) : void
{
output.writeShort(this.guilds.length);
for(var _i1:uint = 0; _i1 < this.guilds.length; _i1++)
{
output.writeShort((this.guilds[_i1] as GuildVersatileInformations).getTypeId());
(this.guilds[_i1] as GuildVersatileInformations).serialize(output);
}
}
public function deserialize(input:ICustomDataInput) : void
{
this.deserializeAs_GuildVersatileInfoListMessage(input);
}
public function deserializeAs_GuildVersatileInfoListMessage(input:ICustomDataInput) : void
{
var _id1:uint = 0;
var _item1:GuildVersatileInformations = null;
var _guildsLen:uint = input.readUnsignedShort();
for(var _i1:uint = 0; _i1 < _guildsLen; _i1++)
{
_id1 = input.readUnsignedShort();
_item1 = ProtocolTypeManager.getInstance(GuildVersatileInformations,_id1);
_item1.deserialize(input);
this.guilds.push(_item1);
}
}
public function deserializeAsync(tree:FuncTree) : void
{
this.deserializeAsyncAs_GuildVersatileInfoListMessage(tree);
}
public function deserializeAsyncAs_GuildVersatileInfoListMessage(tree:FuncTree) : void
{
this._guildstree = tree.addChild(this._guildstreeFunc);
}
private function _guildstreeFunc(input:ICustomDataInput) : void
{
var length:uint = input.readUnsignedShort();
for(var i:uint = 0; i < length; i++)
{
this._guildstree.addChild(this._guildsFunc);
}
}
private function _guildsFunc(input:ICustomDataInput) : void
{
var _id:uint = input.readUnsignedShort();
var _item:GuildVersatileInformations = ProtocolTypeManager.getInstance(GuildVersatileInformations,_id);
_item.deserialize(input);
this.guilds.push(_item);
}
}
}
|
//
// $Id$
package com.threerings.msoy.data {
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.Streamable;
import com.threerings.util.ClassUtil;
import com.threerings.util.Hashable;
import com.threerings.util.Long;
import com.threerings.util.Util;
import com.threerings.presents.dobj.DSet_Entry;
/**
* Contains metadata for a list of items.
*/
public class MemberExperience
implements Hashable, Streamable, DSet_Entry
{
public var dateOccurred :Long;
public var action :int;
public var data :int;
public function MemberExperience ()
{
// used for deserialization
}
// from DSet.Entry
public function getKey () :Object
{
return this;
}
// from Hashable
public function hashCode () :int
{
// this is not the best hashCode, but it's what we've got here on the as side..
return action;
}
// from Hashable
public function equals (other :Object) :Boolean
{
if (this == other) {
return true;
}
if (other == null || !ClassUtil.isSameClass(this, other)) {
return false;
}
const that :MemberExperience = MemberExperience(other);
return (this.action == that.action) && (this.data == that.data) &&
Util.equals(this.dateOccurred, that.dateOccurred);
}
// from interface Streamable
public function readObject (ins :ObjectInputStream) :void
{
dateOccurred = (ins.readField(Long) as Long);
action = ins.readByte();
data = ins.readInt();
}
// from interface Streamable
public function writeObject (out :ObjectOutputStream) :void
{
out.writeField(dateOccurred);
out.writeByte(action);
out.writeInt(data);
}
}
}
|
package control
{
import com.cgpClient.net.Net;
import com.cgpClient.net.NetEvent;
import com.cgpClient.net.NetStatus;
import model.Model;
public class LoginAction
{
public function start(host:String, userName:String, password:String):void
{
Model.instance.loginUserName = userName;
Model.instance.host = host;
Net.login(host, userName, password);
Net.dispatcher.addEventListener(NetEvent.STATUS, statusHandler);
}
private function statusHandler(event:NetEvent):void
{
if (event.newStatus == NetStatus.LOGGED_IN)
{
var loginCompleteAction:LoginCompleteAction = new LoginCompleteAction();
loginCompleteAction.start();
}
}
}
} |
package com.as3nui.nativeExtensions.air.kinect.examples.away3D.riggedModel {
import away3d.animators.skeleton.JointPose;
import away3d.animators.skeleton.Skeleton;
import away3d.animators.skeleton.SkeletonPose;
import away3d.core.math.Quaternion;
import com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint;
import com.as3nui.nativeExtensions.air.kinect.data.User;
import flash.events.EventDispatcher;
import flash.geom.Matrix3D;
import flash.geom.Vector3D;
import flash.utils.Dictionary;
public class RiggedModelAnimationNode extends EventDispatcher// implements ISkeletonAnimationNode
{
private var _kinectUser:User;
private var _jointMapping:Dictionary;
private var _skeleton:Skeleton;
private var _looping:Boolean;
private var _rootDelta:Vector3D;
private var _currentSkeletonPoseDirty:Boolean;
private var _currentSkeletonPose:SkeletonPose;
private var _skeletonBindPose:SkeletonPose;
private var _skeletonKinectPose:SkeletonPose;
private var _globalWisdom:Vector.<Boolean>;
private var _bindPoses:Vector.<Matrix3D>;
private var _bindPoseOrientationsOfTrackedJoints:Dictionary;
private var _bindShoulderOrientation:Vector3D;
private var _bindSpineOrientation:Vector3D;
private var _rootJointIndex:int;
public function RiggedModelAnimationNode(kinectUser:User, jointMapping:Dictionary)
{
_kinectUser = kinectUser;
_jointMapping = jointMapping;
_rootDelta = new Vector3D(0, 0, 0);
_currentSkeletonPose = new SkeletonPose();
_currentSkeletonPoseDirty = true;
}
public function getSkeletonPose(skeleton:Skeleton):SkeletonPose
{
if(_currentSkeletonPoseDirty)
{
updateCurrentSkeletonPose(skeleton);
}
return _currentSkeletonPose;
}
public function get looping():Boolean
{
return _looping;
}
public function set looping(value:Boolean):void
{
_looping = value;
}
public function get rootDelta():Vector3D
{
return _rootDelta;
}
public function update(time:int):void
{
_currentSkeletonPoseDirty = true;
}
public function reset(time:int):void
{
trace("[RiggedModelAnimationNode] reset", time);
}
private function updateCurrentSkeletonPose(skeleton:Skeleton):void
{
_currentSkeletonPoseDirty = false;
if(isNewSkeleton(skeleton))
{
_skeleton = skeleton;
initSkeleton();
initBindPoseOrientations();
}
updatePose();
}
private function isNewSkeleton(skeleton:Skeleton):Boolean
{
return (_skeletonBindPose == null);
}
private function initSkeleton():void
{
_skeletonBindPose = new SkeletonPose();
_skeletonBindPose.jointPoses = new Vector.<JointPose>(_skeleton.numJoints, true);
_skeletonKinectPose = new SkeletonPose();
_skeletonKinectPose.jointPoses = new Vector.<JointPose>(_skeleton.numJoints, true);
_globalWisdom = new Vector.<Boolean>(_skeleton.numJoints, true);
_bindPoses = new Vector.<Matrix3D>(_skeleton.numJoints, true);
for(var i:int = 0; i < _skeleton.numJoints; i++)
{
var joint:away3d.animators.skeleton.SkeletonJoint = _skeleton.joints[i];
_skeletonBindPose.jointPoses[i] = new JointPose();
var bind:Matrix3D = new Matrix3D(joint.inverseBindPose);
bind.invert();
_bindPoses[i] = bind;
_skeletonBindPose.jointPoses[i].orientation = new Quaternion();
if (joint.parentIndex < 0)
{
_rootJointIndex = i;
_skeletonBindPose.jointPoses[i].orientation.fromMatrix(bind);
_skeletonBindPose.jointPoses[i].translation = bind.position;
}
else
{
var parentBind:Matrix3D = new Matrix3D();
parentBind.rawData = _skeleton.joints[joint.parentIndex].inverseBindPose;
var q1:Quaternion = new Quaternion();
var q2:Quaternion = new Quaternion();
q1.fromMatrix(parentBind);
q1.normalize();
q2.fromMatrix(bind);
q2.normalize();
_skeletonBindPose.jointPoses[i].orientation.multiply(q1, q2);
_skeletonBindPose.jointPoses[i].translation = parentBind.transformVector(bind.position);
}
_skeletonKinectPose.jointPoses[i] = new JointPose();
_skeletonKinectPose.jointPoses[i].orientation.copyFrom(_skeletonBindPose.jointPoses[i].orientation);
_skeletonKinectPose.jointPoses[i].translation.copyFrom(_skeletonBindPose.jointPoses[i].translation);
_currentSkeletonPose.jointPoses[i] = new JointPose();
_currentSkeletonPose.jointPoses[i].orientation.copyFrom(_skeletonBindPose.jointPoses[i].orientation);
_currentSkeletonPose.jointPoses[i].translation.copyFrom(_skeletonBindPose.jointPoses[i].translation);
}
}
private function initBindPoseOrientations():void
{
_bindPoseOrientationsOfTrackedJoints = new Dictionary();
_bindShoulderOrientation = new Vector3D();
_bindSpineOrientation = new Vector3D();
getSimpleBindOrientation(com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.RIGHT_SHOULDER, com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.LEFT_SHOULDER, _bindShoulderOrientation);
getSimpleBindOrientation(com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.TORSO, com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.NECK, _bindSpineOrientation);
getSimpleBindOrientation(com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.NECK, com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.HEAD);
getSimpleBindOrientation(com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.LEFT_SHOULDER, com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.LEFT_ELBOW);
getSimpleBindOrientation(com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.LEFT_ELBOW, com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.LEFT_HAND);
getSimpleBindOrientation(com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.RIGHT_SHOULDER, com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.RIGHT_ELBOW);
getSimpleBindOrientation(com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.RIGHT_ELBOW, com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.RIGHT_HAND);
getSimpleBindOrientation(com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.LEFT_HIP, com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.LEFT_KNEE);
getSimpleBindOrientation(com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.LEFT_KNEE, com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.LEFT_FOOT);
getSimpleBindOrientation(com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.RIGHT_HIP, com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.RIGHT_KNEE);
getSimpleBindOrientation(com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.RIGHT_KNEE, com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.RIGHT_FOOT);
}
private function getSimpleBindOrientation(sourceKinectJointName:String, targetKinectJointName:String, storeVec:Vector3D = null):void
{
var pos1:Vector3D;
var pos2:Vector3D;
var mapIndex1:int = _jointMapping[sourceKinectJointName];
var mapIndex2:int = _jointMapping[targetKinectJointName];
var mtx:Matrix3D = new Matrix3D();
if (mapIndex1 < 0 || mapIndex2 < 0) return;
pos1 = _bindPoses[mapIndex1].position;
pos2 = _bindPoses[mapIndex2].position;
if (!storeVec)
(_bindPoseOrientationsOfTrackedJoints[sourceKinectJointName] = pos2.subtract(pos1)).normalize();
else {
storeVec.x = pos2.x - pos1.x;
storeVec.y = pos2.y - pos1.y;
storeVec.z = pos2.z - pos1.z;
storeVec.normalize();
}
}
private function updatePose():void
{
updateCentralPosition();
updateTorso();
updateSimpleJoint(com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.NECK, com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.HEAD);
updateSimpleJoint(com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.LEFT_SHOULDER, com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.LEFT_ELBOW);
updateSimpleJoint(com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.LEFT_ELBOW, com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.LEFT_HAND);
updateSimpleJoint(com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.RIGHT_SHOULDER, com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.RIGHT_ELBOW);
updateSimpleJoint(com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.RIGHT_ELBOW, com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.RIGHT_HAND);
updateSimpleJoint(com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.LEFT_HIP, com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.LEFT_KNEE);
updateSimpleJoint(com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.LEFT_KNEE, com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.LEFT_FOOT);
updateSimpleJoint(com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.RIGHT_HIP, com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.RIGHT_KNEE);
updateSimpleJoint(com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.RIGHT_KNEE, com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.RIGHT_FOOT);
updateGlobalWisdomFromPositionConfidences();
var localSkeletonPose:SkeletonPose = _skeletonKinectPose;
_currentSkeletonPose = localSkeletonPose;
}
private function getPosition(kinectSkeletonJoint:com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint):Vector3D
{
var p:Vector3D = new Vector3D();
p.copyFrom(kinectSkeletonJoint.position.world);
return p;
}
private function updateCentralPosition():void
{
var center:Vector3D = getPosition(_kinectUser.torso);
center.scaleBy(.1);
_skeletonKinectPose.jointPoses[_rootJointIndex].translation.copyFrom(center);
}
private function updateTorso():void
{
var mapIndex:int = _jointMapping[com.as3nui.nativeExtensions.air.kinect.data.SkeletonJoint.TORSO];
if (mapIndex < 0) return;
_globalWisdom[mapIndex] = true;
var torsoYawRotation:Quaternion = getTorsoYaw();
var torsoPitchRotation:Quaternion = getTorsoPitch();
var torsoRollRotation:Quaternion = getTorsoRoll();
var temp:Quaternion = new Quaternion();
temp.multiply(torsoPitchRotation, torsoRollRotation);
_skeletonKinectPose.jointPoses[mapIndex].orientation.multiply(torsoYawRotation, temp);
}
private function getTorsoYaw():Quaternion
{
var shoulderDir:Vector3D = getPosition(_kinectUser.leftShoulder).subtract(getPosition(_kinectUser.rightShoulder));
shoulderDir.y = 0.0;
shoulderDir.normalize();
var axis:Vector3D = _bindShoulderOrientation.crossProduct(shoulderDir);
var torsoYawRotation:Quaternion = new Quaternion();;
torsoYawRotation.fromAxisAngle(axis, Math.acos(_bindShoulderOrientation.dotProduct(shoulderDir)));
return torsoYawRotation;
}
private function getTorsoPitch():Quaternion
{
var pos1:Vector3D = getPosition(_kinectUser.neck);
var pos2:Vector3D = getPosition(_kinectUser.torso);
var spineDir:Vector3D = new Vector3D();
spineDir.x = 0.0;
spineDir.y = pos1.y - pos2.y;
spineDir.z = pos1.z - pos2.z;
spineDir.normalize();
var axis:Vector3D = _bindSpineOrientation.crossProduct(spineDir);
var torsoPitchRotation:Quaternion = new Quaternion();
torsoPitchRotation.fromAxisAngle(axis, Math.acos(_bindSpineOrientation.dotProduct(spineDir)));
return torsoPitchRotation;
}
private function getTorsoRoll():Quaternion
{
var pos1:Vector3D = getPosition(_kinectUser.neck);
var pos2:Vector3D = getPosition(_kinectUser.torso);
var spineDir:Vector3D = new Vector3D();
spineDir.x = pos1.x - pos2.x;
spineDir.y = pos1.y - pos2.y;
spineDir.z = 0;
spineDir.normalize();
var axis:Vector3D = _bindSpineOrientation.crossProduct(spineDir);
var torsoRollRotation:Quaternion = new Quaternion();
torsoRollRotation.fromAxisAngle(axis, Math.acos(_bindSpineOrientation.dotProduct(spineDir)));
return torsoRollRotation;
}
private function updateSimpleJoint(sourceKinectJointName:String, targetKinectJointName:String):void
{
var mapIndex:int = _jointMapping[sourceKinectJointName];
if (mapIndex < 0) return;
var currDir:Vector3D = getPosition(_kinectUser.getJointByName(targetKinectJointName)).subtract(getPosition(_kinectUser.getJointByName(sourceKinectJointName)));
currDir.normalize();
var bindDir:Vector3D = _bindPoseOrientationsOfTrackedJoints[sourceKinectJointName].clone();
var axis:Vector3D = bindDir.crossProduct(currDir);
axis.normalize();
_globalWisdom[mapIndex] = true;
_skeletonKinectPose.jointPoses[mapIndex].orientation.fromAxisAngle(axis, Math.acos(bindDir.dotProduct(currDir)));
}
private function updateGlobalWisdomFromPositionConfidences():void
{
for each(var jointName:String in _kinectUser.skeletonJointNames)
{
var mapIndex:int = _jointMapping[jointName];
if(mapIndex >= 0 && _kinectUser.getJointByName(jointName).positionConfidence < .5)
_globalWisdom[mapIndex] = false;
}
}
}
} |
table tableDescriptions
"Descriptive information about database tables from autoSql / gbdDescriptions"
(
string tableName; "Name of table (with chr*_ replaced with chrN_)"
lstring autoSqlDef; "Contents of autoSql (.as) table definition file"
string gbdAnchor; "Anchor for table description in gbdDescriptions.html"
)
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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/. */
import com.adobe.test.Assert;
var gTestfile = 'regress-3649-n.js';
//-----------------------------------------------------------------------------
// testcase from bug 2235 mff@research.att.com
var BUGNUMBER = 3649;
var summary = 'gc-checking branch callback.';
var actual = 'error';
var expect = 'error';
DESCRIPTION = summary;
EXPECTED = expect;
//printBugNumber(BUGNUMBER);
//printStatus (summary);
var s = "";
s = "abcd";
for (i = 0; i < 100000; i++) {
s += s;
}
expect = 'No Crash';
actual = 'No Crash';
Assert.expectEq(summary, expect, actual);
|
package {
public class Test {}
}
function fn() {
}
class Cls {
public function method() {
}
public static function static_method() {
}
}
trace("///fn is Function");
trace(fn is Function);
trace("///new Cls().method is Function");
trace(new Cls().method is Function);
trace("///Cls.static_method is Function");
trace(Cls.static_method is Function); |
package de.viaboxx.flexboxx.editors {
import mx.binding.utils.BindingUtils;
import mx.binding.utils.ChangeWatcher;
import mx.graphics.SolidColorStroke;
import spark.components.Group;
import spark.primitives.Rect;
public class PropertyEditor extends Group {
protected var content:Group = new Group();
public function PropertyEditor() {
percentWidth = 100;
addElement(content);
var rect:Rect = new Rect();
rect.stroke = new SolidColorStroke(0x333333, 1, 0.3);
rect.percentWidth = 100;
rect.top = 0;
addElement(rect);
}
protected function bindProperty(element:*, elementProperty:String, editor:*, editorProperty:String,
changeHandler:Function = null):void {
editor[editorProperty] = element[elementProperty];
BindingUtils.bindProperty(element, elementProperty, editor, editorProperty);
if (changeHandler)
ChangeWatcher.watch(editor, editorProperty, changeHandler);
}
}
} |
/////////////////////////////////////////////////////////////////////////////////////
//
// Hummingbird Framework Template
// ==============================
//
// Copyright 2013 Pascal ECHEMANN.
// All Rights Reserved.
//
// NOTICE: The author permits you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
/////////////////////////////////////////////////////////////////////////////////////
package controllers {
import constants.ApplicationState;
import events.ModelEvent;
import models.IAppModel;
import org.flashapi.hummingbird.controller.AbstractController;
import org.flashapi.hummingbird.HummingbirdAS;
import org.flashapi.hummingbird.view.IView;
import views.HomeView;
import views.WelcomeScreen;
[Qualifier(alias="ViewsController")]
public final class ViewsController extends AbstractController implements IViewsController {
[Model(alias="AppModel")]
public var model:IAppModel;
public function initApplication():void {
this.model.addEventListener(ModelEvent.APPLICATION_STATE_CHANGE, this.applicationStateChangeHandler);
this.model.setApplicationState(ApplicationState.WELCOME);
}
private var _currentView:IView;
private function applicationStateChangeHandler(e:ModelEvent):void {
if (_currentView) {
HummingbirdAS.removeFromScene(_currentView);
//_currentView.finalize();
}
switch(this.model.getApplicationState()) {
case ApplicationState.WELCOME :
_currentView = HummingbirdAS.getFactory().createView(WelcomeScreen);
break;
case ApplicationState.HOME :
_currentView = HummingbirdAS.getFactory().createView(HomeView);
break;
}
HummingbirdAS.addToScene(_currentView);
}
}
} |
/* 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/. */
// The package definition has been changed, and now all the packages will be under the
// folder Definitions.Classes, and only this will be used and not the subfolders within.
// This means that we cannot import a single Class file as was required to be done earlier.
// All the files in the package folder will be compiled and used.
// IMPORTANT: This might change later, hence only commenting out the import lines
// and not deleting them. This also creates a problem that the compiled file
// might become too big to handle.
package DefaultClass{
import DefaultClass.*;
// Commenting out the import statement as this is not allowed by the compiler now
// import Definitions.Classes.DefaultClass;
// As this is a final class, it will not be seen by the testcase, hence
// creating a wrapper function for this and changing the name for this file.
// FinExtDefaultClassPub extends FinExtDefaultClassPubInner
final class FinExtDefaultClassPub extends DefaultClass {
// access public method of parent from default method of sub class
function subSetArray( a:Array ) { setPubArray( a ); }
function subGetArray() : Array { return getPubArray(); }
// access public method of parent from dynamic method of sub class
function dynSubSetArray( a:Array ) { setPubArray( a ); }
function dynSubGetArray() : Array { return getPubArray(); }
// access public method of parent from public method of sub class
public function pubSubSetArray( a:Array ) { setPubArray( a ); }
public function pubSubGetArray() : Array { return getPubArray(); }
// access public method of parent from static method of sub class
// This is an error case as a static method cannot access any other
// method except a static method and will be addressed in a seperate
// file in the Error folder.
// static function statSubSetArray( a:Array ) { setPubArray( a ); }
// static function statSubGetArray() : Array { return getPubArray(); }
// access public method of parent from final method of sub class
final function finSubSetArray( a:Array ) { setPubArray( a ); }
final function finSubGetArray() : Array { return getPubArray(); }
// access public method of parent from virtual method of sub class
virtual function virSubSetArray( a:Array ) { setPubArray( a ); }
virtual function virSubGetArray() : Array { return getPubArray(); }
// access public method of parent from private method of sub class
private function privSubSetArray( a:Array ) { setPubArray( a ); }
private function privSubGetArray() : Array { return getPubArray(); }
// function to test above using a public function within the class
// this function will be accessible to an object of the class.
public function testPrivSubArray( a:Array ) : Array {
this.privSubSetArray( a );
return this.privSubGetArray();
}
// access public method of parent from public dynamic method of sub class
public function pubDynSubSetArray( a:Array ) { setPubArray( a ); }
public function pubDynSubGetArray() : Array { return getPubArray(); }
// access public method of parent from public static method of sub class
// This is an error case as a static method cannot access any other
// method except a static method and will be addressed in a seperate
// file in the Error folder.
// public static function pubStatSubSetArray( a:Array ) { setPubArray( a ); }
// public static function pubStatSubGetArray() : Array { return getPubArray(); }
// access public method of parent from public final method of sub class
public final function pubFinSubSetArray( a:Array ) { setPubArray( a ); }
final public function pubFinSubGetArray() : Array { return getPubArray(); }
// access public method of parent from public virtual method of sub class
public virtual function pubVirSubSetArray( a:Array ) { setPubArray( a ); }
virtual public function pubVirSubGetArray() : Array { return getPubArray(); }
// access public method of parent from dynamic static method of sub class
// This is an error case as a static method cannot access any other
// method except a static method and will be addressed in a seperate
// file in the Error folder.
// dynamic static function dynStatSubSetArray( a:Array ) { setPubArray( a ); }
// dynamic static function dynStatSubGetArray() : Array { return getPubArray(); }
// access public method of parent from dynamic final method of sub class
final function dynFinSubSetArray( a:Array ) { setPubArray( a ); }
final function dynFinSubGetArray() : Array { return getPubArray(); }
// access public method of parent from dynamic virtual method of sub class
virtual function dynVirSubSetArray( a:Array ) { setPubArray( a ); }
virtual function dynVirSubGetArray() : Array { return getPubArray(); }
// access public method of parent from dynamic private method of sub class
private function dynPrivSubSetArray( a:Array ) { setPubArray( a ); }
private function dynPrivSubGetArray() : Array { return getPubArray(); }
// function to test above from test scripts
public function testPrivDynSubArray( a:Array ) : Array {
this.dynPrivSubSetArray( a );
return this.dynPrivSubGetArray();
}
// access public method of parent from final static method of sub class
// This is an error case as a static method cannot access any other
// method except a static method and will be addressed in a seperate
// file in the Error folder.
// final static function finStatSubSetArray( a:Array ) { setPubArray( a ); }
// static final function finStatSubGetArray() : Array { return getPubArray(); }
// access public method of parent from final virtual method of sub class
// This is an invalid case and compiler should report that a function cannot
// be both final and virtual.
// This case will be moved to the negative test cases - Error folder.
// final virtual function finVirSubSetArray( a:Array ) { setPubArray( a ); }
// virtual final function finVirSubGetArray() : Array { return getPubArray(); }
// access public method of parent from final private method of sub class
final private function finPrivSubSetArray( a:Array ) { setPubArray( a ); }
private final function finPrivSubGetArray() : Array { return getPubArray(); }
// function to test above from test scripts
public function testPrivFinSubArray( a:Array ) : Array {
this.finPrivSubSetArray( a );
return this.finPrivSubGetArray();
}
// access public method of parent from private static method of sub class
// This is an error case as a static method cannot access any other
// method except a static method and will be addressed in a seperate
// file in the Error folder.
private static function privStatSubSetArray( a:Array ) { setPubArray( a ); }
static private function privStatSubGetArray() : Array { return getPubArray(); }
// function to test above from test scripts
public function testPrivStatSubArray( a:Array ) : Array {
this.privStatSubSetArray( a );
return this.privStatSubGetArray();
}
// access public method of parent from private virtual method of sub class
private virtual function privVirSubSetArray( a:Array ) { setPubArray( a ); }
virtual private function privVirSubGetArray() : Array { return getPubArray(); }
// function to test above from test scripts
public function testPrivVirSubArray( a:Array ) : Array {
this.privVirSubSetArray( a );
return this.privVirSubGetArray();
}
// access public method of parent from virtual static method of sub class
// This is an invalid case as a function cannot be both virtual and static.
// This test case will be moved to the Error folder as a negative test case.
// virtual static function virStatSubSetArray( a:Array ) { setPubArray( a ); }
// static virtual function virStatSubGetArray() : Array { return getPubArray(); }
// access default property from default method of sub class
function subSetDPArray( a:Array ) { pubArray = a; }
function subGetDPArray() : Array { return pubArray; }
// access default property from dynamic method of sub class.
function dynSubSetDPArray( a:Array ) { pubArray = a; }
function dynSubGetDPArray() : Array { return pubArray; }
// access default property from public method of sub class
public function pubSubSetDPArray( a:Array ) { pubArray = a; }
public function pubSubGetDPArray() : Array { return pubArray; }
// access default property from private method of sub class
private function privSubSetDPArray( a:Array ) { pubArray = a; }
private function privSubGetDPArray() : Array { return pubArray; }
// public accessor for the above given private functions,
// so that these can be accessed from an object of the class
public function testPrivSubDPArray( a:Array ) : Array {
privSubSetDPArray( a );
return privSubGetDPArray();
}
// access default property from static method of sub class
static function statSubSetDPArray( a:Array ) { pubArray = a; }
static function statSubGetDPArray() : Array { return pubArray; }
// access default property from final method of sub class
final function finSubSetDPArray( a:Array ) { pubArray = a; }
final function finSubGetDPArray() : Array { return pubArray; }
// access default property from virtual method of sub class
virtual function virSubSetDPArray( a:Array ) { pubArray = a; }
virtual function virSubGetDPArray() : Array { return pubArray; }
// access default property from public static method of sub class
public static function pubStatSubSetDPArray( a:Array ) { pubArray = a; }
public static function pubStatSubGetDPArray() : Array { return pubArray; }
// access default property from private static method of sub class
private static function privStatSubSetDPArray( a:Array ) { pubArray = a; }
private static function privStatSubGetDPArray() : Array { return pubArray; }
// public accessor for the above given private functions,
// so that these can be accessed from an object of the class
public function testPrivStatSubDPArray( a:Array ) : Array {
privStatSubSetDPArray( a );
return privStatSubGetDPArray();
}
}
// Create an instance of the final class in the package.
// This object will be used for accessing the methods created
// within the sub class given above.
var EXTDCLASS = new FinExtDefaultClassPub();
// Create a series of public functions that call the methods.
// The same names can be used as used in the class; because we are now
// outside of the class definition.
// The default method of the sub class.
public function subSetArray( a:Array ) { EXTDCLASS.subSetArray( a ); }
public function subGetArray() : Array { return EXTDCLASS.subGetArray(); }
// The dynamic method of the sub class.
public function dynSubSetArray( a:Array ) { EXTDCLASS.dynSubSetArray( a ); }
public function dynSubGetArray() : Array { return EXTDCLASS.dynSubGetArray(); }
// The public method of the sub class.
public function pubSubSetArray( a:Array ) { EXTDCLASS.pubSubSetArray( a ); }
public function pubSubGetArray() : Array { return EXTDCLASS.pubSubGetArray(); }
// The private method of the sub class. Only one is used as we need to call only the
// test function, which in turn calls the actual private methods, as within the class
// we can access the private methods; but not outside of the class.
public function testPrivSubArray( a:Array ) : Array { return EXTDCLASS.testPrivSubArray( a ); }
// The static method of the sub class.
// This case is a negative case and will be put in the Error folder.
// public function statSubSetArray( a:Array ) { FinClassExtDefaultClass.statSubSetArray( a ); }
// public function statSubGetArray() : Array { return FinClassExtDefaultClass.statSubGetArray(); }
// The STATIC class cannot be accessed by an object of the class, but has to be accessed
// by the class name itself. Bug filed for this: 108206
// public function statSubSetArray( a:Array ) { EXTDCLASS.statSubSetArray( a ); }
// public function statSubGetArray() : Array { return EXTDCLASS.statSubGetArray(); }
// The final method of the sub class.
public function finSubSetArray( a : Array ) { EXTDCLASS.finSubSetArray( a ); }
public function finSubGetArray() : Array { return EXTDCLASS.finSubGetArray(); }
// The virtual method of the sub class.
public function virSubSetArray( a : Array ) { EXTDCLASS.virSubSetArray( a ); }
public function virSubGetArray() : Array { return EXTDCLASS.virSubGetArray(); }
// The public dynamic method of the sub class.
public function pubDynSubSetArray( a:Array ) { EXTDCLASS.dynSubSetArray( a ); }
public function pubDynSubGetArray() : Array { return EXTDCLASS.pubDynSubGetArray(); }
// The public final method of the sub class.
public function pubFinSubSetArray( a : Array ) { EXTDCLASS.pubFinSubSetArray( a ); }
public function pubFinSubGetArray() : Array { return EXTDCLASS.pubFinSubGetArray(); }
// The public virtual method of the sub class.
public function pubVirSubSetArray( a : Array ) { EXTDCLASS.pubVirSubSetArray( a ); }
public function pubVirSubGetArray() : Array { return EXTDCLASS.pubVirSubGetArray(); }
// The dynamic private method of the sub class. Only one is used as we need to call only
// the test function, which in turn calls the actual private methods, as within the class
// we can access the private methods; but not outside of the class.
public function testPrivDynSubArray( a:Array ) : Array { return EXTDCLASS.testPrivDynSubArray( a ); }
// The dynamic final method of the sub class.
public function dynFinSubSetArray( a : Array ) { EXTDCLASS.dynFinSubSetArray( a ); }
public function dynFinSubGetArray() : Array { return EXTDCLASS.dynFinSubGetArray(); }
// The dynamic virtual method of the sub class.
public function dynVirSubSetArray( a : Array ) { EXTDCLASS.dynVirSubSetArray( a ); }
public function dynVirSubGetArray() : Array { return EXTDCLASS.dynVirSubGetArray(); }
// The final private method of the sub class. Only one is used as we need to call only
// the test function, which in turn calls the actual private methods, as within the class
// we can access the private methods; but not outside of the class.
public function testPrivFinSubArray( a:Array ) : Array { return EXTDCLASS.testPrivFinSubArray( a ); }
// The private static method of the sub class. Only one is used as we need to call only
// the test function, which in turn calls the actual private methods, as within the class
// we can access the private methods; but not outside of the class.
// This case is a negative case and will be put in the Error folder.
public function testPrivStatSubArray( a:Array ) : Array { return EXTDCLASS.testPrivStatSubArray( a ); }
// The private virtual method of the sub class. Only one is used as we need to call only
// the test function, which in turn calls the actual private methods, as within the class
// we can access the private methods; but not outside of the class.
public function testPrivVirSubArray( a:Array ) : Array { return EXTDCLASS.testPrivVirSubArray( a ); }
// The default property being accessed by the different method attributes.
// The default method attribute.
public function subSetDPArray( a:Array ) { EXTDCLASS.subSetDPArray(a); }
public function subGetDPArray() : Array { return EXTDCLASS.subGetDPArray(); }
// The dynamic method attribute.
public function dynSubSetDPArray( a:Array ) { EXTDCLASS.dynSubSetDPArray(a); }
public function dynSubGetDPArray() : Array { return EXTDCLASS.dynSubGetDPArray(); }
// The public method attribute.
public function pubSubSetDPArray( a:Array ) { EXTDCLASS.pubSubSetDPArray(a); }
public function pubSubGetDPArray() : Array { return EXTDCLASS.pubSubGetDPArray(); }
// The private method attribute.
public function testPrivSubDPArray( a:Array ):Array { return EXTDCLASS.testPrivSubDPArray(a) }
// the static method attribute.
public function statSubSetDPArray( a:Array ) { FinExtDefaultClassPub.statSubSetDPArray(a); }
public function statSubGetDPArray() : Array { return FinExtDefaultClassPub.statSubGetDPArray(); }
// the final method attribute.
public function finSubSetDPArray( a:Array ) { EXTDCLASS.finSubSetDPArray(a); }
public function finSubGetDPArray() : Array { return EXTDCLASS.finSubGetDPArray(); }
// the virtual method attribute.
public function virSubSetDPArray( a:Array ) { EXTDCLASS.virSubSetDPArray(a); }
public function virSubGetDPArray() : Array { return EXTDCLASS.virSubGetDPArray(); }
// the public static method attrbute.
public function pubStatSubSetDPArray( a:Array ) { FinExtDefaultClassPub.pubStatSubSetDPArray(a); }
public function pubStatSubGetDPArray() : Array { return FinExtDefaultClassPub.pubStatSubGetDPArray(); }
// the private static method attribute
public function testPrivStatSubDPArray( a:Array ) : Array { return EXTDCLASS.testPrivStatSubDPArray(a); }
}
|
package com.xgame.godwar.common.object
{
public class MainPlayer extends Player
{
public function MainPlayer()
{
super();
}
}
} |
// =================================================================================================
//
// Starling Framework
// Copyright 2011 Gamua OG. All Rights Reserved.
//
// This program is free software. You can redistribute and/or modify it
// in accordance with the terms of the accompanying license agreement.
//
// =================================================================================================
package starling.text
{
import flash.utils.Dictionary;
import starling.display.Image;
import starling.textures.Texture;
/** A BitmapChar contains the information about one char of a bitmap font.
* <em>You don't have to use this class directly in most cases.
* The TextField class contains methods that handle bitmap fonts for you.</em>
*/
public class BitmapChar
{
private var mTexture:Texture;
private var mCharID:int;
private var mXOffset:Number;
private var mYOffset:Number;
private var mXAdvance:Number;
private var mKernings:Dictionary;
/** Creates a char with a texture and its properties. */
public function BitmapChar(id:int, texture:Texture,
xOffset:Number, yOffset:Number, xAdvance:Number)
{
mCharID = id;
mTexture = texture;
mXOffset = xOffset;
mYOffset = yOffset;
mXAdvance = xAdvance;
mKernings = null;
}
/** Adds kerning information relative to a specific other character ID. */
public function addKerning(charID:int, amount:Number):void
{
if (mKernings == null)
mKernings = new Dictionary();
mKernings[charID] = amount;
}
/** Retrieve kerning information relative to the given character ID. */
public function getKerning(charID:int):Number
{
if (mKernings == null || mKernings[charID] == undefined) return 0.0;
else return mKernings[charID];
}
/** Creates an image of the char. */
public function createImage():Image
{
return new Image(mTexture);
}
/** The unicode ID of the char. */
public function get charID():int { return mCharID; }
/** The number of pixels to move the char in x direction on character arrangement. */
public function get xOffset():Number { return mXOffset; }
/** The number of pixels to move the char in y direction on character arrangement. */
public function get yOffset():Number { return mYOffset; }
/** The number of pixels the cursor has to be moved to the right for the next char. */
public function get xAdvance():Number { return mXAdvance; }
/** The texture of the character. */
public function get texture():Texture { return mTexture; }
}
} |
package com.losttemple.assets.themes
{
// import flash.filters.DropShadowFilter;
/**
* 风格的值
* @author weism
*/
public class StyleValue
{
// 字体名字
// public static const FONT_NAME_FZY4:String = "FZY4";
// 字体大小值
// public static const FONT_SIZE_14:int = 14;
// public static const FONT_SIZE_16:int = 16;
// public static const FONT_SIZE_18:int = 18;
// public static const FONT_SIZE_20:int = 20;
// 字体颜色值
// public static const FONT_COLOR_WHITE:uint = 0xFFFFFF;
// public static const FONT_COLOR_GREEN:uint = 0x00FF00;
// public static const FONT_COLOR_BLUE:uint = 0x0000FF;
// public static const FONT_COLOR_PURPLE:uint = 0x0000FF;
// public static const FONT_COLOR_ORANGE:uint = 0xFFA801;
// public static const FONT_COLOR_RED:uint = 0xCC00FF;
// 风格颜色值
// public static const STYLE_COlOR_DARK:uint = 0x787878; //变暗颜色
// public static const STYLE_COlOR_WHITE:uint = 0xffffff; //白色
// 阴影
// public static var DROPSHADOW_BLACK:DropShadowFilter = new DropShadowFilter(2, 45, 0, 1, 2, 2, 2, 2);
public function StyleValue()
{
}
}
} |
package {
public class Issue158 {
public function Issue158() {
var cls:Class = Object(this).constructor as Class;
}
}
} |
package org.superkaka.KLib.behavior
{
import flash.display.DisplayObject;
/**
* 控制显示对象的行为基类
* @author kaka
*/
public class DisplayObjectBehavior extends BaseBehavior
{
protected var displayObject:DisplayObject;
public function DisplayObjectBehavior(displayObject:DisplayObject, autoStart:Boolean = true):void
{
this.displayObject = displayObject;
super(displayObject, autoStart);
}
}
} |
package
{
import flash.text.TextField;
/**
* ...
* @author acp
*/
public class CustomTextField extends TextField {
public function create ( _x:int, _y:int, _w:int, _h:int ) {
var tf:CustomTextField = new CustomTextField();
tf.x = _x;
tf.y = _y;
tf.width = _w;
tf.height = _h;
}
}
} |
/*
* 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 tests.flex.lang.reflect.klass {
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flex.lang.reflect.Constructor;
import flex.lang.reflect.Field;
import flex.lang.reflect.Klass;
import flex.lang.reflect.Method;
import flex.lang.reflect.metadata.MetaDataAnnotation;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertFalse;
import org.flexunit.asserts.assertNotNull;
import org.flexunit.asserts.assertNull;
import org.flexunit.asserts.assertTrue;
import org.flexunit.constants.AnnotationConstants;
import tests.flex.lang.reflect.klass.helper.Ancestor1;
import tests.flex.lang.reflect.klass.helper.Ancestor2;
import tests.flex.lang.reflect.klass.helper.ClassForIntrospection;
import tests.flex.lang.reflect.klass.helper.IFakeInterface;
public class KlassWithValidData {
private var klass:Klass;
[Before]
public function setupKlass():void {
klass = new Klass( ClassForIntrospection );
}
[Test]
public function shouldReturnClassReference():void {
assertEquals( ClassForIntrospection, klass.asClass );
}
[Test]
public function shouldReturnClassDef():void {
assertEquals( ClassForIntrospection, klass.classDef );
}
[Test]
public function shouldReturnName():void {
assertEquals( "tests.flex.lang.reflect.klass.helper::ClassForIntrospection", klass.name );
}
[Test]
public function shouldFindConstructorWithTwoParams():void {
var constructor:Constructor = klass.constructor;
assertNotNull( constructor );
assertNotNull( constructor.parameterTypes );
assertEquals( 2, constructor.parameterTypes.length );
assertEquals( int, constructor.parameterTypes[ 0 ] );
}
[Test]
public function shouldFindSixFields():void {
var fields:Array = klass.fields;
assertNotNull( fields );
assertEquals( 6, fields.length );
}
[Test]
public function shouldFindThreeMethods():void {
var methods:Array = klass.methods;
assertNotNull( methods );
assertEquals( 3, methods.length );
}
[Test]
public function shouldImplementInterface():void {
assertTrue( klass.implementsInterface( IFakeInterface ) );
}
[Test]
public function shouldNotImplementInterface():void {
assertFalse( klass.implementsInterface( IEventDispatcher ) );
}
[Test]
public function shouldDescendFromSuper():void {
assertTrue( klass.descendsFrom( Ancestor2 ) );
assertTrue( klass.descendsFrom( Ancestor1 ) );
}
[Test]
public function shouldNotDescendFromEventDispatcher():void {
assertFalse( klass.descendsFrom( EventDispatcher ) );
}
[Test]
public function shouldKnowSuperClass():void {
assertEquals( Ancestor2, klass.superClass );
}
[Test]
public function shouldReturnPackageName():void {
assertEquals( "tests.flex.lang.reflect.klass.helper", klass.packageName );
}
[Test]
public function shouldGetInstanceField():void {
var field:Field = klass.getField( "testPropA" );
assertNotNull( field );
assertEquals( "testPropA", field.name );
}
[Test]
public function shouldGetStaticField():void {
var field:Field = klass.getField( "testStaticPropB" );
assertNotNull( field );
assertEquals( "testStaticPropB", field.name );
}
[Test]
public function shouldNotGetNonExistantField():void {
var field:Field = klass.getField( "monkeyProp" );
assertNull( field );
}
[Test]
public function shouldGetInstanceMethod():void {
var method:Method = klass.getMethod( "returnFalse" );
assertNotNull( method );
assertEquals( "returnFalse", method.name );
}
[Test]
public function shouldGetStaticMethod():void {
var method:Method = klass.getMethod( "returnTrue" );
assertNotNull( method );
assertEquals( "returnTrue", method.name );
}
[Test]
public function shouldNotGetNonExistantMethod():void {
var method:Method = klass.getMethod( "monkeyMethod" );
assertNull( method );
}
[Test]
public function shouldFindIgnoreMetaData():void {
assertTrue( klass.hasMetaData( "Ignore" ) );
}
[Test]
public function shouldGetIgnoreMetaData():void {
var annotation:MetaDataAnnotation = klass.getMetaData( "Ignore" );
assertNotNull( annotation );
}
[Test]
public function shouldNotFindMonkeyMetaData():void {
assertFalse( klass.hasMetaData( "Monkey" ) );
}
[Test]
public function shouldNotGetApeMetaData():void {
var annotation:MetaDataAnnotation = klass.getMetaData( "Ape" );
assertNull( annotation );
}
[Test]
public function shouldFindASingleInterface():void {
var interfaces:Array = klass.interfaces;
assertNotNull( interfaces );
assertEquals( 1, interfaces.length );
}
[Test]
public function shouldFindThreeeClassesInInheritance():void {
var classes:Array = klass.classInheritance;
assertNotNull( classes );
assertEquals( 3, classes.length );
}
[Test]
public function shouldGetClassFromDotColonName():void {
var clazz:Class = Klass.getClassFromName( "tests.flex.lang.reflect.klass.helper::ClassForIntrospection" );
assertNotNull( clazz );
assertEquals( ClassForIntrospection, clazz );
}
[Test]
public function shouldNotGetClassFromWrongDotColonName():void {
var clazz:Class = Klass.getClassFromName( "tests.flex.lang.reflect.klass.helper::SomeIntro" );
assertNull( clazz );
}
[Test]
public function shouldFindTestMetaData():void {
var method:Method = klass.getMethod( "baseMethod" );
var annotation:MetaDataAnnotation = method.getMetaData( AnnotationConstants.TEST );
assertNotNull( annotation );
}
[Test]
public function shouldFindSuiteMetaData():void {
var method:Method = klass.getMethod( "baseMethod" );
var annotation:MetaDataAnnotation = method.getMetaData( AnnotationConstants.SUITE );
assertNotNull( annotation );
}
/* [Test]
I don't know that we will ever be able to put this test back in.
Our good friends at Adobe pollute the methods with tons of metadata
when in debug mode. So, this test performs differenty when debugging in
flash builder than runtime
public function shouldGetCorrectMetaDataCount():void {
var annotations:Array = klass.metadata;
assertNotNull( annotations );
assertEquals( 1, annotations.length );
}*/
}
} |
void func(int a) {
}
void test() {
func(b:4);
}
|
// Compile with:
// mtasc -main -header 200:150:30 Test.as -swf test.swf
class Test {
static function main(current) {
var p = { x: 3 };
p.addProperty("x", function() { trace("get x"); }, function(value) { trace("set x to " + value); });
var o = { __proto__: p };
o.watch("x", function(prop, old_val, new_val) { trace("old_val: " + old_val); return new_val; });
o.x = 4;
}
}
|
package ru.kutu.grindplayer.views.mediators {
import flash.display.StageDisplayState;
import flash.events.Event;
import flash.events.FullScreenEvent;
import flash.globalization.LocaleID;
import mx.core.FlexGlobals;
import mx.resources.IResourceManager;
import mx.resources.ResourceManager;
import org.osmf.media.MediaResourceBase;
import org.osmf.media.PluginInfoResource;
import ru.kutu.grind.views.mediators.PlayerViewBaseMediator;
import ru.kutu.grindplayer.config.GrindPlayerConfiguration;
import ru.kutu.grindplayer.events.AdvertisementEvent;
import ru.kutu.grindplayer.events.PlayerVideoZoomEvent;
import ru.kutu.osmf.advertisement.AdvertisementPluginInfo;
import ru.kutu.osmf.subtitles.SubtitlesPluginInfo;
CONFIG::HLS {
import ru.kutu.osmf.hls.OSMFHLSPluginInfo;
}
public class PlayerViewMediator extends PlayerViewBaseMediator {
private var _zoom:int;
override public function initialize():void {
super.initialize();
addContextListener(AdvertisementEvent.ADVERTISEMENT, onAdvertisement, AdvertisementEvent);
}
override protected function processConfiguration(flashvars:Object):void {
CONFIG::DEV {
flashvars.src = "";
}
if ("locale" in flashvars) {
var locale:String = flashvars.locale;
var resourceManager:IResourceManager = ResourceManager.getInstance();
var locales:Vector.<String> = Vector.<String>(resourceManager.localeChain);
locales = LocaleID.determinePreferredLocales(new <String>[locale], locales);
if (locales && locales.length) {
locale = locales[0];
}
if (locale && locale.length) {
var localeChain:Array = resourceManager.localeChain;
var localeIndex:int = localeChain.indexOf(locale);
if (localeIndex != -1) {
localeChain.splice(localeIndex, 1);
localeChain.unshift(locale);
resourceManager.localeChain = localeChain;
}
}
}
super.processConfiguration(flashvars);
}
override protected function onConfigurationReady(event:Event):void {
super.onConfigurationReady(event);
contextView.view.stage.addEventListener(FullScreenEvent.FULL_SCREEN, onFullScreen);
onFullScreen();
var gc:GrindPlayerConfiguration = configuration as GrindPlayerConfiguration;
if (gc && !isNaN(gc.tintColor)) {
FlexGlobals.topLevelApplication.styleManager.getStyleDeclaration("global").setStyle("tintColor", gc.tintColor);
}
}
override protected function addCustomPlugins(pluginConfigurations:Vector.<MediaResourceBase>):void {
pluginConfigurations.push(new PluginInfoResource(new SubtitlesPluginInfo()));
pluginConfigurations.push(new PluginInfoResource(new AdvertisementPluginInfo()));
CONFIG::HLS {
pluginConfigurations.push(new PluginInfoResource(new OSMFHLSPluginInfo(contextView.view.loaderInfo)));
}
}
override protected function initializeView():void {
super.initializeView();
addContextListener(PlayerVideoZoomEvent.ZOOM_IN, onZoom, PlayerVideoZoomEvent);
addContextListener(PlayerVideoZoomEvent.ZOOM_OUT, onZoom, PlayerVideoZoomEvent);
addContextListener(PlayerVideoZoomEvent.ZOOM_RESET, onZoom, PlayerVideoZoomEvent);
}
override protected function onViewResize(event:Event = null):void {
if (mediaContainer) {
const w:Number = view.mediaPlayerContainer.width;
const h:Number = view.mediaPlayerContainer.height;
videoContainer.width = w * (100 + _zoom) / 100;
videoContainer.height = h * (100 + _zoom) / 100;
videoContainer.validateNow();
videoContainer.x = (w - videoContainer.width) / 2;
videoContainer.y = (h - videoContainer.height) / 2;
mediaContainer.width = w;
mediaContainer.height = h;
hitArea.graphics.clear();
hitArea.graphics.beginFill(0);
hitArea.graphics.drawRect(0, 0, w, h);
}
}
private function get zoom():int { return _zoom }
private function set zoom(value:int):void {
if (value < -90) value = -90;
if (value == _zoom) return;
_zoom = value;
onViewResize();
}
private function onZoom(event:PlayerVideoZoomEvent):void {
switch (event.type) {
case PlayerVideoZoomEvent.ZOOM_IN: zoom++; break;
case PlayerVideoZoomEvent.ZOOM_OUT: zoom--; break;
case PlayerVideoZoomEvent.ZOOM_RESET: zoom = 0; break;
}
}
private function onFullScreen(event:FullScreenEvent = null):void {
view.controlBarAutoHide = contextView.view.stage.displayState == StageDisplayState.NORMAL
? configuration.controlBarAutoHide
: configuration.controlBarFullScreenAutoHide;
}
private function onAdvertisement(event:AdvertisementEvent):void {
// check at least one ad has layoutInfo and isAdvertisement
var isAdvertisement:Boolean;
if (event.ads && event.ads is Array) {
for each (var item:Object in event.ads) {
if ("layoutInfo" in item && !item.layoutInfo && "isAdvertisement" in item && item.isAdvertisement) {
isAdvertisement = true;
break;
}
}
}
// remove main media from videoContainer if ad is linear
if (isAdvertisement && videoContainer.containsMediaElement(player.media)) {
videoContainer.removeMediaElement(player.media);
} else if (!isAdvertisement && !videoContainer.containsMediaElement(player.media)) {
videoContainer.addMediaElement(player.media);
}
}
}
}
|
package com.sanbeetle.core
{
import com.sanbeetle.Component;
import com.sanbeetle.events.ControlEvent;
import com.sanbeetle.model.AMark;
import com.sanbeetle.utils.FontNames;
import com.sanbeetle.utils.Utils;
import flash.display.Sprite;
import flash.events.Event;
import flash.geom.Rectangle;
import flash.net.URLVariables;
import flash.text.Font;
import flash.text.StyleSheet;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.engine.BreakOpportunity;
import flash.text.engine.FontLookup;
import flash.text.engine.FontWeight;
import flash.utils.ByteArray;
import flash.utils.getTimer;
import flashx.textLayout.conversion.ConversionType;
import flashx.textLayout.conversion.TextConverter;
import flashx.textLayout.edit.EditManager;
import flashx.textLayout.edit.EditingMode;
import flashx.textLayout.edit.IEditManager;
import flashx.textLayout.edit.ISelectionManager;
import flashx.textLayout.edit.SelectionManager;
import flashx.textLayout.edit.SelectionState;
import flashx.textLayout.elements.Configuration;
import flashx.textLayout.elements.LinkElement;
import flashx.textLayout.elements.TextFlow;
import flashx.textLayout.events.FlowElementMouseEvent;
import flashx.textLayout.events.FlowOperationEvent;
import flashx.textLayout.formats.BlockProgression;
import flashx.textLayout.formats.LineBreak;
import flashx.textLayout.formats.TextLayoutFormat;
import flashx.textLayout.formats.WhiteSpaceCollapse;
import flashx.textLayout.operations.DeleteTextOperation;
import flashx.textLayout.operations.FlowOperation;
import flashx.textLayout.operations.InsertTextOperation;
import flashx.textLayout.operations.PasteOperation;
[Event(name="text_link",type="com.sanbeetle.events.ControlEvent")]
[Event(name="text_link_move",type="com.sanbeetle.events.ControlEvent")]
[Event(name="text_link_over",type="com.sanbeetle.events.ControlEvent")]
[Event(name="text_link_out",type="com.sanbeetle.events.ControlEvent")]
//[Event(name="textInput",type="flash.events.TextEvent")]
[Event(name="change",type="flash.events.Event")]
[Event(name="font_loaded",type="com.sanbeetle.events.ControlEvent")]
/**
* 显示文本,输入框 ,多行文本,html文本
*@author sixf
*/
public class TLFTextBox extends UIComponent
{
protected var _text:String = "default label";
private var _align:String = "left";
private var _wordWrap:Boolean=false;
private var _dropShadow:Boolean = false;
private var _fontSize:String = "14";
private var _color:String = "0x333333";
private var aMarkData:Object = new Object;
private var _leading:Number =6;
private var _border:Boolean=false;
private var _autoSize:String="none";
private var _scrollText:Boolean =false;
private var _bold:Boolean = false;
private var _selectable:Boolean = false;
private var _showHtml:Boolean = false;
private var _multiline:Boolean = false;
private var _lineHeight:Object;
private var _paddingBottom:Number=0;
private var _paddingLeft:Number = 0;
private var _paddingRight:Number = 0;
private var _paddingTop:Number = 0;
private var _textAlign:String="start";
protected var textContainerManager:ExtendsTextContainerManager;
protected var container:Sprite;
private var _textLayoutFormat:TextLayoutFormat;
private var configuration:Configuration;
private var styleSheet:StyleSheet = new StyleSheet();
private var _autoBound:Boolean = false;
private var ccw:Number;
private var cch:Number;
private var _verticalAlign:String="inherit";
private var _currentLinkData:AMark;
private var _blockProgression:String =BlockProgression.TB;
private var isXMLText:Boolean = false;
public function TLFTextBox()
{
_textLayoutFormat = new TextLayoutFormat();
_textLayoutFormat.fontFamily = FontNames.MS_YaHei_Local;
_textLayoutFormat.fontSize = _fontSize;
_textLayoutFormat.whiteSpaceCollapse = WhiteSpaceCollapse.COLLAPSE;
_textLayoutFormat.breakOpportunity = BreakOpportunity.NONE;
_textLayoutFormat.lineBreak = LineBreak.EXPLICIT;
container= new Sprite();
container.name = "container sprite";
configuration = component.configuration;
textContainerManager = new ExtendsTextContainerManager(container,configuration);
textContainerManager.hostFormat = _textLayoutFormat;
textContainerManager.setText(_text);
lineHeight = _lineHeight;
textContainerManager.editingMode = EditingMode.READ_ONLY;
addTextFlowEvent();
}
public function addTextImage(textimage:TextImage):TextImage{
throw new Error("不支持这个属性!");
return null;
}
protected function get textField():TextField{
throw new Error("不支持这个属性!");
return null;
}
/**
* 删除文字,焦点不会消失,
* @param operationState
* @return
*
*/
public function deleteAllText(operationState:SelectionState=null):String{
var str:String = this.text;
var em:EditManager = textContainerManager.getTextFlow().interactionManager as EditManager;
if(em){
em.selectAll();
em.deleteText(operationState);
setFocus();
}
return str;
}
public function get textLayoutFormat():TextLayoutFormat
{
return _textLayoutFormat;
}
override protected function onAddStage():void
{
this.linkStage.addEventListener(ControlEvent.FONT_LOADED,onYaheiFontLoadedHandelr);
}
override protected function onRemoveStage():void
{
this.linkStage.removeEventListener(ControlEvent.FONT_LOADED,onYaheiFontLoadedHandelr);
}
[Inspectable(enumeration = "tb,rl",defaultValue = "tb")]
public function get blockProgression():String
{
return _blockProgression;
}
public function set blockProgression(value:String):void
{
if(_blockProgression!==value){
_blockProgression = value;
_textLayoutFormat.blockProgression = _blockProgression;
textContainerManager.hostFormat =_textLayoutFormat;
this.updateUI();
//_textFlow.flowComposer.updateAllControllers();
//cc.updateContainer();
}
}
public function get currentLinkData():AMark
{
return _currentLinkData;
}
public function set currentLinkData(value:AMark):void
{
_currentLinkData = value;
}
/**
* Constant Defined By </br>
* BOTTOM : String = "bottom" </br>
* [static] Specifies alignment with the bottom edge of the frame. VerticalAlign </br>
* JUSTIFY : String = "justify" </br>
* [static] Specifies vertical line justification within the frame VerticalAlign </br>
* MIDDLE : String = "middle" </br>
* [static] Specifies alignment with the middle of the frame. VerticalAlign </br>
* TOP : String = "top" </br>
* [static] Specifies alignment with the top edge of the frame. VerticalAlign </br>
* FormatValue.INHERIT
* @return
*
*/
[Inspectable(enumeration = "bottom,justify,middle,top,inherit",defaultValue = "inherit")]
public function get verticalAlign():String
{
return _verticalAlign;
}
public function set verticalAlign(value:String):void
{
if(_verticalAlign != value){
_verticalAlign = value;
_textLayoutFormat.verticalAlign = _verticalAlign;
this.updateUI();
}
}
public function setFocus():void{
if(textContainerManager.getTextFlow().interactionManager){
textContainerManager.getTextFlow().interactionManager.setFocus();
textContainerManager.getTextFlow().interactionManager.flushPendingOperations();
}
}
protected function addTextFlowEvent():void{
if(textContainerManager==null){
return;
}
textContainerManager.addEventListener(FlowOperationEvent.FLOW_OPERATION_BEGIN,onFlowOperationBedginHandler);
textContainerManager.addEventListener(FlowOperationEvent.FLOW_OPERATION_COMPLETE,onFlowOperationCompleteHandler);
textContainerManager.addEventListener(FlowOperationEvent.FLOW_OPERATION_END,onFlowOperationEndHandler);
textContainerManager.addEventListener(FlowElementMouseEvent.MOUSE_DOWN,onFlowElementMouseDownHandler);
textContainerManager.getTextFlow().addEventListener(FlowElementMouseEvent.MOUSE_MOVE,onFlowElementMoveHandler);
textContainerManager.getTextFlow().addEventListener(FlowElementMouseEvent.ROLL_OUT,onFlowElementOutHandler);
textContainerManager.getTextFlow().addEventListener(FlowElementMouseEvent.ROLL_OVER,onFlowElementOverHandler);
}
protected function removeTextFlowEvent():void{
if(textContainerManager==null){
return;
}
textContainerManager.removeEventListener(FlowOperationEvent.FLOW_OPERATION_BEGIN,onFlowOperationBedginHandler);
textContainerManager.removeEventListener(FlowOperationEvent.FLOW_OPERATION_COMPLETE,onFlowOperationCompleteHandler);
textContainerManager.removeEventListener(FlowOperationEvent.FLOW_OPERATION_END,onFlowOperationEndHandler);
textContainerManager.removeEventListener(FlowElementMouseEvent.MOUSE_DOWN,onFlowElementMouseDownHandler);
textContainerManager.getTextFlow().removeEventListener(FlowElementMouseEvent.MOUSE_MOVE,onFlowElementMoveHandler);
textContainerManager.getTextFlow().removeEventListener(FlowElementMouseEvent.ROLL_OUT,onFlowElementOutHandler);
textContainerManager.getTextFlow().removeEventListener(FlowElementMouseEvent.ROLL_OVER,onFlowElementOverHandler);
}
protected function onFlowElementOverHandler(event:FlowElementMouseEvent):void
{
var lin:LinkElement = event.flowElement as LinkElement;
if(lin){
disTextEvent(lin,ControlEvent.TEXT_LINK_OVER);
}
}
protected function onFlowElementOutHandler(event:FlowElementMouseEvent):void
{
// TODO Auto-generated method stub
var lin:LinkElement = event.flowElement as LinkElement;
if(lin){
disTextEvent(lin,ControlEvent.TEXT_LINK_OUT);
}
}
protected function onFlowElementMoveHandler(event:FlowElementMouseEvent):void
{
// TODO Auto-generated method stub
var lin:LinkElement = event.flowElement as LinkElement;
if(lin){
disTextEvent(lin,ControlEvent.TEXT_LINK_MOVE);
}
}
protected function onFlowOperationEndHandler(event:FlowOperationEvent):void
{
var op:FlowOperation = event.operation;
if (op is InsertTextOperation)
{
var insertTextOperation:InsertTextOperation =InsertTextOperation(op);
var textToInsert:String = insertTextOperation.text;
// Note: Must process restrict first, then maxChars,
// then displayAsPassword last.
// The text deleted by this operation. If we're doing our
// own manipulation of the textFlow we have to take the deleted
// text into account as well as the inserted text.
var delSelOp:SelectionState = insertTextOperation.deleteSelectionState;
var delLen:int = (delSelOp == null) ? 0 :
delSelOp.absoluteEnd - delSelOp.absoluteStart;
if (maxChars != 0)
{
var length1:int = text.length - delLen;
var length2:int = textToInsert.length;
if (length1 + length2 > maxChars)
textToInsert = textToInsert.substr(0, maxChars - length1);
}
insertTextOperation.text = textToInsert;
}else if (op is PasteOperation){
handlePasteOperation(op as PasteOperation);
}
textContainerManager.endInteraction();
}
private function handlePasteOperation(op:PasteOperation):void
{
// If copied/cut from displayAsPassword field the pastedText
// is '*' characters but this is correct.
if(op.textScrap==null){
return;
}
var pastedText:String = op.textScrap.textFlow.getText();
// See if there is anything we need to do.
if(pastedText==null){
pastedText="";
}
// Save this in case we modify the pasted text. We need to know
// how much text to delete.
var textLength:int = pastedText.length;
// We know it's an EditManager or we wouldn't have gotten here.
var editManager:IEditManager = EditManager(textContainerManager.getTextFlow().interactionManager);
// Generate a CHANGING event for the PasteOperation but not for the
// DeleteTextOperation or the InsertTextOperation which are also part
// of the paste.
if(editManager){
var selectionState:SelectionState = new SelectionState(op.textFlow, op.absoluteStart,op.absoluteStart + textLength);
editManager.deleteText(selectionState);
// Insert the same text, the same place where the paste was done.
// This will go thru the InsertPasteOperation and do the right
// things with restrict, maxChars and displayAsPassword.
selectionState = new SelectionState(op.textFlow, op.absoluteStart, op.absoluteStart);
editManager.insertText(pastedText, selectionState);
// All done with the edit manager.
//dispatchChangeAndChangingEvents = true;
}
}
public function get textXML():String{
return String(exportText(TextConverter.TEXT_LAYOUT_FORMAT,ConversionType.STRING_TYPE));
}
public function set textXML(value:String):void{
var xmlTextFlow:TextFlow;
this.removeTextFlowEvent();
XML.prettyPrinting = false;
XML.ignoreWhitespace = false;
var data:Object = value;
var disstr:String;
var llll:XMLList = new XMLList(value);
if(llll.length()==1){//is xml
if(llll[0].localName()=="TextFlow"){
//trace(data.localName());
disstr = value;
}else{
//var xmll:XMLList = new XMLList(data);
disstr =Utils.copyTextFlowStyle(textContainerManager.getTextFlow(),llll);
}
}else{// is string
disstr =Utils.copyTextFlowStyle(textContainerManager.getTextFlow(),llll);
}
xmlTextFlow = TextConverter.importToFlow(disstr, TextConverter.TEXT_LAYOUT_FORMAT,configuration);
if(xmlTextFlow==null){
throw new Error("TextFlow 的 XML 不正确!");
}
if(textContainerManager){
if(textContainerManager.getTextFlow()){
while(textContainerManager.getTextFlow().numChildren>0){
textContainerManager.getTextFlow().removeChildAt(0);
}
}
}
textContainerManager.setTextFlow(xmlTextFlow);
xmlTextFlow.interactionManager = interactionManager();
//xmlTextFlow.whiteSpaceCollapse=WhiteSpaceCollapse.COLLAPSE;
//_textFlow = xmlTextFlow;
isXMLText = true;
//cc.whiteSpaceCollapse = WhiteSpaceCollapse.COLLAPSE;
var csss:StyleSheet = component.getStyle();
var linkArr:Array = textContainerManager.getTextFlow().getElementsByTypeName("a");
///
var linkNormalFormat_p:TextLayoutFormat = new TextLayoutFormat();
var linkHoverFormat_p:TextLayoutFormat = new TextLayoutFormat();
var linkActiveFormat_p:TextLayoutFormat = new TextLayoutFormat();
//var textformat:TextLayoutFormat = new TextLayoutFormat();
var obj:Object;
obj= csss.getStyle("a")
if(obj!=null){
for(key in obj){
//link.styleName
linkNormalFormat_p.setStyle(key,obj[key]);
linkHoverFormat_p.setStyle(key,obj[key]);
linkActiveFormat_p.setStyle(key,obj[key]);
}
xmlTextFlow.linkNormalFormat = linkNormalFormat_p;
xmlTextFlow.linkHoverFormat = linkHoverFormat_p;
xmlTextFlow.linkActiveFormat = linkActiveFormat_p;
}
obj = csss.getStyle("a:link");
if(obj!=null){
for(key in obj){
//link.styleName
linkNormalFormat_p.setStyle(key,obj[key]);
}
xmlTextFlow.linkNormalFormat = linkNormalFormat_p;
}
obj = csss.getStyle("a:hover");
if(obj!=null){
for(key in obj){
//link.styleName
linkHoverFormat_p.setStyle(key,obj[key]);
}
xmlTextFlow.linkHoverFormat = linkHoverFormat_p;
}
obj = csss.getStyle("a:active");
if(obj!=null){
for(key in obj){
//link.styleName
linkActiveFormat_p.setStyle(key,obj[key]);
}
xmlTextFlow.linkActiveFormat = linkActiveFormat_p;
}
for(var i:int=0;i<linkArr.length;i++){
var link:LinkElement = linkArr[i];
if(link){
var linkNormalFormat:TextLayoutFormat = new TextLayoutFormat(linkNormalFormat_p);
var linkHoverFormat:TextLayoutFormat = new TextLayoutFormat(linkHoverFormat_p);
var linkActiveFormat:TextLayoutFormat = new TextLayoutFormat(linkActiveFormat_p);
var key:String;
if(link.styleName!=null){
obj = csss.getStyle("."+link.styleName);
if(obj!=null){
for(key in obj){
//link.styleName
linkNormalFormat.setStyle(key,obj[key]);
linkHoverFormat.setStyle(key,obj[key]);
linkActiveFormat.setStyle(key,obj[key]);
}
link.linkNormalFormat = linkNormalFormat;
link.linkHoverFormat = linkHoverFormat;
link.linkActiveFormat = linkActiveFormat;
}
obj = csss.getStyle("."+link.styleName+":link");
if(obj!=null){
for(key in obj){
//link.styleName
linkNormalFormat.setStyle(key,obj[key]);
}
link.linkNormalFormat = linkNormalFormat;
}
obj = csss.getStyle("."+link.styleName+":hover");
if(obj!=null){
for(key in obj){
//link.styleName
linkHoverFormat.setStyle(key,obj[key]);
}
link.linkHoverFormat = linkHoverFormat;
}
obj = csss.getStyle("."+link.styleName+":active");
if(obj!=null){
for(key in obj){
//link.styleName
linkActiveFormat.setStyle(key,obj[key]);
link.linkActiveFormat = linkActiveFormat;
}
}
}else{
}
}
}
_textLayoutFormat.blockProgression = _blockProgression;
//xmlTextFlow.format = _textLayoutFormat;
this.addTextFlowEvent();
this.updateUI();
XML.prettyPrinting = true;
XML.ignoreWhitespace = true;
}
protected function onFlowElementMouseDownHandler(event:FlowElementMouseEvent):void
{
var lin:LinkElement = event.flowElement as LinkElement;
if(lin){
disTextEvent(lin,ControlEvent.TEXT_LINK);
}
}
private function disTextEvent(lin:LinkElement,eventType:String):void{
_currentLinkData = new AMark();
if(lin.href){
var tarte:Array = lin.href.split(":");
if(tarte.length>=2){
_currentLinkData.target=tarte[1];
}
if(lin.styles!=null){
if(lin.styles["pam"]==undefined){
_currentLinkData.parameters =new URLVariables();
}else{
_currentLinkData.parameters = new URLVariables(String(lin.styles["pam"]));
}
}else{
_currentLinkData.parameters =new URLVariables();
}
}else{
_currentLinkData.parameters = new URLVariables();
}
this.dispatchEvent(new ControlEvent(eventType,_currentLinkData));
}
private var _regExp:RegExp;
protected function onFlowOperationCompleteHandler(event:FlowOperationEvent):void
{
//Log.out("b");
_text = textContainerManager.getTextFlow().getText();
this.dispatchEvent(new Event(Event.CHANGE));
if(event.operation is DeleteTextOperation){
/*if(p.parent==null){
this.clearnAddText();
}*/
}
//trace(p.parent);
}
/**
* RegExpType 枚举
* @see com.sanbeetle.data.RegExpType
*/
public function get regExp():RegExp
{
return _regExp;
}
/**
* @private
*/
public function set regExp(value:RegExp):void
{
_regExp = value;
}
protected function onFlowOperationBedginHandler(event:FlowOperationEvent):void
{
var intotxt:InsertTextOperation = event.operation as InsertTextOperation;
var str:String;
if(intotxt)
{
str = text+intotxt.text;
if(_regExp!=null)
{
if(!_regExp.test(str))
{
event.preventDefault();
return;
}
}
if ( maxChars > 0 )
{
var _o:int = getStringBytesLength(text,"gb2312");
if(_o>maxChars)
{
event.preventDefault();
}
else
{
intotxt.text = intotxt.text.substring( 0, maxChars - _o );
while( maxChars < _o + getStringBytesLength( intotxt.text ,"gb2312") )
{
intotxt.text = intotxt.text.substring( 0, intotxt.text.length - 1 );
}
}
}
}
}
//获取字符串的字节数
private function getStringBytesLength(str:String,charSet:String):int
{
var bytes:ByteArray = new ByteArray();
bytes.writeMultiByte(str, charSet);
bytes.position = 0;
//Log.out( str + " " + bytes.length );
return bytes.length;
}
/**
* CENTER : String = "center"</br>
* [静态] 指定与容器中心对齐。</br>
* TextAlign</br>
* END : String = "end"</br>
* [静态] 指定结束边缘对齐 - 文本与书写顺序的结束端对齐。</br>
* TextAlign</br>
* JUSTIFY : String = "justify"</br>
* [静态] 指定文本在行内两端对齐,以便位于容器空间范围内。</br>
* TextAlign</br>
* LEFT : String = "left"</br>
* [静态] 指定左边缘对齐。</br>
* TextAlign</br>
* RIGHT : String = "right"</br>
* [静态] 指定右边缘对齐。</br>
* TextAlign</br>
* START : String = "start"</br>
* [静态] 指定起始边缘对齐 - 文本与书写顺序的起始端对齐。 </br>
* @return
*
*/
[Inspectable(enumeration = "center,end,justify,left,right,start",defaultValue = "start")]
public function get textAlign():String
{
return _textAlign;
}
public function set textAlign(value:String):void
{
if(_textAlign !== value){
_textAlign = value;
_textLayoutFormat.textAlign = _textAlign;
this.updateUI();
}
}
/**
* 行高
*/
[Inspectable()]
public function get lineHeight():*
{
return _lineHeight;
}
public function set lineHeight(value:Object):void
{
if(_lineHeight !== value){
_lineHeight = value;
if(_lineHeight==null){
_lineHeight=null;
}else if(_lineHeight==""){
_lineHeight =null;
}
_textLayoutFormat.lineHeight = _lineHeight;
this.updateUI();
}
}
/**
* 在给定的宽度不变的情况下,自己扩展 高度。
* @return
*
*/
[Inspectable]
public function get autoBound():Boolean
{
return _autoBound;
}
public function set autoBound(value:Boolean):void
{
if(_autoBound !== value){
_autoBound = value;
this.updateUI();
}
}
[Inspectable(defaultValue=0)]
public function get paddingTop():Number
{
return _paddingTop;
}
public function set paddingTop(value:Number):void
{
if( _paddingTop !== value)
{
_paddingTop = value;
//_textLayoutFormat.paddingTop = _paddingTop;
//textContainerManager.hostFormat = _textLayoutFormat;
}
}
[Inspectable]
public function get paddingRight():Number
{
return _paddingRight;
}
public function set paddingRight(value:Number):void
{
if( _paddingRight !== value)
{
_paddingRight = value;
//_textLayoutFormat.paddingRight = _paddingRight;
//textContainerManager.hostFormat = _textLayoutFormat;
}
}
[Inspectable(defaultValue=0)]
public function get paddingLeft():Number
{
return _paddingLeft;
}
public function set paddingLeft(value:Number):void
{
if( _paddingLeft !== value)
{
_paddingLeft = value;
//_textLayoutFormat.paddingLeft = _paddingLeft;
//textContainerManager.hostFormat = _textLayoutFormat;
}
}
[Inspectable]
public function get paddingBottom():Number
{
return _paddingBottom;
}
public function set paddingBottom(value:Number):void
{
if( _paddingBottom !== value)
{
_paddingBottom = value;
//_textLayoutFormat.paddingBottom = _paddingBottom;
//textContainerManager.hostFormat = _textLayoutFormat;
}
}
private var _maxChars:int=0;
public function get textFlow():TextFlow
{
if(textContainerManager==null){
return null;
}
return textContainerManager.getTextFlow();
}
[Inspectable(defaultValue =0)]
public function get maxChars():int
{
return _maxChars;
}
public function set maxChars(value:int):void
{
_maxChars = value;
//updateUI();
}
//[Inspectable(defaultValue=false)]
/**
* 是否可以滚动文本
*/
public function get scrollText():Boolean
{
return _scrollText;
}
[Deprecated(message="这个已经废弃了,请改用: 不滚动[ILabel.multiline = true;ILabel.autoBound = true;],滚动[ILabel.multiline = true;ILabel.autoBound = false;]")]
public function set scrollText(value:Boolean):void
{
if(_scrollText!=value){
_scrollText = value;
if(_scrollText){
this.multiline = true;
this.autoBound = false;
}else{
this.multiline = true;
this.autoBound = true;
}
//Log.info("这个禁止滚动的。还没有实现。");
//textfield.mouseWheelEnabled =_scrollText;
}
}
[Inspectable(defaultValue = false)]
public function get dropShadow():Boolean
{
return _dropShadow;
}
public function set dropShadow(value:Boolean):void
{
if(_dropShadow!=value){
_dropShadow = value;
this.updateUI();
}
}
//[Inspectable(enumeration="subpixel,none,pixel",defaultValue = "none")]
public function get gridFitType():String
{
return null;
}
[Deprecated]
public function set gridFitType(value:String):void
{
/*if(_gridFitType!=value){
_gridFitType = value;
textfield.gridFitType = _gridFitType;
this.updateUI();
} */
}
[Inspectable(defaultValue=false)]
/**
* 是否多行
* @return
*
*/
public function get multiline():Boolean
{
return _multiline;
}
//[Deprecated(message="这个属性已经不在使用,")]
public function set multiline(value:Boolean):void
{
if(_multiline!=value){
_multiline = value;
if(_multiline){
_textLayoutFormat.lineBreak = LineBreak.TO_FIT;
_textLayoutFormat.breakOpportunity = BreakOpportunity.AUTO;
}else{
_textLayoutFormat.lineBreak = LineBreak.EXPLICIT;
_textLayoutFormat.breakOpportunity = BreakOpportunity.NONE;
}
textContainerManager.hostFormat =_textLayoutFormat;
textContainerManager.getTextFlow().format = _textLayoutFormat;
this.updateUI();
}
}
[Inspectable(defaultValue = 6)]
/**
* 行高
*/
public function get leading():Number
{
return _leading;
}
[Deprecated(message="这个属性已经不在使用,请使用 lineHeight")]
public function set leading(value:Number):void
{
if(_leading != value){
_leading = value;
if(_multiline==false){
//textFormat.leading = 0;
lineHeight = null;
}else{
//textFormat.leading = _leading;
//lineHeight =_leading;
}
updateUI();
}
}
[Inspectable(defaultValue =false)]
public function get selectable():Boolean
{
return _selectable;
}
/**
* 文本可选则?
* @param value
*
*/
public function set selectable(value:Boolean):void
{
if(_selectable != value){
_selectable = value;
}
}
//[Inspectable(defaultValue = false)]
/**
* 是否显示成html
*/
public function get showHtml():Boolean
{
return _showHtml;
}
[Deprecated(message="已经不用了,要显示 富文本请使用 IRichText 组件")]
public function set showHtml(value:Boolean):void
{
if(_showHtml!==value){
_showHtml = value;
//this._text = "<p>"+this._text+"</p>"
this.updateUI();
}
}
[Inspectable(enumeration = "center,left,none,right",defaultValue = "none")]
/**
*
* 自动尺寸
*/
public function get autoSize():String
{
return _autoSize;
}
[Deprecated(message="autoSize 已经不使用了,请使用 ILabel.autoBound",replacement="ILabel.autoBound")]
public function set autoSize(value:String):void
{
if(_autoSize!= value){
_autoSize = value;
if(_autoSize!=TextFieldAutoSize.NONE){
_autoBound = true;
}else{
_autoBound = false;
}
this.updateUI();
}
}
override public function dispose():void
{
_currentLinkData = null;
removeTextFlowEvent();
styleSheet.clear();
while(textContainerManager.getTextFlow().numChildren>0){
textContainerManager.getTextFlow().removeChildAt(0);
}
//textContainerManager.getTextFlow().flowComposer.removeAllControllers();
textContainerManager.getTextFlow().flowComposer = null;
textContainerManager.getTextFlow().interactionManager = null;
textContainerManager.hostFormat = null;
container.removeChildren();
container.graphics.clear();
if(stage!=null){
stage.removeEventListener(ControlEvent.FONT_LOADED,onYaheiFontLoadedHandelr);
}
_textLayoutFormat =null;
configuration=null;
textContainerManager =null;
container=null;
container = null;
aMarkData=null;
super.dispose();
}
protected function interactionManager():ISelectionManager{
if(this._selectable){
textContainerManager.editingMode = EditingMode.READ_SELECT;
return new SelectionManager();
}else{
textContainerManager.editingMode = EditingMode.READ_ONLY;
return null;
}
}
private function changeCCSize(w:Number,h:Number):void{
if(ccw!=w || cch!=h){
ccw=w;
cch=h;
textContainerManager.compositionWidth =w;
textContainerManager.compositionHeight = h;
if(textContainerManager.isDamaged()){
textContainerManager.compose();
}
}
}
private var containerRect:Rectangle=new Rectangle;
override protected function updateUI():void
{
var t:Number = getTimer();
textContainerManager.hostFormat = _textLayoutFormat;
var rect:Rectangle = textContainerManager.getContentBounds();
containerRect = new Rectangle();
if(_autoBound){
if(_multiline){
changeCCSize(trueWidth-_paddingLeft-_paddingRight,NaN);
rect = textContainerManager.getContentBounds();
changeCCSize(rect.width,NaN);
containerRect.x = 0;
containerRect.y = 0;
containerRect.width = trueWidth;
containerRect.height = rect.height+_paddingBottom+_paddingTop;
}else{
changeCCSize(NaN,NaN);
rect = textContainerManager.getContentBounds();
///trace("a");
//(rect.width,rect.height);
changeCCSize(rect.width,NaN);
//(rect.width,rect.height);
containerRect.x = 0;
containerRect.y = 0;
containerRect.width = rect.width+_paddingLeft+_paddingRight;
containerRect.height = rect.height+_paddingTop+_paddingBottom;
//trace(containerRect.width,containerRect.height);
}
}else{
changeCCSize(trueWidth-_paddingLeft-_paddingRight,trueHeight-_paddingTop-_paddingBottom);
containerRect.x = 0;
containerRect.y = 0;
containerRect.width = trueWidth;
containerRect.height = trueHeight;
}
container.graphics.clear();
container.graphics.lineStyle(5);
container.graphics.beginFill(0xffff00,0);
container.graphics.drawRect(containerRect.x,containerRect.y,containerRect.width,containerRect.height);
container.graphics.endFill();
container.x = _paddingLeft;
container.y = _paddingTop;
drawBorder(containerRect.width,containerRect.height);
if(this._dropShadow){
container.cacheAsBitmap =true;
container.filters=component.ilabelFilters;
}else{
container.cacheAsBitmap =false;
container.filters=null;
}
//trace(container.width,container.height);
textContainerManager.updateContainer();
//trace(container.width,container.height);
}
override public function get height():Number
{
// TODO Auto Generated method stub
return containerRect.height;
//return cc.compositionHeight;
}
override public function get width():Number
{
// TODO Auto Generated method stub
return containerRect.width;
//return cc.compositionWidth;
}
[Inspectable(defaultValue = false)]
public function get bold():Boolean
{
return _bold;
}
public function set bold(value:Boolean):void
{
if(_bold!= value){
_bold = value;
if(_bold){
_textLayoutFormat.fontWeight = FontWeight.BOLD;
}else{
_textLayoutFormat.fontWeight = FontWeight.NORMAL;
}
textContainerManager.hostFormat =_textLayoutFormat;
//textContainerManager.updateContainer();
this.updateUI();
}
}
override protected function createUI():void
{
onYaheiFontLoadedHandelr(null);
textContainerManager.getTextFlow().interactionManager = interactionManager();
this.addChild(container);
}
protected function onYaheiFontLoadedHandelr(event:Event):void
{
if(textContainerManager==null || _textLayoutFormat==null){
return;
}
var fontArr:Array = Font.enumerateFonts();
if(fontArr.length==0){
return;
}
var isHaveFont:Boolean = false;
for each (var f:Font in fontArr)
{
if (f.fontName == FontNames.MS_YaHei_Local)
{
isHaveFont = true;
break;
}
}
if (isHaveFont)
{
textContainerManager.swfContext = Component.MicrosoftYaHei;
_textLayoutFormat.fontFamily = FontNames.MS_YaHei_Local;
_textLayoutFormat.fontLookup = FontLookup.EMBEDDED_CFF;
this.updateUI();
this.dispatchEvent(new ControlEvent(ControlEvent.FONT_LOADED));
}
else
{
_textLayoutFormat.fontFamily = FontNames.MS_YaHei;
//_textFlow.fontLookup = FontLookup.DEVICE;
}
textContainerManager.hostFormat = _textLayoutFormat;
}
[Inspectable(defaultValue = 0x333333)]
public function get color():String
{
return _color;
}
public function set color(value:String):void
{
if(_color!= value){
_color = value;
_textLayoutFormat.color = uint(value);
textContainerManager.hostFormat= _textLayoutFormat;
textContainerManager.updateContainer();
}
}
//[Inspectable(defaultValue = false)]
public function get border():Boolean
{
return _border;
}
[Deprecated(message="border 已经废弃掉了,设置无效。",replacement="无")]
public function set border(value:Boolean):void
{
if(_border!= value){
_border = value;
}
}
//[Inspectable(defaultValue = false)]
public function get wordWrap():Boolean
{
return _wordWrap;
}
[Deprecated(message="已经废弃了,改用 multiline")]
public function set wordWrap(value:Boolean):void
{
if(_wordWrap!= value){
_wordWrap = value;
multiline = _wordWrap;
}
}
[Inspectable(defaultValue = "14")]
public function get fontSize():String
{
return _fontSize;
}
public function set fontSize(value:String):void
{
if(_fontSize!= value){
_fontSize = value;
_textLayoutFormat.fontSize = _fontSize;
textContainerManager.hostFormat=_textLayoutFormat;
updateUI();
//textContainerManager.updateContainer();
//textContainerManager.compose();
/*textContainerManager.updateContainer();
textContainerManager.compose();
textContainerManager.hostFormat=_textLayoutFormat; */
}
}
[Inspectable(enumeration = "left,right,center,justify",defaultValue = "left")]
public function get align():String
{
return _align;
}
[Deprecated(message="这个属性不使用了,改用 textAlign,",replacement="textAlign")]
public function set align(value:String):void
{
if(_align!= value){
_align = value;
//_textAlign = _align;
this.textAlign = _align;
}
}
protected function clearnAddText():void{
/* while(_textFlow.numChildren>0){
_textFlow.removeChildAt(0);
}
while(p.numChildren>0){
p.removeChildAt(0);
}
p.addChild(textContext);
//trace(textTextFlow.numChildren);
this._textFlow.addChild(p);
textContext.text="";
cc.setTextFlow(_textFlow);
cc.compose();*/
}
public function set text(value:String):void
{
if(isXMLText==true){
this.removeTextFlowEvent();
textContainerManager.hostFormat = this._textLayoutFormat;
this.addTextFlowEvent();
}
isXMLText = false;
if(_text!= value){
if(value==null){
value="";
}
_text = value;
textContainerManager.setText(_text);
_textLayoutFormat.blockProgression = _blockProgression;
updateUI();
}
}
[Inspectable(defaultValue = "default label")]
/**
*@default TextFieldAutoSize.NONE
*/
public function get text():String
{
//return _textFlow.getText();
return textContainerManager.getTextFlow().getText();
}
/**
*
* @param type TextConverter 的静态属性
* @param conversionType ConversionType 的静态属性
*
* @return
* @see flashx.textLayout.conversion.TextConverter
* @see flashx.textLayout.conversion.ConversionType
*/
public function exportText(type:String,conversionType:String):Object{
return TextConverter.export(textContainerManager.getTextFlow(),type,conversionType);
}
}
}
|
package com.splunk.charting.properties
{
import com.splunk.charting.labels.AxisTitle;
import com.splunk.properties.ParseUtils;
import com.splunk.properties.PropertyManager;
import com.splunk.properties.TextBlockPropertyParser;
public class AxisTitlePropertyParser extends TextBlockPropertyParser
{
// Private Static Properties
private static var _instance:AxisTitlePropertyParser;
// Public Static Methods
public static function getInstance() : AxisTitlePropertyParser
{
var instance:AxisTitlePropertyParser = AxisTitlePropertyParser._instance;
if (!instance)
instance = AxisTitlePropertyParser._instance = new AxisTitlePropertyParser();
return instance;
}
// Constructor
public function AxisTitlePropertyParser()
{
}
// Public Methods
public override function stringToValue(propertyManager:PropertyManager, str:String) : *
{
if (ParseUtils.trimWhiteSpace(str) == "axisTitle")
return new AxisTitle();
return null;
}
public override function valueToString(propertyManager:PropertyManager, value:*) : String
{
if (value is AxisTitle)
return "axisTitle";
return null;
}
public override function registerProperties(propertyManager:PropertyManager, value:*) : void
{
super.registerProperties(propertyManager, value);
if (value is AxisTitle)
{
propertyManager.registerProperty("placement", this.stringPropertyParser, this.getProperty, this.setProperty);
}
}
}
}
|
package devoron.components.tables
{
/**
* НЕОБХОДИМО ПЕРЕНЕСТИ В НОРМАЛЬНОЕ МЕСТО
* @author Devoron
*/
public interface INewValueGenerator
{
function generateNewValue():*;
}
} |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is [Open Source Virtual Machine.].
*
* The Initial Developer of the Original Code is
* Adobe System Incorporated.
* Portions created by the Initial Developer are Copyright (C) 2004-2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adobe AS3 Team
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
var SECTION = "Definitions"; // provide a document reference (ie, ECMA section)
var VERSION = "AS 3.0"; // Version of JavaScript or ECMA
var TITLE = "Access static method in a namespace of base class from subclass"; // Provide ECMA section title or a description
var BUGNUMBER = "";
startTest(); // leave this alone
/**
* Calls to AddTestCase here. AddTestCase is a function that is defined
* in shell.js and takes three arguments:
* - a string representation of what is being tested
* - the expected result
* - the actual result
*
* For example, a test might look like this:
*
* var helloWorld = "Hello World";
*
* AddTestCase(
* "var helloWorld = 'Hello World'", // description of the test
* "Hello World", // expected result
* helloWorld ); // actual result
*
*/
import StaticPropertyPackage.*;
var obj = new AccNSStatPropSubClassMeth();
// ********************************************
// Access the static method via BaseClass.foo()
// ********************************************
AddTestCase( "*** Access the static method via base class ***", 1, 1 );
AddTestCase( "BaseClass.ns1::echo('hello')", "hello", BaseClass.ns1::echo("hello") );
// ********************************************
// Access the static method via sub class,
// using unadorned "foo()"
// ********************************************
AddTestCase( "*** Access the static method via sub class using unadorned method name ***", 1, 1 );
AddTestCase( "obj.callEcho('world')", "world", obj.callEcho("world") );
// ********************************************
// Access the static method via sub class,
// using "BaseClass.foo()"
// ********************************************
AddTestCase( "*** Access the static method via sub class using adorned method name ***", 1, 1 );
AddTestCase( "obj.callBaseEcho('elvis')", "elvis", obj.callBaseEcho("elvis") );
test(); // leave this alone. this executes the test cases and
// displays results.
|
package laya.display.css {
/**
* @private
*/
public class TransformInfo {
public var translateX:Number = 0;
public var translateY:Number = 0;
public var scaleX:Number = 1;
public var scaleY:Number = 1;
public var rotate:Number = 0;
public var skewX:Number = 0;
public var skewY:Number = 0;
}
} |
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package visualEditor.plugin
{
import flash.events.Event;
import actionScripts.events.ExportVisualEditorProjectEvent;
import actionScripts.plugin.PluginBase;
import actionScripts.plugin.actionscript.as3project.vo.AS3ProjectVO;
import actionScripts.utils.UtilsCore;
import actionScripts.valueObjects.ConstantsCoreVO;
public class ExportToFlexPlugin extends PluginBase
{
public function ExportToFlexPlugin()
{
super();
}
override public function get name():String { return "Export Visual Editor Project to Flex Plugin"; }
override public function get author():String { return ConstantsCoreVO.MOONSHINE_IDE_LABEL +" Project Team"; }
override public function get description():String { return "Exports Visual Editor project to Flex (Adobe Air Desktop)."; }
override public function activate():void
{
super.activate();
dispatcher.addEventListener(
ExportVisualEditorProjectEvent.EVENT_INIT_EXPORT_VISUALEDITOR_PROJECT_TO_FLEX,
initExportVisualEditorProjectToFlexHandler);
}
override public function deactivate():void
{
super.deactivate();
}
private function initExportVisualEditorProjectToFlexHandler(event:Event):void
{
var currentActiveProject:AS3ProjectVO = model.activeProject as AS3ProjectVO;
if (currentActiveProject == null || currentActiveProject.isPrimeFacesVisualEditorProject)
{
error("This is not Visual Editor Flex project");
return;
}
UtilsCore.closeAllRelativeEditors(model.activeProject, false,
function():void
{
dispatcher.dispatchEvent(
new ExportVisualEditorProjectEvent(
ExportVisualEditorProjectEvent.EVENT_EXPORT_VISUALEDITOR_PROJECT_TO_FLEX,
currentActiveProject));
}, false);
}
}
}
|
/**
* This class handles ECard request buttons.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @author David Cary
* @since 04.09.2010
*/
package com.neopets.games.marketing.destination.capriSun.disrespectoids.widgets.ecard
{
//----------------------------------------
// IMPORTS
//----------------------------------------
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import com.neopets.games.marketing.destination.capriSun.disrespectoids.util.BroadcasterClip;
import com.neopets.projects.destination.destinationV3.AbsPage;
public class ECardButton extends BroadcasterClip
{
//----------------------------------------
// VARIABLES
//----------------------------------------
public static const BROADCAST_EVENT:String = "ECard_requested";
//----------------------------------------
// CONSTRUCTOR
//----------------------------------------
public function ECardButton():void {
super();
// set up broadcasts
useParentDispatcher(AbsPage);
// set up mouse behaviour
addEventListener(MouseEvent.CLICK,onClick);
buttonMode = true;
}
//----------------------------------------
// GETTERS AND SETTORS
//----------------------------------------
//----------------------------------------
// PUBLIC METHODS
//----------------------------------------
//----------------------------------------
// PROTECTED METHODS
//----------------------------------------
//----------------------------------------
// PRIVATE METHODS
//----------------------------------------
//----------------------------------------
// EVENT LISTENERS
//----------------------------------------
// Relay click through shared dispatcher.
protected function onClick(ev:MouseEvent) {
broadcast(BROADCAST_EVENT);
}
}
} |
/* 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/. */
import com.adobe.test.Assert;
// var SECTION = "RegExp/exec-001";
// var VERSION = "ECMA_2";
// var TITLE = "RegExp.prototype.exec(string)";
var testcases = getTestCases();
function getTestCases() {
var array = new Array();
var item = 0;
/*
* for each test case, verify:
* - type of object returned
* - length of the returned array
* - value of lastIndex
* - value of index
* - value of input
* - value of the array indices
*/
// test cases without subpatterns
// test cases with subpatterns
// global property is true
// global property is false
// test cases in which the exec returns null
array[item++] = Assert.expectEq( "NO TESTS EXIST", "PASSED", "PASSED");
return array;
}
|
// Copyright 2020 Cadic AB. All Rights Reserved.
// @URL https://github.com/Temaran/Feather
// @Author Fredrik Lindh [Temaran] (temaran@gmail.com)
////////////////////////////////////////////////////////////
import Feather.DebugInterface.FeatherDebugInterfaceWindow;
struct FAutoExecSaveState
{
FString StartUpExecs;
FString ShutDownExecs;
};
UCLASS(Abstract)
class UFeatherDebugInterfaceAutoExecWindow : UFeatherDebugInterfaceWindow
{
default WindowName = n"AutoExec";
private bool bHasRunStartUpExecs = false;
UFUNCTION(BlueprintOverride)
void FeatherConstruct(FFeatherStyle InStyle, FFeatherConfig InConfig)
{
Super::FeatherConstruct(InStyle, InConfig);
GetStartUpBox().OnTextCommitted.AddUFunction(this, n"StartUpExecsCommitted");
GetShutDownBox().OnTextCommitted.AddUFunction(this, n"ShutDownExecsCommitted");
}
UFUNCTION()
void StartUpExecsCommitted(FText& NewExecs, ETextCommit CommitMethod)
{
SaveSettings();
}
UFUNCTION()
void ShutDownExecsCommitted(FText& NewExecs, ETextCommit CommitMethod)
{
SaveSettings();
}
UFUNCTION(BlueprintOverride)
void Destruct()
{
ExecuteCorpusString(GetShutDownBox().GetText().ToString());
}
void ExecuteCorpusString(FString ExecCorpus)
{
FString Corpus = ExecCorpus;
FString CurrentExec;
FString RemainingString;
while(Corpus.Split("\r\n", CurrentExec, RemainingString))
{
CurrentExec = CurrentExec.TrimStartAndEnd();
if(!CurrentExec.IsEmpty())
{
System::ExecuteConsoleCommand(CurrentExec);
}
Corpus = RemainingString;
}
Corpus = Corpus.TrimStartAndEnd();
if(!Corpus.IsEmpty())
{
System::ExecuteConsoleCommand(Corpus);
}
}
UFUNCTION(BlueprintOverride)
void SaveToString(FString& InOutSaveString)
{
Super::SaveToString(InOutSaveString);
FAutoExecSaveState SaveState;
SaveState.StartUpExecs = GetStartUpBox().GetText().ToString();
SaveState.ShutDownExecs = GetShutDownBox().GetText().ToString();
FJsonObjectConverter::AppendUStructToJsonObjectString(SaveState, InOutSaveString);
}
UFUNCTION(BlueprintOverride)
void LoadFromString(const FString& InSaveString)
{
Super::LoadFromString(InSaveString);
FAutoExecSaveState SaveState;
if(FJsonObjectConverter::JsonObjectStringToUStruct(InSaveString, SaveState))
{
GetStartUpBox().SetText(FText::FromString(SaveState.StartUpExecs));
GetShutDownBox().SetText(FText::FromString(SaveState.ShutDownExecs));
}
if(!bHasRunStartUpExecs)
{
ExecuteCorpusString(GetStartUpBox().GetText().ToString());
bHasRunStartUpExecs = true;
}
}
////////////////////////////////////////////////////////////////////////
UFUNCTION(Category = "AutoExec", BlueprintEvent)
UMultiLineEditableText GetStartUpBox()
{
return nullptr;
}
UFUNCTION(Category = "AutoExec", BlueprintEvent)
UMultiLineEditableText GetShutDownBox()
{
return nullptr;
}
};
|
// Action script...
// [Initial MovieClip Action of sprite 20973]
#initclip 238
if (!dofus.graphics.gapi.controls.ItemViewer)
{
if (!dofus)
{
_global.dofus = new Object();
} // end if
if (!dofus.graphics)
{
_global.dofus.graphics = new Object();
} // end if
if (!dofus.graphics.gapi)
{
_global.dofus.graphics.gapi = new Object();
} // end if
if (!dofus.graphics.gapi.controls)
{
_global.dofus.graphics.gapi.controls = new Object();
} // end if
var _loc1 = (_global.dofus.graphics.gapi.controls.ItemViewer = function ()
{
super();
}).prototype;
_loc1.__set__useButton = function (bUseButton)
{
this._bUseButton = bUseButton;
//return (this.useButton());
};
_loc1.__get__useButton = function ()
{
return (this._bUseButton);
};
_loc1.__set__destroyButton = function (bDestroyButton)
{
this._bDestroyButton = bDestroyButton;
//return (this.destroyButton());
};
_loc1.__get__destroyButton = function ()
{
return (this._bDestroyButton);
};
_loc1.__set__targetButton = function (bTargetButton)
{
this._bTargetButton = bTargetButton;
//return (this.targetButton());
};
_loc1.__get__targetButton = function ()
{
return (this._bTargetButton);
};
_loc1.__set__displayPrice = function (bDisplayPrice)
{
this._bPrice = bDisplayPrice;
this._lblPrice._visible = bDisplayPrice;
this._mcKamaSymbol._visible = bDisplayPrice;
//return (this.displayPrice());
};
_loc1.__get__displayPrice = function ()
{
return (this._bPrice);
};
_loc1.__set__hideDesc = function (bDisplayDesc)
{
this._bDesc = !bDisplayDesc;
this._txtDescription._visible = this._bDesc;
this._txtDescription.scrollBarRight = this._bDesc;
//return (this.hideDesc());
};
_loc1.__get__hideDesc = function ()
{
return (this._bDesc);
};
_loc1.__set__itemData = function (oItem)
{
this._oItem = oItem;
this.addToQueue({object: this, method: this.showItemData, params: [oItem]});
//return (this.itemData());
};
_loc1.__get__itemData = function ()
{
return (this._oItem);
};
_loc1.__set__displayWidth = function (nDisplayWidth)
{
this._nDisplayWidth = Math.max(316, nDisplayWidth + 2);
//return (this.displayWidth());
};
_loc1.init = function ()
{
super.init(false, dofus.graphics.gapi.controls.ItemViewer.CLASS_NAME);
};
_loc1.arrange = function ()
{
this._lstInfos._width = this._nDisplayWidth - this._lstInfos._x;
this._txtDescription._width = this._nDisplayWidth - this._txtDescription._x - 1;
this._mcTitle._width = this._nDisplayWidth - this._mcTitle._x;
this._lblLevel._x = this._nDisplayWidth - (316 - this._lblLevel._x);
};
_loc1.createChildren = function ()
{
this.addToQueue({object: this, method: this.initTexts});
this.addToQueue({object: this, method: this.addListeners});
this._btnTabCharacteristics._visible = false;
this._pbEthereal._visible = false;
this._ldrTwoHanded._visible = false;
};
_loc1.initTexts = function ()
{
this._btnTabEffects.label = this.api.lang.getText("EFFECTS");
this._btnTabConditions.label = this.api.lang.getText("CONDITIONS");
this._btnTabCharacteristics.label = this.api.lang.getText("CHARACTERISTICS");
};
_loc1.addListeners = function ()
{
this._btnAction.addEventListener("click", this);
this._btnAction.addEventListener("over", this);
this._btnAction.addEventListener("out", this);
this._btnTabEffects.addEventListener("click", this);
this._btnTabCharacteristics.addEventListener("click", this);
this._btnTabConditions.addEventListener("click", this);
this._pbEthereal.addEventListener("over", this);
this._pbEthereal.addEventListener("out", this);
this._ldrTwoHanded.onRollOver = function ()
{
this._parent.over({target: this});
};
this._ldrTwoHanded.onRollOut = function ()
{
this._parent.out({target: this});
};
};
_loc1.showItemData = function (oItem)
{
if (oItem != undefined)
{
this._lblName.text = oItem.name;
if (dofus.Constants.DEBUG)
{
this._lblName.text = this._lblName.text + (" (" + oItem.unicID + ")");
} // end if
if (oItem.style == "")
{
this._lblName.styleName = "WhiteLeftMediumBoldLabel";
}
else
{
this._lblName.styleName = oItem.style + "LeftMediumBoldLabel";
} // end else if
this._lblLevel.text = this.api.lang.getText("LEVEL_SMALL") + oItem.level;
this._txtDescription.text = oItem.description;
this._ldrIcon.contentParams = oItem.params;
this._ldrIcon.contentPath = oItem.iconFile;
this.updateCurrentTabInformations();
if (oItem.superType == 2)
{
this._btnTabCharacteristics._visible = true;
}
else
{
if (this._sCurrentTab == "Characteristics")
{
this.setCurrentTab("Effects");
} // end if
this._btnTabCharacteristics._visible = false;
} // end else if
this._lblPrice.text = oItem.price == undefined ? ("") : (new ank.utils.ExtendedString(oItem.price).addMiddleChar(this.api.lang.getConfigText("THOUSAND_SEPARATOR"), 3));
this._lblWeight.text = oItem.weight + " " + ank.utils.PatternDecoder.combine(this._parent.api.lang.getText("PODS"), "m", oItem.weight < 2);
if (oItem.isEthereal)
{
var _loc3 = oItem.etherealResistance;
this._pbEthereal.maximum = _loc3.param3;
this._pbEthereal.value = _loc3.param2;
this._pbEthereal._visible = true;
if (_loc3.param2 < 4)
{
this._pbEthereal.styleName = "EtherealCriticalProgressBar";
}
else
{
this._pbEthereal.styleName = "EtherealNormalProgressBar";
} // end else if
}
else
{
this._pbEthereal._visible = false;
} // end else if
this._ldrTwoHanded._visible = oItem.needTwoHands;
}
else if (this._lblName.text != undefined)
{
this._lblName.text = "";
this._lblLevel.text = "";
this._txtDescription.text = "";
this._ldrIcon.contentPath = "";
this._lstInfos.removeAll();
this._lblPrice.text = "";
this._lblWeight.text = "";
this._pbEthereal._visible = false;
this._ldrTwoHanded._visible = false;
} // end else if
};
_loc1.updateCurrentTabInformations = function ()
{
var _loc2 = new ank.utils.ExtendedArray();
switch (this._sCurrentTab)
{
case "Effects":
{
for (var s in this._oItem.effects)
{
if (this._oItem.effects[s].description.length > 0)
{
_loc2.push(this._oItem.effects[s]);
} // end if
} // end of for...in
break;
}
case "Characteristics":
{
for (var s in this._oItem.characteristics)
{
if (this._oItem.characteristics[s].length > 0)
{
_loc2.push(this._oItem.characteristics[s]);
} // end if
} // end of for...in
break;
}
case "Conditions":
{
for (var s in this._oItem.conditions)
{
if (this._oItem.conditions[s].length > 0)
{
_loc2.push(this._oItem.conditions[s]);
} // end if
} // end of for...in
break;
}
} // End of switch
_loc2.reverse();
this._lstInfos.dataProvider = _loc2;
};
_loc1.setCurrentTab = function (sNewTab)
{
var _loc3 = this["_btnTab" + this._sCurrentTab];
var _loc4 = this["_btnTab" + sNewTab];
_loc3.selected = true;
_loc3.enabled = true;
_loc4.selected = false;
_loc4.enabled = false;
this._sCurrentTab = sNewTab;
this.updateCurrentTabInformations();
};
_loc1.click = function (oEvent)
{
switch (oEvent.target._name)
{
case "_btnTabEffects":
{
this.setCurrentTab("Effects");
break;
}
case "_btnTabCharacteristics":
{
this.setCurrentTab("Characteristics");
break;
}
case "_btnTabConditions":
{
this.setCurrentTab("Conditions");
break;
}
case "_btnAction":
{
var _loc3 = this.api.ui.createPopupMenu();
_loc3.addStaticItem(this._oItem.name);
if (this._bUseButton && this._oItem.canUse)
{
_loc3.addItem(this._parent.api.lang.getText("CLICK_TO_USE"), this, this.dispatchEvent, [{type: "useItem", item: this._oItem}]);
} // end if
_loc3.addItem(this._parent.api.lang.getText("CLICK_TO_INSERT"), this.api.kernel.GameManager, this.api.kernel.GameManager.insertItemInChat, [this._oItem]);
if (this._bTargetButton && this._oItem.canTarget)
{
_loc3.addItem(this._parent.api.lang.getText("CLICK_TO_TARGET"), this, this.dispatchEvent, [{type: "targetItem", item: this._oItem}]);
} // end if
_loc3.addItem(this._parent.api.lang.getText("ASSOCIATE_RECEIPTS"), this.api.ui, this.api.ui.loadUIComponent, ["ItemUtility", "ItemUtility", {item: this._oItem}]);
if (this._bDestroyButton && this._oItem.canDestroy)
{
_loc3.addItem(this._parent.api.lang.getText("CLICK_TO_DESTROY"), this, this.dispatchEvent, [{type: "destroyItem", item: this._oItem}]);
} // end if
_loc3.show(_root._xmouse, _root._ymouse);
break;
}
} // End of switch
};
_loc1.over = function (oEvent)
{
switch (oEvent.target._name)
{
case "_pbEthereal":
{
var _loc3 = this._oItem.etherealResistance;
this.gapi.showTooltip(_loc3.description, oEvent.target, -20);
break;
}
case "_ldrTwoHanded":
{
this.gapi.showTooltip(this.api.lang.getText("TWO_HANDS_WEAPON"), this._ldrTwoHanded, -20);
break;
}
} // End of switch
};
_loc1.out = function (oEvent)
{
this.gapi.hideTooltip();
};
_loc1.addProperty("targetButton", _loc1.__get__targetButton, _loc1.__set__targetButton);
_loc1.addProperty("useButton", _loc1.__get__useButton, _loc1.__set__useButton);
_loc1.addProperty("displayPrice", _loc1.__get__displayPrice, _loc1.__set__displayPrice);
_loc1.addProperty("displayWidth", function ()
{
}, _loc1.__set__displayWidth);
_loc1.addProperty("itemData", _loc1.__get__itemData, _loc1.__set__itemData);
_loc1.addProperty("hideDesc", _loc1.__get__hideDesc, _loc1.__set__hideDesc);
_loc1.addProperty("destroyButton", _loc1.__get__destroyButton, _loc1.__set__destroyButton);
ASSetPropFlags(_loc1, null, 1);
(_global.dofus.graphics.gapi.controls.ItemViewer = function ()
{
super();
}).CLASS_NAME = "ItemViewer";
_loc1._nDisplayWidth = 316;
_loc1._bUseButton = false;
_loc1._bDestroyButton = false;
_loc1._bTargetButton = false;
_loc1._sCurrentTab = "Effects";
} // end if
#endinitclip
|
/**
* Created by Administrator on 2015/7/24 0024.
*/
package universal.pattern.event
{
public class GameEventConst
{
/**移动拖拽物*/
public static const MOVE_DRAG_ITEM:String = "move_drag_item";
public static const DOWN_ITEM:String = "down_item";
/*
* {type:String} 1:xyz 2:xy 3:xy 4:yz
* */
public static const DRAG_SELECT_ITEM:String = "drag_select_item";
/*
* {value:boolean} true显示 false隐藏
* */
public static const HIDE_SHOW_AUXILIARYLINE:String = "hide_show_auxiliaryline";
/*
* {item:ObjectContainer3D}
* */
public static const UPDATE_PROPERTY:String = "update_position";
/*
* {type:int} 1立方体 2 圆柱体 3圆锥体 4球体
* */
public static const CREATE_SHAPE:String = "create_shape";
/**
*{key:String,value:Number} key (x y z rotationX rotationY rotationZ scaleX scaleY scaleZ width heigth depth)
* */
public static const CHANGE_PROPERTY:String = "change_position";
/**
* {color:uint}
* */
public static const CHANGE_COLOR:String = "CHANGE_COLOR";
/**
* {width:Number,height:Number}舞台大小改变
* */
public static const STAGE_RESIZE:String = "STAGE_RESIZE";
/*
* {type:int} 1删除单个 2删除全部
* */
public static const DELETE_SHAPE:String = "DELETE_SHAPE";
/*
* {type:int} 1 X轴 2 Y轴 3 Z轴
* */
public static const ROTATION_ANIMATE:String="rotation_animate";
}
}
|
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.filters.GlowFilter;
import flash.geom.Point;
import flash.media.Sound;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.utils.getTimer; // function import
import com.threerings.flash.FrameSprite;
import com.whirled.EffectControl;
/**
* A simple effect that displays a flow gain.
*/
[SWF(width="100", height="200")]
public class FlowGain extends FrameSprite
{
public function FlowGain ()
{
_ctrl = new EffectControl(this);
var message :String = _ctrl.getParameters();
if (message == null) {
trace("No parameters from EffectControl, showing generic message.");
message = "+Flow!";
}
var format :TextFormat = new TextFormat();
format.size = 32;
format.font = "Arial";
format.italic = true;
format.color = 0x000000;
var tf :TextField = new TextField();
tf.defaultTextFormat = format;
tf.autoSize = TextFieldAutoSize.LEFT;
tf.text = message;
tf.width = tf.textWidth + 5;
tf.height = tf.textHeight + 4;
tf.filters = [ new GlowFilter(0xFFFFFF, 1, 2, 2, 255) ];
addChild(tf);
// start out centered
_hotSpot = new Point(tf.width / 2, tf.height / 2);
_ctrl.setHotSpot(_hotSpot.x, _hotSpot.y);
}
override protected function handleAdded (... ignored) :void
{
_stamp = getTimer();
super.handleAdded();
}
override protected function handleFrame (... ignored) :void
{
var elapsed :Number = getTimer() - _stamp;
_ctrl.setHotSpot(_hotSpot.x, _hotSpot.y + (Y_VEL * elapsed));
if (elapsed > 1000) {
if (elapsed > 2000) {
_ctrl.effectFinished();
} else {
this.alpha = (2000 - elapsed) / 1000;
}
}
}
protected var _ctrl :EffectControl;
protected var _stamp :Number;
protected var _hotSpot :Point;
protected static const Y_VEL :Number = .02;
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// The contents of this file are subject to the Mozilla Public License
// Version 1.1 (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
// http://www.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS"
// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
// License for the specific language governing rights and limitations
// under the License.
//
// The Original Code is from the Open Source Flex 3 SDK.
//
// The Initial Developer of the Original Code is Adobe Systems, Inc.
//
// Portions created by Josh Tynjala (joshtynjala.com) are
// Copyright (c) 2007-2010 Josh Tynjala. All Rights Reserved.
//
////////////////////////////////////////////////////////////////////////////////
package com.flextoolbox.skins.halo
{
import flash.display.GradientType;
import mx.core.EdgeMetrics;
import mx.skins.Border;
import mx.skins.halo.*;
import mx.styles.StyleManager;
import mx.utils.ColorUtil;
/**
* The skin for all the states of an TreeMapBranchHeader in a TreeMap.
*
* @see com.flextoolbox.controls.TreeMap
* @author Josh Tynjala; Based on code by Adobe Systems Incorporated
*/
public class TreeMapBranchHeaderSkin extends Border
{
//----------------------------------
// Class Variables
//----------------------------------
/**
* @private
*/
private static var cache:Object = {};
//----------------------------------
// Class Methods
//----------------------------------
/**
* @private
* Several colors used for drawing are calculated from the base colors
* of the component (themeColor, borderColor and fillColors).
* Since these calculations can be a bit expensive,
* we calculate once per color set and cache the results.
*/
private static function calcDerivedStyles(themeColor:uint, borderColor:uint,
falseFillColor0:uint, falseFillColor1:uint, fillColor0:uint, fillColor1:uint):Object
{
var key:String = HaloColors.getCacheKey(themeColor, borderColor,
falseFillColor0, falseFillColor1, fillColor0, fillColor1);
if(!cache[key])
{
var o:Object = cache[key] = {};
// Cross-component styles.
HaloColors.addHaloColors(o, themeColor, fillColor0, fillColor1);
}
return cache[key];
}
//----------------------------------
// Constructor
//----------------------------------
/**
* Constructor.
*/
public function TreeMapBranchHeaderSkin()
{
super();
}
//----------------------------------
// Variables and Properties
//----------------------------------
/**
* @private
* Storage for the borderMetrics property.
*/
private var _borderMetrics:EdgeMetrics = new EdgeMetrics(1, 1, 1, 1);
/**
* @private
*/
override public function get borderMetrics():EdgeMetrics
{
return _borderMetrics;
}
/**
* @private
*/
override public function get measuredWidth():Number
{
return 10;
}
/**
* @private
*/
override public function get measuredHeight():Number
{
return 22;
}
//----------------------------------
// Protected Methods
//----------------------------------
/**
* @private
*/
override protected function updateDisplayList(w:Number, h:Number):void
{
super.updateDisplayList(w, h);
// User-defined styles.
var borderColor:uint = getStyle("borderColor");
var fillAlphas:Array = getStyle("fillAlphas");
var fillColors:Array = getStyle("fillColors");
StyleManager.getColorNames(fillColors);
var highlightAlphas:Array = getStyle("highlightAlphas");
var selectedFillColors:Array = getStyle("selectedFillColors");
var themeColor:uint = getStyle("themeColor");
// Placehold styles stub.
var falseFillColors:Array /* of Color */ = []; // added style prop
falseFillColors[0] = ColorUtil.adjustBrightness2(fillColors[0], -8);
falseFillColors[1] = ColorUtil.adjustBrightness2(fillColors[1], -10);
var borderColorDrk1:Number = ColorUtil.adjustBrightness2(borderColor, -15);
var overFillColor1:Number = ColorUtil.adjustBrightness2(fillColors[0], -4);
var overFillColor2:Number = ColorUtil.adjustBrightness2(fillColors[1], -6);
if(!selectedFillColors)
{
selectedFillColors = []; // So we don't clobber the original...
selectedFillColors[0] = ColorUtil.adjustBrightness2(themeColor, 75);
selectedFillColors[1] = ColorUtil.adjustBrightness2(themeColor, 40);
}
// Derivative styles.
var derStyles:Object = calcDerivedStyles(themeColor, borderColor,
falseFillColors[0],
falseFillColors[1],
fillColors[0], fillColors[1]);
this.graphics.clear();
switch(name)
{
case "upSkin":
case "disabledSkin":
case "selectedDisabledSkin":
{
var upFillColors:Array = [ falseFillColors[0], falseFillColors[1] ];
var upFillAlphas:Array = [ fillAlphas[0], fillAlphas[1] ];
// edge
this.drawRoundRect(0, 0, w, h, 0,
[ borderColor, borderColorDrk1 ], 1,
verticalGradientMatrix(0, 0, w, h),
GradientType.LINEAR, null,
{ x: 1, y: 1, w: w - 2, h: h - 2, r: 0 });
// fill
this.drawRoundRect(1, 1,w - 2, h - 2, 0,
upFillColors, upFillAlphas,
verticalGradientMatrix(1, 1, w - 2, h - 2));
// top highlight
this.drawRoundRect(1, 1, w - 2, (h - 2) / 2, 0,
[ 0xFFFFFF, 0xFFFFFF ], highlightAlphas,
verticalGradientMatrix(1, 1, w - 2, (h - 2) / 2));
// bottom edge bevel shadow
this.drawRoundRect(1, h - 2, w - 2, 1, 0, borderColor, 0.1);
break;
}
case "overSkin":
{
var overFillColors:Array;
if(fillColors.length > 2)
{
overFillColors =
[
ColorUtil.adjustBrightness2(fillColors[2], -4),
ColorUtil.adjustBrightness2(fillColors[3], -6)
];
}
else
{
overFillColors = [ overFillColor1, overFillColor2 ];
}
var overFillAlphas:Array;
if(fillAlphas.length > 2)
{
overFillAlphas = [ fillAlphas[2], fillAlphas[3] ];
}
else
{
overFillAlphas = [ fillAlphas[0], fillAlphas[1] ];
}
// edge
this.drawRoundRect(0, 0, w, h, 0,
[ themeColor, derStyles.themeColDrk1 ], 1,
verticalGradientMatrix(0, 0, w, h),
GradientType.LINEAR, null,
{ x: 1, y: 1, w: w - 2, h: h - 2, r: 0 });
// fill
this.drawRoundRect(1, 1, w - 2, h - 2, 0,
overFillColors, overFillAlphas,
verticalGradientMatrix(1, 1, w - 2, h - 2));
// top highlight
this.drawRoundRect(1, 1, w - 2, (h - 2) / 2, 0,
[ 0xFFFFFF, 0xFFFFFF ], highlightAlphas,
verticalGradientMatrix(1, 1, w - 2, (h - 2) / 2));
// bottom edge bevel shadow
this.drawRoundRect(1, h - 2, w - 2, 1, 0, borderColor, 0.1);
break;
}
case "downSkin":
case "selectedDownSkin":
{
// edge
this.drawRoundRect(0, 0, w, h, 0,
[ themeColor, derStyles.themeColDrk1 ], 1,
verticalGradientMatrix(0, 0, w, h));
// fill
this.drawRoundRect(1, 1, w - 2, h - 2, 0,
[ derStyles.fillColorPress1, derStyles.fillColorPress2 ], 1,
verticalGradientMatrix(1, 1, w - 2, h - 2));
// top highlight
this.drawRoundRect(1, 1, w - 2, (h - 2) / 2, 0,
[ 0xFFFFFF, 0xFFFFFF ], highlightAlphas,
verticalGradientMatrix(1, 1, w - 2, (h - 2) / 2));
break;
}
case "selectedOverSkin":
{
var selectedFillAlphas:Array = [ fillAlphas[0], fillAlphas[1] ];
// edge
this.drawRoundRect(0, 0, w, h, 0,
[ themeColor, derStyles.themeColDrk1 ], 1,
verticalGradientMatrix(0, 0, w, h),
GradientType.LINEAR, null,
{ x: 1, y: 1, w: w - 2, h: h - 2, r: 0 })
// fill
this.drawRoundRect(1, 1, w - 2, h - 2, 0,
[ selectedFillColors[0],
selectedFillColors[1] ], selectedFillAlphas,
verticalGradientMatrix(1, 1, w - 2, h - 2));
// top highlight
this.drawRoundRect(1, 1, w - 2, (h - 2) / 2, 0,
[ 0xFFFFFF, 0xFFFFFF ], highlightAlphas,
verticalGradientMatrix(1, 1, w - 2, (h - 2) / 2));
// bottom edge highlight
this.drawRoundRect(1, h - 2, w - 2, 1, 0, borderColor, 0.05);
break;
}
case "selectedUpSkin":
{
selectedFillAlphas = [ fillAlphas[0], fillAlphas[1] ];
// edge
this.drawRoundRect(0, 0, w, h, 0,
[ borderColor, borderColorDrk1 ], 1,
verticalGradientMatrix(0, 0, w, h),
GradientType.LINEAR, null,
{ x: 1, y: 1, w: w - 2, h: h - 2, r: 0 })
// fill
this.drawRoundRect(1, 1, w - 2, h - 2, 0,
[ selectedFillColors[0],
selectedFillColors[1] ], selectedFillAlphas,
verticalGradientMatrix(1, 1, w - 2, h - 2));
// top highlight
this.drawRoundRect(1, 1, w - 2, (h - 2) / 2, 0,
[ 0xFFFFFF, 0xFFFFFF ], highlightAlphas,
verticalGradientMatrix(1, 1, w - 2, (h - 2) / 2));
// bottom edge highlight
this.drawRoundRect(1, h - 2, w - 2, 1, 0, borderColor, 0.05);
break;
}
}
}
}
}
|
void main() {
print("a" + "b");
}
|
package ageb.modules.scene.op
{
import flash.utils.Dictionary;
import ageb.modules.ae.ISelectableInfo;
import ageb.modules.ae.ObjectInfoEditable;
import ageb.modules.document.Document;
public class ChangeObjectProperties extends SceneOPBase
{
private var oldPropsList:Dictionary;
private var props:Object;
private var selectedObjects:Vector.<ISelectableInfo>;
public function ChangeObjectProperties(doc:Document, selectedObjects:Vector.<ISelectableInfo>, props:Object)
{
super(doc);
this.selectedObjects = selectedObjects;
this.props = props;
}
override public function redo():void
{
for each (var o:ISelectableInfo in selectedObjects)
{
for (var key:String in props)
{
o[key] = props[key];
}
ObjectInfoEditable(o).onPropertiesChange.dispatch(this);
}
}
override protected function saveOld():void
{
oldPropsList = new Dictionary();
for each (var o:ISelectableInfo in selectedObjects)
{
var oldProp:Object = {};
oldPropsList[o] = oldProp;
for (var key:String in props)
{
oldProp[key] = o[key];
}
}
}
override public function undo():void
{
for each (var o:ISelectableInfo in selectedObjects)
{
var oldProps:Object = oldPropsList[o];
for (var key:String in oldProps)
{
o[key] = oldProps[key];
}
ObjectInfoEditable(o).onPropertiesChange.dispatch(this);
}
}
override public function get name():String
{
return "修改属性";
}
}
}
|
/*
* 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.flexunit.runners.model {
import flex.lang.reflect.Method;
import flex.lang.reflect.metadata.MetaDataAnnotation;
import flex.lang.reflect.metadata.MetaDataArgument;
import org.flexunit.constants.AnnotationArgumentConstants;
import org.flexunit.constants.AnnotationConstants;
import org.flexunit.token.AsyncTestToken;
/**
* Used to expand on the number of methods in a class in the presence of a TestNG style
* Parameterized runner where a Test is provided a dataProvider. One of these classes is
* constructed for each dataset
*
* @author mlabriola
*
*/
public class ParameterizedMethod extends FrameworkMethod {
/**
* @private
*/
private var _arguments:Array;
/**
* Arguments to be passed to the test
* @return an array of arguments to be applied
*
*/
public function get arguments():Array {
return _arguments;
}
/**
*
* @inheritDoc
*
*/
override public function get name():String {
var paramName:String = _arguments.join ( "," );
return method.name + ' (' + paramName + ')';
}
/**
*
* @inheritDoc
*
*/
override public function invokeExplosively( target:Object, ...params ):Object {
applyExplosively( target, arguments );
return null;
}
/**
* Produces a new method with modified order metadata to ensure a consistent order of
* execution as compared to the data set order
*
* @param method the existing method which needs expansion
* @param methodIndex Current Index into the data set of this ParameterizedMethod
* @param totalMethods total number of methods needed by the data set
* @return a new Method
*
*/
protected function methodWithGuaranteedOrderMetaData( method : Method, methodIndex : int, totalMethods : int ) : Method {
var newMethod:Method = method.clone();
// CJP: If the method doesn't contain a "TEST" metadata tag, we probably shouldn't be in here anyway... throw Error?
var annotation:MetaDataAnnotation = newMethod.getMetaData( AnnotationConstants.TEST );
var arg:MetaDataArgument;
var arguments:Array;
var orderValueDec : Number = ( methodIndex + 1) / ( Math.pow( 10, totalMethods ) );
if ( annotation ) {
arg = annotation.getArgument( AnnotationArgumentConstants.ORDER, true );
var orderArg:XML = <arg key="order" value="0"/>;
if ( arg ) {
orderArg.@value = orderValueDec + Number( arg.value );
arguments = annotation.arguments;
for ( var i:int=0; i<arguments.length; i++ ) {
if ( arguments[ i ] === arg ) {
//replace the argument with a new one with better ordering
arguments.splice( i, 1, new MetaDataArgument( orderArg ) );
break;
}
}
} else {
orderArg.@value = orderValueDec;
annotation.arguments.push( new MetaDataArgument( orderArg ) );
}
}
/* if ( annotation.getArgument( AnnotationArgumentConstants.ORDER, true ).value == "0" ) {
trace( "New Order " + annotation.getArgument( AnnotationArgumentConstants.ORDER ).value );
}
*/
return newMethod;
}
/**
*
* Constructor
*
*/
public function ParameterizedMethod(method:Method, arguments:Array, methodIndex:uint, totalMethods:uint ) {
var newMethod : Method = methodWithGuaranteedOrderMetaData( method, methodIndex, totalMethods );
super( newMethod );
_arguments = arguments;
}
/**
*
* Indicates that this is a ParameterizedMethod
*
*/
override public function toString():String {
return "ParameterizedMethod " + this.name;
}
}
} |
package com.bojinx.utils
{
public class ObjectPool
{
/*============================================================================*/
/*= PUBLIC PROPERTIES */
/*============================================================================*/
public var clean:Function;
public var create:Function;
public var length:int = 0;
public var minSize:int;
public var size:int = 0;
/*============================================================================*/
/*= PRIVATE PROPERTIES */
/*============================================================================*/
private var disposed:Boolean = false;
private var list:Array = [];
public function ObjectPool( create:Function, clean:Function = null, minSize:int = 0 )
{
this.create = create;
this.clean = clean;
this.minSize = minSize;
for ( var i:int = 0; i < minSize; i++ )
add();
}
/*============================================================================*/
/*= PUBLIC METHODS */
/*============================================================================*/
public function add():void
{
list[ length++ ] = create();
size++;
}
public function checkIn( item:* ):void
{
if ( clean != null )
clean( item );
list[ length++ ] = item;
}
public function checkOut():*
{
if ( length == 0 )
{
size++;
return create();
}
return list[ --length ];
}
public function dispose():void
{
if ( disposed )
return;
disposed = true;
create = null;
clean = null;
list = null;
}
}
}
|
package it.pixeldump.mk.tags {
import flash.utils.*;
import flash.net.*;
import flash.events.*;
import flash.geom.*;
import it.pixeldump.mk.*;
import it.pixeldump.mk.struct.*;
public class PlaceObject extends Tag {
public function get CLASS_NAME():String { return "PlaceObject"; }
public function get CLASS_ID():uint { return Constants.tagList["PlaceObject"]; }
public var depth:uint = 1; // UI16 Depth of character
// public var matrix:Matrix; // MATRIX Transform matrix data
// public var colorTransform:ColorTransform; // ColorTransform (optional) CXFORM Color transform data
function PlaceObject(){
}
//
public override function toByteArray():ByteArray{
var ba:ByteArray = new ByteArray();
ba.endian = Endian.LITTLE_ENDIAN;
/* TODO */
return ba;
}
public override function fromByteArray(ba:ByteArray):void{
ba.position = 0;
super.fromByteArray(ba);
var offset:uint = tagSL ? 6 : 2;
ba.position = offset;
itemID = ba.readUnsignedShort();
depth = ba.readUnsignedShort();
offset += 4;
/* TODO */
}
public override function fetch_xml(tabLevel:uint = 0, includeHeader:Boolean = false):String{
var xmlStr:String = includeHeader ? Constants.XML_HEADER : "" ;
var pfx:String = SwfUtils.get_xml_indent_row(++tabLevel);
xmlStr += pfx +"<" +CLASS_NAME;
xmlStr += " itemID=\"" +itemID +"\" ";
xmlStr += " depth=\"" +depth +"\" ";
xmlStr += " tagLength=\"" +tagLength +"\" />";
return xmlStr;
}
}
}
|
package
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.display.DisplayObjectContainer;
import Objects.*;
public class AnimationManager extends Sprite
{
// Holder for all animated objects.
// All animation is done by manipulating objects in\
// this container
private var animatedObjects : ObjectManager;
// Control variables for stopping / starting animation
private var animationPaused : Boolean;
private var doNextStep : Boolean;
private var awaitingStep : Boolean;
private var currentlyAnimating:Boolean;
// Array holding the code for the animation. This is
// an array of strings, each of which is an animation command
// currentAnimation is an index into this array
private var AnimationSteps:Array;
private var currentAnimation:int;
private var previousAnimationSteps:Array;
// Control variables for where we are in the current animation block.
// currFrame holds the frame number of the current animation block,
// while animationBlockLength holds the length of the current animation
// block (in frame numbers).
private var currFrame:Number;
private var animationBlockLength:Number;
// The animation block that is currently running. Array of singleAnimations
private var currentBlock:Array;
/////////////////////////////////////
// Variables for handling undo.
//////////////////////////////////// already implemented animations.
// A stack of UndoBlock objects (subclassed, UndoBlock is an abstract base class)
// each of which can undo a single animation element
private var undoStack:Array;
private var doingUndo:Boolean = false;
// A stack containing the beginning of each animation block, as an index
// into the AnimationSteps array
private var undoAnimationStepIndices:Array;
private var undoAnimationStepIndicesStack:Array;
/////////////////////////////////////////////////////
// Public Methods
/////////////////////////////////////////////////////
function AnimationManager():void
{
animatedObjects = new ObjectManager();
addChild(animatedObjects);
currentBlock = null;
currentlyAnimating = false;
animationPaused = true;
animationBlockLength = 60;
currFrame = 0;
awaitingStep = false;
undoStack = new Array();
undoAnimationStepIndices = null;
previousAnimationSteps = new Array();
AnimationSteps = null;
undoAnimationStepIndicesStack = new Array();
}
// Pause / unpause animation
public function SetPaused(pausedValue)
{
animationPaused = pausedValue;
if (!animationPaused)
{
step();
}
}
// Set the speed of the animation, from 0 (slow) to 100 (fast)
public function SetSpeed(newSpeed)
{
animationBlockLength = 100-newSpeed + 1;
}
// Start a new animation. The input parameter commands is an array of strings,
// which represents the animation
public function StartNewAnimation(commands)
{
if (AnimationSteps != null)
{
previousAnimationSteps.push(AnimationSteps);
undoAnimationStepIndicesStack.push(undoAnimationStepIndices);
}
if (commands.length != 0)
{
AnimationSteps = commands;
}
else
{
AnimationSteps = ["Step"];
}
undoAnimationStepIndices = new Array();
currentAnimation = 0;
startNextBlock();
currentlyAnimating = true;
dispatchEvent(new AnimationStateEvent(AnimationStateEvent.AnimationStarted));
}
// Step backwards one step. A no-op if the animation is not currently paused
public function stepBack()
{
if (awaitingStep && undoStack != null && undoStack.length != 0)
{
dispatchEvent(new AnimationStateEvent(AnimationStateEvent.AnimationStarted));
awaitingStep = false;
undoLastBlock();
}
else if (!currentlyAnimating && animationPaused && undoAnimationStepIndices != null)
{
dispatchEvent(new AnimationStateEvent(AnimationStateEvent.AnimationStarted));
currentlyAnimating = true;
undoLastBlock();
}
}
// Step forwards one step. A no-op if the animation is not currently paused
public function step()
{
if (awaitingStep)
{
startNextBlock();
dispatchEvent(new AnimationStateEvent(AnimationStateEvent.AnimationStarted));
currentlyAnimating = true;
}
}
// Implement one step of the animation. Must be called on each frame.
public function oneIteration():void
{
if (currentlyAnimating)
{
currFrame = currFrame + 1;
var i:int;
for (i = 0; i < currentBlock.length; i++)
{
if (currFrame >= animationBlockLength)
{
animatedObjects.setNodePosition(currentBlock[i].objectID,
currentBlock[i].toX,
currentBlock[i].toY);
}
else
{
var objectID:int = currentBlock[i].objectID;
var percent:Number = 1 / (animationBlockLength - currFrame);
var oldX:Number = animatedObjects.nodeX(objectID);
var oldY:Number = animatedObjects.nodeY(objectID);
var targetX: Number = currentBlock[i].toX;
var targety: Number = currentBlock[i].toY;
var newX:Number = lerp(animatedObjects.nodeX(objectID), currentBlock[i].toX, percent);
var newY:Number = lerp(animatedObjects.nodeY(objectID), currentBlock[i].toY, percent);
animatedObjects.setNodePosition(objectID,
newX,
newY);
}
}
if (currFrame >= animationBlockLength)
{
if (doingUndo)
{
if (finishUndoBlock(undoStack.pop()))
{
awaitingStep = true;
dispatchEvent(new AnimationStateEvent(AnimationStateEvent.AnimationWaiting));
}
}
else
{
if (animationPaused && (currentAnimation < AnimationSteps.length))
{
awaitingStep = true;
dispatchEvent(new AnimationStateEvent(AnimationStateEvent.AnimationWaiting));
currentBlock = new Array();
}
else
{
startNextBlock();
}
}
}
}
animatedObjects.update();
}
/// WARNING: Could be dangerous to call while an animation is running ...
public function clearHistory():void
{
undoStack = new Array();
undoAnimationStepIndices = null;
previousAnimationSteps = new Array();
undoAnimationStepIndicesStack = new Array();
AnimationSteps = null;
dispatchEvent(new AnimationStateEvent(AnimationStateEvent.AnimationUndoUnavailable));
}
public function skipBack()
{
var keepUndoing:Boolean = undoAnimationStepIndices != null && undoAnimationStepIndices.length != 0;
if (keepUndoing)
{
for (var i:int = 0; currentBlock != null && i < currentBlock.length; i++)
{
var objectID:int = currentBlock[i].objectID;
animatedObjects.setNodePosition(objectID,
currentBlock[i].toX,
currentBlock[i].toY);
}
if (doingUndo)
{
finishUndoBlock(undoStack.pop())
}
while (keepUndoing)
{
undoLastBlock();
for (i = 0; i < currentBlock.length; i++)
{
objectID = currentBlock[i].objectID;
animatedObjects.setNodePosition(objectID,
currentBlock[i].toX,
currentBlock[i].toY);
}
keepUndoing = finishUndoBlock(undoStack.pop());
}
animatedObjects.update();
if (undoStack == null || undoStack.length == 0)
{
dispatchEvent(new AnimationStateEvent(AnimationStateEvent.AnimationUndoUnavailable));
}
}
}
public function resetAll()
{
clearHistory();
animatedObjects.clearAllObjects();
}
public function skipForward()
{
if (currentlyAnimating)
{
animatedObjects.runFast = true;
while (AnimationSteps != null && currentAnimation < AnimationSteps.length)
{
for (var i:int = 0; currentBlock != null && i < currentBlock.length; i++)
{
var objectID:int = currentBlock[i].objectID;
animatedObjects.setNodePosition(objectID,
currentBlock[i].toX,
currentBlock[i].toY);
}
if (doingUndo)
{
finishUndoBlock(undoStack.pop())
}
startNextBlock();
for (i= 0; i < currentBlock.length; i++)
{
objectID = currentBlock[i].objectID;
animatedObjects.setNodePosition(objectID,
currentBlock[i].toX,
currentBlock[i].toY);
}
}
animatedObjects.update();
currentlyAnimating = false;
awaitingStep = false;
doingUndo = false;
animatedObjects.runFast = false;
dispatchEvent(new AnimationStateEvent(AnimationStateEvent.AnimationEnded));
}
}
private function finishUndoBlock(undoBlock) : Boolean
{
for (var i:int = undoBlock.length - 1; i >= 0; i--)
{
undoBlock[i].undoInitialStep(animatedObjects);
}
doingUndo = false;
// If we are at the final end of the animation ...
if (undoAnimationStepIndices.length == 0)
{
awaitingStep = false;
currentlyAnimating = false;
undoAnimationStepIndices = undoAnimationStepIndicesStack.pop();
AnimationSteps = previousAnimationSteps.pop();
dispatchEvent(new AnimationStateEvent(AnimationStateEvent.AnimationEnded));
dispatchEvent(new AnimationStateEvent(AnimationStateEvent.AnimationUndo));
currentBlock = new Array();
if (undoStack == null || undoStack.length == 0)
{
currentlyAnimating = false;
awaitingStep = false;
dispatchEvent(new AnimationStateEvent(AnimationStateEvent.AnimationUndoUnavailable));
}
return false;
}
return true;
}
private function undoLastBlock()
{
if (undoAnimationStepIndices.length == 0)
{
// Nothing on the undo stack. Return
return;
}
if (undoAnimationStepIndices.length > 0)
{
doingUndo = true;
var anyAnimations:Boolean = false;
currentAnimation = undoAnimationStepIndices.pop();
currentBlock= new Array();
var undo : Array = undoStack[undoStack.length - 1];
var i:int;
for (i = undo.length - 1; i >= 0; i--)
{
var animateNext : Boolean = undo[i].addUndoAnimation(currentBlock);
anyAnimations = anyAnimations || animateNext;
}
currFrame = 0;
// Hack: If there are not any animations, and we are currently paused,
// then set the current frame to the end of the animation, so that we will
// advance immediagely upon the next step button. If we are not paused, then
// animate as normal.
if (!anyAnimations && animationPaused )
{
currFrame = animationBlockLength;
}
currentlyAnimating = true;
}
}
private function parseBool(str):Boolean
{
var uppercase:String = str.toUpperCase();
var returnVal:Boolean = ! (uppercase == "False" || uppercase == "f" || uppercase == " 0" || uppercase == "0");
return returnVal;
}
public function setLayer(shown, ...args)
{
animatedObjects.setLayer(shown, args)
}
public function setAllLayers(...args)
{
animatedObjects.setAllLayers(args);
}
private function startNextBlock()
{
awaitingStep = false;
currentBlock = new Array();
var undoBlock : Array = new Array();
if (currentAnimation == AnimationSteps.length )
{
currentlyAnimating = false;
awaitingStep = false;
dispatchEvent(new AnimationStateEvent(AnimationStateEvent.AnimationEnded));
return;
}
undoAnimationStepIndices.push(currentAnimation);
var foundBreak:Boolean = false;
var anyAnimations:Boolean = false;
while (currentAnimation < AnimationSteps.length && !foundBreak)
{
var nextCommand:Array = AnimationSteps[currentAnimation].split(";");
if (nextCommand[0].toUpperCase() == "CREATECIRCLE")
{
animatedObjects.addCircleObject(int(nextCommand[1]), nextCommand[2]);
if (nextCommand.length > 4)
{
animatedObjects.setNodePosition(int(nextCommand[1]), int(nextCommand[3]), int(nextCommand[4]));
undoBlock.push(new UndoCreate(int(nextCommand[1])));
}
}
else if (nextCommand[0].toUpperCase() == "CREATELINKEDLIST")
{
if (nextCommand.length == 11)
{
animatedObjects.addLinkedListObject(int(nextCommand[1]), nextCommand[2], int(nextCommand[3]), int(nextCommand[4]), Number(nextCommand[7]), parseBool(nextCommand[8]), parseBool(nextCommand[9]),int(nextCommand[10]));
}
else
{
animatedObjects.addLinkedListObject(int(nextCommand[1]), nextCommand[2], int(nextCommand[3]), int(nextCommand[4]));
}
if (nextCommand.length > 6)
{
animatedObjects.setNodePosition(int(nextCommand[1]), int(nextCommand[5]), int(nextCommand[6]));
undoBlock.push(new UndoCreate(int(nextCommand[1])));
}
}
else if (nextCommand[0].toUpperCase() == "CREATEBTREENODE")
{
animatedObjects.addBTreeNode(int(nextCommand[1]), Number(nextCommand[2]), Number(nextCommand[3]), int(nextCommand[4]), uint(nextCommand[7]), uint(nextCommand[8]));
animatedObjects.setNodePosition(int(nextCommand[1]), int(nextCommand[5]), int(nextCommand[6]));
undoBlock.push(new UndoCreate(int(nextCommand[1])));
}
else if (nextCommand[0].toUpperCase() == "CREATERECTANGLE")
{
if (nextCommand.length == 9)
{
animatedObjects.addRectangleObject(int(nextCommand[1]), nextCommand[2], int(nextCommand[3]), int(nextCommand[4]), nextCommand[7], nextCommand[8]);
}
else
{
animatedObjects.addRectangleObject(int(nextCommand[1]), nextCommand[2], int(nextCommand[3]), int(nextCommand[4]));
}
if (nextCommand.length > 6)
{
animatedObjects.setNodePosition(int(nextCommand[1]), int(nextCommand[5]), int(nextCommand[6]));
undoBlock.push(new UndoCreate(int(nextCommand[1])));
}
}
else if (nextCommand[0].toUpperCase() == "CREATEHIGHLIGHTCIRCLE")
{
if (nextCommand.length > 5)
{
animatedObjects.addHighlightCircleObject(int(nextCommand[1]), int(nextCommand[2]), Number(nextCommand[5]));
}
else
{
animatedObjects.addHighlightCircleObject(int(nextCommand[1]), int(nextCommand[2]));
}
if (nextCommand.length > 4)
{
animatedObjects.setNodePosition(int(nextCommand[1]), int(nextCommand[3]), int(nextCommand[4]));
}
undoBlock.push(new UndoCreate(int(nextCommand[1])));
}
else if (nextCommand[0].toUpperCase() == "CREATELABEL")
{
if (nextCommand.length == 6)
{
animatedObjects.addLabelObject(int(nextCommand[1]), nextCommand[2], parseBool(nextCommand[5]));
}
else
{
animatedObjects.addLabelObject(int(nextCommand[1]), nextCommand[2]);
}
if (nextCommand.length >= 5)
{
animatedObjects.setNodePosition(int(nextCommand[1]), int(nextCommand[3]), int(nextCommand[4]));
}
undoBlock.push(new UndoCreate(int(nextCommand[1])));
}
else if (nextCommand[0].toUpperCase() == "DELETE")
{
var objectID : int = int(nextCommand[1]);
var i : int;
var removedEdges = animatedObjects.deleteIncident(objectID);
if (removedEdges.length > 0)
{
undoBlock = undoBlock.concat(removedEdges);
}
var obj:AnimatedObject = animatedObjects.getObject(objectID);
if (obj)
{
undoBlock.push(obj.createUndoDelete());
animatedObjects.removeObject(objectID);
}
}
else if (nextCommand[0].toUpperCase() == "MOVE")
{
var nextAnim:SingleAnimation = new SingleAnimation();
nextAnim.objectID = int(nextCommand[1]);
nextAnim.fromX = animatedObjects.nodeX(nextAnim.objectID);
nextAnim.fromY = animatedObjects.nodeY(nextAnim.objectID);
nextAnim.toX = int(nextCommand[2]);
nextAnim.toY = int(nextCommand[3]);
currentBlock.push(nextAnim);
undoBlock.push(new UndoMove(nextAnim.objectID, nextAnim.toX, nextAnim.toY, nextAnim.fromX, nextAnim.fromY));
anyAnimations = true;
}
else if (nextCommand[0].toUpperCase() == "CONNECT")
{
if (nextCommand.length > 7)
{
animatedObjects.connectEdge(int(nextCommand[1]), int(nextCommand[2]), int(nextCommand[3]), Number(nextCommand[4]), parseBool(nextCommand[5]), nextCommand[6], int(nextCommand[7]));
}
else if (nextCommand.length > 6)
{
animatedObjects.connectEdge(int(nextCommand[1]), int(nextCommand[2]), int(nextCommand[3]), Number(nextCommand[4]), parseBool(nextCommand[5]), nextCommand[6]);
}
else if (nextCommand.length > 5)
{
animatedObjects.connectEdge(int(nextCommand[1]), int(nextCommand[2]), int(nextCommand[3]), Number(nextCommand[4]), parseBool(nextCommand[5]));
}
else if (nextCommand.length > 4)
{
animatedObjects.connectEdge(int(nextCommand[1]), int (nextCommand[2]), int(nextCommand[3]), Number(nextCommand[4]));
}
else if (nextCommand.length > 3)
{
animatedObjects.connectEdge(int(nextCommand[1]), int (nextCommand[2]), int(nextCommand[3]));
}
else
{
animatedObjects.connectEdge(int(nextCommand[1]), int (nextCommand[2]));
}
undoBlock.push(new UndoConnect(int(nextCommand[1]), int (nextCommand[2]), false));
}
else if (nextCommand[0].toUpperCase() == "SETFOREGROUNDCOLOR")
{
var id:int = int(nextCommand[1]);
var oldColor = animatedObjects.foregroundColor(id);
animatedObjects.setForegroundColor(id, int (nextCommand[2]));
undoBlock.push(new UndoSetForegroundColor(id, oldColor));
}
else if (nextCommand[0].toUpperCase() == "SETBACKGROUNDCOLOR")
{
id = int(nextCommand[1]);
oldColor = animatedObjects.backgroundColor(id);
animatedObjects.setBackgroundColor(id, int (nextCommand[2]));
undoBlock.push(new UndoSetBackgroundColor(id, oldColor));
}
else if (nextCommand[0].toUpperCase() == "SETHEIGHT")
{
id = int(nextCommand[1]);
animatedObjects.setHeight(id, int (nextCommand[2]));
var oldHeight = animatedObjects.getHeight(id);
undoBlock.push(new UndoSetHeight(id, oldHeight));
}
else if (nextCommand[0].toUpperCase() == "SETWIDTH")
{
id = int(nextCommand[1]);
animatedObjects.setWidth(id, int (nextCommand[2]));
var oldWidth = animatedObjects.getWidth(id);
undoBlock.push(new UndoSetHeight(id, oldWidth));
}
else if (nextCommand[0].toUpperCase() == "DISCONNECT")
{
var undoConnect = animatedObjects.disconnect(int(nextCommand[1]), int (nextCommand[2]));
if (undoConnect != null)
{
undoBlock.push(undoConnect);
}
}
else if (nextCommand[0].toUpperCase() == "SETTEXT")
{
if (nextCommand.length > 2)
{
var oldText:String = animatedObjects.getText(int(nextCommand[1]), int(nextCommand[3]));
animatedObjects.setText(int(nextCommand[1]), nextCommand[2], int(nextCommand[3]));
undoBlock.push(new UndoSetText(int(nextCommand[1]), oldText, int(nextCommand[3]) ));
}
else
{
oldText = animatedObjects.getText(int(nextCommand[1]), 0);
animatedObjects.setText(int(nextCommand[1]), nextCommand[2], 0);
undoBlock.push(new UndoSetText(int(nextCommand[1]), oldText, 0));
}
}
else if (nextCommand[0].toUpperCase() == "SETTEXTCOLOR")
{
if (nextCommand.length > 3)
{
oldColor = animatedObjects.getTextColor(int(nextCommand[1]), int(nextCommand[3]));
animatedObjects.setTextColor(int(nextCommand[1]), uint(nextCommand[2]), int(nextCommand[3]));
undoBlock.push(new UndoSetTextColor(int(nextCommand[1]), oldColor, int(nextCommand[3]) ));
}
else
{
oldColor = animatedObjects.getTextColor(int(nextCommand[1]), 0);
animatedObjects.setTextColor(int(nextCommand[1]),uint(nextCommand[2]), 0);
undoBlock.push(new UndoSetTextColor(int(nextCommand[1]), oldColor, 0));
}
}
else if (nextCommand[0].toUpperCase() == "SETALPHA")
{
var oldAlpha:Number = animatedObjects.getAlpha(int(nextCommand[1]));
animatedObjects.setAlpha(int(nextCommand[1]), Number(nextCommand[2]));
undoBlock.push(new UndoSetAlpha(int(nextCommand[1]), oldAlpha));
}
else if (nextCommand[0].toUpperCase() == "STEP")
{
foundBreak = true;
}
else if (nextCommand[0].toUpperCase() == "SETHIGHLIGHT")
{
var newHighlight:Boolean = parseBool(nextCommand[2]);
animatedObjects.setHighlight( int(nextCommand[1]), newHighlight);
undoBlock.push(new UndoHighlight( int(nextCommand[1]), !newHighlight));
}
else if (nextCommand[0].toUpperCase() == "SETEDGEHIGHLIGHT")
{
newHighlight = parseBool(nextCommand[3]);
var oldHighlight = animatedObjects.setEdgeHighlight( int(nextCommand[1]), int(nextCommand[2]), newHighlight);
undoBlock.push(new UndoHighlightEdge(int(nextCommand[1]), int(nextCommand[2]), oldHighlight));
}
else if (nextCommand[0].toUpperCase() == "SETEDGECOLOR")
{
var newColor = uint(nextCommand[3]);
oldColor = animatedObjects.setEdgeColor( int(nextCommand[1]), int(nextCommand[2]), newColor);
// TODO: ADD UNDO INFORMATION HERE!!
}
else if (nextCommand[0].toUpperCase() == "SETLAYER")
{
animatedObjects.setLayer(int(nextCommand[1]), int(nextCommand[2]));
//TODO: Add undo information here
}
else if (nextCommand[0].toUpperCase() == "SETNUMELEMENTS")
{
var oldElem = animatedObjects.getObject(int(nextCommand[1]));
undoBlock.push(new UndoSetNumElements(oldElem, int(nextCommand[2])));
animatedObjects.setNumElements(int(nextCommand[1]), int(nextCommand[2]));
//TODO: Decreasing the number of elements doesn't save the old one yet ...
}
else if (nextCommand[0].toUpperCase() == "SETPOSITION")
{
var nodeID:int = int(nextCommand[1]);
var oldX:Number = animatedObjects.getNodeX(nodeID);
var oldY:Number = animatedObjects.getNodeY(nodeID);
undoBlock.push(new UndoSetPosition(nodeID, oldX, oldY));
animatedObjects.setNodePosition(nodeID, Number(nextCommand[2]), Number(nextCommand[3]));
//TODO: Decreasing the number of elements doesn't save the old one yet ...
}
else if (nextCommand[0].toUpperCase() == "SETNULL")
{
var oldNull:Boolean = animatedObjects.getNull(int(nextCommand[1]));
animatedObjects.setNull(int(nextCommand[1]), parseBool(nextCommand[2]));
undoBlock.push(new UndoSetNull(int(nextCommand[1]), oldNull));
}
else
{
throw new Error("Unknown command: " + nextCommand[0]);
}
currentAnimation = currentAnimation+1;
}
currFrame = 0;
// Hack: If there are not any animations, and we are currently paused,
// then set the current frame to the end of the anumation, so that we will
// advance immediagely upon the next step button. If we are not paused, then
// animate as normal.
if (!anyAnimations && animationPaused || (!anyAnimations && currentAnimation == AnimationSteps.length) )
{
currFrame = animationBlockLength;
}
undoStack.push(undoBlock);
}
public function lerp(from:Number, to:Number, percent:Number):Number
{
var delta:Number = to - from;
var deltaDiff:Number = delta*percent;
var returnVal:Number = from + deltaDiff;
var returnVal2:int = returnVal;
return returnVal;
// STOP CHANGING ME!
//var returnVal : int = (to - from) * percent + from;
//return returnVal;
// STOP CHANGING ME!
}
}
} |
// Decompiled by AS3 Sorcerer 3.16
// http://www.as3sorcerer.com/
//focusRectSkin
package
{
import flash.display.MovieClip;
public dynamic class focusRectSkin extends MovieClip
{
}
}//package
|
////////////////////////////////////////////////////////////////////////////////
//
// 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.royale.externsjs.inspiretree.beads
{
/**
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.9.8
*/
COMPILE::JS{
import org.apache.royale.core.IBead;
import org.apache.royale.core.IBeadModel;
import org.apache.royale.core.IStrand;
import org.apache.royale.core.Strand;
import org.apache.royale.events.IEventDispatcher;
import org.apache.royale.externsjs.inspiretree.beads.models.InspireTreeModel;
import org.apache.royale.core.StyledUIBase;
import org.apache.royale.utils.sendStrandEvent;
import org.apache.royale.events.ValueEvent;
import org.apache.royale.events.Event;
}
/**
* Simulates the Read-Only state in checkboxes.
* This implementation modifies the 'style' attribute by adding 'z-index:-1' to make the checkbox inaccessible.
* Does not depend on extra CSS classes
*/
COMPILE::JS
public class InspireTreeReadOnlyCheckBead_V0 extends Strand implements IBead
{
/**
* constructor
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.9.7
*/
public function InspireTreeReadOnlyCheckBead_V0()
{
super();
}
protected var lastElementZIndexVal:String = null;
protected var initialized:Boolean = false;
private var _strand:IStrand;
/**
* @copy org.apache.royale.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.9.4
*/
public function get strand():IStrand
{
return _strand;
}
/**
* @copy org.apache.royale.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.9.4
*/
public function set strand(value:IStrand):void
{
_strand = value;
(_strand as IEventDispatcher).addEventListener("onCreationComplete", updateHost);
}
private var _readonly:Boolean = false;
/**
* A boolean flag to enable or disable the host control.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.9.4
*/
[Bindable]
public function get readOnly():Boolean
{
return _readonly;
}
public function set readOnly(value:Boolean):void
{
if(value != _readonly)
{
_readonly = value;
updateHost();
sendStrandEvent(_strand, new ValueEvent("readonlyChange", readOnly));
}
}
private function updateHost(event:Event = null):void
{
if(!strand)
return;
//If it is the first time it is executed and readOnly=false, the process does not need to be performed.
if(!initialized && !readOnly)
return;
var elements:NodeList = (_strand as StyledUIBase).element.querySelectorAll("input[type='checkbox']");
for (var i:int = 0; i < elements.length; i++)
{
var htmlElement:HTMLElement = elements[i] as HTMLElement;
if (htmlElement)
{
if(!initialized){
initialized = true;
var css:CSSStyleDeclaration = getComputedStyle(htmlElement);
lastElementZIndexVal = css['zIndex'];
if(!lastElementZIndexVal)
lastElementZIndexVal = "2";
}
if(_readonly)
htmlElement.style["z-index"] = "-1";
else
htmlElement.style["z-index"] = lastElementZIndexVal; //restore
}
}
}
}
COMPILE::SWF
public class InspireTreeReadOnlyCheckBead_V0
{
}
}
|
// Decompiled by AS3 Sorcerer 3.16
// http://www.as3sorcerer.com/
//fl.managers.StyleManager
package fl.managers
{
import flash.utils.Dictionary;
import fl.core.UIComponent;
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
import flash.utils.getQualifiedSuperclassName;
import flash.text.TextFormat;
public class StyleManager
{
private static var _instance:StyleManager;
private var classToInstancesDict:Dictionary;
private var globalStyles:Object;
private var styleToClassesHash:Object;
private var classToStylesDict:Dictionary;
private var classToDefaultStylesDict:Dictionary;
public function StyleManager()
{
styleToClassesHash = {};
classToInstancesDict = new Dictionary(true);
classToStylesDict = new Dictionary(true);
classToDefaultStylesDict = new Dictionary(true);
globalStyles = UIComponent.getStyleDefinition();
}
public static function clearComponentStyle(_arg_1:Object, _arg_2:String):void
{
var _local_3:Class = getClassDef(_arg_1);
var _local_4:Object = getInstance().classToStylesDict[_local_3];
if (((!((_local_4 == null))) && (!((_local_4[_arg_2] == null)))))
{
delete _local_4[_arg_2];
invalidateComponentStyle(_local_3, _arg_2);
};
}
private static function getClassDef(component:Object):Class
{
if ((component is Class))
{
return ((component as Class));
};
try
{
return ((getDefinitionByName(getQualifiedClassName(component)) as Class));
} catch(e:Error)
{
if ((component is UIComponent))
{
try
{
return ((component.loaderInfo.applicationDomain.getDefinition(getQualifiedClassName(component)) as Class));
} catch(e:Error)
{
};
};
};
return (null);
}
public static function clearStyle(_arg_1:String):void
{
setStyle(_arg_1, null);
}
public static function setComponentStyle(_arg_1:Object, _arg_2:String, _arg_3:Object):void
{
var _local_4:Class = getClassDef(_arg_1);
var _local_5:Object = getInstance().classToStylesDict[_local_4];
if (_local_5 == null)
{
_local_5 = (getInstance().classToStylesDict[_local_4] = {});
};
if (_local_5 == _arg_3)
{
return;
};
_local_5[_arg_2] = _arg_3;
invalidateComponentStyle(_local_4, _arg_2);
}
private static function setSharedStyles(_arg_1:UIComponent):void
{
var _local_5:String;
var _local_2:StyleManager = getInstance();
var _local_3:Class = getClassDef(_arg_1);
var _local_4:Object = _local_2.classToDefaultStylesDict[_local_3];
for (_local_5 in _local_4)
{
_arg_1.setSharedStyle(_local_5, getSharedStyle(_arg_1, _local_5));
};
}
public static function getComponentStyle(_arg_1:Object, _arg_2:String):Object
{
var _local_3:Class = getClassDef(_arg_1);
var _local_4:Object = getInstance().classToStylesDict[_local_3];
return ((((_local_4)==null) ? null : _local_4[_arg_2]));
}
private static function getInstance()
{
if (_instance == null)
{
_instance = new (StyleManager)();
};
return (_instance);
}
private static function invalidateComponentStyle(_arg_1:Class, _arg_2:String):void
{
var _local_4:Object;
var _local_5:UIComponent;
var _local_3:Dictionary = getInstance().classToInstancesDict[_arg_1];
if (_local_3 == null)
{
return;
};
for (_local_4 in _local_3)
{
_local_5 = (_local_4 as UIComponent);
if (_local_5 != null)
{
_local_5.setSharedStyle(_arg_2, getSharedStyle(_local_5, _arg_2));
};
};
}
private static function invalidateStyle(_arg_1:String):void
{
var _local_3:Object;
var _local_2:Dictionary = getInstance().styleToClassesHash[_arg_1];
if (_local_2 == null)
{
return;
};
for (_local_3 in _local_2)
{
invalidateComponentStyle(Class(_local_3), _arg_1);
};
}
public static function registerInstance(instance:UIComponent):void
{
var target:Class;
var defaultStyles:Object;
var styleToClasses:Object;
var n:String;
var inst:StyleManager = getInstance();
var classDef:Class = getClassDef(instance);
if (classDef == null)
{
return;
};
if (inst.classToInstancesDict[classDef] == null)
{
inst.classToInstancesDict[classDef] = new Dictionary(true);
target = classDef;
while (defaultStyles == null)
{
if (target["getStyleDefinition"] != null)
{
defaultStyles = target["getStyleDefinition"]();
break;
};
try
{
target = (instance.loaderInfo.applicationDomain.getDefinition(getQualifiedSuperclassName(target)) as Class);
} catch(err:Error)
{
try
{
target = (getDefinitionByName(getQualifiedSuperclassName(target)) as Class);
} catch(e:Error)
{
defaultStyles = UIComponent.getStyleDefinition();
break;
};
};
};
styleToClasses = inst.styleToClassesHash;
for (n in defaultStyles)
{
if (styleToClasses[n] == null)
{
styleToClasses[n] = new Dictionary(true);
};
styleToClasses[n][classDef] = true;
};
inst.classToDefaultStylesDict[classDef] = defaultStyles;
if (inst.classToStylesDict[classDef] == null)
{
inst.classToStylesDict[classDef] = {};
};
};
inst.classToInstancesDict[classDef][instance] = true;
setSharedStyles(instance);
}
public static function getStyle(_arg_1:String):Object
{
return (getInstance().globalStyles[_arg_1]);
}
private static function getSharedStyle(_arg_1:UIComponent, _arg_2:String):Object
{
var _local_3:Class = getClassDef(_arg_1);
var _local_4:StyleManager = getInstance();
var _local_5:Object = _local_4.classToStylesDict[_local_3][_arg_2];
if (_local_5 != null)
{
return (_local_5);
};
_local_5 = _local_4.globalStyles[_arg_2];
if (_local_5 != null)
{
return (_local_5);
};
return (_local_4.classToDefaultStylesDict[_local_3][_arg_2]);
}
public static function setStyle(_arg_1:String, _arg_2:Object):void
{
var _local_3:Object = getInstance().globalStyles;
if ((((_local_3[_arg_1] === _arg_2)) && (!((_arg_2 is TextFormat)))))
{
return;
};
_local_3[_arg_1] = _arg_2;
invalidateStyle(_arg_1);
}
}
}//package fl.managers
|
/**
* Apache License
* Version 2.0, January 2004
* http://www.apache.org/licenses/
*
* TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
*
* 1. Definitions.
*
* "License" shall mean the terms and conditions for use, reproduction,
* and distribution as defined by Sections 1 through 9 of this document.
*
* "Licensor" shall mean the copyright owner or entity authorized by
* the copyright owner that is granting the License.
*
* "Legal Entity" shall mean the union of the acting entity and all
* other entities that control, are controlled by, or are under common
* control with that entity. For the purposes of this definition,
* "control" means (i) the power, direct or indirect, to cause the
* direction or management of such entity, whether by contract or
* otherwise, or (ii) ownership of fifty percent (50%) or more of the
* outstanding shares, or (iii) beneficial ownership of such entity.
*
* "You" (or "Your") shall mean an individual or Legal Entity
* exercising permissions granted by this License.
*
* "Source" form shall mean the preferred form for making modifications,
* including but not limited to software source code, documentation
* source, and configuration files.
*
* "Object" form shall mean any form resulting from mechanical
* transformation or translation of a Source form, including but
* not limited to compiled object code, generated documentation,
* and conversions to other media types.
*
* "Work" shall mean the work of authorship, whether in Source or
* Object form, made available under the License, as indicated by a
* copyright notice that is included in or attached to the work
* (an example is provided in the Appendix below).
*
* "Derivative Works" shall mean any work, whether in Source or Object
* form, that is based on (or derived from) the Work and for which the
* editorial revisions, annotations, elaborations, or other modifications
* represent, as a whole, an original work of authorship. For the purposes
* of this License, Derivative Works shall not include works that remain
* separable from, or merely link (or bind by name) to the interfaces of,
* the Work and Derivative Works thereof.
*
* "Contribution" shall mean any work of authorship, including
* the original version of the Work and any modifications or additions
* to that Work or Derivative Works thereof, that is intentionally
* submitted to Licensor for inclusion in the Work by the copyright owner
* or by an individual or Legal Entity authorized to submit on behalf of
* the copyright owner. For the purposes of this definition, "submitted"
* means any form of electronic, verbal, or written communication sent
* to the Licensor or its representatives, including but not limited to
* communication on electronic mailing lists, source code control systems,
* and issue tracking systems that are managed by, or on behalf of, the
* Licensor for the purpose of discussing and improving the Work, but
* excluding communication that is conspicuously marked or otherwise
* designated in writing by the copyright owner as "Not a Contribution."
*
* "Contributor" shall mean Licensor and any individual or Legal Entity
* on behalf of whom a Contribution has been received by Licensor and
* subsequently incorporated within the Work.
*
* 2. Grant of Copyright License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* copyright license to reproduce, prepare Derivative Works of,
* publicly display, publicly perform, sublicense, and distribute the
* Work and such Derivative Works in Source or Object form.
*
* 3. Grant of Patent License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* (except as stated in this section) patent license to make, have made,
* use, offer to sell, sell, import, and otherwise transfer the Work,
* where such license applies only to those patent claims licensable
* by such Contributor that are necessarily infringed by their
* Contribution(s) alone or by combination of their Contribution(s)
* with the Work to which such Contribution(s) was submitted. If You
* institute patent litigation against any entity (including a
* cross-claim or counterclaim in a lawsuit) alleging that the Work
* or a Contribution incorporated within the Work constitutes direct
* or contributory patent infringement, then any patent licenses
* granted to You under this License for that Work shall terminate
* as of the date such litigation is filed.
*
* 4. Redistribution. You may reproduce and distribute copies of the
* Work or Derivative Works thereof in any medium, with or without
* modifications, and in Source or Object form, provided that You
* meet the following conditions:
*
* (a) You must give any other recipients of the Work or
* Derivative Works a copy of this License; and
*
* (b) You must cause any modified files to carry prominent notices
* stating that You changed the files; and
*
* (c) You must retain, in the Source form of any Derivative Works
* that You distribute, all copyright, patent, trademark, and
* attribution notices from the Source form of the Work,
* excluding those notices that do not pertain to any part of
* the Derivative Works; and
*
* (d) If the Work includes a "NOTICE" text file as part of its
* distribution, then any Derivative Works that You distribute must
* include a readable copy of the attribution notices contained
* within such NOTICE file, excluding those notices that do not
* pertain to any part of the Derivative Works, in at least one
* of the following places: within a NOTICE text file distributed
* as part of the Derivative Works; within the Source form or
* documentation, if provided along with the Derivative Works; or,
* within a display generated by the Derivative Works, if and
* wherever such third-party notices normally appear. The contents
* of the NOTICE file are for informational purposes only and
* do not modify the License. You may add Your own attribution
* notices within Derivative Works that You distribute, alongside
* or as an addendum to the NOTICE text from the Work, provided
* that such additional attribution notices cannot be construed
* as modifying the License.
*
* You may add Your own copyright statement to Your modifications and
* may provide additional or different license terms and conditions
* for use, reproduction, or distribution of Your modifications, or
* for any such Derivative Works as a whole, provided Your use,
* reproduction, and distribution of the Work otherwise complies with
* the conditions stated in this License.
*
* 5. Submission of Contributions. Unless You explicitly state otherwise,
* any Contribution intentionally submitted for inclusion in the Work
* by You to the Licensor shall be under the terms and conditions of
* this License, without any additional terms or conditions.
* Notwithstanding the above, nothing herein shall supersede or modify
* the terms of any separate license agreement you may have executed
* with Licensor regarding such Contributions.
*
* 6. Trademarks. This License does not grant permission to use the trade
* names, trademarks, service marks, or product names of the Licensor,
* except as required for reasonable and customary use in describing the
* origin of the Work and reproducing the content of the NOTICE file.
*
* 7. Disclaimer of Warranty. Unless required by applicable law or
* agreed to in writing, Licensor provides the Work (and each
* Contributor provides its Contributions) on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied, including, without limitation, any warranties or conditions
* of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
* PARTICULAR PURPOSE. You are solely responsible for determining the
* appropriateness of using or redistributing the Work and assume any
* risks associated with Your exercise of permissions under this License.
*
* 8. Limitation of Liability. In no event and under no legal theory,
* whether in tort (including negligence), contract, or otherwise,
* unless required by applicable law (such as deliberate and grossly
* negligent acts) or agreed to in writing, shall any Contributor be
* liable to You for damages, including any direct, indirect, special,
* incidental, or consequential damages of any character arising as a
* result of this License or out of the use or inability to use the
* Work (including but not limited to damages for loss of goodwill,
* work stoppage, computer failure or malfunction, or any and all
* other commercial damages or losses), even if such Contributor
* has been advised of the possibility of such damages.
*
* 9. Accepting Warranty or Additional Liability. While redistributing
* the Work or Derivative Works thereof, You may choose to offer,
* and charge a fee for, acceptance of support, warranty, indemnity,
* or other liability obligations and/or rights consistent with this
* License. However, in accepting such obligations, You may act only
* on Your own behalf and on Your sole responsibility, not on behalf
* of any other Contributor, and only if You agree to indemnify,
* defend, and hold each Contributor harmless for any liability
* incurred by, or claims asserted against, such Contributor by reason
* of your accepting any such warranty or additional liability.
*
* END OF TERMS AND CONDITIONS
*
* APPENDIX: How to apply the Apache License to your work.
*
* To apply the Apache License to your work, attach the following
* boilerplate notice, with the fields enclosed by brackets "{}"
* replaced with your own identifying information. (Don't include
* the brackets!) The text should be enclosed in the appropriate
* comment syntax for the file format. We also recommend that a
* file or class name and description of purpose be included on the
* same "printed page" as the copyright notice for easier
* identification within third-party archives.
*
* Copyright {yyyy} {name of copyright owner}
*
* 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.deleidos.rtws.tc.models
{
import mx.collections.ArrayCollection;
import mx.collections.Sort;
import mx.collections.SortField;
public class SystemChain
{
private var _name:String;
private var _chain:ArrayCollection = new ArrayCollection();
public function SystemChain(name:String)
{
this._name = name;
var positionSortField:SortField = new SortField();
positionSortField.name = "position";
positionSortField.numeric = true;
var sortChain:Sort = new Sort();
sortChain.fields = [positionSortField];
this._chain.sort = sortChain;
}
public function get name():String
{
return this._name;
}
public function set name(value:String):void
{
this._name = value;
}
public function get chain():ArrayCollection
{
return this._chain;
}
public function addToChain(system:Object):void
{
this._chain.addItem(system);
// Refresh to sort
this._chain.refresh();
}
public function contains(domain:String):Boolean
{
for(var i:int = 0; i < this._chain.length; i++)
{
if(domain == this._chain[i].domain)
{
return true;
}
}
return false;
}
}
} |
package kabam.rotmg.ui.view {
import com.company.assembleegameclient.screens.CharacterSelectionAndNewsScreen;
import com.company.assembleegameclient.ui.dialogs.ErrorDialog;
import flash.events.Event;
import kabam.rotmg.core.signals.InvalidateDataSignal;
import kabam.rotmg.core.signals.SetScreenWithValidDataSignal;
import kabam.rotmg.dialogs.control.CloseDialogsSignal;
import robotlegs.bender.bundles.mvcs.Mediator;
public class ErrorDialogMediator extends Mediator {
[Inject]
public var view:ErrorDialog;
[Inject]
public var invalidateData:InvalidateDataSignal;
[Inject]
public var setScreenWithValidData:SetScreenWithValidDataSignal;
[Inject]
public var close:CloseDialogsSignal;
public function ErrorDialogMediator() {
super();
}
override public function initialize() : void {
addViewListener("complete",this.onComplete);
this.view.ok.addOnce(this.onClose);
}
override public function destroy() : void {
removeViewListener("complete",this.onComplete);
}
public function onClose() : void {
this.close.dispatch();
}
private function onComplete(param1:Event) : void {
this.invalidateData.dispatch();
this.setScreenWithValidData.dispatch(new CharacterSelectionAndNewsScreen());
}
}
}
|
// Copyright 2005 The Closure Library Authors. 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.
/**
* @fileoverview Listener object.
* @see ../demos/events.html
*/
package goog.events {
/**
* Simple class that stores information about a listener
* @param {function(?):?} listener Callback function.
* @param {Function} proxy Wrapper for the listener that patches the event.
* @param {EventTarget|goog.events.Listenable} src Source object for
* the event.
* @param {string} type Event type.
* @param {boolean} capture Whether in capture or bubble phase.
* @param {Object=} opt_handler Object in whose context to execute the callback.
* @implements {goog.events.ListenableKey}
* @constructor
*/
public class Listener implements ListenableKey{
public function Listener(listener:Function,proxy:Function,src:EventTarget,type:String,capture:Boolean,opt_handler:Object = null){
super();
}
/**
* Whether the listener works on capture phase.
*
* @see JSType - [boolean]
* @see [listenable]
*/
public function get capture():Boolean{
return false;
}
public function set capture(value:Boolean):void{
}
/**
* The listener function.
*
* @see JSType - [(function (?): ?|null|{handleEvent: function (?): ?})]
* @see [listenable]
*/
public function get listener():Object{
return null;
}
public function set listener(value:Object):void{
}
/**
* The source event target.
*
* @see JSType - [(Object|goog.events.EventTarget|goog.events.Listenable)]
* @see [listenable]
*/
public function get src():Object{
return null;
}
public function set src(value:Object):void{
}
/**
* The event type the listener is listening to.
*
* @see JSType - [string]
* @see [listenable]
*/
public function get type():String{
return null;
}
public function set type(value:String):void{
}
/**
* A globally unique number to identify the key.
*
* @see JSType - [number]
* @see [listenable]
*/
public function get key():Number{
return 0;
}
public function set key(value:Number):void{
}
/**
* The 'this' object for the listener function's scope.
*
* @see JSType - [(Object|null)]
* @see [listenable]
*/
public function get handler():Object{
return null;
}
public function set handler(value:Object):void{
}
/**
* Reserves a key to be used for ListenableKey#key field.
*
* @see [listenable]
* @returns {number} A number to be used to fill ListenableKey#key field.
*/
public function reserveKey():Number{
return 0;
}
/**
* A wrapper over the original listener. This is used solely to
* handle native browser events (it is used to simulate the capture
* phase and to patch the event object).
* @type {Function}
*/
public var proxy:Function;
/**
* Whether to remove the listener after it has been called.
* @type {boolean}
*/
public var callOnce:Boolean;
/**
* Whether the listener has been removed.
* @type {boolean}
*/
public var removed:Boolean;
/**
* If monitoring the goog.events.Listener instances is enabled, stores the
* creation stack trace of the Disposable instance.
* @type {string}
*/
public var creationStack:String;
/**
* Marks this listener as removed. This also remove references held by
* this listener object (such as listener and event source).
*/
public function markAsRemoved():void {
}
}
}
|
/*
* ********************************************************************************************************************
*
* BACKENDLESS.COM CONFIDENTIAL
*
* ********************************************************************************************************************
*
* Copyright 2012 BACKENDLESS.COM. All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains the property of Backendless.com and its suppliers,
* if any. The intellectual and technical concepts contained herein are proprietary to Backendless.com and its
* suppliers and may be covered by U.S. and Foreign Patents, patents in process, and are protected by trade secret
* or copyright law. Dissemination of this information or reproduction of this material is strictly forbidden
* unless prior written permission is obtained from Backendless.com.
*
* *******************************************************************************************************************
*/
package com.backendless.rpc
{
import com.backendless.Backendless;
import com.backendless.core.backendless;
import com.backendless.data.store.Utils;
import com.backendless.messaging.BackendlessChannel;
import flash.events.EventDispatcher;
import mx.messaging.ChannelSet;
import mx.rpc.AbstractOperation;
import mx.rpc.AsyncToken;
import mx.rpc.IResponder;
import mx.rpc.remoting.RemoteObject;
public class BackendlessClient extends EventDispatcher
{
private static const DEFAULT_DESTINATION:String = "GenericDestination";
private var _channelSet:ChannelSet;
private static var _instance:BackendlessClient;
public function BackendlessClient(lock:BackendlessClientLock):void {
if(lock == null) {
throw new Error("BackendlessClient class is a singleton. Please use BackendlessClient.instance instead of the direct instantiation");
}
}
public function invoke(source:String, methodName:String, args:Array = null, responder:IResponder = null):AsyncToken {
var remoteObject:RemoteObject = new RemoteObject(DEFAULT_DESTINATION);
remoteObject.channelSet = _channelSet;
remoteObject.source = source;
var operation:AbstractOperation = remoteObject.getOperation(methodName);
for( var prop:* in args )
args[ prop ] = Utils.prepareArgForSend( args[ prop ] );
operation.arguments = args;
var token:AsyncToken = operation.send();
if (responder) token.addResponder(responder);
return token;
}
public static function get instance():BackendlessClient
{
if(_instance == null)
_instance = new BackendlessClient(new BackendlessClientLock());
return _instance;
}
backendless function initChannel():void
{
_channelSet = new ChannelSet();
_channelSet.addChannel(new BackendlessChannel(null, Backendless.AMF_ENDPOINT));
}
}
}
class BackendlessClientLock{} |
package pw.agar.pwclient.sidebar
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
import pw.agar.pwclient.sidebar.CheckType;
public class CheckBox extends MovieClip
{
private var checked_state:String;
public function CheckBox()
{
setCheckType(CheckType.CHECKMARK);
this.buttonMode = true;
//this.addEventListener(MouseEvent.CLICK, onMouseMove); event handler added in sidebar
}
public function check():void
{
if (this.currentFrameLabel == "unchecked") {
this.gotoAndStop(checked_state);
}
}
public function uncheck():void
{
if (this.currentFrameLabel != "unchecked") {
this.gotoAndStop("unchecked");
}
}
public function toggle():Boolean
{
var res:Boolean;
switch (this.currentFrameLabel) {
case "unchecked":
check();
res = true;
break;
case checked_state:
uncheck();
res = false;
break;
}
return res;
}
public function setCheckType(checkType:int):void
{
switch (checkType) {
case 1:
checked_state = "checked";
break;
case 2:
checked_state = "checked_x";
break;
}
}
public function isChecked():Boolean
{
switch (this.currentFrameLabel) {
case "unchecked":
return false;
break;
default:
return true;
break;
}
}
}
} |
package org.flexlite.domUI.layouts
{
import flash.events.Event;
import flash.geom.Rectangle;
import org.flexlite.domUI.core.ILayoutElement;
import org.flexlite.domUI.layouts.supportClasses.LayoutBase;
[DXML(show="false")]
/**
* 格子布局
* @author DOM
*/
public class TileLayout extends LayoutBase
{
/**
* 构造函数
*/
public function TileLayout()
{
super();
}
/**
* 标记horizontalGap被显式指定过
*/
private var explicitHorizontalGap:Number = NaN;
private var _horizontalGap:Number = 6;
/**
* 列之间的水平空间(以像素为单位)。
*/
public function get horizontalGap():Number
{
return _horizontalGap;
}
public function set horizontalGap(value:Number):void
{
if (value == _horizontalGap)
return;
explicitHorizontalGap = value;
_horizontalGap = value;
invalidateTargetSizeAndDisplayList();
if(hasEventListener("gapChanged"))
dispatchEvent(new Event("gapChanged"));
}
/**
* 标记verticalGap被显式指定过
*/
private var explicitVerticalGap:Number = NaN;
private var _verticalGap:Number = 6;
/**
* 行之间的垂直空间(以像素为单位)。
*/
public function get verticalGap():Number
{
return _verticalGap;
}
public function set verticalGap(value:Number):void
{
if (value == _verticalGap)
return;
explicitVerticalGap = value;
_verticalGap = value;
invalidateTargetSizeAndDisplayList();
if(hasEventListener("gapChanged"))
dispatchEvent(new Event("gapChanged"));
}
private var _columnCount:int = -1;
/**
* 实际列计数。
*/
public function get columnCount():int
{
return _columnCount;
}
private var _requestedColumnCount:int = 0;
/**
* 要显示的列数。设置为0表示自动确定列计数,默认值0。<br/>
* 注意:当orientation为TileOrientation.COLUMNS(逐列排列元素)且taget被显式设置宽度时,此属性无效。
*/
public function get requestedColumnCount():int
{
return _requestedColumnCount;
}
public function set requestedColumnCount(value:int):void
{
if (_requestedColumnCount == value)
return;
_requestedColumnCount = value;
_columnCount = value;
invalidateTargetSizeAndDisplayList();
}
private var _rowCount:int = -1;
/**
* 实际行计数。
*/
public function get rowCount():int
{
return _rowCount;
}
private var _requestedRowCount:int = 0;
/**
* 要显示的行数。设置为0表示自动确定行计数,默认值0。<br/>
* 注意:当orientation为TileOrientation.ROWS(即逐行排列元素,此为默认值)且target被显式设置高度时,此属性无效。
*/
public function get requestedRowCount():int
{
return _requestedRowCount;
}
public function set requestedRowCount(value:int):void
{
if (_requestedRowCount == value)
return;
_requestedRowCount = value;
_rowCount = value;
invalidateTargetSizeAndDisplayList();
}
/**
* 外部显式指定的列宽
*/
private var explicitColumnWidth:Number = NaN;
private var _columnWidth:Number = NaN;
/**
* 实际列宽(以像素为单位)。 若未显式设置,则从根据最宽的元素的宽度确定列宽度。
*/
public function get columnWidth():Number
{
return _columnWidth;
}
/**
* @private
*/
public function set columnWidth(value:Number):void
{
if (value == _columnWidth)
return;
explicitColumnWidth = value;
_columnWidth = value;
invalidateTargetSizeAndDisplayList();
}
/**
* 外部显式指定的行高
*/
private var explicitRowHeight:Number = NaN;
private var _rowHeight:Number = NaN;
/**
* 行高(以像素为单位)。 如果未显式设置,则从元素的高度的最大值确定行高度。
*/
public function get rowHeight():Number
{
return _rowHeight;
}
/**
* @private
*/
public function set rowHeight(value:Number):void
{
if (value == _rowHeight)
return;
explicitRowHeight = value;
_rowHeight = value;
invalidateTargetSizeAndDisplayList();
}
private var _padding:Number = 0;
/**
* 四个边缘的共同内边距。若单独设置了任一边缘的内边距,则该边缘的内边距以单独设置的值为准。
* 此属性主要用于快速设置多个边缘的相同内边距。默认值:0。
*/
public function get padding():Number
{
return _padding;
}
public function set padding(value:Number):void
{
if(_padding==value)
return;
_padding = value;
invalidateTargetSizeAndDisplayList();
}
private var _paddingLeft:Number = NaN;
/**
* 容器的左边缘与布局元素的左边缘之间的最少像素数,若为NaN将使用padding的值,默认值:NaN。
*/
public function get paddingLeft():Number
{
return _paddingLeft;
}
public function set paddingLeft(value:Number):void
{
if (_paddingLeft == value)
return;
_paddingLeft = value;
invalidateTargetSizeAndDisplayList();
}
private var _paddingRight:Number = NaN;
/**
* 容器的右边缘与布局元素的右边缘之间的最少像素数,若为NaN将使用padding的值,默认值:NaN。
*/
public function get paddingRight():Number
{
return _paddingRight;
}
public function set paddingRight(value:Number):void
{
if (_paddingRight == value)
return;
_paddingRight = value;
invalidateTargetSizeAndDisplayList();
}
private var _paddingTop:Number = NaN;
/**
* 容器的顶边缘与第一个布局元素的顶边缘之间的像素数,若为NaN将使用padding的值,默认值:NaN。
*/
public function get paddingTop():Number
{
return _paddingTop;
}
public function set paddingTop(value:Number):void
{
if (_paddingTop == value)
return;
_paddingTop = value;
invalidateTargetSizeAndDisplayList();
}
private var _paddingBottom:Number = NaN;
/**
* 容器的底边缘与最后一个布局元素的底边缘之间的像素数,若为NaN将使用padding的值,默认值:NaN。
*/
public function get paddingBottom():Number
{
return _paddingBottom;
}
public function set paddingBottom(value:Number):void
{
if (_paddingBottom == value)
return;
_paddingBottom = value;
invalidateTargetSizeAndDisplayList();
}
private var _horizontalAlign:String = HorizontalAlign.JUSTIFY;
/**
* 指定如何在水平方向上对齐单元格内的元素。
* 支持的值有 HorizontalAlign.LEFT、HorizontalAlign.CENTER、
* HorizontalAlign.RIGHT、HorizontalAlign.JUSTIFY。
* 默认值:HorizontalAlign.JUSTIFY
*/
public function get horizontalAlign():String
{
return _horizontalAlign;
}
public function set horizontalAlign(value:String):void
{
if (_horizontalAlign == value)
return;
_horizontalAlign = value;
invalidateTargetSizeAndDisplayList();
}
private var _verticalAlign:String = VerticalAlign.JUSTIFY;
/**
* 指定如何在垂直方向上对齐单元格内的元素。
* 支持的值有 VerticalAlign.TOP、VerticalAlign.MIDDLE、
* VerticalAlign.BOTTOM、VerticalAlign.JUSTIFY。
* 默认值:VerticalAlign.JUSTIFY。
*/
public function get verticalAlign():String
{
return _verticalAlign;
}
public function set verticalAlign(value:String):void
{
if (_verticalAlign == value)
return;
_verticalAlign = value;
invalidateTargetSizeAndDisplayList();
}
private var _columnAlign:String = ColumnAlign.LEFT;
/**
* 指定如何将完全可见列与容器宽度对齐。
* 设置为 ColumnAlign.LEFT 时,它会关闭列两端对齐。在容器的最后一列和右边缘之间可能存在部分可见的列或空白。这是默认值。
*
* 设置为 ColumnAlign.JUSTIFY_USING_GAP 时,horizontalGap 的实际值将增大,
* 这样最后一个完全可见列右边缘会与容器的右边缘对齐。仅存在一个完全可见列时,
* horizontalGap 的实际值将增大,这样它会将任何部分可见列推到容器的右边缘之外。
* 请注意显式设置 horizontalGap 属性不会关闭两端对齐。它仅确定初始间隙值。两端对齐可能会增大它。
*
* 设置为 ColumnAlign.JUSTIFY_USING_WIDTH 时,columnWidth 的实际值将增大,
* 这样最后一个完全可见列右边缘会与容器的右边缘对齐。请注意显式设置 columnWidth 属性不会关闭两端对齐。
* 它仅确定初始列宽度值。两端对齐可能会增大它。
*/
public function get columnAlign():String
{
return _columnAlign;
}
public function set columnAlign(value:String):void
{
if (_columnAlign == value)
return;
_columnAlign = value;
invalidateTargetSizeAndDisplayList();
}
private var _rowAlign:String = RowAlign.TOP;
public function get rowAlign():String
{
return _rowAlign;
}
/**
* 指定如何将完全可见行与容器高度对齐。
* 设置为 RowAlign.TOP 时,它会关闭列两端对齐。在容器的最后一行和底边缘之间可能存在部分可见的行或空白。这是默认值。
*
* 设置为 RowAlign.JUSTIFY_USING_GAP 时,verticalGap 的实际值会增大,
* 这样最后一个完全可见行底边缘会与容器的底边缘对齐。仅存在一个完全可见行时,verticalGap 的值会增大,
* 这样它会将任何部分可见行推到容器的底边缘之外。请注意,显式设置 verticalGap
* 不会关闭两端对齐,而只是确定初始间隙值。两端对齐接着可以增大它。
*
* 设置为 RowAlign.JUSTIFY_USING_HEIGHT 时,rowHeight 的实际值会增大,
* 这样最后一个完全可见行底边缘会与容器的底边缘对齐。请注意,显式设置 rowHeight
* 不会关闭两端对齐,而只是确定初始行高度值。两端对齐接着可以增大它。
*/
public function set rowAlign(value:String):void
{
if (_rowAlign == value)
return;
_rowAlign = value;
invalidateTargetSizeAndDisplayList();
}
private var _orientation:String = TileOrientation.ROWS;
/**
* 指定是逐行还是逐列排列元素。
*/
public function get orientation():String
{
return _orientation;
}
public function set orientation(value:String):void
{
if (_orientation == value)
return;
_orientation = value;
invalidateTargetSizeAndDisplayList();
if(hasEventListener("orientationChanged"))
dispatchEvent(new Event("orientationChanged"));
}
/**
* 标记目标容器的尺寸和显示列表失效
*/
private function invalidateTargetSizeAndDisplayList():void
{
if(target)
{
target.invalidateSize();
target.invalidateDisplayList();
}
}
/**
* @inheritDoc
*/
override public function measure():void
{
if (!target)
return;
var savedColumnCount:int = _columnCount;
var savedRowCount:int = _rowCount;
var savedColumnWidth:int = _columnWidth;
var savedRowHeight:int = _rowHeight;
var measuredWidth:Number = 0;
var measuredHeight:Number = 0;
calculateRowAndColumn(target.explicitWidth,target.explicitHeight);
var columnCount:int = _requestedColumnCount>0 ? _requestedColumnCount: _columnCount;
var rowCount:int = _requestedRowCount>0 ? _requestedRowCount : _rowCount;
var horizontalGap:Number = isNaN(_horizontalGap)?0:_horizontalGap;
var verticalGap:Number = isNaN(_verticalGap)?0:_verticalGap;
if (columnCount > 0)
{
measuredWidth = columnCount * (_columnWidth + horizontalGap) - horizontalGap;
}
if (rowCount > 0)
{
measuredHeight = rowCount * (_rowHeight + verticalGap) - verticalGap;
}
var padding:Number = isNaN(_padding)?0:_padding;
var paddingL:Number = isNaN(_paddingLeft)?padding:_paddingLeft;
var paddingR:Number = isNaN(_paddingRight)?padding:_paddingRight;
var paddingT:Number = isNaN(_paddingTop)?padding:_paddingTop;
var paddingB:Number = isNaN(_paddingBottom)?padding:_paddingBottom;
var hPadding:Number = paddingL + paddingR;
var vPadding:Number = paddingT + paddingB;
target.measuredWidth = Math.ceil(measuredWidth + hPadding);
target.measuredHeight = Math.ceil(measuredHeight + vPadding);
_columnCount = savedColumnCount;
_rowCount = savedRowCount;
_columnWidth = savedColumnWidth;
_rowHeight = savedRowHeight;
}
/**
* 计算行和列的尺寸及数量
*/
private function calculateRowAndColumn(explicitWidth:Number, explicitHeight:Number):void
{
var horizontalGap:Number = isNaN(_horizontalGap)?0:_horizontalGap;
var verticalGap:Number = isNaN(_verticalGap)?0:_verticalGap;
_rowCount = _columnCount = -1;
var numElements:int = target.numElements;
var count:int = numElements;
for(var index:int = 0;index<count;index++)
{
var elt:ILayoutElement = target.getElementAt(index) as ILayoutElement;
if(elt&&!elt.includeInLayout)
{
numElements--;
}
}
if(numElements==0)
{
_rowCount = _columnCount = 0;
return;
}
if(isNaN(explicitColumnWidth)||isNaN(explicitRowHeight))
updateMaxElementSize();
if(isNaN(explicitColumnWidth))
{
_columnWidth = maxElementWidth;
}
else
{
_columnWidth = explicitColumnWidth;
}
if(isNaN(explicitRowHeight))
{
_rowHeight = maxElementHeight;
}
else
{
_rowHeight = explicitRowHeight;
}
var itemWidth:Number = _columnWidth + horizontalGap;
//防止出现除数为零的情况
if(itemWidth <= 0)
itemWidth = 1;
var itemHeight:Number = _rowHeight + verticalGap;
if(itemHeight <= 0)
itemHeight = 1;
var orientedByColumns:Boolean = (orientation == TileOrientation.COLUMNS);
var widthHasSet:Boolean = !isNaN(explicitWidth);
var heightHasSet:Boolean = !isNaN(explicitHeight);
var padding:Number = isNaN(_padding)?0:_padding;
var paddingL:Number = isNaN(_paddingLeft)?padding:_paddingLeft;
var paddingR:Number = isNaN(_paddingRight)?padding:_paddingRight;
var paddingT:Number = isNaN(_paddingTop)?padding:_paddingTop;
var paddingB:Number = isNaN(_paddingBottom)?padding:_paddingBottom;
if (_requestedColumnCount>0 || _requestedRowCount>0)
{
if (_requestedRowCount>0)
_rowCount = Math.min(_requestedRowCount,numElements);
if (_requestedColumnCount>0)
_columnCount = Math.min(_requestedColumnCount,numElements);
}
else if(!widthHasSet&&!heightHasSet)
{
var side:Number = Math.sqrt(numElements*itemWidth*itemHeight);
if(orientedByColumns)
{
_rowCount = Math.max(1,Math.round(side/itemHeight));
}
else
{
_columnCount = Math.max(1,Math.round(side/itemWidth));
}
}
else if(widthHasSet&&(!heightHasSet||!orientedByColumns))
{
var targetWidth:Number = Math.max(0,
explicitWidth - paddingL - paddingR);
_columnCount = Math.floor((targetWidth + horizontalGap)/itemWidth);
_columnCount = Math.max(1,Math.min(_columnCount,numElements));
}
else
{
var targetHeight:Number = Math.max(0,
explicitHeight - paddingT - paddingB);
_rowCount = Math.floor((targetHeight + verticalGap)/itemHeight);
_rowCount = Math.max(1,Math.min(_rowCount,numElements));
}
if (_rowCount==-1)
_rowCount = Math.max(1, Math.ceil(numElements / _columnCount));
if (_columnCount==-1)
_columnCount = Math.max(1, Math.ceil(numElements / _rowCount));
if (_requestedColumnCount>0&&_requestedRowCount>0)
{
if (orientation == TileOrientation.ROWS)
_rowCount = Math.max(1, Math.ceil(numElements / _requestedColumnCount));
else
_columnCount = Math.max(1, Math.ceil(numElements / _requestedRowCount));
}
}
/**
* 缓存的最大子对象宽度
*/
private var maxElementWidth:Number = 0;
/**
* 缓存的最大子对象高度
*/
private var maxElementHeight:Number = 0;
/**
* 更新最大子对象尺寸
*/
private function updateMaxElementSize():void
{
if(!target)
return;
if(useVirtualLayout)
updateMaxElementSizeVirtual();
else
updateMaxElementSizeReal();
}
/**
* 更新虚拟布局的最大子对象尺寸
*/
private function updateMaxElementSizeVirtual():void
{
var typicalHeight:Number = typicalLayoutRect?typicalLayoutRect.height:22;
var typicalWidth:Number = typicalLayoutRect?typicalLayoutRect.width:22;
maxElementWidth = Math.max(maxElementWidth,typicalWidth);
maxElementHeight = Math.max(maxElementHeight,typicalHeight);
if ((startIndex != -1) && (endIndex != -1))
{
for (var index:int = startIndex; index <= endIndex; index++)
{
var elt:ILayoutElement = target.getVirtualElementAt(index) as ILayoutElement;
if(!elt||!elt.includeInLayout)
continue;
maxElementWidth = Math.max(maxElementWidth,elt.preferredWidth);
maxElementHeight = Math.max(maxElementHeight,elt.preferredHeight);
}
}
}
/**
* 更新真实布局的最大子对象尺寸
*/
private function updateMaxElementSizeReal():void
{
var numElements:int = target.numElements;
for(var index:int = 0;index<numElements;index++)
{
var elt:ILayoutElement = target.getElementAt(index) as ILayoutElement;
if(!elt||!elt.includeInLayout)
continue;
maxElementWidth = Math.max(maxElementWidth,elt.preferredWidth);
maxElementHeight = Math.max(maxElementHeight,elt.preferredHeight);
}
}
/**
* @inheritDoc
*/
override public function clearVirtualLayoutCache():void
{
super.clearVirtualLayoutCache();
maxElementWidth = 0;
maxElementHeight = 0;
}
/**
* 当前视图中的第一个元素索引
*/
private var startIndex:int = -1;
/**
* 当前视图中的最后一个元素的索引
*/
private var endIndex:int = -1;
/**
* 视图的第一个和最后一个元素的索引值已经计算好的标志
*/
private var indexInViewCalculated:Boolean = false;
/**
* @inheritDoc
*/
override protected function scrollPositionChanged():void
{
super.scrollPositionChanged();
if(useVirtualLayout)
{
var changed:Boolean = getIndexInView();
if(changed)
{
indexInViewCalculated = true;
target.invalidateDisplayList();
}
}
}
/**
* 获取视图中第一个和最后一个元素的索引,返回是否发生改变
*/
private function getIndexInView():Boolean
{
if(!target||target.numElements==0)
{
startIndex = endIndex = -1;
return false;
}
var numElements:int = target.numElements;
if(!useVirtualLayout)
{
startIndex = 0;
endIndex = numElements-1;
return false;
}
if(isNaN(target.width)||target.width==0||isNaN(target.height)||target.height==0)
{
startIndex = endIndex = -1;
return false;
}
var oldStartIndex:int = startIndex;
var oldEndIndex:int = endIndex;
var padding:Number = isNaN(_padding)?0:_padding;
var paddingL:Number = isNaN(_paddingLeft)?padding:_paddingLeft;
var paddingT:Number = isNaN(_paddingTop)?padding:_paddingTop;
var horizontalGap:Number = isNaN(_horizontalGap)?0:_horizontalGap;
var verticalGap:Number = isNaN(_verticalGap)?0:_verticalGap;
if(orientation == TileOrientation.COLUMNS)
{
var itemWidth:Number = _columnWidth + horizontalGap;
if(itemWidth <= 0)
{
startIndex = 0;
endIndex = numElements-1;
return false;
}
var minVisibleX:Number = target.horizontalScrollPosition;
var maxVisibleX:Number = target.horizontalScrollPosition+target.width;
var startColumn:int = Math.floor((minVisibleX-paddingL)/itemWidth);
if(startColumn<0)
startColumn = 0;
var endColumn:int = Math.ceil((maxVisibleX-paddingL)/itemWidth);
if(endColumn<0)
endColumn = 0;
startIndex = Math.min(numElements-1,Math.max(0,startColumn*_rowCount));
endIndex = Math.min(numElements-1,Math.max(0,endColumn*_rowCount-1));
}
else
{
var itemHeight:Number = _rowHeight + verticalGap;
if(itemHeight <= 0)
{
startIndex = 0;
endIndex = numElements-1;
return false;
}
var minVisibleY:Number = target.verticalScrollPosition;
var maxVisibleY:Number = target.verticalScrollPosition+target.height;
var startRow:int = Math.floor((minVisibleY-paddingT)/itemHeight);
if(startRow<0)
startRow = 0;
var endRow:int = Math.ceil((maxVisibleY-paddingT)/itemHeight);
if(endRow<0)
endRow = 0;
startIndex = Math.min(numElements-1,Math.max(0,startRow*_columnCount));
endIndex = Math.min(numElements-1,Math.max(0,endRow*_columnCount-1));
}
return startIndex != oldStartIndex||endIndex != oldEndIndex;
}
/**
* @inheritDoc
*/
override public function updateDisplayList(width:Number, height:Number):void
{
super.updateDisplayList(width, height);
if (!target)
return;
var padding:Number = isNaN(_padding)?0:_padding;
var paddingL:Number = isNaN(_paddingLeft)?padding:_paddingLeft;
var paddingR:Number = isNaN(_paddingRight)?padding:_paddingRight;
var paddingT:Number = isNaN(_paddingTop)?padding:_paddingTop;
var paddingB:Number = isNaN(_paddingBottom)?padding:_paddingBottom;
var horizontalGap:Number = isNaN(_horizontalGap)?0:_horizontalGap;
var verticalGap:Number = isNaN(_verticalGap)?0:_verticalGap;
if(indexInViewCalculated)
{
indexInViewCalculated = false;
}
else
{
calculateRowAndColumn(width,height);
if(_rowCount==0||_columnCount==0)
{
target.setContentSize(paddingL+paddingR,paddingT+paddingB);
return;
}
adjustForJustify(width,height);
getIndexInView();
}
if(useVirtualLayout)
{
calculateRowAndColumn(width,height);
}
if(startIndex == -1||endIndex==-1)
{
target.setContentSize(0,0);
return;
}
target.setVirtualElementIndicesInView(startIndex,endIndex);
var elt:ILayoutElement;
var x:Number;
var y:Number;
var columnIndex:int;
var rowIndex:int;
var orientedByColumns:Boolean = (orientation == TileOrientation.COLUMNS);
var index:int = startIndex;
for(var i:int = startIndex;i <= endIndex;i++)
{
if(useVirtualLayout)
elt = target.getVirtualElementAt(i) as ILayoutElement;
else
elt = target.getElementAt(i) as ILayoutElement;
if(elt == null||!elt.includeInLayout)
continue;
if(orientedByColumns)
{
columnIndex = Math.ceil((index+1)/_rowCount)-1;
rowIndex = Math.ceil((index+1)%_rowCount)-1;
if(rowIndex == -1)
rowIndex = _rowCount-1;
}
else
{
columnIndex = Math.ceil((index+1)%_columnCount) - 1;
if(columnIndex == -1)
columnIndex = _columnCount - 1;
rowIndex = Math.ceil((index+1)/_columnCount) - 1;
}
x = columnIndex*(_columnWidth+horizontalGap)+paddingL;
y = rowIndex*(_rowHeight+verticalGap)+paddingT;
sizeAndPositionElement(elt,x,y,_columnWidth,rowHeight);
index++;
}
var hPadding:Number = paddingL + paddingR;
var vPadding:Number = paddingT + paddingB;
var contentWidth:Number = (_columnWidth+horizontalGap)*_columnCount-horizontalGap;
var contentHeight:Number = (_rowHeight+verticalGap)*_rowCount-verticalGap;
target.setContentSize(Math.ceil(contentWidth+hPadding),Math.ceil(contentHeight+vPadding));
}
/**
* 为单个元素布局
*/
private function sizeAndPositionElement(element:ILayoutElement,cellX:int,cellY:int,
cellWidth:int,cellHeight:int):void
{
var elementWidth:Number = NaN;
var elementHeight:Number = NaN;
if (horizontalAlign == HorizontalAlign.JUSTIFY)
elementWidth = cellWidth;
else if (!isNaN(element.percentWidth))
elementWidth = cellWidth * element.percentWidth * 0.01;
if (verticalAlign == VerticalAlign.JUSTIFY)
elementHeight = cellHeight;
else if (!isNaN(element.percentHeight))
elementHeight = cellHeight * element.percentHeight * 0.01;
element.setLayoutBoundsSize(Math.round(elementWidth), Math.round(elementHeight));
var x:Number = cellX;
switch (horizontalAlign)
{
case HorizontalAlign.RIGHT:
x += cellWidth - element.layoutBoundsWidth;
break;
case HorizontalAlign.CENTER:
x = cellX + (cellWidth - element.layoutBoundsWidth) / 2;
break;
}
var y:Number = cellY;
switch (verticalAlign)
{
case VerticalAlign.BOTTOM:
y += cellHeight - element.layoutBoundsHeight;
break;
case VerticalAlign.MIDDLE:
y += (cellHeight - element.layoutBoundsHeight) / 2;
break;
}
element.setLayoutBoundsPosition(Math.round(x), Math.round(y));
}
/**
* 为两端对齐调整间隔或格子尺寸
*/
private function adjustForJustify(width:Number,height:Number):void
{
var padding:Number = isNaN(_padding)?0:_padding;
var paddingL:Number = isNaN(_paddingLeft)?padding:_paddingLeft;
var paddingR:Number = isNaN(_paddingRight)?padding:_paddingRight;
var paddingT:Number = isNaN(_paddingTop)?padding:_paddingTop;
var paddingB:Number = isNaN(_paddingBottom)?padding:_paddingBottom;
var targetWidth:Number = Math.max(0,
width - paddingL - paddingR);
var targetHeight:Number = Math.max(0,
height - paddingT - paddingB);
if(!isNaN(explicitVerticalGap))
_verticalGap = explicitVerticalGap;
if(!isNaN(explicitHorizontalGap))
_horizontalGap = explicitHorizontalGap;
_verticalGap = isNaN(_verticalGap)?0:_verticalGap;
_horizontalGap = isNaN(_horizontalGap)?0:_horizontalGap;
var itemWidth:Number = _columnWidth + _horizontalGap;
if(itemWidth <= 0)
itemWidth = 1;
var itemHeight:Number = _rowHeight + _verticalGap;
if(itemHeight <= 0)
itemHeight = 1;
var offsetY:Number = targetHeight-_rowHeight*_rowCount;
var offsetX:Number = targetWidth-_columnWidth*_columnCount;
var gapCount:int;
if(offsetY>0)
{
if(rowAlign == RowAlign.JUSTIFY_USING_GAP)
{
gapCount = Math.max(1,_rowCount-1);
_verticalGap = offsetY/gapCount;
}
else if(rowAlign == RowAlign.JUSTIFY_USING_HEIGHT)
{
if(_rowCount>0)
{
_rowHeight += (offsetY-(_rowCount-1)*_verticalGap)/_rowCount;
}
}
}
if(offsetX>0)
{
if(columnAlign == ColumnAlign.JUSTIFY_USING_GAP)
{
gapCount = Math.max(1,_columnCount-1);
_horizontalGap = offsetX/gapCount;
}
else if(columnAlign == ColumnAlign.JUSTIFY_USING_WIDTH)
{
if(_columnCount>0)
{
_columnWidth += (offsetX-(_columnCount-1)*_horizontalGap)/_columnCount;
}
}
}
}
/**
* @inheritDoc
*/
override protected function getElementBoundsLeftOfScrollRect(scrollRect:Rectangle):Rectangle
{
var bounds:Rectangle = new Rectangle();
var padding:Number = isNaN(_padding)?0:_padding;
var paddingL:Number = isNaN(_paddingLeft)?padding:_paddingLeft;
var paddingR:Number = isNaN(_paddingRight)?padding:_paddingRight;
var horizontalGap:Number = isNaN(_horizontalGap)?0:_horizontalGap;
if(scrollRect.left>target.contentWidth - paddingR)
{
bounds.left = target.contentWidth - paddingR;
bounds.right = target.contentWidth;
}
else if(scrollRect.left>paddingL)
{
var column:int = Math.floor((scrollRect.left - 1 - paddingL) / (_columnWidth + horizontalGap));
bounds.left = leftEdge(column);
bounds.right = rightEdge(column);
}
else
{
bounds.left = 0;
bounds.right = paddingL;
}
return bounds;
}
/**
* @inheritDoc
*/
override protected function getElementBoundsRightOfScrollRect(scrollRect:Rectangle):Rectangle
{
var padding:Number = isNaN(_padding)?0:_padding;
var paddingL:Number = isNaN(_paddingLeft)?padding:_paddingLeft;
var paddingR:Number = isNaN(_paddingRight)?padding:_paddingRight;
var horizontalGap:Number = isNaN(_horizontalGap)?0:_horizontalGap;
var bounds:Rectangle = new Rectangle();
if(scrollRect.right<paddingL)
{
bounds.left = 0;
bounds.right = paddingL;
}
else if(scrollRect.right<target.contentWidth - paddingR)
{
var column:int = Math.floor(((scrollRect.right + 1 + horizontalGap) - paddingL) / (_columnWidth + horizontalGap));
bounds.left = leftEdge(column);
bounds.right = rightEdge(column);
}
else
{
bounds.left = target.contentWidth - paddingR;
bounds.right = target.contentWidth;
}
return bounds;
}
/**
* @inheritDoc
*/
override protected function getElementBoundsAboveScrollRect(scrollRect:Rectangle):Rectangle
{
var padding:Number = isNaN(_padding)?0:_padding;
var paddingT:Number = isNaN(_paddingTop)?padding:_paddingTop;
var paddingB:Number = isNaN(_paddingBottom)?padding:_paddingBottom;
var verticalGap:Number = isNaN(_verticalGap)?0:_verticalGap;
var bounds:Rectangle = new Rectangle();
if(scrollRect.top>target.contentHeight - paddingB)
{
bounds.top = target.contentHeight - paddingB;
bounds.bottom = target.contentHeight;
}
else if(scrollRect.top>paddingT)
{
var row:int = Math.floor((scrollRect.top - 1 - paddingT) / (_rowHeight + verticalGap));
bounds.top = topEdge(row);
bounds.bottom = bottomEdge(row);
}
else
{
bounds.top = 0;
bounds.bottom = paddingT;
}
return bounds;
}
/**
* @inheritDoc
*/
override protected function getElementBoundsBelowScrollRect(scrollRect:Rectangle):Rectangle
{
var padding:Number = isNaN(_padding)?0:_padding;
var paddingT:Number = isNaN(_paddingTop)?padding:_paddingTop;
var paddingB:Number = isNaN(_paddingBottom)?padding:_paddingBottom;
var verticalGap:Number = isNaN(_verticalGap)?0:_verticalGap;
var bounds:Rectangle = new Rectangle();
if(scrollRect.bottom<paddingT)
{
bounds.top = 0;
bounds.bottom = paddingT;
}
else if(scrollRect.bottom<target.contentHeight - paddingB)
{
var row:int = Math.floor(((scrollRect.bottom + 1 + verticalGap) - paddingT) / (_rowHeight + verticalGap));
bounds.top = topEdge(row);
bounds.bottom = bottomEdge(row);
}
else
{
bounds.top = target.contentHeight - paddingB;
bounds.bottom = target.contentHeight;
}
return bounds;
}
private function leftEdge(columnIndex:int):Number
{
if (columnIndex < 0)
return 0;
var padding:Number = isNaN(_padding)?0:_padding;
var paddingL:Number = isNaN(_paddingLeft)?padding:_paddingLeft;
var horizontalGap:Number = isNaN(_horizontalGap)?0:_horizontalGap;
return Math.max(0, columnIndex * (_columnWidth + horizontalGap)) + paddingL;
}
private function rightEdge(columnIndex:int):Number
{
if (columnIndex < 0)
return 0;
var padding:Number = isNaN(_padding)?0:_padding;
var paddingL:Number = isNaN(_paddingLeft)?padding:_paddingLeft;
var horizontalGap:Number = isNaN(_horizontalGap)?0:_horizontalGap;
return Math.min(target.contentWidth, columnIndex * (_columnWidth + horizontalGap) +
_columnWidth) + paddingL;
}
final private function topEdge(rowIndex:int):Number
{
if (rowIndex < 0)
return 0;
var padding:Number = isNaN(_padding)?0:_padding;
var paddingT:Number = isNaN(_paddingTop)?padding:_paddingTop;
var verticalGap:Number = isNaN(_verticalGap)?0:_verticalGap;
return Math.max(0, rowIndex * (_rowHeight + verticalGap)) + paddingT;
}
final private function bottomEdge(rowIndex:int):Number
{
if (rowIndex < 0)
return 0;
var padding:Number = isNaN(_padding)?0:_padding;
var paddingT:Number = isNaN(_paddingTop)?padding:_paddingTop;
var verticalGap:Number = isNaN(_verticalGap)?0:_verticalGap;
return Math.min(target.contentHeight, rowIndex * (_rowHeight + verticalGap) +
_rowHeight) + paddingT;
}
}
} |
class ssNode
{
ssNode( string Node ) { m_Node = Node; }
string GetNode() { return m_Node; }
string m_Node;
};
class ssNode_Float : ssNode
{
ssNode_Float( string Node ) { m_Node = Node; }
}
ssNode ssCreateNode( string Node )
{
ssNode_Float FloatNode( Node );
return FloatNode;
}
|
/* 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 GetSetSameName {
public class GetSetSameNameArg
{
var _e = 4;
public function get e() { return _e}
public function set e(e) { _e = e;}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 flashx.textLayout.formats
{
/**
* Defines a constant for specifying that the value of the <code>borderStyle</code> property
* of the <code>TextLayoutFormat</code> class.
*
* @playerversion Flash 10
* @playerversion AIR 1.5
* @langversion 3.0
* @see flashx.textLayout.formats.TextLayoutFormat#borderStyle TextLayoutFormat.borderStyle
*/
public final class BorderStyle
{
/** none - no border style is applied.
*
* @playerversion Flash 10
* @playerversion AIR 1.5
* @langversion 3.0
*/
public static const NONE:String = "none";
/** hidden - border is hidden.
*
* @playerversion Flash 10
* @playerversion AIR 1.5
* @langversion 3.0
*/
public static const HIDDEN:String = "hidden";
/** dotted - border is made up of dotted lines.
*
* @playerversion Flash 10
* @playerversion AIR 1.5
* @langversion 3.0
*/
public static const DOTTED:String = "dotted";
/** dashed - border is made up of dashed lines.
*
* @playerversion Flash 10
* @playerversion AIR 1.5
* @langversion 3.0
*/
public static const DASHED:String = "dashed";
/** solid - border is made up of solid lines.
*
* @playerversion Flash 10
* @playerversion AIR 1.5
* @langversion 3.0
*/
public static const SOLID:String = "solid";
/** double - border is made up of double lines.
*
* @playerversion Flash 10
* @playerversion AIR 1.5
* @langversion 3.0
*/
public static const DOUBLE:String = "double";
}
} |
package app.part
{
import app.Config;
import app.data.ResourceManager;
import app.data.ResourceNodeData;
import app.message.MessageCenter;
import app.message.Messager;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.filesystem.File;
import flash.net.URLRequest;
import mx.controls.Alert;
import mx.controls.Tree;
import mx.core.FlexGlobals;
import mx.events.ListEvent;
import spark.components.Image;
/**
* 资源树列表
* @author lonewolf
*
*/
public class ResourcePart extends Messager
{
private var _tree:Tree;
// 预览图像
private var _preview:Image;
public function ResourcePart()
{
_tree=FlexGlobals.topLevelApplication.res;
_preview=FlexGlobals.topLevelApplication.preview;
_preview.smooth=true;
_tree.addEventListener(ListEvent.CHANGE,treeChangeHandler);
FlexGlobals.topLevelApplication.refreshRes.addEventListener(MouseEvent.CLICK,refreshResHandler);
}
/**
* 接收消息
* @param sender
* @param type
*
*/
override public function receiveMessage(sender:Object, type:String):void
{
if(type==MessageCenter.NEW_PROJECT)
{
// 新项目,加载新资源
this.loadResources();
}
}
/**
* 加载资源
*
*/
private function loadResources():void
{
Config.resourceManager.load();
_tree.dataProvider=Config.resourceManager.data;
_tree.validateNow();
_tree.expandChildrenOf(Config.resourceManager.data,true);
}
/**
* 刷新资源
* @param event
*
*/
protected function refreshResHandler(event:MouseEvent):void
{
this.loadResources();
}
/**
* 点击树节点显示预览图
* @param event
*
*/
protected function treeChangeHandler(event:ListEvent):void
{
var node:ResourceNodeData=_tree.selectedItem as ResourceNodeData;
if(node.type==Config.RESOURCE_IMAGE||node.type==Config.RESOURCE_PLIST)
{
_preview.source=node.image;
var width:Number=240;
var height:Number=90;
var scale1:Number=width/node.image.width;
var scale2:Number=height/node.image.height;
var scale:Number=scale1<scale2?scale1:scale2;
if(scale>1)
{
scale=1;
}
_preview.scaleX=_preview.scaleY=scale;
}
else
{
_preview.source=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 mx.charts.renderers
{
import flash.display.Graphics;
import flash.geom.Rectangle;
import mx.charts.ChartItem;
import mx.charts.chartClasses.GraphicsUtilities;
import mx.core.IDataRenderer;
import mx.graphics.IFill;
import mx.graphics.IStroke;
import mx.skins.ProgrammaticSkin;
import mx.graphics.SolidColor;
import mx.utils.ColorUtil;
/**
* A simple chart itemRenderer implementation
* that fills an elliptical area.
* This class can be used as an itemRenderer for ColumnSeries, BarSeries, AreaSeries, LineSeries,
* PlotSeries, and BubbleSeries objects.
* It renders its area on screen using the <code>fill</code> and <code>stroke</code> styles
* of its associated series.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public class CircleItemRenderer extends ProgrammaticSkin
implements IDataRenderer
{
include "../../core/Version.as";
//--------------------------------------------------------------------------
//
// Class variables
//
//--------------------------------------------------------------------------
/**
* @private
*/
private static var rcFill:Rectangle = new Rectangle();
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function CircleItemRenderer()
{
super();
}
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
//----------------------------------
// data
//----------------------------------
/**
* @private
* Storage for the data property.
*/
private var _data:Object;
[Inspectable(environment="none")]
/**
* The chartItem that this itemRenderer displays.
* This value is assigned by the owning series.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get data():Object
{
return _data;
}
/**
* @private
*/
public function set data(value:Object):void
{
if (_data == value)
return;
_data = value;
}
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
override protected function updateDisplayList(unscaledWidth:Number,
unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
var fill:IFill;
var state:String = "";
if (_data is ChartItem && _data.hasOwnProperty('fill'))
{
fill = _data.fill;
state = _data.currentState;
}
else
fill = GraphicsUtilities.fillFromStyle(getStyle('fill'));
var color:uint;
var adjustedRadius:Number = 0;
switch (state)
{
case ChartItem.FOCUSED:
case ChartItem.ROLLOVER:
if (styleManager.isValidStyleValue(getStyle('itemRollOverColor')))
color = getStyle('itemRollOverColor');
else
color = ColorUtil.adjustBrightness2(GraphicsUtilities.colorFromFill(fill),-20);
fill = new SolidColor(color);
adjustedRadius = getStyle('adjustedRadius');
if (!adjustedRadius)
adjustedRadius = 0;
break;
case ChartItem.DISABLED:
if (styleManager.isValidStyleValue(getStyle('itemDisabledColor')))
color = getStyle('itemDisabledColor');
else
color = ColorUtil.adjustBrightness2(GraphicsUtilities.colorFromFill(fill),20);
fill = new SolidColor(GraphicsUtilities.colorFromFill(color));
break;
case ChartItem.FOCUSEDSELECTED:
case ChartItem.SELECTED:
if (styleManager.isValidStyleValue(getStyle('itemSelectionColor')))
color = getStyle('itemSelectionColor');
else
color = ColorUtil.adjustBrightness2(GraphicsUtilities.colorFromFill(fill),-30);
fill = new SolidColor(color);
adjustedRadius = getStyle('adjustedRadius');
if (!adjustedRadius)
adjustedRadius = 0;
break;
}
var stroke:IStroke = getStyle("stroke");
var w:Number = stroke ? stroke.weight / 2 : 0;
rcFill.right = unscaledWidth;
rcFill.bottom = unscaledHeight;
var g:Graphics = graphics;
g.clear();
if (stroke)
stroke.apply(g,null,null);
if (fill)
fill.begin(g, rcFill, null);
g.drawEllipse(w - adjustedRadius,w - adjustedRadius,unscaledWidth - 2 * w + adjustedRadius * 2, unscaledHeight - 2 * w + adjustedRadius * 2);
if (fill)
fill.end(g);
}
}
}
|
package com.playata.application.ui.dialogs
{
import com.playata.application.data.character.AppearanceSettings;
import com.playata.application.data.item.Item;
import com.playata.application.data.item_pattern.ItemPatterns;
import com.playata.application.data.user.User;
import com.playata.application.messaging.Message;
import com.playata.application.messaging.MessageRouter;
import com.playata.application.ui.ViewManager;
import com.playata.application.ui.elements.avatar.UiAvatarPreview;
import com.playata.application.ui.elements.generic.button.UiButton;
import com.playata.application.ui.elements.generic.dialog.UiDialog;
import com.playata.application.ui.elements.generic.tab.UiTabButton;
import com.playata.application.ui.elements.item.UiItemGraphic;
import com.playata.application.ui.elements.item.UiItemPatternContent;
import com.playata.application.ui.elements.sewing_machine.UiSewingMachinContent;
import com.playata.application.ui.panels.PanelShop;
import com.playata.framework.input.IInteractionTarget;
import com.playata.framework.input.InteractionEvent;
import com.playata.framework.localization.LocText;
import visuals.ui.dialogs.SymbolDialogSewingMachineGeneric;
public class DialogSewingMachine extends UiDialog
{
private static var _isOpen:Boolean = false;
private var _btnClose:UiButton = null;
private var _btnTabSewingMachine:UiTabButton;
private var _btnTabItemPattern:UiTabButton;
private var _previewAvatar:UiAvatarPreview = null;
private var _sewingMachineContent:UiSewingMachinContent = null;
private var _itemPatternContent:UiItemPatternContent = null;
public function DialogSewingMachine(param1:Item = null)
{
_isOpen = true;
var _loc2_:SymbolDialogSewingMachineGeneric = new SymbolDialogSewingMachineGeneric();
super(_loc2_);
_queued = false;
_sewingMachineContent = new UiSewingMachinContent(_loc2_.sewingMachine,this);
_itemPatternContent = new UiItemPatternContent(_loc2_.itemPattern,this);
_btnClose = new UiButton(_loc2_.btnClose,"",onClickClose);
_btnTabSewingMachine = new UiTabButton(_loc2_.btnTabSewingMachine,LocText.current.text("dialog/sewing_machine/tab_button_sewing_machine"),LocText.current.text("dialog/sewing_machine/tab_button_sewing_machine_tooltip"),onClickTabSewingMachine);
_btnTabItemPattern = new UiTabButton(_loc2_.btnTabItemPattern,LocText.current.text("dialog/sewing_machine/tab_button_item_pattern"),LocText.current.text("dialog/sewing_machine/tab_button_item_pattern_tooltip"),onClickTabSewingMachine);
_btnTabSewingMachine.setTextSize(15,2);
_btnTabItemPattern.setTextSize(15,2);
_loc2_.iconCount.caption.text = "!";
_loc2_.iconCount.bringToTop();
_previewAvatar = new UiAvatarPreview(_loc2_.avatar);
_loc2_.avatar.x = _loc2_.avatar.x - 100;
_loc2_.avatar.bringToTop();
MessageRouter.addListener("ItemMessage.notifyItemDragged",handleMessages);
MessageRouter.addListener("ItemMessage.notifyItemInteractionOver",handleMessages);
MessageRouter.addListener("ItemMessage.notifyItemInteractionOut",handleMessages);
refreshCounter();
if(param1)
{
clickTabSewingMachine(_btnTabSewingMachine);
_sewingMachineContent.setItem(param1);
}
else
{
clickTabSewingMachine(_btnTabItemPattern);
_btnTabSewingMachine.buttonEnabled = false;
}
}
public static function get isOpen() : Boolean
{
return _isOpen;
}
override public function dispose() : void
{
_btnClose.dispose();
_btnClose = null;
_btnTabSewingMachine.dispose();
_btnTabSewingMachine = null;
_btnTabItemPattern.dispose();
_btnTabItemPattern = null;
_previewAvatar.dispose();
_previewAvatar = null;
_sewingMachineContent.dispose();
_sewingMachineContent = null;
_itemPatternContent.dispose();
_itemPatternContent = null;
MessageRouter.removeAllListeners(handleMessages);
super.dispose();
}
public function refreshUI() : void
{
_sewingMachineContent.refreshUI();
}
private function onClickTabSewingMachine(param1:InteractionEvent) : void
{
clickTabSewingMachine(param1.target);
}
private function clickTabSewingMachine(param1:IInteractionTarget) : void
{
_btnTabSewingMachine.tabbed = param1 === _btnTabSewingMachine;
_btnTabItemPattern.tabbed = param1 === _btnTabItemPattern;
if(_btnTabSewingMachine.tabbed)
{
_sewingMachineContent.show();
_itemPatternContent.hide();
}
else
{
_itemPatternContent.show();
_sewingMachineContent.hide();
}
}
private function handleMessages(param1:Message) : void
{
var _loc3_:* = null;
var _loc2_:* = null;
var _loc4_:* = param1.type;
switch(_loc4_)
{
case "ItemMessage.notifyItemDragged":
_previewAvatar.hide();
break;
case "ItemMessage.notifyItemInteractionOver":
_loc3_ = param1.data as UiItemGraphic;
_loc2_ = _loc3_.item;
if(_loc2_.type == 1 || _loc2_.type == 3 || _loc2_.type == 2 || _loc2_.type == 4 || _loc2_.type == 5)
{
_previewAvatar.show(getCharacterSettings(_loc2_));
}
break;
case "ItemMessage.notifyItemInteractionOut":
_previewAvatar.hide();
break;
default:
throw new Error("Encountered unknown message type! type=" + param1.type);
}
}
private function getCharacterSettings(param1:Item) : AppearanceSettings
{
var _loc2_:AppearanceSettings = User.current.character.getCurrentSettings();
if(param1.type == 1)
{
_loc2_.show_head_item = true;
_loc2_.head = param1.identifier;
}
else if(param1.type == 2)
{
_loc2_.show_chest_item = true;
_loc2_.chest = param1.identifier;
}
else if(param1.type == 3)
{
_loc2_.show_belt_item = true;
_loc2_.belt = param1.identifier;
}
else if(param1.type == 4)
{
_loc2_.show_legs_item = true;
_loc2_.legs = param1.identifier;
}
else if(param1.type == 5)
{
_loc2_.show_boots_item = true;
_loc2_.boots = param1.identifier;
}
if(param1.type == 4 && _loc2_.chest != null && User.current.character.getItem("chest_item_id").isOutfitItem)
{
_loc2_.chest = null;
}
return _loc2_;
}
private function onClickClose(param1:InteractionEvent) : void
{
if(!_sewingMachineContent)
{
return;
}
if(_sewingMachineContent.sewingInProgress())
{
return;
}
close();
}
override public function onEscape() : void
{
if(!_sewingMachineContent)
{
return;
}
if(_sewingMachineContent.sewingInProgress())
{
return;
}
close();
}
override public function close(param1:Function = null) : void
{
super.close(param1);
if(ViewManager.instance.activePanelInstance is PanelShop)
{
(ViewManager.instance.activePanelInstance as PanelShop).updateCharacter();
}
_isOpen = false;
}
public function refreshCounter() : void
{
if(!_sewingMachineContent)
{
return;
}
var _loc1_:SymbolDialogSewingMachineGeneric = _vo as SymbolDialogSewingMachineGeneric;
_loc1_.iconCount.visible = ItemPatterns.instance.hasNewItemPattern || ItemPatterns.instance.hasCollectableItemPatternValues;
_itemPatternContent.refreshList();
}
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package com.fenhongxiang.hls.handler {
import flash.system.Capabilities;
import com.fenhongxiang.hls.event.HLSEvent;
import com.fenhongxiang.hls.event.HLSLoadMetrics;
import com.fenhongxiang.hls.event.HLSPlayMetrics;
import com.fenhongxiang.hls.HLS;
import com.fenhongxiang.hls.model.Stats;
CONFIG::LOGGING {
import com.luojianghong.hls.utils.Log;
}
/*
* class that handle per playback session stats
*/
public class StatsHandler {
/** Reference to the HLS controller. **/
private var _hls : HLS;
private var _stats : Stats;
private var _sumLatency : int;
private var _sumKbps : int;
private var _sumAutoLevel : int;
private var _levelLastAuto : Boolean;
public function StatsHandler(hls : HLS) {
_hls = hls;
_hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestLoadedHandler);
_hls.addEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentLoadedHandler);
_hls.addEventListener(HLSEvent.FRAGMENT_PLAYING,_fragmentPlayingHandler);
_hls.addEventListener(HLSEvent.FPS_DROP, _fpsDropHandler);
_hls.addEventListener(HLSEvent.FPS_DROP_LEVEL_CAPPING, _fpsDropLevelCappingHandler);
_hls.addEventListener(HLSEvent.FPS_DROP_SMOOTH_LEVEL_SWITCH, _fpsDropSmoothLevelSwitchHandler);
}
public function dispose() : void {
_hls.removeEventListener(HLSEvent.MANIFEST_LOADED, _manifestLoadedHandler);
_hls.removeEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentLoadedHandler);
_hls.removeEventListener(HLSEvent.FRAGMENT_PLAYING, _fragmentPlayingHandler);
_hls.removeEventListener(HLSEvent.FPS_DROP, _fpsDropHandler);
_hls.removeEventListener(HLSEvent.FPS_DROP_LEVEL_CAPPING, _fpsDropLevelCappingHandler);
_hls.removeEventListener(HLSEvent.FPS_DROP_SMOOTH_LEVEL_SWITCH, _fpsDropSmoothLevelSwitchHandler);
}
public function get stats() : Stats {
return _stats;
}
private function _manifestLoadedHandler(event : HLSEvent) : void {
_stats = new Stats();
_stats.levelNb = event.levels.length;
_stats.levelStart = -1;
_stats.tech = "flashls,"+Capabilities.version;
_stats.fragBuffered = _stats.fragChangedAuto = _stats.fragChangedManual = 0;
_stats.fpsDropEvent = _stats.fpsDropSmoothLevelSwitch = 0;
};
private function _fragmentLoadedHandler(event : HLSEvent) : void {
var metrics : HLSLoadMetrics = event.loadMetrics;
var latency : int = metrics.loading_begin_time-metrics.loading_request_time;
var bitrate : int = 8*metrics.size/(metrics.parsing_end_time-metrics.loading_begin_time);
if(_stats.fragBuffered) {
_stats.fragMinLatency = Math.min(_stats.fragMinLatency,latency);
_stats.fragMaxLatency = Math.max(_stats.fragMaxLatency,latency);
_stats.fragMinKbps = Math.min(_stats.fragMinKbps,bitrate);
_stats.fragMaxKbps = Math.max(_stats.fragMaxKbps,bitrate);
_stats.autoLevelCappingMin = Math.min(_stats.autoLevelCappingMin,_hls.autoLevelCapping);
_stats.autoLevelCappingMax = Math.max(_stats.autoLevelCappingMax,_hls.autoLevelCapping);
_stats.fragBuffered++;
} else {
_stats.fragMinLatency = _stats.fragMaxLatency = latency;
_stats.fragMinKbps = _stats.fragMaxKbps = bitrate;
_stats.fragBuffered = 1;
_stats.fragBufferedBytes = 0;
_stats.autoLevelCappingMin = _stats.autoLevelCappingMax = _hls.autoLevelCapping;
_sumLatency=0;
_sumKbps=0;
}
_sumLatency+=latency;
_sumKbps+=bitrate;
_stats.fragBufferedBytes+=metrics.size;
_stats.fragAvgLatency = _sumLatency/_stats.fragBuffered;
_stats.fragAvgKbps = _sumKbps/_stats.fragBuffered;
_stats.autoLevelCappingLast = _hls.autoLevelCapping;
}
private function _fragmentPlayingHandler(event : HLSEvent) : void {
var metrics : HLSPlayMetrics = event.playMetrics;
var level : int = metrics.level;
var autoLevel : Boolean = metrics.auto_level;
if(_stats.levelStart == -1) {
_stats.levelStart = level;
}
if(autoLevel) {
if(_stats.fragChangedAuto) {
_stats.autoLevelMin = Math.min(_stats.autoLevelMin,level);
_stats.autoLevelMax = Math.max(_stats.autoLevelMax,level);
_stats.fragChangedAuto++;
if(_levelLastAuto && level !== _stats.autoLevelLast) {
_stats.autoLevelSwitch++;
}
} else {
_stats.autoLevelMin = _stats.autoLevelMax = level;
_stats.autoLevelSwitch = 0;
_stats.fragChangedAuto = 1;
_sumAutoLevel = 0;
}
_sumAutoLevel+=level;
_stats.autoLevelAvg = _sumAutoLevel/_stats.fragChangedAuto;
_stats.autoLevelLast = level;
} else {
if(_stats.fragChangedManual) {
_stats.manualLevelMin = Math.min(_stats.manualLevelMin,level);
_stats.manualLevelMax = Math.max(_stats.manualLevelMax,level);
_stats.fragChangedManual++;
if(!_levelLastAuto && level !== _stats.manualLevelLast) {
_stats.manualLevelSwitch++;
}
} else {
_stats.manualLevelMin = _stats.manualLevelMax = level;
_stats.manualLevelSwitch = 0;
_stats.fragChangedManual = 1;
}
_stats.manualLevelLast = level;
}
_levelLastAuto = autoLevel;
}
private function _fpsDropHandler(event : HLSEvent) : void {
_stats.fpsDropEvent++;
_stats.fpsTotalDroppedFrames = _hls.stream.info.droppedFrames;
};
private function _fpsDropLevelCappingHandler(event : HLSEvent) : void {
_stats.fpsDropLevelCappingMin=event.level;
};
private function _fpsDropSmoothLevelSwitchHandler(event : HLSEvent) : void {
_stats.fpsDropSmoothLevelSwitch++;
};
}
}
|
/**
* Benchmark test for use with Moses Gunesch's Go benchmark tester. http://go.mosessupposes.com/?p=5
* To use this class, you'll need to download the appropriate files from the google code site
* http://code.google.com/p/goasap/
*/
package org.as3lib.kitchensync.test {
import com.mosesSupposes.benchmark.tweenbencher.*;
import org.as3lib.kitchensync.test.*;
/**
* @author Moses Gunesch / mosessupposes.com (c)
*/
public class KitchenSyncBenchmark_SyncMode extends KitchenSyncBenchmark {
public function KitchenSyncBenchmark_SyncMode(tweenBencher : TweenBencher)
{
super(tweenBencher, "KitchenSync (sync mode)");
syncMode = true;
}
}
}
|
package com.codeazur.as3swf.data
{
import com.codeazur.as3swf.SWFData;
public class SWFSoundInfo
{
public var syncStop:Boolean;
public var syncNoMultiple:Boolean;
public var hasEnvelope:Boolean;
public var hasLoops:Boolean;
public var hasOutPoint:Boolean;
public var hasInPoint:Boolean;
public var outPoint:uint;
public var inPoint:uint;
public var loopCount:uint;
protected var _envelopeRecords:Vector.<SWFSoundEnvelope>;
public function SWFSoundInfo(data:SWFData = null) {
_envelopeRecords = new Vector.<SWFSoundEnvelope>();
if (data != null) {
parse(data);
}
}
public function get envelopeRecords():Vector.<SWFSoundEnvelope> { return _envelopeRecords; }
public function parse(data:SWFData):void {
var flags:uint = data.readUI8();
syncStop = ((flags & 0x20) != 0);
syncNoMultiple = ((flags & 0x10) != 0);
hasEnvelope = ((flags & 0x08) != 0);
hasLoops = ((flags & 0x04) != 0);
hasOutPoint = ((flags & 0x02) != 0);
hasInPoint = ((flags & 0x01) != 0);
if (hasInPoint) {
inPoint = data.readUI32();
}
if (hasOutPoint) {
outPoint = data.readUI32();
}
if (hasLoops) {
loopCount = data.readUI16();
}
if (hasEnvelope) {
var envPoints:uint = data.readUI8();
for (var i:uint = 0; i < envPoints; i++) {
_envelopeRecords.push(data.readSOUNDENVELOPE());
}
}
}
public function publish(data:SWFData):void {
var flags:uint = 0;
if(syncStop) { flags |= 0x20; }
if(syncNoMultiple) { flags |= 0x10; }
if(hasEnvelope) { flags |= 0x08; }
if(hasLoops) { flags |= 0x04; }
if(hasOutPoint) { flags |= 0x02; }
if(hasInPoint) { flags |= 0x01; }
data.writeUI8(flags)
if (hasInPoint) {
data.writeUI32(inPoint);
}
if (hasOutPoint) {
data.writeUI32(outPoint);
}
if (hasLoops) {
data.writeUI16(loopCount);
}
if (hasEnvelope) {
var envPoints:uint = _envelopeRecords.length;
data.writeUI8(envPoints);
for (var i:uint = 0; i < envPoints; i++) {
data.writeSOUNDENVELOPE(_envelopeRecords[i]);
}
}
}
public function toString():String {
return "[SWFSoundInfo]";
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.