CombinedText
stringlengths
4
3.42M
package com.ixiyou.speUI.mcontrols { import flash.display.*; import flash.events.*; import flash.text.*; import com.ixiyou.speUI.mcontrols.MovieToComboBox; import com.ixiyou.events.DataSpeEvent; /** * ... * @author $(DefaultUser) */ public class CityComboBox extends Sprite { public static var provinceArr:Array = [ '上海', '安徽', '北京', '重庆', '福建', '甘肃', '广东', '广西', '贵州', '海南', '河北', '黑龙江', '河南', '香港', '湖北', '湖南', '江苏', '江西', '吉林', '辽宁', '澳门', '内蒙古', '宁夏', '青海', '山东', '山西', '陕西', '四川', '台湾', '天津', '新疆', '西藏', '云南', '浙江']; /** * 省份列表 * @return */ public function getProvinces():Array { return CityComboBox.provinceArr.concat() } /** * 城市列表 * @param province 省份 * @return */ public function getCity(province:String=''):Array { var cityOptions:Array switch (province) { case "" : cityOptions = new Array("", ""); break; case "安徽" : cityOptions = new Array( "合肥", "合肥", "安庆", "安庆", "蚌埠", "蚌埠", "亳州", "亳州", "巢湖", "巢湖", "滁州", "滁州", "阜阳", "阜阳", "贵池", "贵池", "淮北", "淮北", "淮化", "淮化", "淮南", "淮南", "黄山", "黄山", "九华山", "九华山", "六安", "六安", "马鞍山", "马鞍山", "宿州", "宿州", "铜陵", "铜陵", "屯溪", "屯溪", "芜湖", "芜湖", "宣城", "宣城"); break; case "北京" : cityOptions = new Array( "北京", "北京", "东城", "西城", "崇文", "宣武", "朝阳", "丰台", "石景山", "海淀", "门头沟", "房山", "通州", "顺义", "昌平", "大兴", "平谷", "怀柔", "密云","延庆"); break; case "重庆" : cityOptions = new Array( "重庆", "重庆", "万州", "涪陵", "渝中", "大渡口", "江北", "沙坪坝", "九龙坡", "南岸", "北碚", "万盛", "双挢", "渝北", "巴南", "黔江", "长寿", "綦江", "潼南", "铜梁", "大足", "荣昌", "壁山", "梁平", "城口", "丰都", "垫江", "武隆", "忠县", "开县", "云阳", "奉节", "巫山", "巫溪", "石柱", "秀山", "酉阳", "彭水", "江津", "合川", "永川","南川"); break; case "福建" : cityOptions = new Array( "福州", "福州", "福安", "福安", "龙岩", "龙岩", "南平", "南平", "宁德", "宁德", "莆田", "莆田", "泉州", "泉州", "三明", "三明", "邵武", "邵武", "石狮", "石狮", "永安", "永安", "武夷山", "武夷山", "厦门", "厦门", "漳州", "漳州"); break; case "甘肃" : cityOptions = new Array( "兰州", "兰州", "白银", "白银", "定西", "定西", "敦煌", "敦煌", "甘南", "甘南", "金昌", "金昌", "酒泉", "酒泉", "临夏", "临夏", "平凉", "平凉", "天水", "天水", "武都", "武都", "西峰", "西峰", "张掖", "张掖"); break; case "广东" : cityOptions = new Array( "广州", "广州", "潮阳", "潮阳", "潮州", "潮州", "澄海", "澄海", "东莞", "东莞", "佛山", "佛山", "河源", "河源", "惠州", "惠州", "江门", "江门", "揭阳", "揭阳", "开平", "开平", "茂名", "茂名", "梅州", "梅州", "清远", "清远", "汕头", "汕头", "汕尾", "汕尾", "韶关", "韶关", "深圳", "深圳", "顺德", "顺德", "阳江", "阳江", "阳江", "阳江", "英德", "英德", "云浮", "云浮", "增城", "增城", "湛江", "湛江", "肇庆", "肇庆", "中山", "中山", "珠海", "珠海"); break; case "广西" : cityOptions = new Array( "南宁", "南宁", "百色", "百色", "北海", "北海", "桂林", "桂林", "防城港", "防城港", "河池", "河池", "柳州", "柳州", "钦州", "钦州", "梧州", "梧州", "玉林", "玉林"); break; case "贵州" : cityOptions = new Array( "贵阳", "贵阳", "安顺", "安顺", "毕节", "毕节", "都匀", "都匀", "凯里", "凯里", "六盘水", "六盘水", "铜仁", "铜仁", "兴义", "兴义", "玉屏", "玉屏", "遵义", "遵义"); break; case "海南" : cityOptions = new Array( "海口", "海口", "儋县", "儋县", "陵水", "陵水", "琼海", "琼海", "三亚", "三亚", "通什", "通什", "万宁", "万宁"); break; case "河北" : cityOptions = new Array( "石家庄", "石家庄", "保定", "保定", "北戴河", "北戴河", "沧州", "沧州", "承德", "承德", "丰润", "丰润", "邯郸", "邯郸", "衡水", "衡水", "廊坊", "廊坊", "南戴河", "南戴河", "秦皇岛", "秦皇岛", "唐山", "唐山", "新城", "新城", "邢台", "邢台", "张家口", "张家口"); break; case "黑龙江" : cityOptions = new Array( "哈尔滨", "哈尔滨", "北安", "北安", "大庆", "大庆", "大兴安岭", "大兴安岭", "鹤岗", "鹤岗", "黑河", "黑河", "佳木斯", "佳木斯", "鸡西", "鸡西", "牡丹江", "牡丹江", "齐齐哈尔", "齐齐哈尔", "七台河", "七台河", "双鸭山", "双鸭山", "绥化", "绥化", "伊春", "伊春"); break; case "河南" : cityOptions = new Array( "郑州", "郑州", "安阳", "安阳", "鹤壁", "鹤壁", "潢川", "潢川", "焦作", "焦作", "开封", "开封", "漯河", "漯河", "洛阳", "洛阳", "南阳", "南阳", "平顶山", "平顶山", "濮阳", "濮阳", "三门峡", "三门峡", "商丘", "商丘", "新乡", "新乡", "信阳", "信阳", "许昌", "许昌", "周口", "周口", "驻马店", "驻马店"); break; case "香港" : cityOptions = new Array( "香港", "香港", "九龙", "九龙"); break; case "湖北" : cityOptions = new Array( "武汉", "武汉", "恩施", "恩施", "鄂州", "鄂州", "黄岗", "黄岗", "黄石", "黄石", "荆门", "荆门", "荆州", "荆州", "潜江", "潜江", "十堰", "十堰", "随州", "随州", "武穴", "武穴", "仙桃", "仙桃", "咸宁", "咸宁", "襄阳", "襄阳", "襄樊", "襄樊", "孝感", "孝感", "宜昌", "宜昌"); break; case "湖南" : cityOptions = new Array( "长沙", "长沙", "常德", "常德", "郴州", "郴州", "衡阳", "衡阳", "怀化", "怀化", "吉首", "吉首", "娄底", "娄底", "邵阳", "邵阳", "湘潭", "湘潭", "益阳", "益阳", "岳阳", "岳阳", "永州", "永州", "张家界", "张家界", "株洲", "株洲"); break; case "江苏" : cityOptions = new Array( "南京", "南京", "常熟", "常熟", "常州", "常州", "海门", "海门", "淮安", "淮安", "江都", "江都", "江阴", "江阴", "昆山", "昆山", "连云港", "连云港", "南通", "南通", "启东", "启东", "沭阳", "沭阳", "苏州", "苏州", "太仓", "太仓", "泰州", "泰州", "同里", "同里", "无锡", "无锡", "徐州", "徐州", "盐城", "盐城", "扬州", "扬州", "宜兴", "宜兴", "仪征", "仪征", "张家港", "张家港", "镇江", "镇江", "周庄", "周庄"); break; case "江西" : cityOptions = new Array( "南昌", "南昌", "抚州", "抚州", "赣州", "赣州", "吉安", "吉安", "景德镇", "景德镇", "井冈山", "井冈山", "九江", "九江", "庐山", "庐山", "萍乡", "萍乡", "上饶", "上饶", "新余", "新余", "宜春", "宜春", "鹰潭", "鹰潭"); break; case "吉林" : cityOptions = new Array( "长春", "长春", "白城", "白城", "白山", "白山", "珲春", "珲春", "辽源", "辽源", "梅河", "梅河", "吉林", "吉林", "四平", "四平", "松原", "松原", "通化", "通化", "延吉", "延吉"); break; case "辽宁" : cityOptions = new Array( "沈阳", "沈阳", "鞍山", "鞍山", "本溪", "本溪", "朝阳", "朝阳", "大连", "大连", "丹东", "丹东", "抚顺", "抚顺", "阜新", "阜新", "葫芦岛", "葫芦岛", "锦州", "锦州", "辽阳", "辽阳", "盘锦", "盘锦", "铁岭", "铁岭", "营口", "营口"); break; case "澳门" : cityOptions = new Array( "澳门", "澳门"); break; case "内蒙古" : cityOptions = new Array( "呼和浩特", "呼和浩特", "阿拉善盟", "阿拉善盟", "包头", "包头", "赤峰", "赤峰", "东胜", "东胜", "海拉尔", "海拉尔", "集宁", "集宁", "临河", "临河", "通辽", "通辽", "乌海", "乌海", "乌兰浩特", "乌兰浩特", "锡林浩特", "锡林浩特"); break; case "宁夏" : cityOptions = new Array( "银川", "银川", "固源", "固源", "石嘴山", "石嘴山", "吴忠", "吴忠"); break; case "青海" : cityOptions = new Array( "西宁", "西宁", "德令哈", "德令哈", "格尔木", "格尔木", "共和", "共和", "海东", "海东", "海晏", "海晏", "玛沁", "玛沁", "同仁", "同仁", "玉树", "玉树"); break; case "山东" : cityOptions = new Array( "济南", "济南", "滨州", "滨州", "兖州", "兖州", "德州", "德州", "东营", "东营", "荷泽", "荷泽", "济宁", "济宁", "莱芜", "莱芜", "聊城", "聊城", "临沂", "临沂", "蓬莱", "蓬莱", "青岛", "青岛", "曲阜", "曲阜", "日照", "日照", "泰安", "泰安", "潍坊", "潍坊", "威海", "威海", "烟台", "烟台", "枣庄", "枣庄", "淄博", "淄博"); break; case "上海" : cityOptions = new Array( "上海", "上海", "崇明", "崇明", "朱家角", "朱家角"); break; case "山西" : cityOptions = new Array( "太原","太原", "长治", "长治", "大同", "大同", "候马", "候马", "晋城", "晋城", "离石", "离石", "临汾", "临汾", "宁武", "宁武", "朔州", "朔州", "忻州", "忻州", "阳泉", "阳泉", "榆次", "榆次", "运城", "运城"); break; case "陕西" : cityOptions = new Array( "西安", "西安", "安康", "安康", "宝鸡", "宝鸡", "汉中", "汉中", "渭南", "渭南", "商州", "商州", "绥德", "绥德", "铜川", "铜川", "咸阳", "咸阳", "延安", "延安", "榆林", "榆林"); break; case "四川" : cityOptions = new Array( "成都", "成都", "巴中", "巴中", "达安", "达安", "德阳", "德阳", "都江堰", "都江堰", "峨眉山", "峨眉山", "涪陵", "涪陵", "广安", "广安", "广元", "广元", "九寨沟", "九寨沟", "康定", "康定", "乐山", "乐山", "泸州", "泸州", "马尔康", "马尔康", "绵阳", "绵阳", "南充", "南充", "内江", "内江", "攀枝花", "攀枝花", "遂宁", "遂宁", "汶川", "汶川", "西昌", "西昌", "雅安", "雅安", "宜宾", "宜宾", "自贡", "自贡"); break; case "台湾" : cityOptions = new Array( "台北", "台北", "基隆", "基隆", "台南", "台南", "台中", "台中"); break; case "天津" : cityOptions = new Array( "天津", "天津"); break; case "新疆" : cityOptions = new Array( "乌鲁木齐", "乌鲁木齐", "阿克苏", "阿克苏", "阿勒泰", "阿勒泰", "阿图什", "阿图什", "博乐", "博乐", "昌吉", "昌吉", "东山", "东山", "哈密", "哈密", "和田", "和田", "喀什", "喀什", "克拉玛依", "克拉玛依", "库车", "库车", "库尔勒", "库尔勒", "奎屯", "奎屯", "石河子", "石河子", "塔城", "塔城", "吐鲁番", "吐鲁番", "伊宁", "伊宁"); break; case "西藏" : cityOptions = new Array( "拉萨", "拉萨", "阿里", "阿里", "昌都", "昌都", "林芝", "林芝", "那曲", "那曲", "日喀则", "日喀则", "山南", "山南"); break; case "云南" : cityOptions = new Array( "昆明", "昆明", "大理", "大理", "保山", "保山", "楚雄", "楚雄", "大理", "大理", "东川", "东川", "个旧", "个旧", "景洪", "景洪", "开远", "开远", "临沧", "临沧", "丽江", "丽江", "六库", "六库", "潞西", "潞西", "曲靖", "曲靖", "思茅", "思茅", "文山", "文山", "西双版纳", "西双版纳", "玉溪", "玉溪", "中甸", "中甸", "昭通", "昭通"); break; case "浙江" : cityOptions = new Array( "杭州", "杭州", "安吉", "安吉", "慈溪", "慈溪", "定海", "定海", "奉化", "奉化", "海盐", "海盐", "黄岩", "黄岩", "湖州", "湖州", "嘉兴", "嘉兴", "金华", "金华", "临安", "临安", "临海", "临海", "丽水", "丽水", "宁波", "宁波", "瓯海", "瓯海", "平湖", "平湖", "千岛湖", "千岛湖", "衢州", "衢州", "瑞安", "瑞安", "绍兴", "绍兴", "嵊州", "嵊州", "台州", "台州", "温岭", "温岭", "温州", "温州"); break; default: cityOptions = new Array("", ""); } return cityOptions } private var provinceBox:MovieToComboBox private var cityBox:MovieToComboBox private var _province:String='' private var _city:String = '' private var skin:* /** * 构造函数 */ public function CityComboBox(skin:Sprite,formerly:Boolean=false,parentBool:Boolean=false) { var tempParent:DisplayObjectContainer if (formerly) { this.x = skin.x this.y = skin.y } if (skin.parent&& parentBool) { tempParent=skin.parent this.name=skin.name } this.skin = skin skin.x=skin.y=0 addChild(skin) if(tempParent)tempParent.addChild(this) cityBox = new MovieToComboBox(skin.getChildByName('box2') as Sprite, { data:null }, true, true) cityBox.addEventListener('upData',cityUpData) provinceBox = new MovieToComboBox(skin.getChildByName('box1') as Sprite, { data:null}, true, true) provinceBox.addEventListener('upData', provinceUpData) provinceBox.data=getProvinces() //trace(province,city) } private function cityUpData(e:DataSpeEvent):void { _city = cityBox.seletData.label trace(province,city) } private function provinceUpData(e:DataSpeEvent):void { _province = provinceBox.seletData.label var cityArr:Array=getCity(province) var arr:Array = new Array() var i:int var item:Object if (province == '北京' || province == '重庆') { for(i = 0; i < cityArr.length; i++) { item =cityArr[i]; if (i > 0) arr.push(item) } }else { for (i = 0; i < cityArr.length; i++) { item = cityArr[i]; if(i%2==0)arr.push(item) } } cityBox.data=arr } public function get province():String { return _province; } public function get city():String { return _city; } } }
class smallCalendar.Configuration { ////////////////////////////////////////////////////Calendar static var COLOR_ARROW static var BACKGROUND_COLOR ////name dayWeek static var SU:String="Sunday" static var MO:String="Monday" static var TU:String="Tuesday" static var WE:String="Wednesday" static var TH:String="Thursday" static var FR:String="Friday" static var SA:String="Saturday" ///name Month static var JANUARY="January" static var FEBRUAY="Februay" static var MARCH="March" static var APRIL="April" static var MAY="May" static var JUNE="June" static var JULY="July" static var AUGUST="August" static var SEPTEMBER="September" static var OCTOBER="October" static var NOVEMBER="November" static var DECEMBER="December" static var COLOR_NUMBER static var COLOR_NUMBER_WEEK static var COLOR_DATE static var COLOR_FRAME_TODAY static var COLOR_GLOW_NORMAL static var COLOR_GLOW_EVENTS static var COLOR_BACKGROUND_NUMBER ////space calendar static var WIDTH_BACKGROUND_NUMBER static var HEIGHT_BACKGROUND_NUMBER static var SPACE_X_NUMBER static var SPACE_y_NUMBER static var SIZE_NUMBER static var FIRSTDAYWEEK:Number=0 /////firstDayWeek ( 0-Su ; 1-Mo ; 2-Tu ; 3-We ; 4-Th ; 5-Fr ; 6-Sa ) static var CALENDAR_X:Number ///position x static var CALENDAR_Y:Number ///position Y static var AUTO_DISPLAY_EVENT:String="true" /// auto display the event for the current date ///static var ///////////////////////////////////textArea static var TEXT_CSS_STYLE static var TEXT_X:Number static var TEXT_Y:Number static var TEXT_WIDTH:Number static var TEXT_HEIGHT:Number static var TEXT_BORDER:Boolean static var TEXT_BORDER_COLOR static var TEXT_COLOR_SCROLL_BACKGROUND static var TEXT_COLOR_SCROLL static var SPEED_SCROLL:Number static var TEXT_URL_STYLE_CSS:String static var __data:XML static var _loaded:Number /////////////////////////////////////////////////////////////////////////////////////////////// static function load(xml){ __data=new XML() __data.ignoreWhite=true __data.onLoad=function(){ Configuration._loaded=1 } __data.load(xml) } /////////////////////////////////////////////////////////////////////////////////////////////// static function get loaded(){ return _loaded } /////////////////////////////////////////////////////////////////////////////////////////////// static function setXml(date_){ var len=date_.firstChild.childNodes.length for(var i=0;i<len;i++){ var nod=date_.firstChild.childNodes[i] var node_name=nod.nodeName Configuration[node_name]=nod.firstChild.nodeValue } } /////////////////////////////////////////////////////////////////////////////////////////////// }
/* * 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.internals.runners.statements { import org.flexunit.async.AsyncLocator; import org.flexunit.constants.AnnotationConstants; import org.flexunit.internals.runners.statements.IAsyncStatement; import org.flexunit.internals.runners.statements.SequencerWithDecoration; import org.flexunit.runners.model.FrameworkMethod; /** * The <code>RunBefores</code> is a <code>SequencerWithDecoration</code> for potential methods that have * <code>Before</code> metadata and should be run before a test has started. This class also determines * whether methods tagged as before methods are asynchronous. */ public class RunBefores extends SequencerWithDecoration implements IAsyncStatement { /** * @inheritDoc */ override protected function withPotentialAsync( method:FrameworkMethod, test:Object, statement:IAsyncStatement ):IAsyncStatement { var async:Boolean = ExpectAsync.hasAsync( method, AnnotationConstants.BEFORE ); var needsMonitor:Boolean = false; //Do we already have an ExpectAsync instance for this class? if ( async ) { needsMonitor = ( !AsyncLocator.hasCallableForTest( test ) ); } return ( async && needsMonitor ) ? new ExpectAsync( test, statement ) : statement; } /** * Constructor. * * @param befores An array containing all statements that need to be executed before a test is executed. * @param target The test class. */ public function RunBefores( befores:Array, target:Object, statement:IAsyncStatement=null ) { super( befores, target ); } /** * @private * @return */ override public function toString():String { return "RunBefores"; } } }
package com.winonetech.consts { /** * * 定义缓存路径。 * */ import cn.vision.core.NoInstance; public final class PathConsts extends NoInstance { /** * * 文件相对缓存路径。 * * @default cache * */ public static const PATH_FILE:String = "cache"; /** * * 存储服务端文件是否存在的缓存列表。 * * @default cache/fileList.lst * */ public static const PATH_FILE_LIST_CACHE:String = "cache/fileList.lst"; } }
/* Feathers Copyright 2012-2015 Bowler Hat LLC. 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 feathers.controls.text { import feathers.core.FeathersControl; import feathers.core.FocusManager; import feathers.core.IMultilineTextEditor; import feathers.events.FeathersEventType; import feathers.skins.IStyleProvider; import feathers.text.StageTextField; import feathers.utils.display.stageToStarling; import feathers.utils.geom.matrixToScaleX; import feathers.utils.geom.matrixToScaleY; import flash.display.BitmapData; import flash.events.Event; import flash.events.FocusEvent; import flash.events.KeyboardEvent; import flash.events.SoftKeyboardEvent; import flash.geom.Matrix; import flash.geom.Matrix3D; import flash.geom.Point; import flash.geom.Rectangle; import flash.geom.Vector3D; import flash.system.Capabilities; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFormat; import flash.text.TextFormatAlign; import flash.text.engine.FontPosture; import flash.text.engine.FontWeight; import flash.ui.Keyboard; import flash.utils.getDefinitionByName; import starling.core.RenderSupport; import starling.core.Starling; import starling.display.DisplayObject; import starling.display.Image; import starling.events.Event; import starling.textures.ConcreteTexture; import starling.textures.Texture; import starling.utils.MatrixUtil; import starling.utils.SystemUtil; /** * Dispatched when the text property changes. * * <p>The properties of the event object have the following values:</p> * <table class="innertable"> * <tr><th>Property</th><th>Value</th></tr> * <tr><td><code>bubbles</code></td><td>false</td></tr> * <tr><td><code>currentTarget</code></td><td>The Object that defines the * event listener that handles the event. For example, if you use * <code>myButton.addEventListener()</code> to register an event listener, * myButton is the value of the <code>currentTarget</code>.</td></tr> * <tr><td><code>data</code></td><td>null</td></tr> * <tr><td><code>target</code></td><td>The Object that dispatched the event; * it is not always the Object listening for the event. Use the * <code>currentTarget</code> property to always access the Object * listening for the event.</td></tr> * </table> */ [Event(name="change",type="starling.events.Event")] /** * Dispatched when the user presses the Enter key while the editor has * focus. This event may not be dispatched on some platforms, depending on * the value of <code>returnKeyLabel</code>. This issue may even occur when * using the <em>default value</em> of <code>returnKeyLabel</code>! * * <p>The properties of the event object have the following values:</p> * <table class="innertable"> * <tr><th>Property</th><th>Value</th></tr> * <tr><td><code>bubbles</code></td><td>false</td></tr> * <tr><td><code>currentTarget</code></td><td>The Object that defines the * event listener that handles the event. For example, if you use * <code>myButton.addEventListener()</code> to register an event listener, * myButton is the value of the <code>currentTarget</code>.</td></tr> * <tr><td><code>data</code></td><td>null</td></tr> * <tr><td><code>target</code></td><td>The Object that dispatched the event; * it is not always the Object listening for the event. Use the * <code>currentTarget</code> property to always access the Object * listening for the event.</td></tr> * </table> * * @eventType feathers.events.FeathersEventType.ENTER * @see #returnKeyLabel */ [Event(name="enter",type="starling.events.Event")] /** * Dispatched when the text editor receives focus. * * <p>The properties of the event object have the following values:</p> * <table class="innertable"> * <tr><th>Property</th><th>Value</th></tr> * <tr><td><code>bubbles</code></td><td>false</td></tr> * <tr><td><code>currentTarget</code></td><td>The Object that defines the * event listener that handles the event. For example, if you use * <code>myButton.addEventListener()</code> to register an event listener, * myButton is the value of the <code>currentTarget</code>.</td></tr> * <tr><td><code>data</code></td><td>null</td></tr> * <tr><td><code>target</code></td><td>The Object that dispatched the event; * it is not always the Object listening for the event. Use the * <code>currentTarget</code> property to always access the Object * listening for the event.</td></tr> * </table> * * @eventType feathers.events.FeathersEventType.FOCUS_IN */ [Event(name="focusIn",type="starling.events.Event")] /** * Dispatched when the text editor loses focus. * * <p>The properties of the event object have the following values:</p> * <table class="innertable"> * <tr><th>Property</th><th>Value</th></tr> * <tr><td><code>bubbles</code></td><td>false</td></tr> * <tr><td><code>currentTarget</code></td><td>The Object that defines the * event listener that handles the event. For example, if you use * <code>myButton.addEventListener()</code> to register an event listener, * myButton is the value of the <code>currentTarget</code>.</td></tr> * <tr><td><code>data</code></td><td>null</td></tr> * <tr><td><code>target</code></td><td>The Object that dispatched the event; * it is not always the Object listening for the event. Use the * <code>currentTarget</code> property to always access the Object * listening for the event.</td></tr> * </table> * * @eventType feathers.events.FeathersEventType.FOCUS_OUT */ [Event(name="focusOut",type="starling.events.Event")] /** * Dispatched when the soft keyboard is activated. Not all text editors will * activate a soft keyboard. * * <p>The properties of the event object have the following values:</p> * <table class="innertable"> * <tr><th>Property</th><th>Value</th></tr> * <tr><td><code>bubbles</code></td><td>false</td></tr> * <tr><td><code>currentTarget</code></td><td>The Object that defines the * event listener that handles the event. For example, if you use * <code>myButton.addEventListener()</code> to register an event listener, * myButton is the value of the <code>currentTarget</code>.</td></tr> * <tr><td><code>data</code></td><td>null</td></tr> * <tr><td><code>target</code></td><td>The Object that dispatched the event; * it is not always the Object listening for the event. Use the * <code>currentTarget</code> property to always access the Object * listening for the event.</td></tr> * </table> * * @eventType feathers.events.FeathersEventType.SOFT_KEYBOARD_ACTIVATE */ [Event(name="softKeyboardActivate",type="starling.events.Event")] /** * Dispatched when the soft keyboard is deactivated. Not all text editors * will activate a soft keyboard. * * <p>The properties of the event object have the following values:</p> * <table class="innertable"> * <tr><th>Property</th><th>Value</th></tr> * <tr><td><code>bubbles</code></td><td>false</td></tr> * <tr><td><code>currentTarget</code></td><td>The Object that defines the * event listener that handles the event. For example, if you use * <code>myButton.addEventListener()</code> to register an event listener, * myButton is the value of the <code>currentTarget</code>.</td></tr> * <tr><td><code>data</code></td><td>null</td></tr> * <tr><td><code>target</code></td><td>The Object that dispatched the event; * it is not always the Object listening for the event. Use the * <code>currentTarget</code> property to always access the Object * listening for the event.</td></tr> * </table> * * @eventType feathers.events.FeathersEventType.SOFT_KEYBOARD_DEACTIVATE */ [Event(name="softKeyboardDeactivate",type="starling.events.Event")] /** * Text that may be edited at runtime by the user with the * <code>TextInput</code> component, rendered with the native * <code>flash.text.StageText</code> class in Adobe AIR and the custom * <code>feathers.text.StageTextField</code> class in Adobe Flash Player * (<code>StageTextField</code> simulates <code>StageText</code> using * <code>flash.text.TextField</code>). When not in focus, the * <code>StageText</code> (or <code>StageTextField</code>) is drawn to * <code>BitmapData</code> and uploaded to a texture on the GPU. Textures * are managed internally by this component, and they will be automatically * disposed when the component is disposed. * * <p>The following example shows how to use * <code>StageTextTextEditor</code> with a <code>TextInput</code>:</p> * * <listing version="3.0"> * var input:TextInput = new TextInput(); * input.textEditorFactory = function():ITextEditor * { * return new StageTextTextEditor(); * }; * this.addChild( input );</listing> * * @see feathers.controls.TextInput * @see ../../../../help/text-editors.html Introduction to Feathers text editors * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/StageText.html flash.text.StageText * @see feathers.text.StageTextField */ public class StageTextTextEditor extends FeathersControl implements IMultilineTextEditor { /** * @private */ private static var HELPER_MATRIX3D:Matrix3D; /** * @private */ private static var HELPER_POINT3D:Vector3D; /** * @private */ private static const HELPER_MATRIX:Matrix = new Matrix(); /** * @private */ private static const HELPER_POINT:Point = new Point(); /** * The default <code>IStyleProvider</code> for all <code>StageTextTextEditor</code> * components. * * @default null * @see feathers.core.FeathersControl#styleProvider */ public static var globalStyleProvider:IStyleProvider; /** * Constructor. */ public function StageTextTextEditor() { this._stageTextIsTextField = /^(Windows|Mac OS|Linux) .*/.exec(Capabilities.os); this.isQuickHitAreaEnabled = true; this.addEventListener(starling.events.Event.REMOVED_FROM_STAGE, textEditor_removedFromStageHandler); } /** * @private */ override protected function get defaultStyleProvider():IStyleProvider { return globalStyleProvider; } /** * The StageText instance. It's typed Object so that a replacement class * can be used in browser-based Flash Player. */ protected var stageText:Object; /** * An image that displays a snapshot of the native <code>StageText</code> * in the Starling display list when the editor doesn't have focus. */ protected var textSnapshot:Image; /** * @private */ protected var _needsNewTexture:Boolean = false; /** * @private */ protected var _ignoreStageTextChanges:Boolean = false; /** * @private */ protected var _text:String = ""; /** * The text displayed by the input. * * <p>In the following example, the text is changed:</p> * * <listing version="3.0"> * textEditor.text = "Lorem ipsum";</listing> * * @default "" */ public function get text():String { return this._text; } /** * @private */ public function set text(value:String):void { if(!value) { //don't allow null or undefined value = ""; } if(this._text == value) { return; } this._text = value; this.invalidate(INVALIDATION_FLAG_DATA); this.dispatchEventWith(starling.events.Event.CHANGE); } /** * @private */ protected var _measureTextField:TextField; /** * @private * This flag tells us if StageText is implemented by a TextField under * the hood. We want to eliminate that damn TextField gutter to improve * consistency across platforms. */ protected var _stageTextIsTextField:Boolean = false; /** * @private */ protected var _stageTextHasFocus:Boolean = false; /** * @private */ protected var _isWaitingToSetFocus:Boolean = false; /** * @private */ protected var _pendingSelectionBeginIndex:int = -1; /** * @inheritDoc */ public function get selectionBeginIndex():int { if(this._pendingSelectionBeginIndex >= 0) { return this._pendingSelectionBeginIndex; } if(this.stageText) { return this.stageText.selectionAnchorIndex; } return 0; } /** * @private */ protected var _pendingSelectionEndIndex:int = -1; /** * @inheritDoc */ public function get selectionEndIndex():int { if(this._pendingSelectionEndIndex >= 0) { return this._pendingSelectionEndIndex; } if(this.stageText) { return this.stageText.selectionActiveIndex; } return 0; } /** * @private */ protected var _stageTextIsComplete:Boolean = false; /** * @inheritDoc */ public function get baseline():Number { if(!this._measureTextField) { return 0; } return this._measureTextField.getLineMetrics(0).ascent; } /** * @private */ protected var _autoCapitalize:String = "none"; /** * Controls how a device applies auto capitalization to user input. This * property is only a hint to the underlying platform, because not all * devices and operating systems support this functionality. * * <p>In the following example, the auto capitalize behavior is changed:</p> * * <listing version="3.0"> * textEditor.autoCapitalize = AutoCapitalize.WORD;</listing> * * @default flash.text.AutoCapitalize.NONE * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/StageText.html#autoCapitalize Full description of flash.text.StageText.autoCapitalize in Adobe's Flash Platform API Reference */ public function get autoCapitalize():String { return this._autoCapitalize; } /** * @private */ public function set autoCapitalize(value:String):void { if(this._autoCapitalize == value) { return; } this._autoCapitalize = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _autoCorrect:Boolean = false; /** * Indicates whether a device auto-corrects user input for spelling or * punctuation mistakes. This property is only a hint to the underlying * platform, because not all devices and operating systems support this * functionality. * * <p>In the following example, auto correct is enabled:</p> * * <listing version="3.0"> * textEditor.autoCorrect = true;</listing> * * @default false * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/StageText.html#autoCorrect Full description of flash.text.StageText.autoCorrect in Adobe's Flash Platform API Reference */ public function get autoCorrect():Boolean { return this._autoCorrect; } /** * @private */ public function set autoCorrect(value:Boolean):void { if(this._autoCorrect == value) { return; } this._autoCorrect = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _color:uint = 0x000000; /** * Specifies text color as a number containing three 8-bit RGB * components. * * <p>In the following example, the text color is changed:</p> * * <listing version="3.0"> * textEditor.color = 0xff9900;</listing> * * @default 0x000000 * * @see #disabledColor * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/StageText.html#color Full description of flash.text.StageText.color in Adobe's Flash Platform API Reference */ public function get color():uint { return this._color; } /** * @private */ public function set color(value:uint):void { if(this._color == value) { return; } this._color = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _disabledColor:uint = 0x999999; /** * Specifies text color when the component is disabled as a number * containing three 8-bit RGB components. * * <p>In the following example, the text color is changed:</p> * * <listing version="3.0"> * textEditor.isEnabled = false; * textEditor.disabledColor = 0xff9900;</listing> * * @default 0x999999 * * @see #disabledColor * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/StageText.html#color Full description of flash.text.StageText.color in Adobe's Flash Platform API Reference */ public function get disabledColor():uint { return this._disabledColor; } /** * @private */ public function set disabledColor(value:uint):void { if(this._disabledColor == value) { return; } this._disabledColor = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _displayAsPassword:Boolean = false; /** * <p>This property is managed by the <code>TextInput</code>.</p> * * @copy feathers.controls.TextInput#displayAsPassword * * @see feathers.controls.TextInput#displayAsPassword * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/StageText.html#displayAsPassword Full description of flash.text.StageText.displayAsPassword in Adobe's Flash Platform API Reference */ public function get displayAsPassword():Boolean { return this._displayAsPassword; } /** * @private */ public function set displayAsPassword(value:Boolean):void { if(this._displayAsPassword == value) { return; } this._displayAsPassword = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _isEditable:Boolean = true; /** * <p>This property is managed by the <code>TextInput</code>.</p> * * @copy feathers.controls.TextInput#isEditable * * @see feathers.controls.TextInput#isEditable */ public function get isEditable():Boolean { return this._isEditable; } /** * @private */ public function set isEditable(value:Boolean):void { if(this._isEditable == value) { return; } this._isEditable = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _isSelectable:Boolean = true; /** * <p>This property is managed by the <code>TextInput</code>.</p> * * @copy feathers.controls.TextInput#isSelectable * * @see feathers.controls.TextInput#isSelectable */ public function get isSelectable():Boolean { return this._isEditable; } /** * @private */ public function set isSelectable(value:Boolean):void { if(this._isSelectable == value) { return; } this._isSelectable = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @inheritDoc * * @default true */ public function get setTouchFocusOnEndedPhase():Boolean { return true; } /** * @private */ protected var _fontFamily:String = null; /** * Indicates the name of the current font family. A value of null * indicates the system default. * * <p>In the following example, the font family is changed:</p> * * <listing version="3.0"> * textEditor.fontFamily = "Source Sans Pro";</listing> * * @default null * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/StageText.html#fontFamily Full description of flash.text.StageText.fontFamily in Adobe's Flash Platform API Reference */ public function get fontFamily():String { return this._fontFamily; } /** * @private */ public function set fontFamily(value:String):void { if(this._fontFamily == value) { return; } this._fontFamily = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _fontPosture:String = FontPosture.NORMAL; /** * Specifies the font posture, using constants defined in the * <code>flash.text.engine.FontPosture</code> class. * * <p>In the following example, the font posture is changed:</p> * * <listing version="3.0"> * textEditor.fontPosture = FontPosture.ITALIC;</listing> * * @default flash.text.engine.FontPosture.NORMAL * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/StageText.html#fontPosture Full description of flash.text.StageText.fontPosture in Adobe's Flash Platform API Reference * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/engine/FontPosture.html flash.text.engine.FontPosture */ public function get fontPosture():String { return this._fontPosture; } /** * @private */ public function set fontPosture(value:String):void { if(this._fontPosture == value) { return; } this._fontPosture = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _fontSize:int = 12; /** * The size in pixels for the current font family. * * <p>In the following example, the font size is increased to 16 pixels:</p> * * <listing version="3.0"> * textEditor.fontSize = 16;</listing> * * @default 12 * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/StageText.html#fontSize Full description of flash.text.StageText.fontSize in Adobe's Flash Platform API Reference */ public function get fontSize():int { return this._fontSize; } /** * @private */ public function set fontSize(value:int):void { if(this._fontSize == value) { return; } this._fontSize = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _fontWeight:String = FontWeight.NORMAL; /** * Specifies the font weight, using constants defined in the * <code>flash.text.engine.FontWeight</code> class. * * <p>In the following example, the font weight is changed to bold:</p> * * <listing version="3.0"> * textEditor.fontWeight = FontWeight.BOLD;</listing> * * @default flash.text.engine.FontWeight.NORMAL * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/StageText.html#fontWeight Full description of flash.text.StageText.fontWeight in Adobe's Flash Platform API Reference * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/engine/FontWeight.html flash.text.engine.FontWeight */ public function get fontWeight():String { return this._fontWeight; } /** * @private */ public function set fontWeight(value:String):void { if(this._fontWeight == value) { return; } this._fontWeight = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _locale:String = "en"; /** * Indicates the locale of the text. <code>StageText</code> uses the * standard locale identifiers. For example <code>"en"</code>, * <code>"en_US"</code> and <code>"en-US"</code> are all English. * * <p>In the following example, the locale is changed to Russian:</p> * * <listing version="3.0"> * textEditor.locale = "ru";</listing> * * @default "en" * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/StageText.html#locale Full description of flash.text.StageText.locale in Adobe's Flash Platform API Reference */ public function get locale():String { return this._locale; } /** * @private */ public function set locale(value:String):void { if(this._locale == value) { return; } this._locale = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _maxChars:int = 0; /** * <p>This property is managed by the <code>TextInput</code>.</p> * * @copy feathers.controls.TextInput#maxChars * * @see feathers.controls.TextInput#maxChars * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/StageText.html#maxChars Full description of flash.text.StageText.maxChars in Adobe's Flash Platform API Reference */ public function get maxChars():int { return this._maxChars; } /** * @private */ public function set maxChars(value:int):void { if(this._maxChars == value) { return; } this._maxChars = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _multiline:Boolean = false; /** * Indicates whether the StageText object can display more than one line * of text. This property is configurable after the text editor is * created, unlike a regular <code>StageText</code> instance. The text * editor will dispose and recreate its internal <code>StageText</code> * instance if the value of the <code>multiline</code> property is * changed after the <code>StageText</code> is initially created. * * <p>In the following example, multiline is enabled:</p> * * <listing version="3.0"> * textEditor.multiline = true;</listing> * * When setting this property to <code>true</code>, it is recommended * that the text input's <code>verticalAlign</code> property is set to * <code>TextInput.VERTICAL_ALIGN_JUSTIFY</code>. * * @default false * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/StageText.html#multiline Full description of flash.text.StageText.multiline in Adobe's Flash Platform API Reference */ public function get multiline():Boolean { return this._multiline; } /** * @private */ public function set multiline(value:Boolean):void { if(this._multiline == value) { return; } this._multiline = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _restrict:String; /** * <p>This property is managed by the <code>TextInput</code>.</p> * * @copy feathers.controls.TextInput#restrict * * @see feathers.controls.TextInput#restrict * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/StageText.html#restrict Full description of flash.text.StageText.restrict in Adobe's Flash Platform API Reference */ public function get restrict():String { return this._restrict; } /** * @private */ public function set restrict(value:String):void { if(this._restrict == value) { return; } this._restrict = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _returnKeyLabel:String = "default"; /** * Indicates the label on the Return key for devices that feature a soft * keyboard. The available values are constants defined in the * <code>flash.text.ReturnKeyLabel</code> class. This property is only a * hint to the underlying platform, because not all devices and * operating systems support this functionality. * * <p>In the following example, the return key label is changed:</p> * * <listing version="3.0"> * textEditor.returnKeyLabel = ReturnKeyLabel.GO;</listing> * * @default flash.text.ReturnKeyLabel.DEFAULT * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/StageText.html#returnKeyLabel Full description of flash.text.StageText.returnKeyLabel in Adobe's Flash Platform API Reference * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/ReturnKeyLabel.html flash.text.ReturnKeyLabel */ public function get returnKeyLabel():String { return this._returnKeyLabel; } /** * @private */ public function set returnKeyLabel(value:String):void { if(this._returnKeyLabel == value) { return; } this._returnKeyLabel = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _softKeyboardType:String = "default"; /** * Controls the appearance of the soft keyboard. Valid values are * defined as constants in the <code>flash.text.SoftKeyboardType</code> * class. This property is only a hint to the underlying platform, * because not all devices and operating systems support this * functionality. * * <p>In the following example, the soft keyboard type is changed:</p> * * <listing version="3.0"> * textEditor.softKeyboardType = SoftKeyboardType.NUMBER;</listing> * * @default flash.text.SoftKeyboardType.DEFAULT * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/StageText.html#softKeyboardType Full description of flash.text.StageText.softKeyboardType in Adobe's Flash Platform API Reference * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/SoftKeyboardType.html flash.text.SoftKeyboardType */ public function get softKeyboardType():String { return this._softKeyboardType; } /** * @private */ public function set softKeyboardType(value:String):void { if(this._softKeyboardType == value) { return; } this._softKeyboardType = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _textAlign:String = TextFormatAlign.START; /** * Indicates the paragraph alignment. Valid values are defined as * constants in the <code>flash.text.TextFormatAlign</code> class. * * <p>In the following example, the text is centered:</p> * * <listing version="3.0"> * textEditor.textAlign = TextFormatAlign.CENTER;</listing> * * @default flash.text.TextFormatAlign.START * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/StageText.html#textAlign Full description of flash.text.StageText.textAlign in Adobe's Flash Platform API Reference * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/TextFormatAlign.html flash.text.TextFormatAlign */ public function get textAlign():String { return this._textAlign; } /** * @private */ public function set textAlign(value:String):void { if(this._textAlign == value) { return; } this._textAlign = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _lastGlobalScaleX:Number = 0; /** * @private */ protected var _lastGlobalScaleY:Number = 0; /** * @private */ protected var _updateSnapshotOnScaleChange:Boolean = false; /** * Refreshes the texture snapshot every time that the text editor is * scaled. Based on the scale in global coordinates, so scaling the * parent will require a new snapshot. * * <p>Warning: setting this property to true may result in reduced * performance because every change of the scale requires uploading a * new texture to the GPU. Use with caution. Consider setting this * property to false temporarily during animations that modify the * scale.</p> * * <p>In the following example, the snapshot will be updated when the * text editor is scaled:</p> * * <listing version="3.0"> * textEditor.updateSnapshotOnScaleChange = true;</listing> * * @default false */ public function get updateSnapshotOnScaleChange():Boolean { return this._updateSnapshotOnScaleChange; } /** * @private */ public function set updateSnapshotOnScaleChange(value:Boolean):void { if(this._updateSnapshotOnScaleChange == value) { return; } this._updateSnapshotOnScaleChange = value; this.invalidate(INVALIDATION_FLAG_DATA); } /** * @private */ override public function dispose():void { if(this._measureTextField) { Starling.current.nativeStage.removeChild(this._measureTextField); this._measureTextField = null; } if(this.stageText) { this.disposeStageText(); } if(this.textSnapshot) { //avoid the need to call dispose(). we'll create a new snapshot //when the renderer is added to stage again. this.textSnapshot.texture.dispose(); this.removeChild(this.textSnapshot, true); this.textSnapshot = null; } super.dispose(); } /** * @private */ override public function render(support:RenderSupport, parentAlpha:Number):void { if(this.textSnapshot && this._updateSnapshotOnScaleChange) { this.getTransformationMatrix(this.stage, HELPER_MATRIX); if(matrixToScaleX(HELPER_MATRIX) != this._lastGlobalScaleX || matrixToScaleY(HELPER_MATRIX) != this._lastGlobalScaleY) { //the snapshot needs to be updated because the scale has //changed since the last snapshot was taken. this.invalidate(INVALIDATION_FLAG_SIZE); this.validate(); } } //we'll skip this if the text field isn't visible to avoid running //that code every frame. if(this.stageText && this.stageText.visible) { this.refreshViewPortAndFontSize(); } if(this.textSnapshot) { this.positionSnapshot(); } super.render(support, parentAlpha); } /** * @inheritDoc */ public function setFocus(position:Point = null):void { //setting the editable property of a StageText to false seems to be //ignored on Android, so this is the workaround if(!this._isEditable && SystemUtil.platform === "AND") { return; } if(!this._isEditable && !this._isSelectable) { return; } if(this.stage && !this.stageText.stage) { this.stageText.stage = Starling.current.nativeStage; } if(this.stageText && this._stageTextIsComplete) { if(position) { var positionX:Number = position.x + 2; var positionY:Number = position.y + 2; if(positionX < 0) { this._pendingSelectionBeginIndex = this._pendingSelectionEndIndex = 0; } else { this._pendingSelectionBeginIndex = this._measureTextField.getCharIndexAtPoint(positionX, positionY); if(this._pendingSelectionBeginIndex < 0) { if(this._multiline) { var lineIndex:int = int(positionY / this._measureTextField.getLineMetrics(0).height); try { this._pendingSelectionBeginIndex = this._measureTextField.getLineOffset(lineIndex) + this._measureTextField.getLineLength(lineIndex); if(this._pendingSelectionBeginIndex != this._text.length) { this._pendingSelectionBeginIndex--; } } catch(error:Error) { //we may be checking for a line beyond the //end that doesn't exist this._pendingSelectionBeginIndex = this._text.length; } } else { this._pendingSelectionBeginIndex = this._measureTextField.getCharIndexAtPoint(positionX, this._measureTextField.getLineMetrics(0).ascent / 2); if(this._pendingSelectionBeginIndex < 0) { this._pendingSelectionBeginIndex = this._text.length; } } } else { var bounds:Rectangle = this._measureTextField.getCharBoundaries(this._pendingSelectionBeginIndex); var boundsX:Number = bounds.x; if(bounds && (boundsX + bounds.width - positionX) < (positionX - boundsX)) { this._pendingSelectionBeginIndex++; } } this._pendingSelectionEndIndex = this._pendingSelectionBeginIndex; } } else { this._pendingSelectionBeginIndex = this._pendingSelectionEndIndex = -1; } this.stageText.visible = true; this.stageText.assignFocus(); } else { this._isWaitingToSetFocus = true; } } /** * @inheritDoc */ public function clearFocus():void { if(!this._stageTextHasFocus) { return; } //setting the focus to Starling.current.nativeStage doesn't work //here, so we need to use null. on Android, if we give focus to the //nativeStage, focus will be removed from the StageText, but the //soft keyboard will incorrectly remain open. Starling.current.nativeStage.focus = null; } /** * @inheritDoc */ public function selectRange(beginIndex:int, endIndex:int):void { if(this._stageTextIsComplete && this.stageText) { this._pendingSelectionBeginIndex = -1; this._pendingSelectionEndIndex = -1; this.stageText.selectRange(beginIndex, endIndex); } else { this._pendingSelectionBeginIndex = beginIndex; this._pendingSelectionEndIndex = endIndex; } } /** * @inheritDoc */ public function measureText(result:Point = null):Point { if(!result) { result = new Point(); } var needsWidth:Boolean = this.explicitWidth !== this.explicitWidth; //isNaN var needsHeight:Boolean = this.explicitHeight !== this.explicitHeight; //isNaN if(!needsWidth && !needsHeight) { result.x = this.explicitWidth; result.y = this.explicitHeight; return result; } //if a parent component validates before we're added to the stage, //measureText() may be called before initialization, so we need to //force it. if(!this._isInitialized) { this.initializeInternal(); } var stylesInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STYLES); var dataInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_DATA); if(stylesInvalid || dataInvalid) { this.refreshMeasureProperties(); } result = this.measure(result); return result; } /** * @private */ override protected function initialize():void { if(this._measureTextField && !this._measureTextField.parent) { Starling.current.nativeStage.addChild(this._measureTextField); } else if(!this._measureTextField) { this._measureTextField = new TextField(); this._measureTextField.visible = false; this._measureTextField.mouseEnabled = this._measureTextField.mouseWheelEnabled = false; this._measureTextField.autoSize = TextFieldAutoSize.LEFT; this._measureTextField.multiline = false; this._measureTextField.wordWrap = false; this._measureTextField.embedFonts = false; this._measureTextField.defaultTextFormat = new TextFormat(null, 11, 0x000000, false, false, false); Starling.current.nativeStage.addChild(this._measureTextField); } this.createStageText(); } /** * @private */ override protected function draw():void { var sizeInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_SIZE); this.commit(); sizeInvalid = this.autoSizeIfNeeded() || sizeInvalid; this.layout(sizeInvalid); } /** * @private */ protected function commit():void { var stateInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STATE); var stylesInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STYLES); var dataInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_DATA); if(stylesInvalid || dataInvalid) { this.refreshMeasureProperties(); } var oldIgnoreStageTextChanges:Boolean = this._ignoreStageTextChanges; this._ignoreStageTextChanges = true; if(stateInvalid || stylesInvalid) { this.refreshStageTextProperties(); } if(dataInvalid) { if(this.stageText.text != this._text) { if(this._pendingSelectionBeginIndex < 0) { this._pendingSelectionBeginIndex = this.stageText.selectionActiveIndex; this._pendingSelectionEndIndex = this.stageText.selectionAnchorIndex; } this.stageText.text = this._text; } } this._ignoreStageTextChanges = oldIgnoreStageTextChanges; if(stylesInvalid || stateInvalid) { this.stageText.editable = this._isEditable && this._isEnabled; } } /** * @private */ protected function measure(result:Point = null):Point { if(!result) { result = new Point(); } var needsWidth:Boolean = this.explicitWidth !== this.explicitWidth; //isNaN var needsHeight:Boolean = this.explicitHeight !== this.explicitHeight; //isNaN this._measureTextField.autoSize = TextFieldAutoSize.LEFT; var newWidth:Number = this.explicitWidth; if(needsWidth) { newWidth = this._measureTextField.textWidth; if(newWidth < this._minWidth) { newWidth = this._minWidth; } else if(newWidth > this._maxWidth) { newWidth = this._maxWidth; } } //the +4 is accounting for the TextField gutter this._measureTextField.width = newWidth + 4; var newHeight:Number = this.explicitHeight; if(needsHeight) { //since we're measuring with TextField, but rendering with //StageText, we're using height instead of textHeight here to be //sure that the measured size is on the larger side, in case the //rendered size is actually bigger than textHeight //if only StageText had an API for text measurement, we wouldn't //be in this mess... newHeight = this._measureTextField.height; if(newHeight < this._minHeight) { newHeight = this._minHeight; } else if(newHeight > this._maxHeight) { newHeight = this._maxHeight; } } this._measureTextField.autoSize = TextFieldAutoSize.NONE; //put the width and height back just in case we measured without //a full validation //the +4 is accounting for the TextField gutter this._measureTextField.width = this.actualWidth + 4; this._measureTextField.height = this.actualHeight; result.x = newWidth; result.y = newHeight; return result; } /** * @private */ protected function layout(sizeInvalid:Boolean):void { var stateInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STATE); var stylesInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STYLES); var dataInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_DATA); var skinInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_SKIN); if(sizeInvalid || stylesInvalid || skinInvalid || stateInvalid) { this.refreshViewPortAndFontSize(); this.refreshMeasureTextFieldDimensions() var viewPort:Rectangle = this.stageText.viewPort; var textureRoot:ConcreteTexture = this.textSnapshot ? this.textSnapshot.texture.root : null; this._needsNewTexture = this._needsNewTexture || !this.textSnapshot || textureRoot.scale != Starling.contentScaleFactor || viewPort.width != textureRoot.width || viewPort.height != textureRoot.height; } if(!this._stageTextHasFocus && (stateInvalid || stylesInvalid || dataInvalid || sizeInvalid || this._needsNewTexture)) { var hasText:Boolean = this._text.length > 0; if(hasText) { this.refreshSnapshot(); } if(this.textSnapshot) { this.textSnapshot.visible = !this._stageTextHasFocus; this.textSnapshot.alpha = hasText ? 1 : 0; } this.stageText.visible = false; } this.doPendingActions(); } /** * If the component's dimensions have not been set explicitly, it will * measure its content and determine an ideal size for itself. If the * <code>explicitWidth</code> or <code>explicitHeight</code> member * variables are set, those value will be used without additional * measurement. If one is set, but not the other, the dimension with the * explicit value will not be measured, but the other non-explicit * dimension will still need measurement. * * <p>Calls <code>setSizeInternal()</code> to set up the * <code>actualWidth</code> and <code>actualHeight</code> member * variables used for layout.</p> * * <p>Meant for internal use, and subclasses may override this function * with a custom implementation.</p> */ protected function autoSizeIfNeeded():Boolean { var needsWidth:Boolean = this.explicitWidth !== this.explicitWidth; //isNaN var needsHeight:Boolean = this.explicitHeight !== this.explicitHeight; //isNaN if(!needsWidth && !needsHeight) { return false; } this.measure(HELPER_POINT); return this.setSizeInternal(HELPER_POINT.x, HELPER_POINT.y, false); } /** * @private */ protected function refreshMeasureProperties():void { var nativeScaleFactor:Number = 1; if(Starling.current.supportHighResolutions) { nativeScaleFactor = Starling.current.nativeStage.contentsScaleFactor; } this._measureTextField.displayAsPassword = this._displayAsPassword; this._measureTextField.maxChars = this._maxChars; this._measureTextField.restrict = this._restrict; this._measureTextField.multiline = this._measureTextField.wordWrap = this._multiline; var format:TextFormat = this._measureTextField.defaultTextFormat; format.color = this._color; format.font = this._fontFamily; format.italic = this._fontPosture == FontPosture.ITALIC; format.size = this._fontSize * nativeScaleFactor; format.bold = this._fontWeight == FontWeight.BOLD; var alignValue:String = this._textAlign; if(alignValue == TextFormatAlign.START) { alignValue = TextFormatAlign.LEFT; } else if(alignValue == TextFormatAlign.END) { alignValue = TextFormatAlign.RIGHT; } format.align = alignValue; this._measureTextField.defaultTextFormat = format; this._measureTextField.setTextFormat(format); if(this._text.length == 0) { this._measureTextField.text = " "; } else { this._measureTextField.text = this._text; } } /** * @private */ protected function refreshStageTextProperties():void { if(this.stageText.multiline != this._multiline) { if(this.stageText) { this.disposeStageText(); } this.createStageText(); } this.stageText.autoCapitalize = this._autoCapitalize; this.stageText.autoCorrect = this._autoCorrect; if(this._isEnabled) { this.stageText.color = this._color; } else { this.stageText.color = this._disabledColor; } this.stageText.displayAsPassword = this._displayAsPassword; this.stageText.fontFamily = this._fontFamily; this.stageText.fontPosture = this._fontPosture; this.stageText.fontWeight = this._fontWeight; this.stageText.locale = this._locale; this.stageText.maxChars = this._maxChars; this.stageText.restrict = this._restrict; this.stageText.returnKeyLabel = this._returnKeyLabel; this.stageText.softKeyboardType = this._softKeyboardType; this.stageText.textAlign = this._textAlign; } /** * @private */ protected function doPendingActions():void { if(this._isWaitingToSetFocus) { this._isWaitingToSetFocus = false; this.setFocus(); } if(this._pendingSelectionBeginIndex >= 0) { var startIndex:int = this._pendingSelectionBeginIndex; var endIndex:int = (this._pendingSelectionEndIndex < 0) ? this._pendingSelectionBeginIndex : this._pendingSelectionEndIndex; this._pendingSelectionBeginIndex = -1; this._pendingSelectionEndIndex = -1; if(this.stageText.selectionAnchorIndex != startIndex || this.stageText.selectionActiveIndex != endIndex) { //if the same range is already selected, don't try to do it //again because on iOS, if the StageText is multiline, this //will cause the clipboard menu to appear when it shouldn't. this.selectRange(startIndex, endIndex); } } } /** * @private */ protected function texture_onRestore():void { if(this.textSnapshot.texture.scale != Starling.contentScaleFactor) { //if we've changed between scale factors, we need to recreate //the texture to match the new scale factor. this.invalidate(INVALIDATION_FLAG_SIZE); } else { this.refreshSnapshot(); if(this.textSnapshot) { this.textSnapshot.visible = !this._stageTextHasFocus; this.textSnapshot.alpha = this._text.length > 0 ? 1 : 0; } if(!this._stageTextHasFocus) { this.stageText.visible = false; } } } /** * @private */ protected function refreshSnapshot():void { //StageText's stage property cannot be null when we call //drawViewPortToBitmapData() if(this.stage && !this.stageText.stage) { this.stageText.stage = Starling.current.nativeStage; } if(!this.stageText.stage) { //we need to keep a flag active so that the snapshot will be //refreshed after the text editor is added to the stage this.invalidate(INVALIDATION_FLAG_DATA); return; } var viewPort:Rectangle = this.stageText.viewPort; if(viewPort.width == 0 || viewPort.height == 0) { return; } var nativeScaleFactor:Number = 1; if(Starling.current.supportHighResolutions) { nativeScaleFactor = Starling.current.nativeStage.contentsScaleFactor; } //StageText sucks because it requires that the BitmapData's width //and height exactly match its view port width and height. //(may be doubled on Retina Mac) try { var bitmapData:BitmapData = new BitmapData(viewPort.width * nativeScaleFactor, viewPort.height * nativeScaleFactor, true, 0x00ff00ff); this.stageText.drawViewPortToBitmapData(bitmapData); } catch(error:Error) { //drawing stage text to the bitmap data at double size may fail //on runtime versions less than 15, so fall back to using a //snapshot that is half size. it's not ideal, but better than //nothing. bitmapData.dispose(); bitmapData = new BitmapData(viewPort.width, viewPort.height, true, 0x00ff00ff); this.stageText.drawViewPortToBitmapData(bitmapData); } var newTexture:Texture; if(!this.textSnapshot || this._needsNewTexture) { var scaleFactor:Number = Starling.contentScaleFactor; //skip Texture.fromBitmapData() because we don't want //it to create an onRestore function that will be //immediately discarded for garbage collection. newTexture = Texture.empty(bitmapData.width / scaleFactor, bitmapData.height / scaleFactor, true, false, false, scaleFactor); newTexture.root.uploadBitmapData(bitmapData); newTexture.root.onRestore = texture_onRestore; } if(!this.textSnapshot) { this.textSnapshot = new Image(newTexture); this.addChild(this.textSnapshot); } else { if(this._needsNewTexture) { this.textSnapshot.texture.dispose(); this.textSnapshot.texture = newTexture; this.textSnapshot.readjustSize(); } else { //this is faster, if we haven't resized the bitmapdata var existingTexture:Texture = this.textSnapshot.texture; existingTexture.root.uploadBitmapData(bitmapData); } } this.getTransformationMatrix(this.stage, HELPER_MATRIX); var globalScaleX:Number = matrixToScaleX(HELPER_MATRIX); var globalScaleY:Number = matrixToScaleY(HELPER_MATRIX); if(this._updateSnapshotOnScaleChange) { this.textSnapshot.scaleX = 1 / globalScaleX; this.textSnapshot.scaleY = 1 / globalScaleY; this._lastGlobalScaleX = globalScaleX; this._lastGlobalScaleY = globalScaleY; } else { this.textSnapshot.scaleX = 1; this.textSnapshot.scaleY = 1; } if(nativeScaleFactor > 1 && bitmapData.width == viewPort.width) { //when we fall back to using a snapshot that is half size on //older runtimes, we need to scale it up. this.textSnapshot.scaleX *= nativeScaleFactor; this.textSnapshot.scaleY *= nativeScaleFactor; } bitmapData.dispose(); this._needsNewTexture = false; } /** * @private */ protected function refreshViewPortAndFontSize():void { HELPER_POINT.x = HELPER_POINT.y = 0; var desktopGutterPositionOffset:Number = 0; var desktopGutterDimensionsOffset:Number = 0; if(this._stageTextIsTextField) { desktopGutterPositionOffset = 2; desktopGutterDimensionsOffset = 4; } this.getTransformationMatrix(this.stage, HELPER_MATRIX); if(this._stageTextHasFocus || this._updateSnapshotOnScaleChange) { var globalScaleX:Number = matrixToScaleX(HELPER_MATRIX); var globalScaleY:Number = matrixToScaleY(HELPER_MATRIX); var smallerGlobalScale:Number = globalScaleX; if(globalScaleY < smallerGlobalScale) { smallerGlobalScale = globalScaleY; } } else { globalScaleX = 1; globalScaleY = 1; smallerGlobalScale = 1; } if(this.is3D) { HELPER_MATRIX3D = this.getTransformationMatrix3D(this.stage, HELPER_MATRIX3D); HELPER_POINT3D = MatrixUtil.transformCoords3D(HELPER_MATRIX3D, -desktopGutterPositionOffset, -desktopGutterPositionOffset, 0, HELPER_POINT3D); HELPER_POINT.setTo(HELPER_POINT3D.x, HELPER_POINT3D.y); } else { MatrixUtil.transformCoords(HELPER_MATRIX, -desktopGutterPositionOffset, -desktopGutterPositionOffset, HELPER_POINT); } var nativeScaleFactor:Number = 1; if(Starling.current.supportHighResolutions) { nativeScaleFactor = Starling.current.nativeStage.contentsScaleFactor; } var scaleFactor:Number = Starling.contentScaleFactor / nativeScaleFactor; var starlingViewPort:Rectangle = Starling.current.viewPort; var stageTextViewPort:Rectangle = this.stageText.viewPort; if(!stageTextViewPort) { stageTextViewPort = new Rectangle(); } stageTextViewPort.x = Math.round(starlingViewPort.x + HELPER_POINT.x * scaleFactor); stageTextViewPort.y = Math.round(starlingViewPort.y + HELPER_POINT.y * scaleFactor); var viewPortWidth:Number = Math.round((this.actualWidth + desktopGutterDimensionsOffset) * scaleFactor * globalScaleX); if(viewPortWidth < 1 || viewPortWidth !== viewPortWidth) //isNaN { viewPortWidth = 1; } var viewPortHeight:Number = Math.round((this.actualHeight + desktopGutterDimensionsOffset) * scaleFactor * globalScaleY); if(viewPortHeight < 1 || viewPortHeight !== viewPortHeight) //isNaN { viewPortHeight = 1; } stageTextViewPort.width = viewPortWidth; stageTextViewPort.height = viewPortHeight; this.stageText.viewPort = stageTextViewPort; //for some reason, we don't need to account for the native scale factor here scaleFactor = Starling.contentScaleFactor; //StageText's fontSize property is an int, so we need to //specifically avoid using Number here. var newFontSize:int = this._fontSize * scaleFactor * smallerGlobalScale; if(this.stageText.fontSize != newFontSize) { //we need to check if this value has changed because on iOS //if displayAsPassword is set to true, the new character //will not be shown if the font size changes. instead, it //immediately changes to a bullet. (Github issue #881) this.stageText.fontSize = newFontSize; } } /** * @private */ protected function refreshMeasureTextFieldDimensions():void { //the +4 is accounting for the TextField gutter this._measureTextField.width = this.actualWidth + 4; this._measureTextField.height = this.actualHeight; } /** * @private */ protected function positionSnapshot():void { this.getTransformationMatrix(this.stage, HELPER_MATRIX); var desktopGutterPositionOffset:Number = 0; if(this._stageTextIsTextField) { desktopGutterPositionOffset = 2; } this.textSnapshot.x = Math.round(HELPER_MATRIX.tx) - HELPER_MATRIX.tx - desktopGutterPositionOffset; this.textSnapshot.y = Math.round(HELPER_MATRIX.ty) - HELPER_MATRIX.ty - desktopGutterPositionOffset; } /** * @private */ protected function disposeStageText():void { if(!this.stageText) { return; } this.stageText.removeEventListener(flash.events.Event.CHANGE, stageText_changeHandler); this.stageText.removeEventListener(KeyboardEvent.KEY_DOWN, stageText_keyDownHandler); this.stageText.removeEventListener(KeyboardEvent.KEY_UP, stageText_keyUpHandler); this.stageText.removeEventListener(FocusEvent.FOCUS_IN, stageText_focusInHandler); this.stageText.removeEventListener(FocusEvent.FOCUS_OUT, stageText_focusOutHandler); this.stageText.removeEventListener(flash.events.Event.COMPLETE, stageText_completeHandler); this.stageText.removeEventListener(SoftKeyboardEvent.SOFT_KEYBOARD_ACTIVATE, stageText_softKeyboardActivateHandler); this.stageText.removeEventListener(SoftKeyboardEvent.SOFT_KEYBOARD_DEACTIVATE, stageText_softKeyboardDeactivateHandler); this.stageText.stage = null; this.stageText.dispose(); this.stageText = null; } /** * Creates and adds the <code>stageText</code> instance. * * <p>Meant for internal use, and subclasses may override this function * with a custom implementation.</p> */ protected function createStageText():void { this._stageTextIsComplete = false; var StageTextType:Class; var initOptions:Object; try { StageTextType = Class(getDefinitionByName("flash.text.StageText")); var StageTextInitOptionsType:Class = Class(getDefinitionByName("flash.text.StageTextInitOptions")); initOptions = new StageTextInitOptionsType(this._multiline); } catch(error:Error) { StageTextType = StageTextField; initOptions = { multiline: this._multiline }; } this.stageText = new StageTextType(initOptions); this.stageText.visible = false; this.stageText.addEventListener(flash.events.Event.CHANGE, stageText_changeHandler); this.stageText.addEventListener(KeyboardEvent.KEY_DOWN, stageText_keyDownHandler); this.stageText.addEventListener(KeyboardEvent.KEY_UP, stageText_keyUpHandler); this.stageText.addEventListener(FocusEvent.FOCUS_IN, stageText_focusInHandler); this.stageText.addEventListener(FocusEvent.FOCUS_OUT, stageText_focusOutHandler); this.stageText.addEventListener(SoftKeyboardEvent.SOFT_KEYBOARD_ACTIVATE, stageText_softKeyboardActivateHandler); this.stageText.addEventListener(SoftKeyboardEvent.SOFT_KEYBOARD_DEACTIVATE, stageText_softKeyboardDeactivateHandler); this.stageText.addEventListener(flash.events.Event.COMPLETE, stageText_completeHandler); this.invalidate(); } /** * @private */ protected function dispatchKeyFocusChangeEvent(event:KeyboardEvent):void { var starling:Starling = stageToStarling(this.stage); var focusEvent:FocusEvent = new FocusEvent(FocusEvent.KEY_FOCUS_CHANGE, true, false, null, event.shiftKey, event.keyCode); starling.nativeStage.dispatchEvent(focusEvent); } /** * @private */ protected function textEditor_removedFromStageHandler(event:starling.events.Event):void { //remove this from the stage, if needed //it will be added back next time we receive focus this.stageText.stage = null; } /** * @private */ protected function stageText_changeHandler(event:flash.events.Event):void { if(this._ignoreStageTextChanges) { return; } this.text = this.stageText.text; } /** * @private */ protected function stageText_completeHandler(event:flash.events.Event):void { this.stageText.removeEventListener(flash.events.Event.COMPLETE, stageText_completeHandler); this.invalidate(); this._stageTextIsComplete = true; } /** * @private */ protected function stageText_focusInHandler(event:FocusEvent):void { this._stageTextHasFocus = true; this.addEventListener(starling.events.Event.ENTER_FRAME, hasFocus_enterFrameHandler); if(this.textSnapshot) { this.textSnapshot.visible = false; } this.invalidate(INVALIDATION_FLAG_SKIN); this.dispatchEventWith(FeathersEventType.FOCUS_IN); } /** * @private */ protected function stageText_focusOutHandler(event:FocusEvent):void { this._stageTextHasFocus = false; //since StageText doesn't expose its scroll position, we need to //set the selection back to the beginning to scroll there. it's a //hack, but so is everything about StageText. //in other news, why won't 0,0 work here? this.stageText.selectRange(1, 1); this.invalidate(INVALIDATION_FLAG_DATA); this.invalidate(INVALIDATION_FLAG_SKIN); this.dispatchEventWith(FeathersEventType.FOCUS_OUT); } /** * @private */ protected function hasFocus_enterFrameHandler(event:starling.events.Event):void { if(this._stageTextHasFocus) { var target:DisplayObject = this; do { if(!target.hasVisibleArea) { this.stageText.stage.focus = null; break; } target = target.parent; } while(target) } else { this.removeEventListener(starling.events.Event.ENTER_FRAME, hasFocus_enterFrameHandler); } } /** * @private */ protected function stageText_keyDownHandler(event:KeyboardEvent):void { if(!this._multiline && (event.keyCode == Keyboard.ENTER || event.keyCode == Keyboard.NEXT)) { event.preventDefault(); this.dispatchEventWith(FeathersEventType.ENTER); } else if(event.keyCode == Keyboard.BACK) { //even a listener on the stage won't detect the back key press that //will close the application if the StageText has focus, so we //always need to prevent it here event.preventDefault(); Starling.current.nativeStage.focus = Starling.current.nativeStage; } if(event.keyCode === Keyboard.TAB && FocusManager.isEnabledForStage(this.stage)) { event.preventDefault(); this.dispatchKeyFocusChangeEvent(event); } } /** * @private */ protected function stageText_keyUpHandler(event:KeyboardEvent):void { if(!this._multiline && (event.keyCode == Keyboard.ENTER || event.keyCode == Keyboard.NEXT)) { event.preventDefault(); } if(event.keyCode === Keyboard.TAB && FocusManager.isEnabledForStage(this.stage)) { event.preventDefault(); } } /** * @private */ protected function stageText_softKeyboardActivateHandler(event:SoftKeyboardEvent):void { this.dispatchEventWith(FeathersEventType.SOFT_KEYBOARD_ACTIVATE, true); } /** * @private */ protected function stageText_softKeyboardDeactivateHandler(event:SoftKeyboardEvent):void { this.dispatchEventWith(FeathersEventType.SOFT_KEYBOARD_DEACTIVATE, true); } } }
package org.helvector.textmate.views { public interface BasicViewInterface { } }
package { import flash.events.Event; import com.milkmangames.nativeextensions.*; import com.milkmangames.nativeextensions.events.*; import starling.display.Stage; public class Rating { static function setup(stage:Stage) { if (CONFIG::AIR && RateBox.isSupported()) { Environment.ratingSupported = true; RateBox.create("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","Enjoying Dropsy?","To say thanks, we'll give you 20 FREE Elims just for rating.","Rate Now","Ask Me Later","Don't ask again"); //RateBox.rateBox.useTestMode(); RateBox.rateBox.setAutoPrompt(false); RateBox.rateBox.addEventListener(RateBoxEvent.RATE_SELECTED,onDidRate); RateBox.rateBox.addEventListener(RateBoxEvent.NEVER_SELECTED,onWillNeverRate); function onDidRate(e:RateBoxEvent):void { Data.saveObj.hasRated = true; Data.flushSave(); } function onWillNeverRate(evt:RateBoxEvent):void { Data.saveObj.declinedRating = true; Data.flushSave(); } } } static function showRateBox() { if (CONFIG::AIR && !RateBox.rateBox.didRateCurrentVersion()) { RateBox.rateBox.showRatingPrompt("Enjoying Dropsy?","To say thanks, we'll give you 20 FREE Elims just for rating.","Rate Now","Ask Me Later","Don't ask again"); } } } }
/* Feathers Copyright 2012-2020 Bowler Hat LLC. 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 feathers.controls.supportClasses { import feathers.core.FeathersControl; import feathers.text.FontStylesSet; import feathers.utils.geom.matrixToRotation; import feathers.utils.geom.matrixToScaleX; import feathers.utils.geom.matrixToScaleY; import flash.display.Sprite; import flash.events.TextEvent; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; import flash.text.AntiAliasType; import flash.text.FontType; import flash.text.GridFitType; import flash.text.StyleSheet; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFormat; import starling.core.Starling; import starling.display.DisplayObject; import starling.events.Event; import starling.rendering.Painter; import starling.text.TextFormat; import starling.utils.MatrixUtil; import starling.utils.Pool; import starling.utils.SystemUtil; /** * @private * Used internally by ScrollText. Not meant to be used on its own. * * @productversion Feathers 1.0.0 */ public class TextFieldViewPort extends FeathersControl implements IViewPort { public function TextFieldViewPort() { super(); this.addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler); this.addEventListener(Event.REMOVED_FROM_STAGE, removedFromStageHandler); } private var _textFieldContainer:Sprite; private var _textField:TextField; /** * @private */ public function get nativeFocus():TextField { return this._textField; } /** * @private */ private var _text:String = ""; /** * @see feathers.controls.ScrollText#text */ public function get text():String { return this._text; } /** * @private */ public function set text(value:String):void { if(!value) { value = ""; } if(this._text == value) { return; } this._text = value; this.invalidate(INVALIDATION_FLAG_DATA); } /** * @private */ private var _isHTML:Boolean = false; /** * @see feathers.controls.ScrollText#isHTML */ public function get isHTML():Boolean { return this._isHTML; } /** * @private */ public function set isHTML(value:Boolean):void { if(this._isHTML == value) { return; } this._isHTML = value; this.invalidate(INVALIDATION_FLAG_DATA); } /** * @private */ protected var _fontStylesTextFormat:flash.text.TextFormat; /** * @private */ protected var _fontStyles:FontStylesSet; /** * Generic font styles. */ public function get fontStyles():FontStylesSet { return this._fontStyles; } /** * @private */ public function set fontStyles(value:FontStylesSet):void { if(this._fontStyles === value) { return; } if(this._fontStyles !== null) { this._fontStyles.removeEventListener(Event.CHANGE, fontStylesSet_changeHandler); } this._fontStyles = value; if(this._fontStyles !== null) { this._fontStyles.addEventListener(Event.CHANGE, fontStylesSet_changeHandler); } this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _currentTextFormat:flash.text.TextFormat; /** * @private */ private var _textFormat:flash.text.TextFormat; /** * @see feathers.controls.ScrollText#textFormat */ public function get textFormat():flash.text.TextFormat { return this._textFormat; } /** * @private */ public function set textFormat(value:flash.text.TextFormat):void { if(this._textFormat == value) { return; } this._textFormat = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _disabledTextFormat:flash.text.TextFormat; /** * @see feathers.controls.ScrollText#disabledTextFormat */ public function get disabledTextFormat():flash.text.TextFormat { return this._disabledTextFormat; } /** * @private */ public function set disabledTextFormat(value:flash.text.TextFormat):void { if(this._disabledTextFormat == value) { return; } this._disabledTextFormat = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _styleSheet:StyleSheet; /** * @see feathers.controls.ScrollText#styleSheet */ public function get styleSheet():StyleSheet { return this._styleSheet; } /** * @private */ public function set styleSheet(value:StyleSheet):void { if(this._styleSheet == value) { return; } this._styleSheet = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _embedFonts:Boolean = false; /** * @see feathers.controls.ScrollText#embedFonts */ public function get embedFonts():Boolean { return this._embedFonts; } /** * @private */ public function set embedFonts(value:Boolean):void { if(this._embedFonts == value) { return; } this._embedFonts = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _antiAliasType:String = AntiAliasType.ADVANCED; /** * @see feathers.controls.ScrollText#antiAliasType */ public function get antiAliasType():String { return this._antiAliasType; } /** * @private */ public function set antiAliasType(value:String):void { if(this._antiAliasType == value) { return; } this._antiAliasType = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _background:Boolean = false; /** * @see feathers.controls.ScrollText#background */ public function get background():Boolean { return this._background; } /** * @private */ public function set background(value:Boolean):void { if(this._background == value) { return; } this._background = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _backgroundColor:uint = 0xffffff; /** * @see feathers.controls.ScrollText#backgroundColor */ public function get backgroundColor():uint { return this._backgroundColor; } /** * @private */ public function set backgroundColor(value:uint):void { if(this._backgroundColor == value) { return; } this._backgroundColor = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _border:Boolean = false; /** * @see feathers.controls.ScrollText#border */ public function get border():Boolean { return this._border; } /** * @private */ public function set border(value:Boolean):void { if(this._border == value) { return; } this._border = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _borderColor:uint = 0x000000; /** * @see feathers.controls.ScrollText#borderColor */ public function get borderColor():uint { return this._borderColor; } /** * @private */ public function set borderColor(value:uint):void { if(this._borderColor == value) { return; } this._borderColor = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _cacheAsBitmap:Boolean = true; /** * @see feathers.controls.ScrollText#cacheAsBitmap */ public function get cacheAsBitmap():Boolean { return this._cacheAsBitmap; } /** * @private */ public function set cacheAsBitmap(value:Boolean):void { if(this._cacheAsBitmap == value) { return; } this._cacheAsBitmap = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _condenseWhite:Boolean = false; /** * @see feathers.controls.ScrollText#condenseWhite */ public function get condenseWhite():Boolean { return this._condenseWhite; } /** * @private */ public function set condenseWhite(value:Boolean):void { if(this._condenseWhite == value) { return; } this._condenseWhite = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _displayAsPassword:Boolean = false; /** * @see feathers.controls.ScrollText#displayAsPassword */ public function get displayAsPassword():Boolean { return this._displayAsPassword; } /** * @private */ public function set displayAsPassword(value:Boolean):void { if(this._displayAsPassword == value) { return; } this._displayAsPassword = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _gridFitType:String = GridFitType.PIXEL; /** * @see feathers.controls.ScrollText#gridFitType */ public function get gridFitType():String { return this._gridFitType; } /** * @private */ public function set gridFitType(value:String):void { if(this._gridFitType == value) { return; } this._gridFitType = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _sharpness:Number = 0; /** * @see feathers.controls.ScrollText#sharpness */ public function get sharpness():Number { return this._sharpness; } /** * @private */ public function set sharpness(value:Number):void { if(this._sharpness == value) { return; } this._sharpness = value; this.invalidate(INVALIDATION_FLAG_DATA); } /** * @private */ private var _thickness:Number = 0; /** * @see feathers.controls.ScrollText#thickness */ public function get thickness():Number { return this._thickness; } /** * @private */ public function set thickness(value:Number):void { if(this._thickness == value) { return; } this._thickness = value; this.invalidate(INVALIDATION_FLAG_DATA); } private var _actualMinVisibleWidth:Number = 0; private var _explicitMinVisibleWidth:Number; public function get minVisibleWidth():Number { if(this._explicitMinVisibleWidth !== this._explicitMinVisibleWidth) //isNaN { return this._actualMinVisibleWidth; } return this._explicitMinVisibleWidth; } public function set minVisibleWidth(value:Number):void { if(this._explicitMinVisibleWidth == value) { return; } var valueIsNaN:Boolean = value !== value; //isNaN if(valueIsNaN && this._explicitMinVisibleWidth !== this._explicitMinVisibleWidth) //isNaN { return; } var oldValue:Number = this._explicitMinVisibleWidth; this._explicitMinVisibleWidth = value; if(valueIsNaN) { this._actualMinVisibleWidth = 0; this.invalidate(INVALIDATION_FLAG_SIZE); } else { this._actualMinVisibleWidth = value; if(this._explicitVisibleWidth !== this._explicitVisibleWidth && //isNaN (this._actualVisibleWidth < value || this._actualVisibleWidth == oldValue)) { //only invalidate if this change might affect the visibleWidth this.invalidate(INVALIDATION_FLAG_SIZE); } } } private var _maxVisibleWidth:Number = Number.POSITIVE_INFINITY; public function get maxVisibleWidth():Number { return this._maxVisibleWidth; } public function set maxVisibleWidth(value:Number):void { if(this._maxVisibleWidth == value) { return; } if(value !== value) //isNaN { throw new ArgumentError("maxVisibleWidth cannot be NaN"); } var oldValue:Number = this._maxVisibleWidth; this._maxVisibleWidth = value; if(this._explicitVisibleWidth !== this._explicitVisibleWidth && //isNaN (this._actualVisibleWidth > value || this._actualVisibleWidth == oldValue)) { //only invalidate if this change might affect the visibleWidth this.invalidate(INVALIDATION_FLAG_SIZE); } } private var _actualVisibleWidth:Number = 0; private var _explicitVisibleWidth:Number = NaN; public function get visibleWidth():Number { if(this._explicitVisibleWidth !== this._explicitVisibleWidth) //isNaN { return this._actualVisibleWidth; } return this._explicitVisibleWidth; } public function set visibleWidth(value:Number):void { if(this._explicitVisibleWidth == value || (value !== value && this._explicitVisibleWidth !== this._explicitVisibleWidth)) //isNaN { return; } this._explicitVisibleWidth = value; if(this._actualVisibleWidth != value) { this.invalidate(INVALIDATION_FLAG_SIZE); } } private var _actualMinVisibleHeight:Number = 0; private var _explicitMinVisibleHeight:Number; public function get minVisibleHeight():Number { if(this._explicitMinVisibleHeight !== this._explicitMinVisibleHeight) //isNaN { return this._actualMinVisibleHeight; } return this._explicitMinVisibleHeight; } public function set minVisibleHeight(value:Number):void { if(this._explicitMinVisibleHeight == value) { return; } var valueIsNaN:Boolean = value !== value; //isNaN if(valueIsNaN && this._explicitMinVisibleHeight !== this._explicitMinVisibleHeight) //isNaN { return; } var oldValue:Number = this._explicitMinVisibleHeight; this._explicitMinVisibleHeight = value; if(valueIsNaN) { this._actualMinVisibleHeight = 0; this.invalidate(INVALIDATION_FLAG_SIZE); } else { this._actualMinVisibleHeight = value; if(this._explicitVisibleHeight !== this._explicitVisibleHeight && //isNaN (this._actualVisibleHeight < value || this._actualVisibleHeight == oldValue)) { //only invalidate if this change might affect the visibleHeight this.invalidate(INVALIDATION_FLAG_SIZE); } } } private var _maxVisibleHeight:Number = Number.POSITIVE_INFINITY; public function get maxVisibleHeight():Number { return this._maxVisibleHeight; } public function set maxVisibleHeight(value:Number):void { if(this._maxVisibleHeight == value) { return; } if(value !== value) //isNaN { throw new ArgumentError("maxVisibleHeight cannot be NaN"); } var oldValue:Number = this._maxVisibleHeight; this._maxVisibleHeight = value; if(this._explicitVisibleHeight !== this._explicitVisibleHeight && //isNaN (this._actualVisibleHeight > value || this._actualVisibleHeight == oldValue)) { //only invalidate if this change might affect the visibleHeight this.invalidate(INVALIDATION_FLAG_SIZE); } } private var _actualVisibleHeight:Number = 0; private var _explicitVisibleHeight:Number = NaN; public function get visibleHeight():Number { if(this._explicitVisibleHeight !== this._explicitVisibleHeight) //isNaN { return this._actualVisibleHeight; } return this._explicitVisibleHeight; } public function set visibleHeight(value:Number):void { if(this._explicitVisibleHeight == value || (value !== value && this._explicitVisibleHeight !== this._explicitVisibleHeight)) //isNaN { return; } this._explicitVisibleHeight = value; if(this._actualVisibleHeight != value) { this.invalidate(INVALIDATION_FLAG_SIZE); } } public function get contentX():Number { return 0; } public function get contentY():Number { return 0; } private var _scrollStep:Number; public function get horizontalScrollStep():Number { return this._scrollStep; } public function get verticalScrollStep():Number { return this._scrollStep; } private var _horizontalScrollPosition:Number = 0; public function get horizontalScrollPosition():Number { return this._horizontalScrollPosition; } public function set horizontalScrollPosition(value:Number):void { if(this._horizontalScrollPosition == value) { return; } this._horizontalScrollPosition = value; this.invalidate(INVALIDATION_FLAG_SCROLL); } private var _verticalScrollPosition:Number = 0; public function get verticalScrollPosition():Number { return this._verticalScrollPosition; } public function set verticalScrollPosition(value:Number):void { if(this._verticalScrollPosition == value) { return; } this._verticalScrollPosition = value; this.invalidate(INVALIDATION_FLAG_SCROLL); } public function get requiresMeasurementOnScroll():Boolean { return false; } private var _paddingTop:Number = 0; public function get paddingTop():Number { return this._paddingTop; } public function set paddingTop(value:Number):void { if(this._paddingTop == value) { return; } this._paddingTop = value; this.invalidate(INVALIDATION_FLAG_STYLES); } private var _paddingRight:Number = 0; public function get paddingRight():Number { return this._paddingRight; } public function set paddingRight(value:Number):void { if(this._paddingRight == value) { return; } this._paddingRight = value; this.invalidate(INVALIDATION_FLAG_STYLES); } private var _paddingBottom:Number = 0; public function get paddingBottom():Number { return this._paddingBottom; } public function set paddingBottom(value:Number):void { if(this._paddingBottom == value) { return; } this._paddingBottom = value; this.invalidate(INVALIDATION_FLAG_STYLES); } private var _paddingLeft:Number = 0; public function get paddingLeft():Number { return this._paddingLeft; } public function set paddingLeft(value:Number):void { if(this._paddingLeft == value) { return; } this._paddingLeft = value; this.invalidate(INVALIDATION_FLAG_STYLES); } override public function render(painter:Painter):void { //this component is an overlay above Starling, and it should be //excluded from the render cache painter.excludeFromCache(this); var starling:Starling = this.stage !== null ? this.stage.starling : Starling.current; var starlingViewPort:Rectangle = starling.viewPort; var matrix:Matrix = Pool.getMatrix(); var point:Point = Pool.getPoint(); this.parent.getTransformationMatrix(this.stage, matrix); MatrixUtil.transformCoords(matrix, 0, 0, point); var nativeScaleFactor:Number = 1; if(starling.supportHighResolutions) { nativeScaleFactor = starling.nativeStage.contentsScaleFactor; } var scaleFactor:Number = starling.contentScaleFactor / nativeScaleFactor; this._textFieldContainer.x = starlingViewPort.x + point.x * scaleFactor; this._textFieldContainer.y = starlingViewPort.y + point.y * scaleFactor; this._textFieldContainer.scaleX = matrixToScaleX(matrix) * scaleFactor; this._textFieldContainer.scaleY = matrixToScaleY(matrix) * scaleFactor; this._textFieldContainer.rotation = matrixToRotation(matrix) * 180 / Math.PI; this._textFieldContainer.alpha = painter.state.alpha; Pool.putPoint(point); Pool.putMatrix(matrix); super.render(painter); } override protected function initialize():void { this._textFieldContainer = new Sprite(); this._textFieldContainer.visible = false; this._textField = new TextField(); this._textField.autoSize = TextFieldAutoSize.LEFT; this._textField.selectable = false; this._textField.mouseWheelEnabled = false; this._textField.wordWrap = true; this._textField.multiline = true; this._textField.addEventListener(TextEvent.LINK, textField_linkHandler); this._textFieldContainer.addChild(this._textField); } override protected function draw():void { var dataInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_DATA); var sizeInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_SIZE); var scrollInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_SCROLL); var stylesInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STYLES); var stateInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STATE); if(stylesInvalid) { this.refreshTextFormat(); this._textField.antiAliasType = this._antiAliasType; this._textField.background = this._background; this._textField.backgroundColor = this._backgroundColor; this._textField.border = this._border; this._textField.borderColor = this._borderColor; this._textField.condenseWhite = this._condenseWhite; this._textField.displayAsPassword = this._displayAsPassword; this._textField.gridFitType = this._gridFitType; this._textField.sharpness = this._sharpness; this._textField.thickness = this._thickness; this._textField.cacheAsBitmap = this._cacheAsBitmap; this._textField.x = this._paddingLeft; this._textField.y = this._paddingTop; } var starling:Starling = this.stage !== null ? this.stage.starling : Starling.current; if(dataInvalid || stylesInvalid || stateInvalid) { if(this._styleSheet !== null) { this._textField.embedFonts = this._embedFonts; this._textField.styleSheet = this._styleSheet; } else { if(!this._embedFonts && this._currentTextFormat === this._fontStylesTextFormat) { //when font styles are passed in from the parent component, we //automatically determine if the TextField should use embedded //fonts, unless embedFonts is explicitly true this._textField.embedFonts = SystemUtil.isEmbeddedFont( this._currentTextFormat.font, this._currentTextFormat.bold, this._currentTextFormat.italic, FontType.EMBEDDED); } else { this._textField.embedFonts = this._embedFonts; } this._textField.styleSheet = null; this._textField.defaultTextFormat = this._currentTextFormat; } if(this._isHTML) { this._textField.htmlText = this._text; } else { this._textField.text = this._text; } this._scrollStep = this._textField.getLineMetrics(0).height * starling.contentScaleFactor; } var calculatedVisibleWidth:Number = this._explicitVisibleWidth; if(calculatedVisibleWidth != calculatedVisibleWidth) { if(this.stage !== null) { calculatedVisibleWidth = this.stage.stageWidth; } else { calculatedVisibleWidth = starling.stage.stageWidth; } if(calculatedVisibleWidth < this._explicitMinVisibleWidth) { calculatedVisibleWidth = this._explicitMinVisibleWidth; } else if(calculatedVisibleWidth > this._maxVisibleWidth) { calculatedVisibleWidth = this._maxVisibleWidth; } } this._textField.width = calculatedVisibleWidth - this._paddingLeft - this._paddingRight; var totalContentHeight:Number = this._textField.height + this._paddingTop + this._paddingBottom; var calculatedVisibleHeight:Number = this._explicitVisibleHeight; if(calculatedVisibleHeight != calculatedVisibleHeight) { calculatedVisibleHeight = totalContentHeight; if(calculatedVisibleHeight < this._explicitMinVisibleHeight) { calculatedVisibleHeight = this._explicitMinVisibleHeight; } else if(calculatedVisibleHeight > this._maxVisibleHeight) { calculatedVisibleHeight = this._maxVisibleHeight; } } sizeInvalid = this.saveMeasurements( calculatedVisibleWidth, totalContentHeight, calculatedVisibleWidth, totalContentHeight) || sizeInvalid; this._actualVisibleWidth = calculatedVisibleWidth; this._actualVisibleHeight = calculatedVisibleHeight; this._actualMinVisibleWidth = calculatedVisibleWidth; this._actualMinVisibleHeight = calculatedVisibleHeight; if(sizeInvalid || scrollInvalid) { var scrollRect:Rectangle = this._textFieldContainer.scrollRect; if(!scrollRect) { scrollRect = new Rectangle(); } scrollRect.width = calculatedVisibleWidth; scrollRect.height = calculatedVisibleHeight; scrollRect.x = this._horizontalScrollPosition; scrollRect.y = this._verticalScrollPosition; this._textFieldContainer.scrollRect = scrollRect; } } protected function refreshTextFormat():void { if(!this._isEnabled && this._disabledTextFormat !== null) { this._currentTextFormat = this._disabledTextFormat; } else if(this._textFormat !== null) { this._currentTextFormat = this._textFormat; } else if(this._fontStyles !== null) { this._currentTextFormat = this.getTextFormatFromFontStyles(); } } protected function getTextFormatFromFontStyles():flash.text.TextFormat { if(this.isInvalid(INVALIDATION_FLAG_STYLES) || this.isInvalid(INVALIDATION_FLAG_STATE)) { var fontStylesFormat:starling.text.TextFormat; if(this._fontStyles !== null) { fontStylesFormat = this._fontStyles.getTextFormatForTarget(this); } if(fontStylesFormat !== null) { this._fontStylesTextFormat = fontStylesFormat.toNativeFormat(this._fontStylesTextFormat); } else if(this._fontStylesTextFormat === null) { //fallback to a default so that something is displayed this._fontStylesTextFormat = new flash.text.TextFormat(); } } return this._fontStylesTextFormat; } private function addedToStageHandler(event:Event):void { this.stage.starling.nativeStage.addChild(this._textFieldContainer); this.addEventListener(Event.ENTER_FRAME, enterFrameHandler); } private function removedFromStageHandler(event:Event):void { this.stage.starling.nativeStage.removeChild(this._textFieldContainer); this.removeEventListener(Event.ENTER_FRAME, enterFrameHandler); } private function enterFrameHandler(event:Event):void { var target:DisplayObject = this; do { if(!target.visible) { this._textFieldContainer.visible = false; return; } target = target.parent; } while(target) this._textFieldContainer.visible = true; } protected function textField_linkHandler(event:TextEvent):void { this.dispatchEventWith(Event.TRIGGERED, false, event.text); } protected function fontStylesSet_changeHandler(event:Event):void { this.invalidate(INVALIDATION_FLAG_STYLES); } } }
package sfxworks { import flash.display.MovieClip; import flash.filesystem.File; import mx.events.ModuleEvent; import mx.modules.IModuleInfo; import mx.modules.ModuleManager; /** * ... * @author Samuel Jacob Walker */ public class NetworkSidebar extends MovieClip { public function NetworkSidebar(c:Communications) { } private function listModules():void { var moduleFolder:File = new File(File.applicationStorageDirectory.resolvePath("modules" + File.separator); var dirListing:Array = moduleFolder.getDirectoryListing(); for each (var file:File in dirListing) { if (file.extension == ".swf") { loadModule(file.nativePath); } } } private function loadModule(url:String):void { var info:IModuleInfo = ModuleManager.getModule(url); info.addEventListener(ModuleEvent.READY, handleModuleReady); info.load(null, null, null, moduleFactory); //?? New object or just that? } private function handleModuleReady(e:ModuleEvent):void { } } }
package away3d.core.partition { import away3d.core.base.SubMesh; import away3d.core.traverse.PartitionTraverser; import away3d.entities.Mesh; /** * MeshNode is a space partitioning leaf node that contains a Mesh object. */ public class MeshNode extends EntityNode { private var _mesh:Mesh; /** * Creates a new MeshNode object. * @param mesh The mesh to be contained in the node. */ public function MeshNode(mesh:Mesh) { super(mesh); _mesh = mesh; // also keep a stronger typed reference } /** * The mesh object contained in the partition node. */ public function get mesh():Mesh { return _mesh; } /** * @inheritDoc */ override public function acceptTraverser(traverser:PartitionTraverser):void { if (traverser.enterNode(this)) { super.acceptTraverser(traverser); var subs:Vector.<SubMesh> = _mesh.subMeshes; var i:uint; var len:uint = subs.length; while (i < len) traverser.applyRenderable(subs[i++]); } } } }
package { import flash.display.Sprite; import com.adobe.utils.IntUtil; import flash.utils.ByteArray; import com.hurlant.crypto.symmetric.AESKey; import com.hurlant.crypto.symmetric.ICipher; import com.hurlant.crypto.symmetric.IVMode; import com.hurlant.crypto.symmetric.CBCMode; import com.hurlant.crypto.symmetric.IMode; import com.hurlant.crypto.symmetric.NullPad; import com.hurlant.crypto.symmetric.PKCS5; import com.hurlant.crypto.symmetric.IPad; import com.hurlant.util.Base64; import com.hurlant.util.Hex; import com.hurlant.crypto.Crypto; import com.adobe.crypto.MD5; import com.adobe.serialization.json.JSON; public class PubnubCrypto extends Sprite { private var type:String='aes-cbc'; //Basic encryption for string public function encryptString(cipher_key:String, plainStr:String ):String { cipher_key = md5Key(cipher_key); var key:ByteArray = Hex.toArray(cipher_key); var data:ByteArray = Hex.toArray(Hex.fromString(plainStr)); var cbc:CBCMode = new CBCMode(new AESKey(key),new PKCS5()); cbc.IV = Hex.toArray(Hex.fromString("0123456789012345")); cbc.encrypt(data); return Base64.encodeByteArray(data); } //Basic decryption for string public function decryptString(cipher_key:String, cipherStr:String):String { var data:ByteArray = Base64.decodeToByteArray(cipherStr); cipher_key = md5Key(cipher_key); var key:ByteArray = Hex.toArray(cipher_key); var testkey:ByteArray = new ByteArray; var cbc:CBCMode = new CBCMode(new AESKey(key), new PKCS5()); cbc.IV = Hex.toArray(Hex.fromString("0123456789012345")); cbc.decrypt(data); return Hex.toString(Hex.fromArray(data)); } //Encryption for string/object/array public function encrypt(cipher_key:String, plainObj:* ):* { if(typeof(plainObj) == "object") { if(plainObj.length == undefined) //plainObj is object { var cipherObj:Object = new Object(); for(var s:String in plainObj) { cipherObj[s] = encryptString(cipher_key,plainObj[s]); } return cipherObj; } else { //plainObj is array var cipherArray:Array = new Array(); for(var i:int =0;i<plainObj.length;i++) { cipherArray[i] = encryptString(cipher_key,plainObj[i]) } return cipherArray; } } else if(typeof(plainObj) == "string") { return encryptString(cipher_key,plainObj); } } //Decryption for string/object/array public function decrypt(cipher_key:String, cipherObj:* ):* { if(typeof(cipherObj) == "object") { if(cipherObj.length == undefined) //cipherObj is object { var plainObj:Object = new Object(); for(var s:String in cipherObj) { plainObj[s] = decryptString(cipher_key,cipherObj[s]); } return JSON.encode(plainObj); } else { //cipherObj is array var plainArray:Array = new Array(); for(var i:int =0;i<cipherObj.length;i++) { plainArray[i] = decryptString(cipher_key,cipherObj[i]) } return JSON.encode(plainArray); } } else if(typeof(cipherObj) =="string") { return JSON.encode(decryptString(cipher_key,cipherObj)); } } function md5Key(s:String) :String { var ba:ByteArray = new ByteArray(); ba.writeUTFBytes(s); return MD5.hashBinary(ba); } } }
/* * 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. */ package svgeditor { import flash.display.*; import flash.events.*; import flash.filters.GlowFilter; import flash.geom.*; import flash.text.TextField; import assets.Resources; import translation.Translator; import ui.parts.UIPart; import uiwidgets.*; import flash.text.TextFormat; public class DrawPropertyUI extends Sprite { public static const ONCHANGE:String = 'onchange'; public static const ONFONTCHANGE:String = 'onfontchange'; private var editor:ImageEdit; private var currentValues:DrawProperties; private var disableEvents:Boolean; // Stroke and eraser UI private var strokeWidthDisplay:Shape; private var strokeWidthSlider:Slider; private var strokeSmoothnessSlider:Slider; private var smoothStrokeBtn:Button; private var eraserStrokeDisplay:Sprite; private var eraserStrokeMode:Boolean; // Fill UI private var fillUI:Sprite; private var fillBtnSolid:IconButton; private var fillBtnHorizontal:IconButton; private var fillBtnVertical:IconButton; private var fillBtnRadial:IconButton; // Font UI private var fontLabel:TextField; private var fontMenuButton:IconButton; // Shape UI private var shapeUI:Sprite; private var shapeBtnFill:IconButton; private var shapeBtnHollow:IconButton; private var isEllipse:Boolean; // Smoothness UI private var smoothnessUI:Sprite; // Color picker private var colorPicker:ColorPicker; // Other UI elements private var bg:Shape; // background rectangle private var zoomButtons:Sprite; private var modeLabel:TextField; private var modeButton:Button; // Readouts private var sizeLabel:TextField; private var sizeReadout:TextField; private var zoomReadout:TextField; public function DrawPropertyUI(editor:ImageEdit) { this.editor = editor; currentValues = new DrawProperties(); disableEvents = false; eraserStrokeMode = false; addChild(bg = new Shape()); addChild(colorPicker = new ColorPicker(editor, this)); makeShapeUI(); makeStrokeUI(); makeFillUI(); makeFontUI(); makeSmoothnessUI(); makeZoomButtons(); makeModeLabelAndButton(); makeReadouts(); addEventListener(ONCHANGE, updateStrokeWidthDisplay); updateStrokeWidthDisplay(); } public static function strings():Array { return [ 'Smooth', 'Set Costume Center', 'Font:', 'Bitmap Mode', 'Vector Mode', 'Convert to bitmap', 'Convert to vector', 'Line width', 'Eraser width']; } public var w:int, h:int; public function setWidthHeight(w:int, h:int):void { this.w = w; this.h = h; var g:Graphics = bg.graphics; g.clear(); g.lineStyle(1, CSS.borderColor); g.beginFill(0xF6F6F6); g.drawRect(0, 0, w - 1, h); fixLayout(w, h); } private function fixLayout(w:int, h:int):void { colorPicker.x = 105 + Math.max(0, Math.floor((w - 390) / 2)); colorPicker.y = 6; zoomButtons.x = w - zoomButtons.width - 5; zoomButtons.y = 5; var modeX:int = w - 5 - Math.max(modeLabel.width, modeButton.width) / 2; modeLabel.x = modeX - modeLabel.width / 2; modeLabel.y = h - 47; modeButton.x = modeX - modeButton.width / 2; modeButton.y = modeLabel.y + 22; // hide in embedded editor??? //modeLabel.visible = modeButton.visible = !isEmbedded; updateZoomReadout(); } public function get settings():DrawProperties { return currentValues; } public function set settings(props:DrawProperties):void { currentValues = props; colorPicker.pickColor(); strokeWidthSlider.value = props.strokeWidth; updateStrokeWidthDisplay(); } public function getStrokeSmoothness():Number { return strokeSmoothnessSlider.value; } public function updateUI(props:DrawProperties):void { disableEvents = true; settings = props; disableEvents = false; } public function updateZoomReadout():void { var percent:int = Math.floor(100 * editor.getZoomAndScroll()[0]); zoomReadout.text = percent + '%'; zoomReadout.x = zoomButtons.x + ((zoomButtons.width - zoomReadout.textWidth) / 2); zoomReadout.y = zoomButtons.y + zoomButtons.height + 3; } public function setCurrentColor(color:uint, alpha:Number):void { colorPicker.setCurrentColor(color, alpha); } public function toggleFillUI(enabled:Boolean):void { fillUI.visible = enabled; eraserStrokeDisplay.visible = !enabled && eraserStrokeMode; strokeWidthDisplay.visible = !enabled && !eraserStrokeMode; strokeWidthSlider.visible = !enabled; if (enabled) { updateFillUI(); for(var i:uint=0; i<fillUI.numChildren; ++i) if(fillUI.getChildAt(i) is IconButton) { var ib:IconButton = (fillUI.getChildAt(i) as IconButton); ib.setOn(ib.name == settings.fillType); } } } public function toggleShapeUI(enabled:Boolean, ellipse:Boolean = false):void { shapeUI.visible = enabled; isEllipse = ellipse; updateShapeUI(); shapeBtnFill.setOn(currentValues.filledShape); shapeBtnHollow.setOn(!currentValues.filledShape); } public function showSmoothnessUI(flag:Boolean, forDrawing:Boolean = true):void { smoothnessUI.visible = flag; if (flag) { smoothStrokeBtn.visible = !forDrawing; // strokeSmoothnessSlider.visible = forDrawing; } } public function showStrokeUI(isStroke:Boolean, isEraser:Boolean):void { eraserStrokeDisplay.visible = isEraser; eraserStrokeMode = isEraser; strokeWidthDisplay.visible = isStroke; strokeWidthSlider.visible = isStroke || isEraser; disableEvents = true; SimpleTooltips.add(strokeWidthSlider.parent, {text: (isEraser ? 'Eraser width' : 'Line width'), direction: 'top'}); strokeWidthSlider.value = currentValues.strokeWidth; disableEvents = false; updateStrokeWidthDisplay(); } public function sendChangeEvent():void { if(!disableEvents) dispatchEvent(new Event(ONCHANGE)); if (fillUI.visible) updateFillUI(); if (shapeUI.visible) updateShapeUI(); } private function makeFillUI():void { fillUI = new Sprite(); fillBtnSolid = new IconButton(setFillStyle, null, null, true); fillBtnSolid.name = 'solid'; fillBtnSolid.setOn(true); fillUI.addChild(fillBtnSolid); fillBtnHorizontal = new IconButton(setFillStyle, null, null, true); fillBtnHorizontal.name = 'linearHorizontal'; fillBtnHorizontal.x = 42; fillUI.addChild(fillBtnHorizontal); fillBtnVertical = new IconButton(setFillStyle, null, null, true); fillBtnVertical.name = 'linearVertical'; fillBtnVertical.y = 31; fillUI.addChild(fillBtnVertical); fillBtnRadial = new IconButton(setFillStyle, null, null, true); fillBtnRadial.name = 'radial'; fillBtnRadial.x = 42; fillBtnRadial.y = 31; fillUI.addChild(fillBtnRadial); fillUI.x = 15; fillUI.y = 15; fillUI.visible = false; updateFillUI(); addChild(fillUI); } private function updateFillUI():void { // Update the icons of the fill UI with new colors. fillBtnSolid.setImage( makeFillIcon('solid', true), makeFillIcon('solid', false)); fillBtnHorizontal.setImage( makeFillIcon('linearHorizontal', true), makeFillIcon('linearHorizontal', false)); fillBtnVertical.setImage( makeFillIcon('linearVertical', true), makeFillIcon('linearVertical', false)); fillBtnRadial.setImage( makeFillIcon('radial', true), makeFillIcon('radial', false)); } private function makeFillIcon(fill:String, isOn:Boolean):Sprite { // Fill button icon. Fill is one of: 'solid', 'linearHorizontal', 'linearVertical', or 'radial' const buttonSize:Point = new Point(37, 25); const iconW:int = 29; const iconH:int = 17; var colors:Array = [currentValues.color, currentValues.secondColor]; if (currentValues.alpha < 1) colors[0] = 0xFFFFFF; if (currentValues.secondAlpha < 1) colors[1] = 0xFFFFFF; var icon:Shape = new Shape(); var m:Matrix = new Matrix(); var g:Graphics = icon.graphics; switch (fill) { case 'linearHorizontal': m.createGradientBox(iconW, iconH, 0, 0, 0); g.beginGradientFill(GradientType.LINEAR, colors, [1, 1], [0, 255], m); break; case 'linearVertical': m.createGradientBox(iconW, iconH, (Math.PI / 2), 0, 0); g.beginGradientFill(GradientType.LINEAR, colors, [1, 1], [0, 255], m); break; case 'radial': m.createGradientBox(iconW, iconH); g.beginGradientFill(GradientType.RADIAL, colors, [1, 1], [0, 255], m); break; case 'hollow': g.lineStyle(4, colors[0]); case 'solid': default: g.beginFill(colors[0]); } g.drawRect(0, 0, iconW, iconH); return ImageEdit.buttonFrame(icon, isOn, buttonSize); } private function makeFontUI():void { function fontMenu():void { var m:Menu = new Menu(fontSelected); m.itemHeight = 20; m.addItem('Donegal'); m.addItem('Gloria'); m.addItem('Helvetica'); m.addItem('Marker'); m.addItem('Mystery'); m.addItem('Scratch'); m.showOnStage(Scratch.app.stage); } function fontSelected(fontName:String):void { updateFontUI(fontName); currentValues.fontName = fontName; if (!disableEvents) dispatchEvent(new Event(ONFONTCHANGE)); } const fmt:TextFormat = new TextFormat(CSS.font, 14, CSS.textColor, true); addChild(fontLabel = Resources.makeLabel(Translator.map('Font:'), fmt, 8, 8)); addChild(fontMenuButton = UIPart.makeMenuButton('Hevetica', fontMenu, true, CSS.textColor)); fontMenuButton.x = 12; fontMenuButton.y = 30; } public function showFontUI(flag:Boolean):void { fontLabel.visible = flag; fontMenuButton.visible = flag; if (flag) updateFontUI(currentValues.fontName); } public function updateFontUI(fontName:String):void { var onImg:Sprite = UIPart.makeButtonLabel(fontName, CSS.buttonLabelOverColor, true); var offImg:Sprite = UIPart.makeButtonLabel(fontName, CSS.textColor, true); fontMenuButton.setImage(onImg, offImg); currentValues.fontName = fontName; } public function updateTranslation():void { fontLabel.text = Translator.map('Font:'); smoothStrokeBtn.setLabel(Translator.map('Smooth')); modeLabel.text = Translator.map(editor is SVGEdit ? 'Vector Mode' : 'Bitmap Mode'); modeButton.setLabel(Translator.map(editor is SVGEdit ? 'Convert to bitmap' : 'Convert to vector')); SimpleTooltips.add(strokeWidthSlider.parent, {text: eraserStrokeMode ? 'Eraser width' : 'Line width', direction: 'top'}); fixLayout(w, h); } private function makeShapeUI():void { shapeUI = new Sprite(); shapeBtnFill = new IconButton(setShapeStyle, null, null, true); shapeBtnFill.x = 40; shapeBtnFill.name = 'filled'; shapeUI.addChild(shapeBtnFill); shapeBtnHollow = new IconButton(setShapeStyle, null, null, true); shapeBtnHollow.name = 'hollow'; shapeBtnHollow.setOn(true); shapeUI.addChild(shapeBtnHollow); shapeUI.x = 15; shapeUI.y = 15; shapeUI.visible = false; updateShapeUI(); addChild(shapeUI); } private function updateShapeUI(ignore:* = null):void { // Update the icons of the fill UI with new colors. shapeBtnFill.setImage( makeShapeIcon('solid', true), makeShapeIcon('solid', false)); shapeBtnHollow.setImage( makeShapeIcon('hollow', true), makeShapeIcon('hollow', false)); } private function makeShapeIcon(fill:String, isOn:Boolean):Sprite { // Shape button icon. Fill is 'hollow' or 'solid'. const buttonSize:Point = new Point(37, 25); const iconW:int = 29; const iconH:int = 17; const lineW:int = 3; var icon:Shape = new Shape(); var g:Graphics = icon.graphics; if ('hollow' == fill) g.lineStyle(lineW, currentValues.color); else g.beginFill(currentValues.color); var inset:Number = ('hollow' == fill) ? lineW / 2 : 0 if (isEllipse) g.drawEllipse(inset, inset, iconW, iconH); else g.drawRect(inset, inset, iconW, iconH); return ImageEdit.buttonFrame(icon, isOn, buttonSize); } private function setShapeStyle(ib:IconButton):void { currentValues.filledShape = (ib.name == 'filled'); // If they want to draw a hollow shape and the stroke width was zero, set it to 2. if(!currentValues.filledShape && currentValues.strokeWidth == 0) { currentValues.strokeWidth = 2; } } private function setFillStyle(ib:IconButton):void { currentValues.fillType = ib.name; } private function makeSmoothnessUI():void { function smoothStroke():void { (editor as SVGEdit).smoothStroke(); } function updateSmoothness(s:Number):void { currentValues.smoothness = s; } smoothnessUI = new Sprite(); smoothnessUI.x = 10; smoothnessUI.y = 10; smoothnessUI.visible = false; smoothStrokeBtn = new Button(Translator.map('Smooth'), smoothStroke); smoothStrokeBtn.x = 22; smoothnessUI.addChild(smoothStrokeBtn); strokeSmoothnessSlider = new Slider(100, 6, updateSmoothness); strokeSmoothnessSlider.min = 0.1; strokeSmoothnessSlider.max = 40; strokeSmoothnessSlider.value = 1; strokeSmoothnessSlider.y = 25; strokeSmoothnessSlider.visible = false; smoothnessUI.addChild(strokeSmoothnessSlider); addChild(smoothnessUI); } private function makeStrokeUI():void { function updateStrokeWidth(w:Number):void { currentValues.strokeWidth = w; updateStrokeWidthDisplay(); sendChangeEvent(); } var ttBg:Sprite = new Sprite(); addChild(ttBg); strokeWidthSlider = new Slider(85, 6, updateStrokeWidth); strokeWidthSlider.min = 0.1; strokeWidthSlider.max = 15; strokeWidthSlider.value = 2.0; strokeWidthSlider.x = 10; strokeWidthSlider.y = 90; ttBg.addChild(strokeWidthSlider); strokeWidthDisplay = new Shape(); strokeWidthDisplay.x = strokeWidthSlider.x + 10; strokeWidthDisplay.y = 65; ttBg.addChild(strokeWidthDisplay); eraserStrokeDisplay = new Sprite(); eraserStrokeDisplay.visible = false; eraserStrokeDisplay.x = strokeWidthDisplay.x - 7; eraserStrokeDisplay.y = strokeWidthDisplay.y - 20; ttBg.addChild(eraserStrokeDisplay); // Draw an area that will be used for showing tooltips updateStrokeWidthDisplay(); var r:Rectangle = ttBg.getBounds(ttBg); ttBg.graphics.beginFill(0xFF0000, 0); ttBg.graphics.drawRect(r.x, r.y, r.width, r.height); ttBg.graphics.endFill(); } private function updateStrokeWidthDisplay(ignore:* = null):void { var w:Number = currentValues.strokeWidth; if (editor is BitmapEdit) { if (19 == w) w = 17; if (29 == w) w = 20; else if (47 == w) w = 25; else if (75 == w) w = 30; else w = w + 1; } var g:Graphics; if (eraserStrokeMode) { g = eraserStrokeDisplay.graphics; g.clear(); g.lineStyle(1, 0, 1); var m:Matrix = new Matrix(); m.scale(0.25, 0.25); g.beginBitmapFill(Resources.createBmp('canvasGrid').bitmapData, m); g.drawCircle(40, 0, w); g.endFill(); } else { g = strokeWidthDisplay.graphics; g.clear(); g.lineStyle(w, currentValues.color, currentValues.alpha); g.moveTo(0, 0); g.lineTo(65, 0); strokeWidthDisplay.filters = (currentValues.alpha == 0 ? [new GlowFilter(0x28A5DA)] : []); } updateStrokeReadout(); } private function updateStrokeReadout():void { // xxx to be done } /* Right-side elements */ private function makeZoomButtons():void { addChild(zoomButtons = new Sprite()); var zoomToolNames:Array = ['zoomOut', 'noZoom', 'zoomIn']; var x:int = 0; for each (var toolName:String in zoomToolNames) { var ib:IconButton = new IconButton( editor.handleImmediateTool, Resources.createBmp(toolName + 'On'), Resources.createBmp(toolName + 'Off'), false); ib.isRadioButton = true; ib.name = name; ib.x = x; x += ib.width; editor.registerToolButton(toolName, ib); zoomButtons.addChild(ib); } } private function makeModeLabelAndButton():void { function convertToBitmap():void { editor.imagesPart.convertToBitmap() } function convertToVector():void { editor.imagesPart.convertToVector() } modeLabel = Resources.makeLabel( Translator.map((editor is SVGEdit) ? 'Vector Mode' : 'Bitmap Mode'), CSS.titleFormat, 0, 71); addChild(modeLabel); modeButton = (editor is SVGEdit) ? new Button(Translator.map('Convert to bitmap'), convertToBitmap, true) : new Button(Translator.map('Convert to vector'), convertToVector, true); addChild(modeButton); } private function makeReadouts():void { addChild(sizeLabel = Resources.makeLabel('', CSS.normalTextFormat, 0, 0)); addChild(sizeReadout = Resources.makeLabel('', CSS.normalTextFormat, 0, 0)); addChild(zoomReadout = Resources.makeLabel('', CSS.normalTextFormat, 0, 0)); } }}
package serverProto.battleRoyale { public final class ProtoBattleRoyaleFieldCampType { public static const PROTO_BATTLE_ROYALE_CAMP_TYPE_FROG:int = 0; public static const PROTO_BATTLE_ROYALE_CAMP_TYPE_SNAKE:int = 1; public static const PROTO_BATTLE_ROYALE_CAMP_TYPE_SLUGS:int = 2; public function ProtoBattleRoyaleFieldCampType() { super(); } } }
/* * 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 flexUnitTests.flexUnit4.suites.frameworkSuite.parameterizedSuite { import flexUnitTests.flexUnit4.suites.frameworkSuite.parameterizedSuite.helper.ParamDataHelper; import flexunit.framework.Assert; import org.flexunit.runners.Parameterized; [RunWith("org.flexunit.runners.Parameterized")] public class TestJUnitParameterizedExternalLoader { private var foo : Parameterized; public static var testCount : int = 0; [Parameters] public static var ensureRunOnceData : Array = [ [ 0 ] ]; public static var dataRetriever1:ParamDataHelper = new ParamDataHelper( "TestJUnitParameterizedExternal.stuff" ); [Parameters(loader="dataRetriever1")] public static var someData:Array; protected var num : int; [AfterClass] public static function afterClass() : void { // NOTE: If this fails, it will not show up as a failure on the tests, but as a "null" failure within the suite. Assert.assertEquals( testCount, 4 ); } [Test] public function parameterized_junit_verifyAllDatapointsLoadedPtTwo() : void { // Since the loader has a timer that delays the datapoint construction, can assume this will run in order... ++testCount; // NOTE: TEST FAILING: Order can't be assumed? //Assert.assertEquals( num, testCount ); } public function TestJUnitParameterizedExternalLoader( num : int ) { this.num = num; } } }
package { // No instancegc, value is primitive. [native(cls="NumberClass", classgc="exact", instance="double", methods="auto", construct="override")] public final class Number { public static native function get MAX_VALUE():Number; public static native function get MIN_VALUE():Number; public static native function get NaN():Number; public static native function get NEGATIVE_INFINITY():Number; public static native function get POSITIVE_INFINITY():Number; AS3 native function toString(radix=10):String; AS3 native function valueOf():Number; AS3 native function toExponential(p=0):String; AS3 native function toPrecision(p=0):String; AS3 native function toFixed(p=0):String; public native function Number(value = 0); } // No instancegc, value is primitive. [native(cls="IntClass", classgc="exact", instance="int32_t", methods="auto", construct="override")] public final class int { AS3 native function toString(radix=10):String; AS3 native function valueOf():int; AS3 native function toExponential(p=0):String; AS3 native function toPrecision(p=0):String; AS3 native function toFixed(p=0):String; public native function int(value = 0); } // No instancegc, value is primitive. [native(cls="UIntClass", classgc="exact", instance="uint32_t", methods="auto", construct="override")] public final class uint { AS3 native function toString(radix=10):String; AS3 native function valueOf():int; AS3 native function toExponential(p=0):String; AS3 native function toPrecision(p=0):String; AS3 native function toFixed(p=0):String; public native function uint(value = 0); } }
package game.view.tavern.render { import com.langue.Langue; import game.data.HeroData; import game.data.SkillData; import game.view.viewBase.TavernSkillBase; import starling.events.Event; public class TavernSkillRender extends TavernSkillBase { public function TavernSkillRender() { super(); skillTitle.text=Langue.getLangue("heroSkill"); bg.downState=null; bg.addEventListener(Event.TRIGGERED, onVisible); } private function onVisible(e:Event):void { this.visible=false; } public function set data(heroData:HeroData):void { if (!heroData) { this.visible=false; return; } if (heroData.skill1 > 0) { var skillData1:SkillData=SkillData.getSkill(heroData.skill1); skillName1.text=skillData1.name; skillName1.border=false; skillDetail1.text=skillData1.desc; } else { skillName1.text=skillDetail1.text="" } if (heroData.skill2 > 0) { var skillData2:SkillData=SkillData.getSkill(heroData.skill2); skillName2.text=skillData2.name; skillDetail2.text=skillData2.desc; } else { skillName2.text=skillDetail2.text="" } if (heroData.skill3 > 0) { var skillData3:SkillData=SkillData.getSkill(heroData.skill3); skillName3.text=skillData3.name; skillDetail3.text=skillData3.desc; } else { skillName3.text=skillDetail3.text="" } } } }
/** * Copyright (c) 2010 Doug Koellmer * * 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 quickb2.thirdparty.flash { import quickb2.math.geo.coords.qb2GeoPoint; import quickb2.display.retained.qb2I_Actor; import quickb2.display.retained.qb2I_ActorContainer; import quickb2.display.retained.qb2I_ArrayBasedActorContainer; import flash.display.DisplayObject; import flash.display.MovieClip; /** * ... * @author Doug Koellmer */ public class qb2FlashMovieClipActor extends MovieClip implements qb2I_ArrayBasedActorContainer { public function getX():Number { return x; } public function setX(value:Number):qb2I_Actor { x = value; return this; } public function getY():Number { return y; } public function setY(value:Number):qb2I_Actor { y = value; return this; } /*public function getPosition():qb2GeoPoint { return new qb2GeoPoint(x, y); } public function setPosition(point:qb2GeoPoint):qb2I_Actor { x = point.getX(); y = point.getY(); return this; }*/ public function getRotation():Number { return rotation; } public function setRotation(value:Number):qb2I_Actor { rotation = value; return this; } public function scale(xValue:Number, yValue:Number):qb2I_Actor { qb2U_FlashActor.scaleActor(this, xValue, yValue); return this; } public function getActorParent():qb2I_ActorContainer { return parent as qb2I_ActorContainer; } public function clone(deep:Boolean = true):qb2I_Actor { return qb2U_FlashActor.cloneSprite(this) as qb2I_Actor } public function addActorChild(actor:qb2I_Actor):void { addChild(actor as DisplayObject); } public function removeActorChild(actor:qb2I_Actor):void { removeChild(actor as DisplayObject); } public function getActorChildAt(index:int):qb2I_Actor { return getChildAt(index) as qb2I_Actor; } public function removeActorChildAt(index:int):qb2I_Actor { return removeChildAt(index) as qb2I_Actor; } public function getActorChildCount():int { return this.numChildren; } } }
package com.winonetech.core { /** * * 容器基类。 * */ import cn.vision.system.Callback; import cn.vision.utils.ArrayUtil; import flash.net.dns.AAAARecord; import mx.events.FlexEvent; import spark.components.Group; public class Vessel extends Group { /** * * 构造函数。 * */ public function Vessel() { super(); waitCreationComplete(); } /** * @inheritDoc */ protected function executeCallbacks():void { var l:int = callbacks.length; var callback:Callback, result:Boolean; while (--l >= 0) { callback = ArrayUtil.shift(callbacks); result = callback.call(); if (!result) ArrayUtil.push(callbacks, callback); } } /** * @inheritDoc */ override public function addEventListener( $type:String, $listener:Function, $useCapture:Boolean = false, $priority:int = 0, $useWeakReference:Boolean = false):void { var l1:Object = listeners[$type] = listeners[$type] || {}; var l2:Array = l1[$useCapture] = l1[$useCapture] || []; if (l2.indexOf($listener) == -1) { l2[l2.length] = $listener; super.addEventListener($type, $listener, $useCapture, $priority, $useWeakReference); } } /** * @inheritDoc */ override public function removeEventListener( $type:String, $listener:Function, $useCapture:Boolean = false):void { var l1:Object = listeners[$type]; if (l1) { var l2:Array = l1[$useCapture]; if (l2) { var index:int = l2.indexOf($listener); if (index!= -1) { super.removeEventListener($type, $listener, $useCapture); l2.splice(index, 1); if(!l2.length) delete l1[$useCapture]; } } } } /** * * 申请一个回调函数,该操作在设置属性时将会非常有用。<br> * 该操作需要一个返回 Boolean 类型的函数,回调函数中需要进行必要条件判断才执行下一步操作; * 调用此操作时,首先在设置属性时会执行一次,如果执行不成功(返回false),则在creationComplete之后再次执行。<br> * 队列执行顺序为默认为后进先出。 * * @param $callback:Function 回调函数。 * @param $priority:Boolean (default = true) 加入后执行的顺序,为true时,会放在队列开头,优先执行,为false时会放在队列末尾。 * @param $args 回调函数的参数。 * */ protected function applyCallback($callback:Function, $priority:Boolean = true, ...$args):void { const l:uint = $args ? $args.length : 0; const callback:Callback = new Callback($callback, $args); //相当于把回调方法对象化。 const different:Function = function($item:Callback, $index:int = 0, $array:Array = null):Boolean { var r:Boolean =($item.callback != callback.callback), i:uint; if(!r && l) { r =(l != $item.args.length); if(!r) { for (i = 0; i < l; i++) if (r =($args[i] != $item.args[i])) break; } } return r; }; if (callback.call()) //此处判定被回调的返回值。 { if (callbacks.length) { var i:uint = 0; while (i < callbacks.length) { if(!different(callbacks[i])) callbacks.splice(i, 1); else i++; } } } else { //如果队列中不包含该属性回调,则插入队列 if (callbacks.every(different)) { //优先执行时,会加入数组开头,否则加入数组末尾。 $priority ? ArrayUtil.unshift(callbacks, callback) : ArrayUtil.push (callbacks, callback); } } } /** * * 清楚所有的监听事件。 * */ protected function removeAllEventListeners():void { for (var l1:String in listeners) { for each (var l2:Array in listeners[l1]) { for each (var handler:Function in l2) { super.removeEventListener(l1, handler); } } delete listeners[l1]; } } /** * @private */ private function waitCreationComplete():void { var handler:Function = function(e:FlexEvent):void { removeEventListener(FlexEvent.CREATION_COMPLETE, handler); executeCallbacks(); }; addEventListener(FlexEvent.CREATION_COMPLETE, handler, false, int.MAX_VALUE); } /** * @private */ private const listeners:Object = {}; /** * @private */ private const callbacks:Array = []; } }
package citrus.view.spriteview { import citrus.core.CitrusObject; import citrus.objects.CitrusSprite; import flash.display.MovieClip; /** * This class is created by the SpriteView if a CitrusSprite has no view mentionned. It is made for a quick debugging object's view. */ public class SpriteDebugArt extends MovieClip { public function SpriteDebugArt() { } public function initialize(object:CitrusObject):void { var citrusSprite:CitrusSprite = object as CitrusSprite; if (citrusSprite) { graphics.lineStyle(1, 0x222222); graphics.beginFill(0x888888); graphics.drawRect(0, 0, citrusSprite.width, citrusSprite.height); graphics.endFill(); } } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package spark.components { import flash.events.Event; import flash.events.MouseEvent; import mx.core.mx_internal; import spark.components.supportClasses.ButtonBase; use namespace mx_internal; /** * The caret state of the button representing the menu item. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ [SkinState("showsCaret")] /** * The ViewMenuItem control displays a label and icon * for a menu item in the ViewMenu container. * Write an event handler for the <code>click</code> event * to perform an operation when the menu item is selected. * * <p>The following image shows a ViewMenu container with five * ViewMenuItem controls:</p> * * <p> * <img src="../../images/vm_open_menu_vm.png" alt="View menu" /> * </p> * * @mxml <p>The <code>&lt;s:ViewMenuItem&gt;</code> tag inherits all of the tag * attributes of its superclass and adds the following tag attributes:</p> * * <pre> * &lt;s:ViewMenuItem/&gt; * </pre> * * @see spark.components.ViewMenu * @see spark.layouts.ViewMenuLayout * @see spark.components.supportClasses.ViewNavigatorApplicationBase * @see spark.skins.mobile.ViewMenuItemSkin * * @includeExample examples/ViewMenuExampleHome.mxml -noswf * @includeExample examples/ViewMenuExample.mxml -noswf * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public class ViewMenuItem extends ButtonBase { //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function ViewMenuItem() { super(); skinDestructionPolicy = "auto"; } //---------------------------------- // showsCaret //---------------------------------- /** * @private * Storage for the showsCaret property */ private var _showsCaret:Boolean = false; /** * Contains <code>true</code> if the ViewMenuItem control * is in the caret state. * * @default false * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get showsCaret():Boolean { return _showsCaret; } /** * @private */ public function set showsCaret(value:Boolean):void { if (value == _showsCaret) return; _showsCaret = value; invalidateSkinState(); invalidateDisplayList(); } /** * @private */ override protected function getCurrentSkinState():String { var skinState:String = super.getCurrentSkinState(); // showsCaret has lower priority than disabled and down states if (showsCaret && enabled && skinState != "down") return "showsCaret"; return skinState; } } }
// Action script... // [Initial MovieClip Action of sprite 20666] #initclip 187 if (!ank.gapi.controls.PopupMenu) { if (!ank) { _global.ank = new Object(); } // end if if (!ank.gapi) { _global.ank.gapi = new Object(); } // end if if (!ank.gapi.controls) { _global.ank.gapi.controls = new Object(); } // end if var _loc1 = (_global.ank.gapi.controls.PopupMenu = function () { super(); }).prototype; _loc1.addStaticItem = function (text) { var _loc3 = new Object(); _loc3.text = text; _loc3.bStatic = true; _loc3.bEnabled = false; this._aItems.push(_loc3); }; _loc1.addItem = function (text, obj, fn, args, bEnabled) { if (bEnabled == undefined) { bEnabled = true; } // end if var _loc7 = new Object(); _loc7.text = text; _loc7.bStatic = false; _loc7.bEnabled = bEnabled; _loc7.obj = obj; _loc7.fn = fn; _loc7.args = args; this._aItems.push(_loc7); }; _loc1.__get__items = function () { return (this._aItems); }; _loc1.show = function (nX, nY, bMaximize, bUseRightCorner, nTimer) { ank.utils.Timer.removeTimer(this._name); if (nX == undefined) { nX = _root._xmouse; } // end if if (nY == undefined) { nY = _root._ymouse; } // end if this.layoutContent(nX, nY, bMaximize, bUseRightCorner); if (!_global.isNaN(Number(nTimer))) { ank.utils.Timer.setTimer(this, this._name, this, this.remove, nTimer); this._bCloseOnMouseUp = false; } // end if this.addToQueue({object: Mouse, method: Mouse.addListener, params: [this]}); }; _loc1.init = function () { super.init(false, ank.gapi.controls.PopupMenu.CLASS_NAME); this._aItems = new Array(); }; _loc1.createChildren = function () { this.createEmptyMovieClip("_mcBorder", 10); this.createEmptyMovieClip("_mcBackground", 20); this.createEmptyMovieClip("_mcForeground", 30); this.createEmptyMovieClip("_mcItems", 40); }; _loc1.size = function () { this.arrange(); }; _loc1.arrange = function () { if (this._bInitialized && (this.__width != undefined && this.__height != undefined)) { this._mcItems._x = this._mcItems._y = 2; this._mcBorder._width = this.__width; this._mcBorder._height = this.__height; this._mcBackground._x = this._mcBackground._y = 1; this._mcBackground._width = this.__width - 2; this._mcBackground._height = this.__height - 2; this._mcForeground._x = this._mcForeground._y = 2; this._mcForeground._width = this.__width - 4; this._mcForeground._height = this.__height - 4; var _loc2 = this._aItems.length; while (_loc2-- > 0) { this.arrangeItem(_loc2, this.__width - 4); } // end while } // end if }; _loc1.draw = function () { var _loc2 = this.getStyle(); this._mcBorder.clear(); this._mcBackground.clear(); this._mcForeground.clear(); this.drawRoundRect(this._mcBorder, 0, 0, 1, 1, 0, _loc2.bordercolor); this.drawRoundRect(this._mcBackground, 0, 0, 1, 1, 0, _loc2.backgroundcolor); this.drawRoundRect(this._mcForeground, 0, 0, 1, 1, 0, _loc2.foregroundcolor); }; _loc1.drawItem = function (i, index, nY) { var _loc4 = this._mcItems.createEmptyMovieClip("item" + index, index); var _loc5 = (ank.gapi.controls.Label)(_loc4.attachMovie("Label", "_lbl", 20, {_width: ank.gapi.controls.PopupMenu.MAX_ITEM_WIDTH, styleName: this.getStyle().labelenabledstyle, wordWrap: true, text: i.text})); _loc5.setPreferedSize("left"); var _loc6 = Math.max(ank.gapi.controls.PopupMenu.ITEM_HEIGHT, _loc5.textHeight + 6); if (i.bStatic) { _loc5.styleName = this.getStyle().labelstaticstyle; } else if (!i.bEnabled) { _loc5.styleName = this.getStyle().labeldisabledstyle; } // end else if _loc4.createEmptyMovieClip("bg", 10); this.drawRoundRect(_loc4.bg, 0, 0, 1, _loc6, 0, this.getStyle().itembgcolor); _loc4._y = nY; if (i.bEnabled) { _loc4.bg.onRelease = function () { i.fn.apply(i.obj, i.args); this._parent._parent._parent.remove(true); }; _loc4.bg.onRollOver = function () { var _loc2 = new Color(this); _loc2.setRGB(this._parent._parent._parent.getStyle().itemovercolor); this._parent._parent._parent.onItemOver(); }; _loc4.bg.onRollOut = _loc4.bg.onReleaseOutside = function () { var _loc2 = new Color(this); _loc2.setRGB(this._parent._parent._parent.getStyle().itembgcolor); this._parent._parent._parent.onItemOut(); }; } else { _loc4.bg.onPress = function () { }; _loc4.bg.useHandCursor = false; var _loc7 = new Color(_loc4.bg); if (i.bStatic) { _loc7.setRGB(this.getStyle().itemstaticbgcolor); } else { _loc7.setRGB(this.getStyle().itembgcolor); } // end else if } // end else if return ({w: _loc5.textWidth, h: _loc6}); }; _loc1.arrangeItem = function (nIndex, nWidth) { var _loc4 = this._mcItems["item" + nIndex]; _loc4._lbl.setSize(nWidth, ank.gapi.controls.PopupMenu.ITEM_HEIGHT); _loc4.bg._width = nWidth; }; _loc1.layoutContent = function (x, y, bMaximize, bUseRightCorner) { var _loc6 = this._aItems.length; var _loc7 = 0; var _loc8 = 0; var _loc9 = 0; while (++_loc9, _loc9 < this._aItems.length) { var _loc10 = this.drawItem(this._aItems[_loc9], _loc9, _loc8); _loc8 = _loc8 + _loc10.h; _loc7 = Math.max(_loc7, _loc10.w); } // end while this.setSize(_loc7 + 16, _loc8 + 4); var _loc11 = bMaximize ? (Stage.width) : (this.gapi.screenWidth); var _loc12 = bMaximize ? (Stage.height) : (this.gapi.screenHeight); if (bUseRightCorner == true) { x = x - this.__width; } // end if if (x > _loc11 - this.__width) { this._x = _loc11 - this.__width; } else if (x < 0) { this._x = 0; } else { this._x = x; } // end else if if (y > _loc12 - this.__height) { this._y = _loc12 - this.__height; } else if (y < 0) { this._y = 0; } else { this._y = y; } // end else if }; _loc1.remove = function () { Mouse.removeListener(this); this.removeMovieClip(); }; _loc1.onItemOver = function () { this._bOver = true; }; _loc1.onItemOut = function () { this._bOver = false; }; _loc1.onMouseUp = function () { if (!this._bOver && this._bCloseOnMouseUp) { this.remove(); } // end if }; _loc1.addProperty("items", _loc1.__get__items, function () { }); ASSetPropFlags(_loc1, null, 1); (_global.ank.gapi.controls.PopupMenu = function () { super(); }).CLASS_NAME = "PopupMenu"; (_global.ank.gapi.controls.PopupMenu = function () { super(); }).MAX_ITEM_WIDTH = 150; (_global.ank.gapi.controls.PopupMenu = function () { super(); }).ITEM_HEIGHT = 18; _loc1._bOver = false; _loc1._bCloseOnMouseUp = true; } // end if #endinitclip
package { import net.flashpunk.Graphic; import net.flashpunk.graphics.Text; /** * ... * @author jjp */ public class TextSidebar extends EntitySidebar { public function TextSidebar(sidebar:Sidebar, st:String, zoom:int = 1) { var text:Text = new Text(st); text.scale = zoom; text.x = (sidebar.width / 2) - (text.scaledWidth / 2); super(sidebar, text.scaledHeight, text); } override public function Fade(pct:Number):void { super.Fade(pct); Text(graphic).alpha = pct; } } }
// ActionScript file import Components.Switch; import flash.events.Event; import flash.events.TimerEvent; import flash.utils.Timer; import mx.collections.ArrayCollection; import mx.controls.Alert; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; private var c_iscomplete:Boolean = false; private var s_iscomplete:Boolean = false; private var h_iscomplete:Boolean = false; private var l_iscomplete:Boolean = false; private var f_iscomplete:Boolean = false; private var p_iscomplete:Boolean = false; private var switch_number:int = 0 ; private var counter:int = 0; private var counter2:int = 0; private var app_iscomplete:Boolean = false; private var topo_iscomplete:Boolean = false; private var istopo_groupcomplete:Boolean = false; private var timer:Timer; private function init():void{ timer=new Timer(1000*8,2); timer.addEventListener(TimerEvent.TIMER,onTime); loading("img/loading.gif"); timer.start(); dbInfo_getAll_Service.controller_getAll(); dbInfo_getAll_Service.host_getAll(); //dbInfo_getAll_Service.flow_getAll(); dbInfo_getAll_Service.port_getAll(); dbInfo_getAll_Service.link_getAll(); //dbInfo_getAll_Service.portStats_getAll(); dbInfo_getAll_Service.switch_getAll(); //dbInfo_getAll_Service.portStats_getAll(); //CoordinatorService.InitController(); //} create(); //call function to get menu data set } /*private function getDataBaseData():void{ //dbInfo_getAll_Service.flow_getAll(); dbInfo_getAll_Service.portStats_getAll(); }*/ private function onTime(event:TimerEvent):void{ if(timer.currentCount==1){ if(!(c_iscomplete && h_iscomplete &&s_iscomplete)){ Alert.show("connect overtime, please check out network status","failed to access topology"); PopUpManager.removePopUp(img); } } if(timer.currentCount==2){ if(!(l_iscomplete &&p_iscomplete)){ PopUpManager.removePopUp(img); Alert.show("connect overtime, please check out network status","failed to access network info"); } } } private function faultHandler(event:FaultEvent):void{ Alert.show("Fault:"+event.fault.toString()); } private function controller_resultHandler(event:ResultEvent):void{ ac_controller = event.result as ArrayCollection; c_iscomplete = true; counter++; if(s_iscomplete && h_iscomplete && l_iscomplete && counter==4 ){ counter--; topo_iscomplete=true; counter2++; if(app_iscomplete && counter2==2){ counter2--; networkPanel_creationCompleteHandler(); PopUpManager.removePopUp(img); //CoordinatorTopoCompleteHandler(); } } } private function switch_resultHandler(event:ResultEvent):void{ switch_number++; if(switch_number==1){ ac_switch = event.result as ArrayCollection; s_iscomplete = true; counter++; if(c_iscomplete && h_iscomplete && l_iscomplete && counter==4){ counter--; topo_iscomplete=true; counter2++; if(app_iscomplete && counter2==2 ){ counter2--; networkPanel_creationCompleteHandler(); PopUpManager.removePopUp(img); //CoordinatorTopoCompleteHandler(); } } }else{ ac_switch = event.result as ArrayCollection; } } private function flow_resultHandler(event:ResultEvent):void{ ac_flow.removeAll(); ac_flow = event.result as ArrayCollection; f_iscomplete=true; } private function port_resultHandler(event:ResultEvent):void{ ac_port = event.result as ArrayCollection; p_iscomplete=true; } private function host_resultHandler(event:ResultEvent):void{ ac_host = event.result as ArrayCollection; h_iscomplete = true; counter++; if(c_iscomplete && s_iscomplete && l_iscomplete && counter==4){ counter--; topo_iscomplete=true; counter2++; if(app_iscomplete && counter2==2){ counter2--; PopUpManager.removePopUp(img); networkPanel_creationCompleteHandler(); //CoordinatorTopoCompleteHandler(); } } } private function link_resultHandler(event:ResultEvent):void{ ac_link = event.result as ArrayCollection; l_iscomplete=true; counter++; if(c_iscomplete && s_iscomplete && h_iscomplete && counter==4){ counter--; topo_iscomplete=true; counter2++; if(app_iscomplete && counter2==2) { counter2--; networkPanel_creationCompleteHandler(); PopUpManager.removePopUp(img); //CoordinatorTopoCompleteHandler(); } } } private function portStats_resultHandler(event:ResultEvent):void{ ac_package.removeAll(); ac_package = event.result as ArrayCollection; } private function firewall_resultHandler(event:ResultEvent):void{ ac_firewall_enable = event.result as String; if(ac_firewall_enable == "[Ryu]Switch firewall enable successd.") trace(ac_firewall_enable); else Alert.show(ac_firewall_enable); }
/* 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 = "Definitions"; // provide a document reference (ie, ECMA section) // var VERSION = "AS3"; // Version of JavaScript or ECMA // var TITLE = "Testing nested try block with multiple catch blocks, the inner try and multiple catch block inside the try block of the outer try and multiple catch blocks"; // Provide ECMA section title or a description var BUGNUMBER = ""; thisError = "no error"; thisError1="no error"; try{ //throw new ReferenceError(); try { throw new TypeError(); }catch(ei:TypeError){ thisError="This is Inner Type Error:"+ei.toString(); //print(thisError); }catch(ei1:ReferenceError){ thisError="Inner reference error:"+ei1.toString(); }catch(ei2:URIError){ thisError="This is inner URI Error:"+ei2.toString(); }catch(ei3:EvalError){ thisError="This is inner Eval Error:"+ei3.toString(); }catch(ei4:RangeError){ thisError="This is inner Range Error:"+ei4.toString(); }catch(ei5:SecurityError){ thisError="This is inner Security Error!!!"+ei5.toString(); }catch(ei6:ArgumentError){ thisError="This is inner Argument Error"+ei6.toString(); }finally{ Assert.expectEq( "Testing Nested try block with multiple catch block inside the try block of the outer try block","This is inner finally:This is Inner Type Error:TypeError","This is inner finally:"+thisError ); } }catch(eo:ReferenceError){ thisError1 = "This is outer reference error:"+" "+eo.toString(); //print(thisError1); }catch(eo1:TypeError){ thisError1="This is outer TypeError:"+eo1.toString(); }catch(eo2:ArgumentError){ thisError1="This is outer Argument Error"+eo2.toString(); }catch(eo3:URIError){ thisError1="This is outer URI Error"+eo3.toString(); }catch(eo4:EvalError){ thisError1="This is outer Eval Error"+eo4.toString(); }catch(eo5:RangeError){ thisError1="This is outer Range Error"+eo5.toString(); }catch(eo6:SecurityError){ thisError1="This is outer Security Error!!!"+eo6.toString(); }catch(eo7:Error){ thisError1="This is outer Error:"+eo7.toString(); }finally{ } // displays results.
package { public class Main { public function Main() { foo$(EntryPoint)(new Object()); } } }
package cmodule.lua_wrapper { const __time_using_locale:int = gstaticInitter.alloc(4,4); }
package com.andywoods.multitrialapp.manager { import com.andywoods.multitrialapp.data.DragProperties; import com.andywoods.multitrialapp.model.AppModel; import com.andywoods.multitrialapp.util.Delegate; import flash.display.DisplayObject; import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; import flash.utils.Dictionary; public class DragManager { [Inject] public var model:AppModel; public var draggableObjects:Dictionary; public var isDragging:Boolean; public function init():void { draggableObjects = new Dictionary(); isDragging = false; log( this, "Initialized." ); } public function enableDrag( displayObj:DisplayObject, dragProperties:DragProperties = null ):void { displayObj.addEventListener(MouseEvent.MOUSE_DOWN, startDrag); draggableObjects[displayObj] = dragProperties; } public function disableDrag( displayObj:DisplayObject ):void { displayObj.removeEventListener(MouseEvent.MOUSE_DOWN, startDrag); delete draggableObjects[displayObj]; } public function clear():void { for each(var key:Object in draggableObjects) { var targetProps:DragProperties = draggableObjects[key]; var target:Sprite = draggableObjects[key].target as Sprite; disableDrag(target); } } protected function startDrag(event:Event):void { var displayObj:Sprite = event.target as Sprite; var dragProperties:DragProperties = draggableObjects[displayObj]; displayObj.startDrag(dragProperties.snapToCenter, dragProperties.dragRect); displayObj.stage.addEventListener(MouseEvent.MOUSE_UP, stopDrag); displayObj.stage.addEventListener(MouseEvent.MOUSE_MOVE, handleMove); isDragging = true; } protected function stopDrag(event:MouseEvent):void { var displayObj:Sprite = event.target as Sprite; var dragProperties:DragProperties = draggableObjects[displayObj]; if( displayObj ) { displayObj.stopDrag(); displayObj.stage.removeEventListener(MouseEvent.MOUSE_UP, stopDrag); displayObj.stage.removeEventListener(MouseEvent.MOUSE_MOVE, handleMove); } isDragging = false; if(dragProperties && dragProperties.onRelease) Delegate.execute(dragProperties.onRelease, dragProperties.onReleaseParams); } protected function handleMove(event:MouseEvent):void { var displayObj:Sprite = event.target as Sprite; var dragProperties:DragProperties = draggableObjects[displayObj]; if(dragProperties && dragProperties.onUpdate) Delegate.execute(dragProperties.onUpdate, dragProperties.onUpdateParams); event.updateAfterEvent(); } } }
package kabam.rotmg.account.core.commands { import kabam.rotmg.account.core.view.MoneyFrame; import kabam.rotmg.dialogs.control.OpenDialogSignal; public class InternalOpenMoneyWindowCommand { public function InternalOpenMoneyWindowCommand() { super(); } [Inject] public var openDialog:OpenDialogSignal; public function execute():void { this.openDialog.dispatch(new MoneyFrame()); } } }
package away3d.animators.utils { import away3d.arcane; import away3d.animators.data.*; import away3d.animators.nodes.*; import flash.geom.*; use namespace arcane; public class SkeletonUtils { public static function generateDifferenceClip(source:SkeletonClipNode, referencePose:SkeletonPose):SkeletonClipNode { var diff:SkeletonClipNode = new SkeletonClipNode(); var numFrames:uint = source.frames.length; for (var i:uint = 0; i < numFrames; ++i) diff.addFrame(generateDifferencePose(source.frames[i], referencePose), source.durations[i]); return diff; } public static function generateDifferencePose(source:SkeletonPose, reference:SkeletonPose):SkeletonPose { if (source.numJointPoses != reference.numJointPoses) throw new Error("joint counts don't match!"); var numJoints:uint = source.numJointPoses; var diff:SkeletonPose = new SkeletonPose(); var srcPose:JointPose; var refPose:JointPose; var diffPose:JointPose; var mtx:Matrix3D = new Matrix3D(); var tempMtx:Matrix3D = new Matrix3D(); var vec:Vector.<Vector3D>; for (var i:int = 0; i < numJoints; ++i) { srcPose = source.jointPoses[i]; refPose = reference.jointPoses[i]; diffPose = new JointPose(); diff.jointPoses[i] = diffPose; diffPose.name = srcPose.name; refPose.toMatrix3D(mtx); mtx.invert(); mtx.append(srcPose.toMatrix3D(tempMtx)); vec = mtx.decompose(Orientation3D.QUATERNION); diffPose.translation.copyFrom(vec[0]); diffPose.orientation.x = vec[1].x; diffPose.orientation.y = vec[1].y; diffPose.orientation.z = vec[1].z; diffPose.orientation.w = vec[1].w; } return diff; } } }
package nape.shape { import zpp_nape.shape.ZPP_Circle; import nape.geom.Vec2; import nape.phys.Material; import nape.dynamics.InteractionFilter; import zpp_nape.geom.ZPP_Vec2; import flash._-2v; import zpp_nape.phys.ZPP_Material; import zpp_nape.dynamics.ZPP_InteractionFilter; import zpp_nape.callbacks.ZPP_CbType; public class Circle extends Shape { public function Circle(param1:Number, param2:Vec2 = undefined, param3:Material = undefined, param4:InteractionFilter = undefined) { var _loc5_:* = null as ZPP_Vec2; if(_-2v._-7E) { return; } super(); zpp_inner_zn = new ZPP_Circle(); zpp_inner_zn.outer = this; zpp_inner_zn.outer_zn = this; zpp_inner = zpp_inner_zn; zpp_inner_i = zpp_inner; zpp_inner_i.outer_i = this; zpp_inner.immutable_midstep("Circle::radius"); if(param1 != zpp_inner_zn.radius) { zpp_inner_zn.radius = param1; zpp_inner_zn.invalidate_radius(); } zpp_inner_zn.radius; if(param2 == null) { zpp_inner.localCOMx = 0; zpp_inner.localCOMy = 0; } else { _loc5_ = param2.zpp_inner; if(_loc5_._validate != null) { _loc5_._validate(); } zpp_inner.localCOMx = param2.zpp_inner.x; _loc5_ = param2.zpp_inner; if(_loc5_._validate != null) { _loc5_._validate(); } zpp_inner.localCOMy = param2.zpp_inner.y; if(param2.zpp_inner.weak) { param2.dispose(); true; } else { false; } } if(param3 == null) { if(ZPP_Material.zpp_pool == null) { zpp_inner.material = new ZPP_Material(); } else { zpp_inner.material = ZPP_Material.zpp_pool; ZPP_Material.zpp_pool = zpp_inner.material.next; zpp_inner.material.next = null; } null; } else { zpp_inner.immutable_midstep("Shape::material"); zpp_inner.setMaterial(param3.zpp_inner); zpp_inner.material.wrapper(); } if(param4 == null) { if(ZPP_InteractionFilter.zpp_pool == null) { zpp_inner.filter = new ZPP_InteractionFilter(); } else { zpp_inner.filter = ZPP_InteractionFilter.zpp_pool; ZPP_InteractionFilter.zpp_pool = zpp_inner.filter.next; zpp_inner.filter.next = null; } null; } else { zpp_inner.immutable_midstep("Shape::filter"); zpp_inner.setFilter(param4.zpp_inner); zpp_inner.filter.wrapper(); } zpp_inner_i.insert_cbtype(ZPP_CbType.ANY_SHAPE.zpp_inner); } public static function copy(param1:Circle) : Circle { var _loc2_:Shape = param1.zpp_inner.copy(); return _loc2_.isCircle()?_loc2_.zpp_inner.circle.outer_zn:null; } public var zpp_inner_zn:ZPP_Circle; public function set radius(param1:Number) : Number { zpp_inner.immutable_midstep("Circle::radius"); if(param1 != zpp_inner_zn.radius) { zpp_inner_zn.radius = param1; zpp_inner_zn.invalidate_radius(); } return zpp_inner_zn.radius; } public function get radius() : Number { return zpp_inner_zn.radius; } } }
/** * InputField.as * * Copyright (c) 2011 Jonathan Pace * * 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 core.ui.managers { import flash.display.DisplayObject; import flash.display.Stage; import flash.events.Event; import flash.events.EventDispatcher; import core.ui.components.Application; import core.ui.components.UIComponent; import core.ui.events.ComponentFocusEvent; public class FocusManager extends EventDispatcher { private static var instance :FocusManager; public static function getInstance():FocusManager { return instance; } private var focusedComponent :UIComponent; public function FocusManager() { if ( instance ) return; instance = this; } public static function setFocus( value:UIComponent ):void { instance.setFocus( value ); } public static function getCurrentFocus():UIComponent { return instance.getCurrentFocus(); } public static function isFocusedItemAChildOf( parent:UIComponent ):Boolean { return instance.isFocusedItemAChildOf(parent); } public function setFocus( value:UIComponent ):void { // Walk up the display list until we hit a component that can be focused. var comp:DisplayObject = value; while ( true ) { if ( comp == null ) return; if ( comp is UIComponent == false ) { comp = comp.parent; continue; } if ( UIComponent(comp).focusEnabled == false ) { comp = comp.parent; continue; } break; } value = UIComponent(comp); if ( value == focusedComponent ) return; trace("FocusManager.setFocus() : " + value); //trace(value); var previouslyFocusedComponent:UIComponent = focusedComponent; if ( previouslyFocusedComponent ) { focusedComponent.removeEventListener( Event.REMOVED_FROM_STAGE, focusedComponentRemovedFromStageHandler ); previouslyFocusedComponent.onLoseComponentFocus(); previouslyFocusedComponent.dispatchEvent( new ComponentFocusEvent( ComponentFocusEvent.COMPONENT_FOCUS_OUT, value, false, false ) ); dispatchEvent( new ComponentFocusEvent( ComponentFocusEvent.COMPONENT_FOCUS_OUT, previouslyFocusedComponent, false, false ) ); } focusedComponent = value; if ( focusedComponent ) { focusedComponent.onGainComponentFocus(); focusedComponent.dispatchEvent( new ComponentFocusEvent( ComponentFocusEvent.COMPONENT_FOCUS_IN, previouslyFocusedComponent, false, false ) ); focusedComponent.addEventListener( Event.REMOVED_FROM_STAGE, focusedComponentRemovedFromStageHandler ); dispatchEvent( new ComponentFocusEvent( ComponentFocusEvent.COMPONENT_FOCUS_IN, focusedComponent, false, false ) ); } } public function getCurrentFocus():UIComponent { return focusedComponent; } public function isFocusedItemAChildOf( parent:UIComponent ):Boolean { if ( focusedComponent == null ) return false; var currentItem:DisplayObject = focusedComponent; while ( currentItem ) { if ( currentItem == parent ) return true; currentItem = currentItem.parent; } return false; } private function focusedComponentRemovedFromStageHandler( event:Event ):void { setFocus(null); } } }
/** * __ __ __ * ____/ /_ ____/ /______ _ ___ / /_ * / __ / / ___/ __/ ___/ / __ `/ __/ * / /_/ / (__ ) / / / / / /_/ / / * \__,_/_/____/_/ /_/ /_/\__, /_/ * / / * \/ * http://distriqt.com * * @author Michael (https://github.com/marchbold) * @created 18/5/21 */ package com.apm.client.commands.project { import com.apm.client.APM; import com.apm.client.commands.Command; import com.apm.client.events.CommandEvent; import com.apm.client.logging.Log; import flash.events.EventDispatcher; public class ProjectConfigCommand extends EventDispatcher implements Command { //////////////////////////////////////////////////////// // CONSTANTS // private static const TAG:String = "ProjectConfigCommand"; public static const NAME:String = "project/config"; //////////////////////////////////////////////////////// // VARIABLES // private var _parameters:Array; //////////////////////////////////////////////////////// // FUNCTIONALITY // public function ProjectConfigCommand() { super(); _parameters = []; } public function setParameters( parameters:Array ):void { _parameters = parameters; } public function get name():String { return NAME; } public function get category():String { return ""; } public function get requiresNetwork():Boolean { return false; } public function get requiresProject():Boolean { return true; } public function get description():String { return "controls the configuration parameters saved in the project definition"; } public function get usage():String { return description + "\n" + "\n" + "apm project config set <param> <value> Sets a <param> configuration parameter to the specified <value> \n" + "apm project config get <param> Prints the configuration parameter value for the <param> parameter \n" + "apm project config Prints all configuration parameters \n"; } public function execute():void { Log.d( TAG, "execute(): " + (_parameters.length > 0 ? _parameters[ 0 ] : "...") + "\n" ); try { for (var i:int = 0; i < _parameters.length; i++) { var arg:String = _parameters[ i ]; switch (arg) { case "set": { if (_parameters.length < 3) { dispatchEvent( new CommandEvent( CommandEvent.PRINT_USAGE, name )); dispatchEvent( new CommandEvent( CommandEvent.COMPLETE, APM.CODE_ERROR )); return; } var set_param:String = _parameters[ ++i ]; var set_value:String = _parameters.slice( ++i ).join(" "); APM.config.projectDefinition.setConfigurationParam( set_param, set_value ); APM.config.projectDefinition.save(); dispatchEvent( new CommandEvent( CommandEvent.COMPLETE, APM.CODE_OK )); return; break; } case "get": { if (_parameters.length >= 2) { var param:String = _parameters[ ++i ]; var value:String = APM.config.projectDefinition.getConfigurationParam( param ); APM.io.writeLine( param + "=" + (value == null ? "null" : value) ); dispatchEvent( new CommandEvent( CommandEvent.COMPLETE, APM.CODE_OK )); return; } else { dispatchEvent( new CommandEvent( CommandEvent.PRINT_USAGE, name )); dispatchEvent( new CommandEvent( CommandEvent.COMPLETE, APM.CODE_ERROR )); return; } break; } } } // print all config for (var key:String in APM.config.projectDefinition.configuration) { APM.io.writeLine( key + "=" + APM.config.projectDefinition.getConfigurationParam( key ) ); } dispatchEvent( new CommandEvent( CommandEvent.COMPLETE, APM.CODE_OK )); } catch (e:Error) { APM.io.error( e ); dispatchEvent( new CommandEvent( CommandEvent.COMPLETE, APM.CODE_ERROR )); } } } }
/** * Keyboard input management of the players MCV pattern. * SPACE: playpause,UP:prev,DOWN:next,LEFT:volume-10,RIGHT:volume+10 * * @author Jeroen Wijering * @version 1.3 **/ import com.jeroenwijering.players.*; class com.jeroenwijering.players.InputView extends AbstractView { /** The current volume **/ private var currentVolume:Number; /** The current elapsed time **/ private var currentTime:Number; /** Constructor **/ function InputView(ctr:AbstractController,cfg:Object,fed:Object) { super(ctr,cfg,fed); Key.addListener(this); }; /** Save current elapsed time **/ private function setTime(elp:Number,rem:Number) { currentTime = elp; }; /** Save current volume **/ private function setVolume(vol:Number) { currentVolume = vol; }; /** KeyDown handler, forwarded by Key object **/ public function onKeyDown() { if (Key.getCode() == 32) { sendEvent("playpause"); } else if (Key.getCode() == 37) { if(feeder.feed.length == 1) { sendEvent("scrub",currentTime-15); } else { sendEvent("prev"); } } else if (Key.getCode() == 39) { if(feeder.feed.length == 1) { sendEvent("scrub",currentTime+15); } else { sendEvent("next"); } } else if (Key.getCode() == 38) { sendEvent("volume",currentVolume+10); } else if (Key.getCode() == 40) { sendEvent("volume",currentVolume-10); } else if (Key.getCode() == 77) { sendEvent("volume",0); } }; }
package org.justincrounds.actionscript { import caurina.transitions.*; import flash.media.*; import flash.utils.*; import flash.events.*; import flash.display.MovieClip; public class Maestro extends MovieClip { private var _controller:Controller; private var soundChannel:SoundChannel; private var sTransform:SoundTransform = new SoundTransform(); private var _soundtrack; private var _tempo:Number = 0; public var dictionary:Dictionary = new Dictionary(true); private var currentTick:Number; private var currentBeat:Number; private var currentTime:Number = 0; private var tickInterval:Number; private var beatInterval:Number; public var loop:Boolean = false; private var currentPosition:Number = 0; private var isPaused:Boolean = false; private var newTempo:Number = 0; private var maestroTimer = new Timer(1); public function Maestro() { addEventListener(Event.REMOVED_FROM_STAGE, removedFromStage, false, 0, true); } public function set controller(controller:Controller) { _controller = controller; _controller.addEventListener("MAESTRO START", maestroStart, false, 0, true); _controller.addEventListener("MAESTRO STOP", maestroStop, false, 0, true); _controller.addEventListener("MAESTRO TRACK", maestroTrack, false, 0, true); _controller.addEventListener("MAESTRO TEMPO", maestroTempo, false, 0, true); _controller.addEventListener("MAESTRO FADE IN", maestroFadeIn, false, 0, true); _controller.addEventListener("MAESTRO FADE OUT", maestroFadeOut, false, 0, true); _controller.addEventListener("MAESTRO END", maestroEnd, false, 0, true); _controller.addEventListener("PAUSE", pauseHandler, false, 0, true); } public function set soundtrack(soundtrack:String) { var ClassReference:Class = getDefinitionByName(soundtrack) as Class; _soundtrack = new ClassReference(); } public function set tempo(tempo:Number) { _tempo = newTempo = tempo; } public function get tempo() { return _tempo; } public function set volume(volume:Number) { sTransform.volume = volume; soundChannel.soundTransform = sTransform; } public function get volume() { return sTransform.volume; } private function pauseHandler(event:BroadcastEvent) { if (!isPaused) { maestroStop(); } else { maestroStart(); } isPaused = !isPaused; } private function maestroStart(event:BroadcastEvent = null) { tempo = newTempo; soundChannel = _soundtrack.play(currentPosition, 0, sTransform); soundChannel.addEventListener(Event.SOUND_COMPLETE, soundComplete, false, 0, true); if (tempo != 0) { maestroTimer.addEventListener("timer", timerHandler); maestroTimer.start(); } } private function maestroStop(event:BroadcastEvent = null) { currentPosition = soundChannel.position; soundChannel.stop(); soundChannel.removeEventListener(Event.SOUND_COMPLETE, soundComplete); maestroTimer.removeEventListener("timer", timerHandler); maestroTimer.reset(); } private function maestroTrack(event:BroadcastEvent) { soundtrack = event.object.toString(); } private function maestroTempo(event:BroadcastEvent) { newTempo = Number(event.object.toString()); } private function maestroFadeIn(event:BroadcastEvent) { maestroStart(); volume = 0; Tweener.addTween(this, { volume: 1, time: Number(event.object) }); } private function maestroFadeOut(event:BroadcastEvent) { Tweener.addTween(this, { volume: 0, time: Number(event.object), onCompleteScope: this, onComplete: function() { maestroStop(); } }); } private function maestroEnd(event:BroadcastEvent = null) { var key = (_tempo != 0) ? (currentTime - 1) + Math.ceil((_soundtrack.length - soundChannel.position) / ((60 / _tempo) * 1000)) : null; if (dictionary[key] == undefined) { dictionary[key] = "MAESTRO STOP"; } else { dictionary[key] += ",MAESTRO STOP"; } } private function soundComplete(event:Event) { soundChannel.removeEventListener(Event.SOUND_COMPLETE, soundComplete); if (loop) { currentPosition = 0; maestroStart(); } else { maestroStop(); } } private function processNoteEvent(currentTime:String) { if (dictionary[currentTime] != undefined) { for each (var currentEvents in dictionary[currentTime].split(",")) { var e = currentEvents.split("="); _controller.broadcast(e[0], e[1]); } } } private function timerHandler(event:TimerEvent) { var beat = Math.floor(soundChannel.position / ((60 / _tempo) * 1000)); if (currentBeat != beat) { currentBeat = beat; _controller.broadcast("MAESTRO BEAT", currentBeat); _controller.broadcast("MAESTRO TIME", currentTime); processNoteEvent(currentTime.toString()); currentTime++; } var tick = Math.floor(soundChannel.position / (((60 / _tempo) * 1000) / 60)); if (currentTick != tick) { currentTick = tick % 60; _controller.broadcast("MAESTRO TICK", currentTick); } } private function removedFromStage(event:Event) { removeEventListener(Event.REMOVED_FROM_STAGE, removedFromStage); _controller.removeEventListener("MAESTRO START", maestroStart); _controller.removeEventListener("MAESTRO STOP", maestroStop); _controller.removeEventListener("MAESTRO TRACK", maestroTrack); _controller.removeEventListener("MAESTRO TEMPO", maestroTempo); _controller.removeEventListener("MAESTRO FADE IN", maestroFadeIn); _controller.removeEventListener("MAESTRO FADE OUT", maestroFadeOut); _controller.removeEventListener("MAESTRO END", maestroEnd); _controller.removeEventListener("PAUSE", pauseHandler); } } }
# Caio Henrique Pardal dos Santos RA:195216 LAB03.as .org 0x000 LOAD M(arraySize) SUB M(Constant1) STOR M(arraySize) laco: LOAD M(firstArray) ADD M(i) STA M(pos1) LOAD M(secondArray) ADD M(i) STA M(pos2) pos1: LOAD MQ, M(0x000) pos2: MUL M(0x000) LOAD MQ ADD M(soma) STOR M(soma) LOAD M(i) ADD M(Constant1) STOR M(i) LOAD M(arraySize) SUB M(i) JUMP+ M(laco) LOAD M(soma) JUMP M(0x0000000400) .org 0x05A soma: .word 0x0000000000 i: .word 0x0000000000 Constant1: .word 0x0000000001 .org 0x3FD arraySize: .word 0x2 firstArray: .word 0x100 secondArray: .word 0x200
/* Copyright 2012 XTD Studios Ltd. 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.xtdstudios.dmt.demo { import flash.events.MouseEvent; import flash.text.TextField; import starling.core.Starling; import starling.display.Sprite; public class ExamplesManager extends starling.display.Sprite { private var m_examplesClasses : Array = [HelloDMT, PivotExample, HierarchyExample, MovieClipDMT/*, CoreAPI */]; private var m_currentExample : Sprite; private var m_exampleTitle : TextField; private var m_exampleIdx : int = 0; public function ExamplesManager() { super(); Starling.current.nativeStage.addEventListener(MouseEvent.CLICK, onClick); m_exampleTitle = Starling.current.nativeStage.getChildByName("exampleTitle") as TextField; m_exampleIdx = -1; nextExample(); } protected function onClick(event:MouseEvent):void { nextExample(); } private function nextExample():void { m_exampleIdx++; if (m_exampleIdx>=m_examplesClasses.length) m_exampleIdx = 0; if (m_currentExample) { m_currentExample.dispose(); removeChild(m_currentExample); } m_currentExample = new m_examplesClasses[m_exampleIdx]; addChild(m_currentExample); m_exampleTitle.text = m_currentExample.name; } } }
package org.osflash.dom.path.builder { /** * @author Simon Richardson - me@simonrichardson.info */ public interface IDOMPathMethodArgumentBuilder { function addInt(value : int) : IDOMPathMethodArgumentBuilder; function addUint(value : uint) : IDOMPathMethodArgumentBuilder; function addNumber(value : Number) : IDOMPathMethodArgumentBuilder; function addString(value : String) : IDOMPathMethodArgumentBuilder; function addBoolean(value : Boolean) : IDOMPathMethodArgumentBuilder; function addArray(value : Array) : IDOMPathMethodArgumentBuilder; function endArguments() : IDOMPathMethodBuilder; } }
/** * User: MerlinDS * Date: 13.07.2014 * Time: 15:57 */ package com.merlinds.miracle_tool.views.widgets { import com.merlinds.debug.log; import com.merlinds.debug.warning; import com.merlinds.miracle_tool.events.EditorEvent; import com.merlinds.miracle_tool.models.vo.SheetToolsVO; import com.merlinds.miracle_tool.models.vo.SourceVO; import com.merlinds.miracle_tool.services.FileSystemService; import com.merlinds.miracle_tool.views.logger.StatusBar; import flash.events.Event; public class SheetToolsMediator extends WidgetMediator { [Inject] public var fileSystemService:FileSystemService; //============================================================================== //{region PUBLIC METHODS public function SheetToolsMediator() { super(); } override public function onRegister():void { super.onRegister(); this.addViewListener(Event.OPEN, this.openHandler); this.addViewListener(Event.SELECT_ALL, this.selectHandler); this.addContextListener(EditorEvent.SELECT_ITEM, this.editorHandler); this.addContextListener(EditorEvent.ANIMATION_ATTACHED, this.editorHandler); this.addContextListener(EditorEvent.SOURCE_ATTACHED, this.editorHandler); } override public function onRemove():void { super.onRemove(); this.removeViewListener(Event.OPEN, this.openHandler); this.removeViewListener(Event.SELECT_ALL, this.selectHandler); this.removeContextListener(EditorEvent.SELECT_ITEM, this.editorHandler); this.removeContextListener(EditorEvent.ANIMATION_ATTACHED, this.editorHandler); this.removeContextListener(EditorEvent.SOURCE_ATTACHED, this.editorHandler); } //} endregion PUBLIC METHODS =================================================== //============================================================================== //{region PRIVATE\PROTECTED METHODS override protected function editorHandler(event:EditorEvent):void { log(this, "editorHandler"); super.editorHandler(event); if(event.type == EditorEvent.SELECT_ITEM){ // this.viewComponent.cancel(); }else{ var sources:Array = []; var numElements:Vector.<int> = new <int>[]; var n:int = this.projectModel.sources.length; for(var i:int = 0; i < n; i++){ var source:SourceVO = this.projectModel.sources[i]; sources.push(source.name); numElements.push(source.elements.length); } this.data = new SheetToolsVO(sources, numElements, this.projectModel.sheetSize); } } //} endregion PRIVATE\PROTECTED METHODS ======================================== //============================================================================== //{region EVENTS HANDLERS private function openHandler(event:Event):void { if(this.viewComponent.data > 0 && this.projectModel.sources.length == 0){ var text:String = "Can not attach animation till no sources was attached"; warning(this, "selectHandler", text); StatusBar.warning(text); }else{ var method:Function = this.viewComponent.data == 0 ? this.fileSystemService.readSource : this.fileSystemService.readAnimation; method.apply(this); } } private function selectHandler(event:Event):void { var n:int = this.projectModel.sources.length; for(var i:int = 0; i < n; i++){ var source:SourceVO = this.projectModel.sources[i]; source.selected = source.name == this.viewComponent.data; } this.dispatch(new EditorEvent(EditorEvent.SELECT_ITEM)); this.dispatch(new EditorEvent(EditorEvent.SELECT_SHEETS, this.viewComponent.data)); } //} endregion EVENTS HANDLERS ================================================== //============================================================================== //{region GETTERS/SETTERS //} endregion GETTERS/SETTERS ================================================== } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package { import flash.display.DisplayObject; import flash.external.ExternalInterface; import mx.core.mx_internal; use namespace mx_internal; /** * Instead of a property, we use an event so the MXML * compiler will wrap the code in a function for us */ [Event(name="valueExpression", type="flash.events.Event")] /** * The test step that sets the browser to a specific URL * MXML attributes: * url * waitTarget (optional) * waitEvent (optional) * timeout (optional); */ public class SetURL extends TestStep { /** * Set the target's property to the specified value */ override protected function doStep():void { var count:int = 0; if (url.indexOf("BACK") == 0) { if (url.length > 4) count = parseInt(url.substring(4)); if (count > 0) ExternalInterface.call("goForwardOrBackInHistory", -count); else ExternalInterface.call("backButton"); } else if (url.indexOf("FORWARD") == 0) { if (url.length > 7) count = parseInt(url.substring(7)); if (count > 0) ExternalInterface.call("goForwardOrBackInHistory", count); else ExternalInterface.call("forwardButton"); } else { ExternalInterface.call("setURL", url); } } /** * The url to navigate to. Can also be "BACK" or "FORWARD" */ public var url:String; /** * customize string representation */ override public function toString():String { var s:String = "SetURL"; if (url) s += ", url = " + url; return s; } } }
package giftSystem.data { import ddt.data.goods.ShopItemInfo; import ddt.manager.ShopManager; public class MyGiftCellInfo { public var amount:int = 0; public var TemplateID:int = 0; public function MyGiftCellInfo() { super(); } public function get info() : ShopItemInfo { return ShopManager.Instance.getMoneyShopItemByTemplateIDForGiftSystem(this.TemplateID); } } }
package fr.manashield.flex.thex.blocks { import fr.manashield.flex.thex.utils.Color; import fr.manashield.flex.thex.geometry.Hexagon; import flash.display.Sprite; import flash.display.Stage; import flash.geom.Point; /** * @author Morgan Peyre (morgan@peyre.info) * @author Paul Bonnet */ public class HexagonalGrid extends Sprite { protected static var _instance:HexagonalGrid; protected var _grid:Object; protected var _gridSize:int; /* * create the singleton */ public static function init(stage:Stage, cellRadius:int, width:int = 100, height:int = 100):void { _instance = new HexagonalGrid(stage, cellRadius, 0, width, height); new Block(HexagonalGrid.instance.cell(new Point(0,0)), new Color(0x5c5c5c)); } /* * constructor */ public function HexagonalGrid(stage:Stage, cellRadius:uint, childIndex:uint = 0, width:uint = 100, height:uint = 100) : void { _grid = new Object(); _gridSize = cellRadius; stage.addChildAt(this, childIndex); for(var u:int = -width/2; u < width/2; ++u) for(var v:int = -height/2; v < height/2; ++v) { _grid[[u, v]] = new HexagonalCell(new Point(u, v), this); } // add background grid var radius:uint = Math.min(width,height)/2; for(var i:uint=1; i<radius; ++i) { var currentColor:uint = i%2?0xF5F5F5:0xFAFAFA; var nextCell:HexagonalCell = _grid[[0, i]]; for(var j:uint=0; j<i*6; ++j) { nextCell = nextCell.clockwiseNeighbor; var hex:Hexagon = new Hexagon(nextCell.center, HexagonalCell(_grid[[0, i]]).parent.gridSize, (j+1)%i?currentColor:0xE8E8E8, "flat"); addChild(hex); } } } /* * Hexagonal to Cartesian coordinates conversion (everyone knows that the cartesian doctrine is way better than the hexagonal. repent yourself sinners !) */ public function hexToCartesian(point:Point) : Point { var x:int = diapothem()*point.x*Math.cos(Math.PI/6) + Number(stage.stageWidth)/2; var y:int = - diapothem()*(point.y + point.x*Math.sin(Math.PI/6)) + Number(stage.stageHeight)/2; return new Point(x, y); } /* * Cartesian to Hexagonal coordinates conversion */ public function cartesianToHex(point:Point) : Point { var u:int = Math.round((point.x - Number(stage.stageWidth)/2)/(diapothem()*Math.cos(Math.PI/6))); var v:int = Math.round(-(point.y - Number(stage.stageHeight)/2)/diapothem() - u*Math.sin(Math.PI/6)); return new Point(u, v); } /* * getter for the grid's size */ public function get gridSize():int { return this._gridSize; } /* * Super badass function to calculate the apothem (i'm sure you didn't even heard about it before), * and then multiply it by 2 ! How crazy is that ? */ protected function diapothem():Number { return 2 * _gridSize * Math.cos(Math.PI/6); } /* * return the choosen cell. Even throw amazing Errors sometimes. */ public function cell(hexCoordinates:Point):HexagonalCell { return this._grid[[hexCoordinates.x,hexCoordinates.y]]; } /* * getter for the instance */ public static function get instance():HexagonalGrid { return _instance; } public function ring(radius:uint):Vector.<HexagonalCell> { var cells:Vector.<HexagonalCell> = new Vector.<HexagonalCell>(); var currentCell:HexagonalCell = this.cell(new Point(0,radius)); for(var i:uint=0; i<6*radius; ++i) { cells.push(currentCell); currentCell = currentCell.clockwiseNeighbor; } return cells; } } }
package kabam.rotmg.pets.view.dialogs { import com.company.assembleegameclient.ui.DeprecatedTextButton; import flash.display.Bitmap; import flash.display.DisplayObject; import flash.display.Sprite; import flash.events.MouseEvent; import kabam.rotmg.pets.util.PetsViewAssetFactory; import kabam.rotmg.pets.view.components.PopupWindowBackground; import kabam.rotmg.text.model.TextKey; import kabam.rotmg.text.view.TextFieldDisplayConcrete; import kabam.rotmg.text.view.stringBuilder.LineBuilder; import kabam.rotmg.ui.view.SignalWaiter; import org.osflash.signals.Signal; public class EggHatchedDialog extends Sprite { private const background:PopupWindowBackground = PetsViewAssetFactory.returnEggHatchWindowBackground(289, 279); private const titleTextfield:TextFieldDisplayConcrete = PetsViewAssetFactory.returnTextfield(0xFFFFFF, 18, true); private const typeTextfield:TextFieldDisplayConcrete = PetsViewAssetFactory.returnTextfield(16777103, 16, true); private const eggHatchImage:DisplayObject = new EggHatchImage(); private const sendToYardButton:DeprecatedTextButton = new DeprecatedTextButton(16, "Pets.sendToYard", 120); public const closed:Signal = new Signal(); private var EggHatchImage:Class; var skinType:int; private var petBitmap:Bitmap; private var petName:String; public function EggHatchedDialog(_arg1:String, _arg2:int) { this.EggHatchImage = EggHatchedDialog_EggHatchImage; super(); this.petName = _arg1; this.skinType = _arg2; this.sendToYardButton.addEventListener(MouseEvent.MOUSE_DOWN, this.onSendToYard); } private function onSendToYard(_arg1:MouseEvent):void { this.closed.dispatch(); } public function init(_arg1:Bitmap):void { this.petBitmap = _arg1; this.setTextValues(); this.waitForTextChanged(); this.addChildren(); this.positionAssets(); } private function setTextValues():void { this.titleTextfield.setStringBuilder(new LineBuilder().setParams(TextKey.PET_EGG_HATCHED)); this.typeTextfield.setStringBuilder(new LineBuilder().setParams(this.petName)); } private function onClosed():void { this.closed.dispatch(); } private function addChildren():void { this.eggHatchImage.y = 31; addChild(this.background); addChild(this.titleTextfield); addChild(this.typeTextfield); addChild(this.eggHatchImage); addChild(this.sendToYardButton); addChild(this.petBitmap); } private function positionAssets():void { this.positionThis(); this.petBitmap.x = ((287 - this.petBitmap.width) * 0.5); this.eggHatchImage.x = 1; this.eggHatchImage.y = 32; this.petBitmap.x = (this.petBitmap.x - 5); this.petBitmap.y = 41; } private function positionThis():void { this.x = ((stage.stageWidth - this.width) * 0.5); this.y = ((stage.stageHeight - this.height) * 0.5); } private function waitForTextChanged():void { var _local1:SignalWaiter = new SignalWaiter(); _local1.push(this.titleTextfield.textChanged); _local1.push(this.typeTextfield.textChanged); _local1.complete.addOnce(this.positionTextField); this.sendToYardButton.textChanged.add(this.positionButtonBar); } private function positionButtonBar():void { this.sendToYardButton.x = ((287 - this.sendToYardButton.width) * 0.5); this.sendToYardButton.y = 240; } private function positionTextField():void { this.titleTextfield.x = ((287 - this.titleTextfield.width) * 0.5); this.titleTextfield.y = 23; this.typeTextfield.x = ((287 - this.typeTextfield.width) * 0.5); this.typeTextfield.y = 230; } } }
package away3d.events { import away3d.core.render.*; import flash.events.Event; /** * Passed as a parameter when a session event occurs */ public class SessionEvent extends Event { /** * Defines the value of the type property of a sessionUpdated event object. */ public static const SESSION_UPDATED:String = "sessionUpdated"; /** * A reference to the session object that is relevant to the event. */ public var session:AbstractRenderSession; /** * Creates a new <code>FaceEvent</code> object. * * @param type The type of the event. Possible values are: <code>FaceEvent.UPDATED</code></code>. * @param session A reference to the session object that is relevant to the event. */ public function SessionEvent(type:String, session:AbstractRenderSession) { super(type); this.session = session; } /** * Creates a copy of the FaceEvent object and sets the value of each property to match that of the original. */ public override function clone():Event { return new SessionEvent(type, session); } } }
//////////////////////////////////////////////////////////////////////////////// // // 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.jewel { import org.apache.royale.jewel.supportClasses.ISelectableContent; COMPILE::JS { import org.apache.royale.core.WrappedHTMLElement; import org.apache.royale.html.util.addElementToWrapper; } /** * The TabBarContent class is a Container component capable of parenting * the other organized content that implements ISelectableContent interface * (i.e, a SectionContent) * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.9.4 */ public class TabBarContent extends Container { /** * constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.9.4 */ public function TabBarContent() { super(); typeNames = "jewel tabbarcontent"; } private var _selectedContent:String; /** * shows a concrete content and hides the rest * * @param name, the name of the container to show * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.9.4 */ public function get selectedContent():String { return _selectedContent; } public function set selectedContent(name:String):void { if(_selectedContent != name) { _selectedContent = name; selectContent(); } } public function selectContent():void { try { for (var i:int = 0; i < numElements; i++) { var content:ISelectableContent = getElementAt(i) as ISelectableContent; if(content.name == _selectedContent) { content.isSelected = true; } else { content.isSelected = false; } } } catch (error:Error) { throw new Error ("One or more content in TabBarContent is not implementing ISelectableContent interface."); } } /** * @royaleignorecoercion org.apache.royale.core.WrappedHTMLElement */ COMPILE::JS override protected function createElement():WrappedHTMLElement { return addElementToWrapper(this, 'div'); } /** * The method called when added to a parent. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.9.6 */ override public function addedToParent():void { super.addedToParent(); selectContent(); } } }
class Enemy { private var mShip:MovieClip; private var lives:Number; private var shoot:Boolean; private var score:Number; private var moveType:Number; private var moveSpeed:Number; private var pointReached:Boolean = false; private var fireDelay:Number; private var fireCounter:Number; //Enemy constructor which requires: //1) Movie clip - for the enemy //2) Lives - The number of lives the enemy has //3) Shoot - Whether or not the enemy has the ability to shoot or not. //4) Score - The score given to the player if the enemy is killed. //5) MoveType - The path the enemy should move on. //6) MoveSpeed - The speed at which the enemy should move. //7) startX - The starting x position. //8) startY - The starting y position. //9) FireDelay - The delay between firing. public function Enemy(mShip:MovieClip, lives:Number, shoot:Boolean, score:Number, moveType:Number, moveSpeed:Number, startX:Number, startY:Number, fireDelay:Number) { this.mShip = mShip; this.lives = lives; this.shoot = shoot; this.score = score; this.moveType = moveType; this.moveSpeed = moveSpeed; this.mShip._x = startX; this.mShip._y = startY; this.fireDelay = fireDelay; fireCounter = fireDelay; } //Update the enemies counter before he can fire again. public function updateEnemy() { ++fireCounter; } //Return a boolean value which shows if the enemy can fire or not. public function canFire() { if ((fireCounter > fireDelay) && shoot) { return true; } else { return false; } } //Set the Counter before the enemy can fire. public function setFireCounter(fireCounter:Number) :Void { this.fireCounter = fireCounter; } //Return whether or not the enemy has the ability to shoot. public function getShoot() :Boolean { return shoot; } //Return the score given to the player by this enemy. public function getScore() :Number { return score; } //Set the score to a given value. public function setScore(score:Number) :Void { score = score; } //Set the number of lives the enemy has. public function setLives(l:Number) :Void { lives = l; } //Increment the number of lives the enemy has. public function incrementLives() :Void { ++lives; } //Decrement the number of lives the enemy has. public function decrementLives() :Void { --lives; } //Retuen the Movie Clip public function getMovieClip() :MovieClip { return mShip; } //Move the enemy depending upon the movetype of the enemy. public function moveEnemy() :Void { //Move left to right and back again. if (moveType == 0) { if (mShip._x < (Stage.width - mShip._width) && (pointReached == false)) { mShip._x = mShip._x + moveSpeed; } else { pointReached = true; } if ((mShip._x > mShip._width) && (pointReached == true)) { mShip._x = mShip._x - moveSpeed; } else { pointReached = false; } } else if (moveType == 1) { if (mShip._x < (Stage.width - mShip._width) && (pointReached == false)) { mShip._x = mShip._x + moveSpeed; } else if (mShip._x >= (Stage.width - mShip._width) && (pointReached == false)) { pointReached = true; mShip._y = mShip._y + (mShip._height * 1.5); } else if ((mShip._x > mShip._width) && (pointReached == true)) { mShip._x = mShip._x - moveSpeed; } else if ((mShip._x <= mShip._width) && (pointReached == true)) { pointReached = false; mShip._y = mShip._y + (mShip._height * 1.5); } } } }
/* See LICENSE for copyright and terms of use */ import org.actionstep.constants.NSRunResponse; /** * The following values are derivatives of <code>org.actionstep.constants.NSRunResponse</code>, * since functions handling these values are not aware of their content and merely * pass it along. * * These values are used as return codes from <code>NSAlert</code> functions. * * Please note that return values for buttons are position dependant. If you have * more than three buttons on your alert, the button-position return value is * NSThirdButtonReturn + n, where n is an integer. * * Localization is as yet unsupported. */ class org.actionstep.constants.NSAlertReturn extends NSRunResponse { //****************************************************** //* Class members //****************************************************** /** * A map of constant values to constants. */ private static var g_valueToConstant:Object ; //****************************************************** //* Return values for alert panels //****************************************************** /** * The value returned if running the NSAlertPanel resulted in an error. */ public static var NSError:NSAlertReturn = new NSAlertReturn(-2); //****************************************************** //* Return values for buttons //****************************************************** /** The user clicked the first (rightmost) button on the dialog or sheet. */ public static var NSFirstButton:NSAlertReturn = new NSAlertReturn(1000); /** The user clicked the second button from the right edge of the dialog or sheet. */ public static var NSSecondButton:NSAlertReturn = new NSAlertReturn(1001); /** The user clicked the third button from the right edge of the dialog or sheet. */ public static var NSThirdButton:NSAlertReturn = new NSAlertReturn(1002); //****************************************************** //* Construction //****************************************************** /** * Private constructor */ private function NSAlertReturn(value:Number) { super(value); if (g_valueToConstant == null) { g_valueToConstant = {}; } g_valueToConstant[value.toString()] = this; } //****************************************************** //* Getting other return values //****************************************************** /** * Returns the alert return constant for the specified button number. The * button number is 0-indexed, so 0 corresponds to the first button, 1 to * the second and so on. */ public static function alertReturnForButtonNumber(num:Number):NSAlertReturn { return alertReturnForValue(NSFirstButton.value + num); } /** * Returns the alert return constant for the specified constant value. */ public static function alertReturnForValue(val:Number):NSAlertReturn { var ret:NSAlertReturn = NSAlertReturn(g_valueToConstant[val.toString()]); if (ret == null) { ret = new NSAlertReturn(val); } return ret; } }
package com.napkee.exporters { import com.adobe.utils.StringUtil; import com.napkee.utils.ColorUtils; import com.napkee.utils.ComponentParser; import com.napkee.utils.StringUtils; import mx.containers.Canvas; import mx.controls.Label; import mx.core.UIComponent; public class StickyNoteParser extends BasicParser implements IControlParser { public function StickyNoteParser(controlCode:XML,offsetModifier:OffsetModifier) { super(controlCode,offsetModifier); templateName = "stickynote.xml"; if (StringUtils.isBlank(control.controlProperties.text)){ if (control.controlProperties.child("text").length() > 0){ control.controlProperties.text = ""; } else { control.controlProperties.text = "A comment"; } } control.controlProperties.align = "center"; } public override function getHtml():String { var cp:ComponentParser = getBaseHtml(); var text:String = (control.controlProperties.text); if (text.indexOf("%0A") > -1){ control.controlProperties.align = "left"; var code:String = ""; var crumbs:Array = text.split("%0A"); for (var i:int = 0;i<crumbs.length;i++){ var line:String = StringUtil.trim(unescape(crumbs[i] as String)); code += StringUtils.escapeCharsAndGetHtml(line) + '<br/>'; } cp.setPlaceHolder("label",code); } else { control.controlProperties.align = "center"; cp.setPlaceHolder("label",StringUtils.escapeCharsAndGetHtml(unescape(text))); } //cp.setPlaceHolder("label",StringUtils.escapeCharsAndGetHtml(unescape(control.controlProperties.text))); return cp.getParsed(); } public override function getCss():String { var cp:ComponentParser = getBaseCss(); if (StringUtils.isNotBlank(control.controlProperties.color)){ cp.setPlaceHolder("color","#"+ColorUtils.intToHex(control.controlProperties.color)); } else { cp.setPlaceHolder("color","#DACE5F"); } return cp.getParsed(); } } }
/* * Copyright (C) 2003-2012 Igniterealtime Community Contributors * * Daniel Henninger * Derrick Grigg <dgrigg@rogers.com> * Juga Paazmaya <olavic@gmail.com> * Nick Velloff <nick.velloff@gmail.com> * Sean Treadway <seant@oncotype.dk> * Sean Voisen <sean@voisen.org> * Mark Walters <mark@yourpalmark.com> * Michael McCarthy <mikeycmccarthy@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 org.igniterealtime.xiff.bookmark { import flash.events.EventDispatcher; import org.igniterealtime.xiff.core.UnescapedJID; import org.igniterealtime.xiff.data.INodeProxy; import org.igniterealtime.xiff.data.XMPPStanza; import org.igniterealtime.xiff.data.privatedata.PrivateDataExtension; import org.igniterealtime.xiff.events.BookmarkChangedEvent; import org.igniterealtime.xiff.events.BookmarkRetrievedEvent; import org.igniterealtime.xiff.privatedata.PrivateDataManager; import org.igniterealtime.xiff.util.Callback; /** * @eventType org.igniterealtime.xiff.events.BookmarkChangedEvent.GROUPCHAT_BOOKMARK_ADDED */ [Event(name="groupchatBookmarkAdded", type="org.igniterealtime.xiff.events.BookmarkChangedEvent")] /** * @eventType org.igniterealtime.xiff.events.BookmarkChangedEvent.GROUPCHAT_BOOKMARK_REMOVED */ [Event(name="groupchatBookmarkRemoved", type="org.igniterealtime.xiff.events.BookmarkChangedEvent")] /** * @eventType org.igniterealtime.xiff.events.BookmarkRetrievedEvent.BOOKMARK_RETRIEVED */ [Event(name="bookmarkRetrieved", type="org.igniterealtime.xiff.events.BookmarkRetrievedEvent")] /** * XEP-0048: Bookmarks * * @see http://xmpp.org/extensions/xep-0048.html */ public class BookmarkManager extends EventDispatcher { private var _bookmarks:BookmarkPrivatePayload; private var _privateDataManager:PrivateDataManager; /** * * @param privateDataManager */ public function BookmarkManager( privateDataManager:PrivateDataManager ) { _privateDataManager = privateDataManager; } /** * * @param serverBookmark */ public function addGroupChatBookmark( serverBookmark:GroupChatBookmark ):void { if ( !_bookmarks ) { _privateDataManager.getPrivateData( "storage", "storage:bookmarks", new Callback( this, this[ "_processBookmarksAdd" ], serverBookmark )); } else { _addBookmark( serverBookmark ); } } public function fetchBookmarks():void { if ( !_bookmarks ) { _privateDataManager.getPrivateData( "storage", "storage:bookmarks", new Callback( this, this[ "_processBookmarks" ])); } else { dispatchEvent( new BookmarkRetrievedEvent()); } } /** * Get a group chat bookmark with the given JID * * @param jid * @return */ public function getGroupChatBookmark( jid:UnescapedJID ):GroupChatBookmark { for each ( var bookmark:GroupChatBookmark in _bookmarks.groupChatBookmarks ) { if ( bookmark.jid.unescaped.equals( jid, false )) { return bookmark; } } return null; } /** * Does there exist a group chat bookmark with the given JID * * @param jid * @return */ public function isGroupChatBookmarked( jid:UnescapedJID ):Boolean { for each ( var bookmark:GroupChatBookmark in _bookmarks.groupChatBookmarks ) { if ( bookmark.jid.unescaped.equals( jid, false )) { return true; } } return false; } /** * Remove * @param jid */ public function removeGroupChatBookmark( jid:UnescapedJID ):void { if ( !_bookmarks ) { _privateDataManager.getPrivateData( "storage", "storage:bookmarks", new Callback( this, this[ "_processBookmarksRemove" ], jid )); } else { _removeBookmark( jid ); } } /** * Set autoJoin for the given bookmark JID * * @param jid * @param state */ public function setAutoJoin( jid:UnescapedJID, state:Boolean ):void { if ( !_bookmarks ) { _privateDataManager.getPrivateData( "storage", "storage:bookmarks", new Callback( this, this[ "_processBookmarksSetAuto" ], jid, state )); } else { _setAutoJoin( jid, state ); } } private function _addBookmark( bookmark:INodeProxy ):void { var groupChats:Array = _bookmarks.groupChatBookmarks; var urls:Array = _bookmarks.urlBookmarks; if ( bookmark is GroupChatBookmark ) { groupChats.push( bookmark ); } else if ( bookmark is UrlBookmark ) { urls.push( bookmark ); } var payload:BookmarkPrivatePayload = new BookmarkPrivatePayload( groupChats, urls ); _privateDataManager.setPrivateData( "storage", "storage:bookmarks", payload ); _bookmarks = payload; dispatchEvent( new BookmarkChangedEvent( BookmarkChangedEvent.GROUPCHAT_BOOKMARK_ADDED, bookmark )); } private function _processBookmarks( bookmarksIq:XMPPStanza ):void { var privateData:PrivateDataExtension = bookmarksIq.getAllExtensionsByNS( "jabber:iq:private" )[ 0 ]; _bookmarks = BookmarkPrivatePayload( privateData.payload ); dispatchEvent( new BookmarkRetrievedEvent()); } private function _processBookmarksAdd( bookmark:INodeProxy, bookmarksIq:XMPPStanza ):void { _processBookmarks( bookmarksIq ); _addBookmark( bookmark ); } private function _processBookmarksRemove( jid:UnescapedJID, bookmarksIq:XMPPStanza ):void { _processBookmarks( bookmarksIq ); _removeBookmark( jid ); } private function _processBookmarksSetAuto( jid:UnescapedJID, state:Boolean, bookmarksIq:XMPPStanza ):void { _processBookmarks( bookmarksIq ); _setAutoJoin( jid, state ); } private function _removeBookmark( jid:UnescapedJID ):void { var removedBookmark:GroupChatBookmark = _bookmarks.removeGroupChatBookmark( jid ); _updateBookmarks(); dispatchEvent( new BookmarkChangedEvent( BookmarkChangedEvent.GROUPCHAT_BOOKMARK_REMOVED, removedBookmark )); } private function _setAutoJoin( jid:UnescapedJID, state:Boolean ):void { for each ( var bookmark:GroupChatBookmark in _bookmarks.groupChatBookmarks ) { if ( bookmark.jid.unescaped.equals( jid, false )) { bookmark.autoJoin = state; } } _updateBookmarks(); } private function _updateBookmarks():void { var groupChats:Array = _bookmarks.groupChatBookmarks; var urls:Array = _bookmarks.urlBookmarks; var payload:BookmarkPrivatePayload = new BookmarkPrivatePayload( groupChats, urls ); _privateDataManager.setPrivateData( "storage", "storage:bookmarks", payload ); } /** * */ public function get bookmarks():BookmarkPrivatePayload { return _bookmarks; } } }
package elements.menu { import flash.display.Sprite; import flash.events.MouseEvent; import flash.external.ExternalInterface; import flash.text.TextField; import flash.text.TextFieldType; import flash.text.TextFormat; public class CameraIcon extends menuItem { public function CameraIcon(chartId:String, props:Properties) { super(chartId, props); } protected override function add_elements(): Number { this.draw_camera(); var width:Number = this.add_text(this.props.get('text'), 35); return width+30; // 30 is the icon width } private function draw_camera():void { var s:Sprite = new Sprite(); s.graphics.beginFill(0x505050); s.graphics.drawRoundRect(2, 4, 26, 14, 2, 2); s.graphics.drawRect(20, 1, 5, 3); s.graphics.endFill(); s.graphics.beginFill(0x202020); s.graphics.drawCircle(9, 11, 4.5); s.graphics.endFill(); this.addChild(s); } } }
package com.longtailvideo.jwplayer.utils { import flash.events.ErrorEvent; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.SharedObject; import flash.net.URLLoader; import flash.net.URLRequest; /** * Sent when the configuration block has been successfully retrieved * * @eventType flash.events.Event.COMPLETE */ [Event(name="complete", type = "flash.events.Event")] /** * Sent when an error in the config has * * @eventType flash.events.ErrorEvent.ERROR */ [Event(name="error", type = "flash.events.ErrorEvent")] public class Configger extends EventDispatcher { private var _config:Object = {}; /** The loaded config object; can an XML object or a hash map. **/ public function get config():Object { return _config; } /** * @return * @throws Error if something bad happens. */ public function loadConfig():void { loadCookies(); if (this.xmlConfig) { loadXML(this.xmlConfig); } else { loadFlashvars(RootReference.parameters); } } /** Whether the "config" flashvar is set **/ public function get xmlConfig():String { return RootReference.root.loaderInfo.parameters['config']; } /** * Loads a config block from an XML file * @param url The location of the config file. Can be absolute URL or path relative to the player SWF. */ public function loadXML(url:String):void { var xmlLoader:URLLoader = new URLLoader(); xmlLoader.addEventListener(IOErrorEvent.IO_ERROR, xmlFail); xmlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, xmlFail); xmlLoader.addEventListener(Event.COMPLETE, loadComplete); xmlLoader.load(new URLRequest(url)); } /** * Loads configuration flashvars * @param params Hash map containing key/value pairs */ public function loadFlashvars(params:Object):void { try { for (var param:String in params) { setConfigParam(param, params[param]); } dispatchEvent(new Event(Event.COMPLETE)); } catch (e:Error) { dispatchEvent(new ErrorEvent(ErrorEvent.ERROR, false, false, e.message)); } } public static function saveCookie(param:String, value:*):void { try { var cookie:SharedObject = SharedObject.getLocal('com.jeroenwijering','/'); cookie.data[param] = value; cookie.flush(); } catch (err:Error) {} } private function loadCookies():void { try { var cookie:SharedObject = SharedObject.getLocal('com.jeroenwijering','/'); writeCookieData(cookie.data); } catch (err:Error) {} } /** Overwrite cookie data. **/ private function writeCookieData(obj:Object):void { for (var cfv:String in obj) { setConfigParam(cfv.toLowerCase(), obj[cfv]); } } private function loadComplete(evt:Event):void { var loadedXML:XML = XML((evt.target as URLLoader).data); if (loadedXML.name().toString().toLowerCase() == "config" && loadedXML.children().length() > 0) { parseXML(loadedXML); loadFlashvars(RootReference.root.loaderInfo.parameters); } else { dispatchEvent(new ErrorEvent(ErrorEvent.ERROR, false, false, "Config was empty")); } } private function xmlFail(evt:ErrorEvent):void { dispatchEvent(new ErrorEvent(ErrorEvent.ERROR, false, false, evt.text)); } private function parseXML(xml:XML):void { for each(var item:XML in xml.children()) { if (item.name() == "pluginconfig") { parsePluginConfig(item); } else { setConfigParam(item.name().toString(), item.toString()); } } } private function parsePluginConfig(pluginconfig:XML):void { for each(var plugin:XML in pluginconfig.plugin) { for each(var pluginParam:XML in plugin.children()) { setConfigParam(plugin.@name + "." + pluginParam.name(), pluginParam.toString()); } } } private function setConfigParam(name:String, value:String):void { if (name != "fullscreen") { _config[name.toLowerCase()] = Strings.serialize(Strings.trim(value)); } } } }
/* ***** 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) 2005-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 = "15.7.2"; var VERSION = "ECMA_1"; startTest(); var TITLE = "The Number Constructor"; writeHeaderToLog( SECTION + " "+ TITLE); var testcases = new Array(); testcases = getTestCases(); test(); function getTestCases() { var array = new Array(); var item = 0; // To verify that the object's prototype is the Number.prototype, check to see if the // object's // constructor property is the same as Number.prototype.constructor. array[item++] = new TestCase(SECTION, "(new Number()).constructor", Number.prototype.constructor, (new Number()).constructor ); array[item++] = new TestCase(SECTION, "typeof (new Number())", "number", typeof (new Number()) ); array[item++] = new TestCase(SECTION, "(new Number()).valueOf()", 0, (new Number()).valueOf() ); NUMB = new Number(); array[item++] = new TestCase(SECTION, "NUMB = new Number();NUMB.toString=Object.prototype.toString;NUMB.toString()", "0", NUMB.toString() ); array[item++] = new TestCase(SECTION, "(new Number(0)).constructor", Number.prototype.constructor, (new Number(0)).constructor ); array[item++] = new TestCase(SECTION, "typeof (new Number(0))", "number", typeof (new Number(0)) ); array[item++] = new TestCase(SECTION, "(new Number(0)).valueOf()", 0, (new Number(0)).valueOf() ); NUMB = new Number(0); array[item++] = new TestCase(SECTION, "NUMB = new Number(0);NUMB.toString=Object.prototype.toString;NUMB.toString()", "0", NUMB.toString() ); array[item++] = new TestCase(SECTION, "(new Number(1)).constructor", Number.prototype.constructor, (new Number(1)).constructor ); array[item++] = new TestCase(SECTION, "typeof (new Number(1))", "number", typeof (new Number(1)) ); array[item++] = new TestCase(SECTION, "(new Number(1)).valueOf()", 1, (new Number(1)).valueOf() ); NUMB = new Number(1); array[item++] = new TestCase(SECTION, "NUMB = new Number(1);NUMB.toString=Object.prototype.toString;NUMB.toString()", "1", NUMB.toString() ); array[item++] = new TestCase(SECTION, "(new Number(-1)).constructor", Number.prototype.constructor, (new Number(-1)).constructor ); array[item++] = new TestCase(SECTION, "typeof (new Number(-1))", "number", typeof (new Number(-1)) ); array[item++] = new TestCase(SECTION, "(new Number(-1)).valueOf()", -1, (new Number(-1)).valueOf() ); NUMB = new Number(-1); array[item++] = new TestCase(SECTION, "NUMB = new Number(-1);NUMB.toString=Object.prototype.toString;NUMB.toString()", "-1", NUMB.toString() ); array[item++] = new TestCase(SECTION, "(new Number(Number.NaN)).constructor", Number.prototype.constructor, (new Number(Number.NaN)).constructor ); array[item++] = new TestCase(SECTION, "typeof (new Number(Number.NaN))", "number", typeof (new Number(Number.NaN)) ); array[item++] = new TestCase(SECTION, "(new Number(Number.NaN)).valueOf()", Number.NaN, (new Number(Number.NaN)).valueOf() ); NUMB = new Number(Number.NaN); array[item++] = new TestCase(SECTION, "NUMB = new Number(Number.NaN);NUMB.toString=Object.prototype.toString;NUMB.toString()", "NaN", NUMB.toString() ); array[item++] = new TestCase(SECTION, "(new Number('string')).constructor", Number.prototype.constructor, (new Number('string')).constructor ); array[item++] = new TestCase(SECTION, "typeof (new Number('string'))", "number", typeof (new Number('string')) ); array[item++] = new TestCase(SECTION, "(new Number('string')).valueOf()", Number.NaN, (new Number('string')).valueOf() ); NUMB = new Number('string'); array[item++] = new TestCase(SECTION, "NUMB = new Number('string');NUMB.toString=Object.prototype.toString;NUMB.toString()", "NaN", NUMB.toString() ); array[item++] = new TestCase(SECTION, "(new Number(new String())).constructor", Number.prototype.constructor, (new Number(new String())).constructor ); array[item++] = new TestCase(SECTION, "typeof (new Number(new String()))", "number", typeof (new Number(new String())) ); array[item++] = new TestCase(SECTION, "(new Number(new String())).valueOf()", 0, (new Number(new String())).valueOf() ); NUMB = new Number(new String()); array[item++] = new TestCase(SECTION, "NUMB = new Number(new String());NUMB.toString=Object.prototype.toString;NUMB.toString()", "0", NUMB.toString() ); array[item++] = new TestCase(SECTION, "(new Number('')).constructor", Number.prototype.constructor, (new Number('')).constructor ); array[item++] = new TestCase(SECTION, "typeof (new Number(''))", "number", typeof (new Number('')) ); array[item++] = new TestCase(SECTION, "(new Number('')).valueOf()", 0, (new Number('')).valueOf() ); NUMB = new Number(''); array[item++] = new TestCase(SECTION, "NUMB = new Number('');NUMB.toString=Object.prototype.toString;NUMB.toString()", "0", NUMB.toString() ); array[item++] = new TestCase(SECTION, "(new Number(Number.POSITIVE_INFINITY)).constructor", Number.prototype.constructor, (new Number(Number.POSITIVE_INFINITY)).constructor ); array[item++] = new TestCase(SECTION, "typeof (new Number(Number.POSITIVE_INFINITY))", "number", typeof (new Number(Number.POSITIVE_INFINITY)) ); array[item++] = new TestCase(SECTION, "(new Number(Number.POSITIVE_INFINITY)).valueOf()", Number.POSITIVE_INFINITY, (new Number(Number.POSITIVE_INFINITY)).valueOf() ); NUMB = new Number(Number.POSITIVE_INFINITY); array[item++] = new TestCase(SECTION, "NUMB = new Number(Number.POSITIVE_INFINITY);NUMB.toString=Object.prototype.toString;NUMB.toString()", "Infinity", NUMB.toString() ); array[item++] = new TestCase(SECTION, "(new Number(Number.NEGATIVE_INFINITY)).constructor", Number.prototype.constructor, (new Number(Number.NEGATIVE_INFINITY)).constructor ); array[item++] = new TestCase(SECTION, "typeof (new Number(Number.NEGATIVE_INFINITY))", "number", typeof (new Number(Number.NEGATIVE_INFINITY)) ); array[item++] = new TestCase(SECTION, "(new Number(Number.NEGATIVE_INFINITY)).valueOf()", Number.NEGATIVE_INFINITY, (new Number(Number.NEGATIVE_INFINITY)).valueOf() ); NUMB = new Number(Number.NEGATIVE_INFINITY); array[item++] = new TestCase(SECTION, "NUMB = new Number(Number.NEGATIVE_INFINITY);NUMB.toString=Object.prototype.toString;NUMB.toString()", "-Infinity", NUMB.toString() ); array[item++] = new TestCase(SECTION, "(new Number()).constructor", Number.prototype.constructor, (new Number()).constructor ); array[item++] = new TestCase(SECTION, "typeof (new Number())", "number", typeof (new Number()) ); array[item++] = new TestCase(SECTION, "(new Number()).valueOf()", 0, (new Number()).valueOf() ); NUMB = new Number(); array[item++] = new TestCase(SECTION, "NUMB = new Number();NUMB.toString=Object.prototype.toString;NUMB.toString()", "0", NUMB.toString() ); array[item++] = new TestCase(SECTION, "new Number()", 0, new Number() ); array[item++] = new TestCase(SECTION, "new Number(void 0)", Number.NaN, new Number(void 0) ); array[item++] = new TestCase(SECTION, "new Number(null)", 0, new Number(null) ); array[item++] = new TestCase(SECTION, "new Number(new Number())", 0, Number( new Number() ) ); array[item++] = new TestCase(SECTION, "new Number(0)", 0, new Number(0) ); array[item++] = new TestCase(SECTION, "new Number(1)", 1, new Number(1) ); array[item++] = new TestCase(SECTION, "new Number(-1)", -1, new Number(-1) ); array[item++] = new TestCase(SECTION, "new Number(NaN)", Number.NaN, new Number( Number.NaN ) ); array[item++] = new TestCase(SECTION, "new Number('string')", Number.NaN, new Number( "string") ); array[item++] = new TestCase(SECTION, "new Number(new String())", 0, new Number( new String() ) ); array[item++] = new TestCase(SECTION, "new Number('')", 0, new Number( "" ) ); array[item++] = new TestCase(SECTION, "new Number(Infinity)", Number.POSITIVE_INFINITY, new Number("Infinity") ); array[item++] = new TestCase(SECTION, "new Number(-Infinity)", Number.NEGATIVE_INFINITY, new Number("-Infinity") ); array[item++] = new TestCase(SECTION, "new Number(3.141592653589793)", Math.PI, new Number("3.141592653589793") ); array[item++] = new TestCase(SECTION, "new Number(4294967297)", (Math.pow(2,32)+1), new Number("4294967297") ); array[item++] = new TestCase(SECTION, "new Number(1e2000)", Infinity, new Number(1e2000) ); array[item++] = new TestCase(SECTION, "new Number(-1e2000)", -Infinity, new Number(-1e2000) ); array[item++] = new TestCase(SECTION, "new Number(1e-2000)", 0, new Number(1e-2000) ); array[item++] = new TestCase(SECTION, "new Number(1/1e-2000)", Infinity, new Number(1/1e-2000) ); array[item++] = new TestCase(SECTION, "new Number(true)", 1, new Number(true) ); array[item++] = new TestCase(SECTION, "new Number(false)", 0, new Number(false) ); array[item++] = new TestCase(SECTION, "new Number(new Boolean(false)", 0, new Number(new Boolean(false)) ); array[item++] = new TestCase(SECTION, "new Number(new String('Number.POSITIVE_INFINITY')", Infinity, new Number(new String(Number.POSITIVE_INFINITY)) ); array[item++] = new TestCase(SECTION, "new Number(new Number(false)", 0, new Number(new Number(false)) ); array[item++] = new TestCase(SECTION, "new Number('3000000000.25')", (3000000000.25), new Number("3000000000.25") ); array[item++] = new TestCase(SECTION, "new Number(-'3000000000.25')", (-3000000000.25), new Number(-"3000000000.25") ); array[item++] = new TestCase(SECTION, "new Number('1.79769313486231e+308')",(Number.MAX_VALUE+""),new Number("1.79769313486231e+308")+"" ); array[item++] = new TestCase(SECTION, "new Number('4.9406564584124654e-324')",(Number.MIN_VALUE+""),new Number("4.9406564584124654e-324")+"" ); array[item++] = new TestCase(SECTION, "new Number(new MyObject(100))", 100, new Number(new MyObject(100)) ); var s:String = "0xFFFFFFFFFFFFF80000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; array[item++] = new TestCase(SECTION, "new Number(s)",parseInt(s),new Number(s) ); array[item++] = new TestCase(SECTION, "new Number(-s)",((-5.03820925841965e+263)+""), new Number(-s)+"" ); array[item++] = new TestCase( SECTION, "new Number(-\"\")", 0, new Number(-"" )); array[item++] = new TestCase( SECTION, "new Number(-\" \")", 0, new Number(-" " )); array[item++] = new TestCase( SECTION, "new Number(-\"999\")", -999, new Number(-"999") ); array[item++] = new TestCase( SECTION, "new Number(-\" 999\")", -999, new Number(-" 999") ); array[item++] = new TestCase( SECTION, "new Number(-\"\\t999\")", -999, new Number(-"\t999") ); array[item++] = new TestCase( SECTION, "new Number(-\"013 \")", -13, new Number(-"013 " )); array[item++] = new TestCase( SECTION, "new Number(-\"999\\t\")", -999, new Number(-"999\t") ); array[item++] = new TestCase( SECTION, "new Number(-\"-Infinity\")", Infinity, new Number(-"-Infinity" )); array[item++] = new TestCase( SECTION, "new Number(-\"-infinity\")", NaN, new Number(-"-infinity")); array[item++] = new TestCase( SECTION, "new Number(-\"+Infinity\")", -Infinity, new Number(-"+Infinity") ); array[item++] = new TestCase( SECTION, "new Number(-\"+Infiniti\")", NaN, new Number(-"+Infiniti")); array[item++] = new TestCase( SECTION, "new Number(- -\"0x80000000\")", 2147483648, new Number(- -"0x80000000")); array[item++] = new TestCase( SECTION, "new Number(- -\"0x100000000\")", 4294967296, new Number(- -"0x100000000") ); array[item++] = new TestCase( SECTION, "new Number(- \"-0x123456789abcde8\")", 81985529216486880, new Number(- "-0x123456789abcde8")); return ( array ); } function MyObject( value ) { this.value = value; this.valueOf = function() { return this.value; } }
package com.tencent.morefun.naruto.plugin.exui.tooltip { import flash.display.Sprite; import com.tencent.morefun.naruto.plugin.exui.tooltip.data.CommonUserPopupMenuData; import flash.utils.Dictionary; import flash.display.InteractiveObject; import flash.events.MouseEvent; import com.tencent.morefun.naruto.plugin.ui.layer.LayerManager; import com.tencent.morefun.naruto.plugin.ui.layer.def.LayerDef; import ui.plugin.rank.PopupMenuUI; import flash.text.StyleSheet; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.events.TextEvent; import guild.command.JoinGuildProtoCommand; import crew.cmd.OpenOthersCrewBoxCommand; import friend.command.RequestAddFriendCommand; public class CommonUserPopuoMenu extends Sprite { private static var mData:CommonUserPopupMenuData; private static var bingdingInfoMap:Dictionary = new Dictionary(); private static var instance:com.tencent.morefun.naruto.plugin.exui.tooltip.CommonUserPopuoMenu; private var _view:PopupMenuUI; public function CommonUserPopuoMenu() { super(); this._view = new PopupMenuUI(); this.addChild(this._view); this._view.content.addEventListener(TextEvent.LINK,this.linkClickHandler); LayerManager.singleton.stage.addEventListener(MouseEvent.MOUSE_WHEEL,this.wheelHandler); LayerManager.singleton.stage.addEventListener(MouseEvent.CLICK,this.stageClickHandler,false,int.MIN_VALUE); } public static function get singleton() : com.tencent.morefun.naruto.plugin.exui.tooltip.CommonUserPopuoMenu { if(instance == null) { instance = new com.tencent.morefun.naruto.plugin.exui.tooltip.CommonUserPopuoMenu(); } return instance; } public static function bingding(param1:InteractiveObject, param2:CommonUserPopupMenuData) : void { param1.addEventListener(MouseEvent.CLICK,onBingdingUIClick); bingdingInfoMap[param1] = param2; } public static function unbingding(param1:InteractiveObject) : void { param1.removeEventListener(MouseEvent.CLICK,onBingdingUIClick); delete bingdingInfoMap[param1]; } private static function onBingdingUIClick(param1:MouseEvent) : void { param1.stopImmediatePropagation(); mData = bingdingInfoMap[param1.currentTarget]; LayerManager.singleton.addItemToLayer(singleton,LayerDef.TEXT_BOX); singleton.x = LayerManager.singleton.stage.mouseX; singleton.y = LayerManager.singleton.stage.mouseY - 10; mData && singleton.render(); } private function stageClickHandler(param1:MouseEvent) : void { this.dispose(); } private function wheelHandler(param1:MouseEvent) : void { this.dispose(); } private function render() : void { /* * Decompilation error * Code may be obfuscated * Tip: You can try enabling "Automatic deobfuscation" in Settings * Error type: IndexOutOfBoundsException (Index: 3, Size: 3) */ throw new flash.errors.IllegalOperationError("Not decompiled due to error"); } private function linkClickHandler(param1:TextEvent) : void { /* * Decompilation error * Code may be obfuscated * Tip: You can try enabling "Automatic deobfuscation" in Settings * Error type: IndexOutOfBoundsException (Index: 3, Size: 3) */ throw new flash.errors.IllegalOperationError("Not decompiled due to error"); } public function dispose() : void { LayerManager.singleton.stage.removeEventListener(MouseEvent.MOUSE_WHEEL,this.wheelHandler); LayerManager.singleton.stage.removeEventListener(MouseEvent.CLICK,this.stageClickHandler,false); LayerManager.singleton.removeItemToLayer(singleton); instance.removeChildren(); this._view.content.removeEventListener(TextEvent.LINK,this.linkClickHandler); this._view = null; mData = null; instance = null; } public function get data() : CommonUserPopupMenuData { return mData; } } }
/* Copyright (c) 2011 Taro Hanamura See LICENSE.txt for full license information. */ package org.typefest.display.layout { public class ComplexBridge extends Bridge { ///// range public function get rangeX():Number { return _b.x - _a.x } public function get rangeY():Number { return _b.y - _a.y } ///// offset protected var _offsetX:Number = NaN; protected var _offsetY:Number = NaN; public function get offsetX():Number { return _offsetX } public function set offsetX(_:Number):void { if (_offsetX !== _) { _offsetX = _; _update(); } } public function get offsetY():Number { return _offsetY } public function set offsetY(_:Number):void { if (_offsetY !== _) { _offsetY = _; _update(); } } ///// ratio override public function get ratio():Number { return 0 } override public function set ratio(_:Number):void {} ///// ratio protected var _ratioX:Number = 0; protected var _ratioY:Number = 0; public function get ratioX():Number { return _ratioX } public function set ratioX(_:Number):void { if (_ratioX !== _) { _ratioX = _; _update(); } } public function get ratioY():Number { return _ratioY } public function set ratioY(_:Number):void { if (_ratioY !== _) { _ratioY = _; _update(); } } //--------------------------------------- // constructor //--------------------------------------- public function ComplexBridge() { super(); } //--------------------------------------- // set offset //--------------------------------------- public function setOffset(x:Number, y:Number):void { if (_offsetX !== x || _offsetY !== y) { _offsetX = x; _offsetY = y; _update(); } } //--------------------------------------- // set ratio //--------------------------------------- public function setRatio(x:Number, y:Number):void { if (_ratioX !== x || _ratioY !== y) { _ratioX = x; _ratioY = y; _update(); } } //--------------------------------------- // update //--------------------------------------- override protected function _update():void { var x:Number; var y:Number; if (isNaN(_offsetX)) { x = _a.x + (_b.x - _a.x) * _ratioX; } else { x = _a.x + _offsetX; } if (isNaN(_offsetY)) { y = _a.y + (_b.y - _a.y) * _ratioY; } else { y = _a.y + _offsetY; } if (_x !== x || _y !== y) { _x = x; _y = y; _reposition(); } } } }
/* Feathers Copyright 2012-2019 Bowler Hat LLC. 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 feathers.motion.effectClasses { /** * Gives a component the ability to control a resize effect. * * @see ../../../help/effects.html Effects and animation for Feathers components */ public interface IResizeEffectContext extends IEffectContext { /** * The old width of the target. */ function get oldWidth():Number; /** * @private */ function set oldWidth(value:Number):void; /** * The old height of the target. */ function get oldHeight():Number; /** * @private */ function set oldHeight(value:Number):void; /** * The new width of the target. */ function get newWidth():Number; /** * @private */ function set newWidth(value:Number):void; /** * The new height of the target. */ function get newHeight():Number; /** * @private */ function set newHeight(value:Number):void; } }
package org.as3wavsound.sazameki.format.wav.chunk { import flash.utils.ByteArray; import org.as3wavsound.sazameki.core.AudioSamples; import org.as3wavsound.sazameki.core.AudioSetting; import org.as3wavsound.sazameki.format.riff.Chunk; /** * ... * * @author Takaaki Yamazaki(zk design), * @author Benny Bottema (modified, optimized and cleaned up code) */ public class WavdataChunk extends Chunk { private var _samples:AudioSamples; public function WavdataChunk() { super('data'); } public function setAudioData(samples:AudioSamples):void { _samples = samples; } override protected function encodeData():ByteArray { var bytes:ByteArray = new ByteArray(); bytes.endian = ENDIAN; var setting:AudioSetting = _samples.setting; var i:int; var sig:Number; var len:int = _samples.left.length; var left:Vector.<Number>; if (setting.channels == 2) { left=_samples.left; var right:Vector.<Number>=_samples.right; if (setting.bitRate == 16) { for (i = 0; i < len; i++) { sig = left[i]; if (sig < -1) bytes.writeShort( -32767); else if (sig > 1) bytes.writeShort( 32767); else bytes.writeShort(sig * 32767); sig = right[i]; if (sig < -1) bytes.writeShort(-32767); else if (sig > 1) bytes.writeShort(32767); else bytes.writeShort(sig * 32767); } } else { for (i = 0; i < len; i++) { sig = left[i]; if (sig<-1) bytes.writeByte(0); else if (sig>1) bytes.writeByte(255); else bytes.writeByte(sig*127+128); sig = right[i]; if (sig<-1) bytes.writeByte(0); else if (sig>1) bytes.writeByte(255); else bytes.writeByte(sig*127+128); } } } else { left = _samples.left; if (setting.bitRate == 16) { for (i = 0; i < len; i++) { sig = left[i]; if (sig < -1) bytes.writeShort(-32767); else if (sig > 1) bytes.writeShort(32767); else bytes.writeShort(sig * 32768); } } else { for (i = 0; i < len; i++) { sig = left[i]; if (sig<-1) bytes.writeByte(0); else if (sig>1) bytes.writeByte(255); else bytes.writeByte(sig*127+128); } } } return bytes; } public function decodeData(bytes:ByteArray, setting:AudioSetting):AudioSamples { bytes.position = 0; bytes.endian = ENDIAN; var samples:AudioSamples = new AudioSamples(setting); var length:int = bytes.length / (setting.bitRate / 8) / setting.channels; var i:int; var left:Vector.<Number>; if (setting.channels == 2) { left = samples.left; var right:Vector.<Number> = samples.right; if (setting.bitRate == 16) { for (i = 0; i < length; ++i) { left[i] = bytes.readShort() / 32767; right[i] = bytes.readShort() / 32767; } } else { for (i = 0; i < length; i++) { left[i] = bytes.readUnsignedByte() / 127.5 - 1; right[i] = bytes.readUnsignedByte() / 127.5 - 1; } } } else { left = samples.left; if (setting.bitRate == 16) { for (i = 0; i < length; i++) { left[i] = bytes.readShort() / 32767; } } else { for (i = 0; i < length; i++) { left[i] = bytes.readUnsignedByte() / 127.5 - 1; } } } return samples; } } }
/* * ______ _____ _______ * .-----..--.--..----..-----.| __ \ \| ___| * | _ || | || _|| -__|| __/ -- | ___| * | __||_____||__| |_____||___| |_____/|___| * |__| * $Id: ShadingUtils.as 362 2010-05-05 16:53:53Z alessandro.crugnola $ * $Author Alessandro Crugnola $ * $Rev: 362 $ $LastChangedDate: 2010-05-05 12:53:53 -0400 (Wed, 05 May 2010) $ * $URL: http://purepdf.googlecode.com/svn/trunk/src/org/purepdf/utils/ShadingUtils.as $ * * The contents of this file are subject to LGPL license * (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the * provisions of LGPL are applicable instead of those above. If you wish to * allow use of your version of this file only under the terms of the LGPL * License and not to allow others to use your version of this file under * the MPL, indicate your decision by deleting the provisions above and * replace them with the notice and other provisions required by the LGPL. * If you do not delete the provisions above, a recipient may use your version * of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE * * 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 'iText, a free JAVA-PDF library' ( version 4.2 ) by Bruno Lowagie. * All the Actionscript ported code and all the modifications to the * original java library are written by Alessandro Crugnola (alessandro@sephiroth.it) * * This library is free software; you can redistribute it and/or modify it * under the terms of the MPL as stated above or under the terms of the GNU * Library General Public License as published by the Free Software Foundation; * either version 2 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU LIBRARY GENERAL PUBLIC LICENSE for more * details * * If you didn't download this code from the following link, you should check if * you aren't using an obsolete version: * http://code.google.com/p/purepdf * */ package org.purepdf.utils { import org.purepdf.colors.GrayColor; import org.purepdf.colors.RGBColor; import org.purepdf.pdf.PdfContentByte; import org.purepdf.pdf.PdfDictionary; import org.purepdf.pdf.PdfGState; import org.purepdf.pdf.PdfName; import org.purepdf.pdf.PdfShading; import org.purepdf.pdf.PdfShadingPattern; import org.purepdf.pdf.PdfTemplate; import org.purepdf.pdf.PdfTransparencyGroup; public class ShadingUtils { /** * Draws a rectangle with a multiple alpha gradient colors<br /> * Example:<br /> * <pre> * var colors: Vector.&lt;RGBColor&gt; = Vector.&lt;RGBColor&gt;([ RGBColor.BLACK, RGBColor.YELLOW, RGBColor.RED, RGBColor.CYAN ] ); * var ratios: Vector.&lt;Number&gt; = Vector.&lt;Number&gt;([0, 0.5, 0.7, 1]); * var alphas: Vector.&lt;Number&gt; = Vector.&lt;Number&gt;([ 0, 0.2, 0.3, 0.6 ]); * ShadingUtils.drawRectangleGradient( cb, 100, 100, 100, PageSize.A4.height - 200, colors, ratios, alphas ); * </pre> * * @param cb * @param x * @param y * @param width * @param height * @param colors Vector of RGBColor * @param ratios Vector of numbers ( 0 to 1 ) * @param alpha Vector of numbers ( 0 to 1 ) * @param extendStart * @param extendEnd */ public static function drawRectangleGradient( cb: PdfContentByte, x: Number, y: Number, width: Number, height: Number, colors: Vector.<RGBColor>, ratios: Vector.<Number>, alpha: Vector.<Number>, extendStart: Boolean = true, extendEnd: Boolean = true ): void { assert_true( colors.length == alpha.length, "Colors and Alpha vectors must be same length" ); var shading: PdfShading; var template: PdfTemplate; var gState: PdfGState; cb.moveTo( x, y ); cb.lineTo( x + width, y ); cb.lineTo( x + width, y + height ); cb.lineTo( x, y + height ); // Create template template = cb.createTemplate( x + width, y + height ); var transGroup: PdfTransparencyGroup = new PdfTransparencyGroup(); transGroup.put( PdfName.CS, PdfName.DEVICERGB ); transGroup.isolated = true; transGroup.knockout = false; template.group = transGroup; gState = new PdfGState(); var maskDict: PdfDictionary = new PdfDictionary(); maskDict.put( PdfName.TYPE, PdfName.MASK ); maskDict.put( PdfName.S, new PdfName( "Luminosity" ) ); maskDict.put( new PdfName( "G" ), template.indirectReference ); gState.put( PdfName.SMASK, maskDict ); cb.setGState( gState ); var alphas: Vector.<GrayColor> = new Vector.<GrayColor>( alpha.length, true ); for ( var k: int = 0; k < alpha.length; ++k ) { alphas[k] = new GrayColor( alpha[k] ); } shading = PdfShading.complexAxial( cb.writer, 0, y, 0, height, Vector.<RGBColor>( alphas ), ratios ); template.paintShading( shading ); shading = PdfShading.complexAxial( cb.writer, 0, y, 0, height, colors, ratios ); var axialPattern: PdfShadingPattern = new PdfShadingPattern( shading ); cb.setShadingFill( axialPattern ); cb.fill(); } /** * * @param cb * @param x * @param y * @param r0 * @param r1 * @param colors * @param ratios * @param alpha * @param extendStart * @param extendEnd */ public static function drawRadialGradient( cb: PdfContentByte, x: Number, y: Number, r0: Number, r1: Number, colors: Vector.<RGBColor>, ratios: Vector.<Number>, alpha: Vector.<Number>, extendStart: Boolean = true, extendEnd: Boolean = true ): void { assert_true( colors.length == alpha.length, "Colors and Alpha vectors must be same length" ); var shading: PdfShading; var template: PdfTemplate; var gState: PdfGState; cb.circle( x, y, r1 ); // Create template template = cb.createTemplate( x+ r1*2, y + r1*2 ); var transGroup: PdfTransparencyGroup = new PdfTransparencyGroup(); transGroup.put( PdfName.CS, PdfName.DEVICERGB ); transGroup.isolated = true; transGroup.knockout = false; template.group = transGroup; gState = new PdfGState(); var maskDict: PdfDictionary = new PdfDictionary(); maskDict.put( PdfName.TYPE, PdfName.MASK ); maskDict.put( PdfName.S, new PdfName( "Luminosity" ) ); maskDict.put( new PdfName( "G" ), template.indirectReference ); gState.put( PdfName.SMASK, maskDict ); cb.setGState( gState ); var alphas: Vector.<GrayColor> = new Vector.<GrayColor>( alpha.length, true ); for ( var k: int = 0; k < alpha.length; ++k ) { alphas[k] = new GrayColor( alpha[k] ); } shading = PdfShading.complexRadial( cb.writer, x, y, x, y, r0, r1, Vector.<RGBColor>( alphas ), ratios ); template.paintShading( shading ); shading = PdfShading.complexRadial( cb.writer, x, y, x, y, r0, r1, colors, ratios ); var axialPattern: PdfShadingPattern = new PdfShadingPattern( shading ); cb.setShadingFill( axialPattern ); cb.fill(); } } }
/** * Глобальные параметры */ package { import classes.api.CustomEventDispatcher; import flash.external.ExternalInterface; public class Settings { public static const MIN_APPLICATION_WIDTH : Number = 760; public static const MIN_APPLICATION_HEIGHT : Number = 740; public static const DEFAULT_PROJECT_NAME : String = 'Torama project'; public static const DEFAULT_PROJECT_FILE : String = 'torama_project'; public static const EXTENSION_FOR_PROJECT : String = '.xml'; public static const DEFAULT_PROJECT_FILE_NAME : String = DEFAULT_PROJECT_NAME + EXTENSION_FOR_PROJECT; public static const SETTINGS_FILE : String = 'data.xml'; /** * Высота линейки по умолчанию */ public static const RULLER_HEIGHT : Number = 18.0; /** * Высота дорожки по умолчанию */ public static const TRACK_HEIGHT : Number = 60; /** * BPM проекта по умолчанию */ public static const DEFAULT_PROJECT_BPM : Number = 128.0; /** * Максимальная громкость звучания дорожки */ public static const MAX_TRACK_SOUND_VOLUME : Number = 2.0; /** * Громкость звучания дорожки по умолчанию */ public static const DEFAULT_TRACK_SOUND_VOLUME : Number = 1.6; /** * Минимальное BPM */ public static const MIN_BMP : Number = 30; /** * Максимальное BPM */ public static const MAX_BPM : Number = 350; /** * Длина timeline проекта по умолчанию в секундах */ public static const DEFAULT_PROJECT_DURATION : Number = 300.0; //5 минут /** * Максимальная доступная длина timeline в секундах */ public static const MAX_PROJECT_DURATION : Number = 3600; //1 час /** * Минимальная длина микса для публикации в фреймах */ public static const MIN_PUBLICATION_LENGTH : Number = 44100 * 5; /** * Адрес amf сервера LOOPERMAN_API */ public static var AMF_HOST : String = 'music3000/'; /** * Корень песочницы приложения * */ public static var SANDBOX_URL : String = ''; public static var LOOPERMAN_CATEGORIES : Array = []; public static var LOOPERMAN_GENRES : Array = []; public static var APPLICATION_NAME : String = 'Музыкальный Конструктор'; public static var APPLICATION_SUPPORT : String = 'odnoklassniki.ru/group/52091635695706'; public static var VIDEO_HELP : String; /** * Уведомляет о изменении настроек */ public static const notifier : CustomEventDispatcher = new CustomEventDispatcher(); /** * Настройки загружены или нет */ public static var loaded : Boolean; /** * Используемый протокол. http или https */ public static var protocol : String; /** * Подставляет в начало url текущий протокол * @param url * @return * */ public static function resolveProtocol( url : String ) : String { if ( ! protocol ) { if ( ExternalInterface.available ) { protocol = ExternalInterface.call( "document.location.protocol.toString" ); } if ( ( protocol != 'http:' ) && ( protocol != 'https:' ) ) { protocol = 'http:'; } protocol += '//'; } return protocol + url; } public static function parseSettings( xml : XML ) : void { if ( xml.help != undefined ) { if ( xml.help.video != undefined ) { VIDEO_HELP = resolveProtocol( xml.help.video.text() ); } if ( xml.help.support != undefined ) { APPLICATION_SUPPORT = resolveProtocol( xml.help.support.text() ); } } AMF_HOST = resolveProtocol( xml.apiURL.text() ); if ( xml.sandboxURL != undefined ) { SANDBOX_URL = resolveProtocol( xml.sandboxURL.text() ) + '/'; } var item : XML; for each( item in xml.looperman.localization.categorys.elements( 'item' ) ) { LOOPERMAN_CATEGORIES.push( { id : item.@id.toString(), icon : SANDBOX_URL + 'icons/' + item.@icon.toString(), short : ( ( item.@short == undefined ) ? item.text() : item.@short.toString() ), label : item.text() } ); } LOOPERMAN_CATEGORIES.sortOn( 'label' ); for each( item in xml.looperman.localization.genres.elements( 'item' ) ) { LOOPERMAN_GENRES.push( { id : item.@id.toString(), label : item.text() } ); } LOOPERMAN_GENRES.sortOn( 'label' ); } public static function getAcapellaGenderDescription( gender : String ) : String { if ( gender == 'M' ) return 'Мужской вокал'; if ( gender == 'F' ) return 'Женский вокал'; return gender; } public static function getAcapellaStyleDescription( style : String ) : String { if ( style == 'R' ) return 'Реп'; if ( style == 'S' ) return 'Песня'; if ( style == 'R&P' ) return 'Реп и песня'; return style; } public static function getYesNoDescription( value : String ) : String { if ( value == 'Y' ) return 'Да'; if ( value == 'N' ) return 'Нет'; return value; } public static function getCategoryDescription( category : String ) : Object { var i : int = 0; while( i < LOOPERMAN_CATEGORIES.length ) { if ( LOOPERMAN_CATEGORIES[ i ].id == category ) { return LOOPERMAN_CATEGORIES[ i ]; } i ++; } return { id : category, label : category }; } public static function getGenreDescription( genre : String ) : Object { var i : int = 0; while( i < LOOPERMAN_GENRES.length ) { if ( LOOPERMAN_GENRES[ i ].id == genre ) { return LOOPERMAN_GENRES[ i ]; } i ++; } return { id : genre, label : genre }; } public static function processGenres( items : Array, ignoreNotExists : Boolean = false ) : Array { var result : Array = []; var i : int = 0; var j : int; var genreFound : Boolean while( i < items.length ) { j = 0; genreFound = false; while( j < LOOPERMAN_GENRES.length ) { if ( items[ i ] == LOOPERMAN_GENRES[ j ].id ) { result.push( LOOPERMAN_GENRES[ j ] ); genreFound = true; break; } j ++; } if ( ! ignoreNotExists && ! genreFound ) { result.push( { id : items[ i ], label : items[ i ] } ); } i ++; } result.sortOn( 'label' ); return result; //return LOOPERMAN_GENRES; } public static function processCategories( items : Array ) : Array { var result : Array = []; var i : int = 0; var j : int; var categoryFound : Boolean; while( i < items.length ) { j = 0; categoryFound = false; while( j < LOOPERMAN_CATEGORIES.length ) { if ( items[ i ] == LOOPERMAN_CATEGORIES[ j ].id ) { result.push( LOOPERMAN_CATEGORIES[ j ] ); categoryFound = true; break; } j ++; } if ( ! categoryFound ) { result.push( { id : items[ i ], label : items[ i ] } ); } i ++; } result.sortOn( 'label' ); return result; //return LOOPERMAN_CATEGORYS; } } }
package kabam.rotmg.pets.view { import kabam.rotmg.maploading.signals.ChangeMapSignal; import kabam.rotmg.pets.data.PetSlotsState; import robotlegs.bender.bundles.mvcs.Mediator; public class ClearsPetSlotsMediator extends Mediator { [Inject] public var petSlotsState:PetSlotsState; [Inject] public var changeMapSignal:ChangeMapSignal; override public function initialize():void { this.changeMapSignal.add(this.onMapChange); } override public function destroy():void { this.changeMapSignal.remove(this.onMapChange); } private function onMapChange():void { this.petSlotsState.clear(); } } }
package com.playfab.ServerModels { public class RemovePlayerTagResult { public function RemovePlayerTagResult(data:Object=null) { if(data == null) return; } } }
/* * Copyright 2007-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.springextensions.actionscript.ioc.config.impl.xml.namespacehandler { import org.springextensions.actionscript.ioc.config.impl.xml.parser.IXMLObjectDefinitionsParser; import org.springextensions.actionscript.ioc.objectdefinition.IObjectDefinition; /** * Interface to be implemented when creating a custom namespace handler. * * <p>A namespace handler can be added to the main XMLObjectDefinitionsParser to handle user defined xml * namespaces.</p> * @docref extensible_xml_authoring.html#coding_an_inamespacehandler_implementation * @author Christophe Herreman */ public interface INamespaceHandler { /** * Return the namespace supported by this namespace handler. */ function getNamespace():Namespace; /** * Parses the given node and returns the resulting object definition. * * @param node the xml node to parse * @param context the root xml parser (XXX this might change to a parser context object) */ function parse(node:XML, context:IXMLObjectDefinitionsParser):IObjectDefinition; } }
package org.red5.samples.publisher.events { /** * RED5 Open Source Flash Server - http://www.osflash.org/red5 * * Copyright (c) 2006-2009 by respective authors (see below). All rights reserved. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation; either version 2.1 of the License, or (at your option) any later * version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along * with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ import com.adobe.cairngorm.control.CairngormEvent; import org.red5.samples.publisher.control.DashboardController; /** * @copy org.red5.samples.publisher.command.PublishStreamCommand * @author Thijs Triemstra */ public class PublishStreamEvent extends CairngormEvent { /** * */ public var publishMode : String; /** * */ public var streamName : String; /** * * @return * */ public function PublishStreamEvent( publishMode : String, streamName : String ) { super( DashboardController.EVENT_PUBLISH_STREAM ); this.publishMode = publishMode; this.streamName = streamName; } } }
/* * * 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.display { /** * @royalesuppressexport * This class is not available for reflection */ public class JPEGEncoderOptions { /** * @royalesuppresspublicvarwarning */ public var quality:uint; public function JPEGEncoderOptions(quality:uint = 80) { this.quality = quality; } } }
package { import org.flixel.*; import Components.*; import org.flixel.data.FlxKong; import States.*; import Buttons.AudioButton; import flash.events.Event; import TapeEngine.BinaryHelper; //import QueryString; [SWF(width="640", height="480", backgroundColor="#000000")] [Frame(factoryClass = "Preloader")] public class Manufactoria extends FlxGame { [Embed(source = "/music/TRUNC.mp3")] private static const MUSIC:Class; //Shostakovich_VS private static var music_timer:Number; public static var components:Array; public static var grid:Array; public static var GRID_DIM:int; public static var grid_offset:int; public static var inv_offset:int; public static var buttonLayout:Array; public static var levelsByName:Array; public static var save:FlxSave = new FlxSave(); public static var unlocked:Array; public static var savedLevels:Array; public static var linkCode:String = null; public static var overwrite:Boolean = true; public static var timeRecords:Array; public static var componentRecords:Array; public static var OFFLINE:Boolean = false; public static const KONG:Boolean = false; public static const ALL_UNLOCKED:Boolean = false; public static const VERSION:String = "1.30l"; public static var KONG_INIT:Boolean = false; public static var _self:Manufactoria; public static var levelEntry:Class = MenuState; //state to go back to, from the level public function Manufactoria() { var levels:Array = loadLevels(); if (save.bind("Manufactoria")) { unlocked = save.data.unlocked ? save.data.unlocked : new Array(CUSTOM_OFFSET); if (!unlocked[PROTO1]) unlocked[PROTO1] = UNLOCKED; if (unlocked[BONUS_OFFSET] == BEATEN && !unlocked[BONUS_OFFSET + 1]) unlocked[BONUS_OFFSET + 1] = UNLOCKED; //TODO: remove? if (unlocked[BONUS_OFFSET + 1] == BEATEN && !unlocked[BONUS_OFFSET + 2]) unlocked[BONUS_OFFSET + 2] = UNLOCKED; //TODO: likewise savedLevels = save.data.levels ? save.data.levels : new Array(levels.length); IntroState.viewedScenes = save.data.scenes ? save.data.scenes : new Array(6); loadCustomLevels(levels, save.data.custom); //CUSTOM CUSTOM CUSTOM loadRecords(save.data.time, save.data.components); compensateForVersion(save.data.version); } else { unlocked = new Array(CUSTOM_OFFSET); savedLevels = new Array(levels.length); IntroState.viewedScenes = new Array(6); loadRecords(null, null); } components = new Array(); var level:int = loadFromURL(levels) var initialState:Class; if (level >= 0 && levels[level]) { initialState = BuildState; setGrid(levels[level].dimensions); } else if (unlocked[PROTO2]) initialState = MenuState; else { initialState = IntroState; level = PROTO1; } super(320, 240, initialState, 2); FlxState.bgColor = 0xffa1a1a1; useDefaultHotKeys = false; //pause = new ManuPause(); if (save.data.volume != null) FlxG.volume = save.data.volume; if (save.data.mute != null) FlxG.mute = save.data.mute// (save.data.mute == 'm'); _self = this; //hax FlxG.levels = levels; FlxG.level = level; updateUnlocked(); //addEventListener(Event.CLOSE, onExit); } private function test(e:Event = null):void { FlxG.log('woo'); } public static function setGrid(dim:int = 0):void { GRID_DIM = dim ? dim : FlxG.levels[FlxG.level].dimensions; grid = new Array(GRID_DIM * GRID_DIM); grid_offset = GRID_DIM / 2; inv_offset = 7 - grid_offset; } protected function loadLevels():Array { var i:int; var levels:Array = new Array(); levels.push(new Level( "Robotoast!", "ACCEPT: Move robots from the entrance (top) to the exit (bottom)!", "You put bread in. With a click, heat begins to build. Then - a sound - motion - fresh toast! ROBO-TOAST. 49.99.", new UnlockRequirement(false), 5, PROTO_TOOLS, 12, ['brb'], function _toast_(input:String, output:String):Boolean { return output != 'x' } )); levels.push(new Level( "Robocoffee!", "If a robot's string starts with blue, accept. Otherwise, reject!", "Coffee - ambrosia - the 'water of life.' But - so hard to make! WORRY NO MORE. Robo Coffee: Never Sleep Again.", new UnlockRequirement(true, 'Robotoast!'), 5, BASIC_TOOLS, 12, ['br', 'rb'], function _coffee_(input:String, output:String):Boolean { return ((input.length && (input.charAt(0) == 'b')) == (output != 'x')) } )); levels.push(new Level( "Robolamp!", "ACCEPT: if there are three or more blues!", "Our hi-tech 'lavalamps' will sense your mood, glowing and moving as you think! 'Creepy'? Try 'incredible!'", new UnlockRequirement(true, "Robocoffee!"), 7, BASIC_TOOLS, 12, ['rrrrrrrbbb', 'rrrrrrrrbb'], function _lampAcc_(input:String, output:String):Boolean { var blues:int = 0; for (var j:int = 0; blues < 3 && j < input.length; j++) blues += input.charAt(j) == 'b'; return (blues < 3) == (output == 'x'); } )); levels.push(new Level( "Robofish!", "ACCEPT: if a robot contains NO red!", "Robot fish! Sold with ten amazing pre-programmed swim patterns, and almost always waterproofed!", new UnlockRequirement(true, "Robolamp!"), 5, BASIC_TOOLS, 12, ['bbbbbbbbbb', 'bbbbbbbbrb'], function _fishAcc_(input:String, output:String):Boolean { return (input.indexOf('r') == -1) == (output != 'x'); } )); levels.push(new Level( "Robobugs!", "ACCEPT: if the tape has only alternating colors!", "Robot flies! Ever thought, 'if I could be a fly on that wall?' Well, YOU can't - but these are the next best thing!", new UnlockRequirement(true, "Robofish!"), 9, BASIC_TOOLS, 12, ['brbrbrbrbrbr','brbrbrbrbbrr'], function _bugAcc_(input:String, output:String):Boolean { if (input.length < 2) return output != 'x'; var currentChar:String = input.charAt(0); for (var j:int = 1; j < input.length; j++) if (input.charAt(j) == currentChar) return output == 'x'; else currentChar = input.charAt(j); return output != 'x'; } )); levels.push(new Level( "Robocats!", "ACCEPT: if the tape ends with two blues!", "Robot kitties! Their lustrous fur is 100% authentic - each strand taken from the back of a real kitten, just for you!", new UnlockRequirement(true, "Robobugs!"), 9, BASIC_TOOLS, 12, ['brbrrbrrb', 'brbrbrrbb'], function _catAcc_(input:String, output:String):Boolean { //FlxG.log(input.length +", " + input.charAt(input.length - 1) + ", " + input.charAt(input.length - 2)); return (input.length >= 2 && input.charAt(input.length - 1) == 'b' && input.charAt(input.length - 2) == 'b') == (output != 'x'); } )); levels.push(new Level( "Robobears!", "ACCEPT: Strings that begin and end with the same color!", //kinda easy, but still maybe OK "Enormous metal polar bears! They like to catch fish, even though they can't eat any. It's disarming! Then they eat you.", new UnlockRequirement(true, "Robocats!"), 9, BASIC_TOOLS, 12, ['brbrrrbrrrbrb', 'brbrrrbrrrbbr'], function _acc_(input:String, output:String):Boolean { //FlxG.log(input.length +", " + input.charAt(input.length - 1) + ", " + input.charAt(input.length - 2)); return (input.length < 2 || input.charAt(input.length - 1) == input.charAt(0)) == (output != 'x'); } )); levels.push(new Level( "RC Cars!", "OUTPUT: The input, but with the first symbol at the end!", "They go 'vroom'! They're remote controlled! The best and last robo-toy your child will ever want!", new UnlockRequirement(true, "Robolamp!"), 5, WRITING_TOOLS, 12, ['brbrbbbrb'], null, function _out_(input:String):String { return input.slice(1) + input.charAt(0); } )); levels.push(new Level( "Robocars!", "OUTPUT: Replace blue with green, and red with yellow!", "Robot-driven cars! Now, when you enjoy a glass or two of port on the way to work, you needn't feel guilty about it!", new UnlockRequirement(true, "RC Cars!"), 7, COLOR_TOOLS, 12, ['rbrbrrrb'], null, function _out_(input:String):String { var output:String = ''; for (var j:int = 0; j < input.length; j++) output += input.charAt(j) == 'b' ? 'g' : 'y'; return output; } )); levels.push(new Level( "Robostilts!", "OUTPUT: Put a green at the beginning, and a yellow at the end!", "Want to tower above your fellow man? Of course you do! But you're probably afraid of falling. Well - FEAR NO LONGER!", new UnlockRequirement(true, "Robocars!"), 9, FULL_TOOLS, 10, ['rrbrbrbbr'], null, function _out_(input:String):String { return 'g' + input + 'y'; } )); levels.push(new Level( "Milidogs!", "ACCEPT: With blue as 1 and red as 0, accept odd binary strings!", "Our first defense contract: robot dogs! They sniff out the enemy with their mechani-noses, and then - well!", new UnlockRequirement(true, "Robocats!"), 7, BASIC_TOOLS, 12, ['brrrrbrb', 'brrrrbbr'], function _acc_(input:String, output:String):Boolean { return (input.charAt(input.length - 1) == 'b') == (output != 'x'); }, null, Level.binaryMalevoTest, true)); levels.push(new Level( "Soldiers!", "OUTPUT: With blue as 1 and red as 0, multiply by 8!", "Robot soldiers! Plated with armor, bristling with weapons, and ready to send the Reds all the way back to Moscow!", new UnlockRequirement(true, "Androids!,Milidogs!"), //should really be "RC Cars!,Soldiers!", but that messes with the graph like nothing else 9, WRITING_TOOLS, 12, ['rbrbbrbr'], null, function _out_(input:String):String { return input + 'rrr'; }, Level.binaryMalevoTest, true)); levels.push(new Level( "Officers!", "OUTPUT: With blue as 1 and red as 0, add 1 to the binary string!", "Robotic officers serve in the newly formed Metal Regiments, commanding by radio-wave with uncanny speed!", new UnlockRequirement(true, "Soldiers!"), 13, FULL_TOOLS, 9, ['brrbrbbbb'], null, function _out_(input:String):String { var binary:Array = BinaryHelper.toBinary(input); binary[0] += 1; return BinaryHelper.fromBinary(binary); }, Level.binaryMalevoTest, true)); levels.push(new Level( "Generals!", //UNTESTED "OUTPUT: Subtract 1 from the binary string! (Input >= 1)", "Robot generals analyze their goals and optimize, without human limits. They are literally unbeatable.", new UnlockRequirement(true, "Officers!"), 13, FULL_TOOLS, 9, ['brrbrbbbb'], null, function _out_(input:String):String { var binary:Array = BinaryHelper.toBinary(input); binary[0] -= 1; return BinaryHelper.fromBinary(binary); }, Level.gt0MalevoTest, true)); levels.push(new Level( "Robotanks!", "ACCEPT: With blue as 1 and red as 0, accept binary strings > 15!", "Robotic armor! Rated 30% cheaper than human-crewed equivalents, and nearly 60% better at crushing foes!", //"Robot pilots! Rated for: 30 Gs, up to 5 minutes. No O2, up to 1 hour. Bombing peasants: until the sun goes down!", new UnlockRequirement(true, "Milidogs!"), 11, BASIC_TOOLS, 9, ['rrrrrbbbb', 'rrrrbbbbr'], function _acc_(input:String, output:String):Boolean { return (BinaryHelper.toBinary(input)[0] > 15) == (output != 'x'); }, null, Level.binaryMalevoTest, true)); levels.push(new Level( "Robospies!", "ACCEPT: With blue as 1 and red as 0, accept natural powers of four!", "Designation: HUM/ELINT primary infiltration/investigation asset. Further details: classified.", new UnlockRequirement(true, "Androids!,Robotanks!"), 9, FULL_TOOLS, 12, ['brrrrrrrr', 'brrrrrbrr'], function _acc_(input:String, output:String):Boolean { var significantBlue:int = input.indexOf('b'); if (significantBlue == -1) return output == 'x'; for (var j:int = significantBlue + 1; j < input.length; j++) if (input.charAt(j) != 'r') return output == 'x'; return ((j - (significantBlue + 1)) % 2 == 0) == (output != 'x'); }, null, Level.binaryMalevoTest, true)); levels.push(new Level( "Androids!", "ACCEPT: Some number of blue, then the same number of red!", "Robots in the shape of men - and with minds to match! A breakthrough like none before!", new UnlockRequirement(true, "Robocats!,Robostilts!"), 9, FULL_TOOLS, 12, ['bbbbrrrr', 'bbbbrrr'], function _acc_(input:String, output:String):Boolean { /*if (input == "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr" || input == "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr") trace(input, output);*/ if (input.length % 2 == 1) //odd! return output == 'x'; for (var j:int = 0; j < input.length / 2; j++) if (input.charAt(j) != 'b') return output == 'x'; for (; j < input.length; j++) if (input.charAt(j) != 'r') return output == 'x'; return output != 'x'; } )); levels.push(new Level( "Robo-children!", "ACCEPT: An equal number of blue and red, in any order!", "These robo-scamps are guaranteed to brighten your life, even without use of their vast, glowing eyes!", new UnlockRequirement(true, "Androids!"), 11, FULL_TOOLS, 12, ['rrbbbrbr', 'bbrrbrr'], function _acc_(input:String, output:String):Boolean { var balance:int = 0; for (var j:int = 0; j < input.length; j++) balance += input.charAt(j) == 'b' ? 1 : -1; /*if (input == "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr" || input == "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr") trace(input, output);*/ return (balance == 0) == (output != 'x'); } )); levels.push(new Level( "Police!", "OUTPUT: Put a yellow in the middle of the (even-length) string!", "Overwhelmed by rampant crime? Upgrade your police force! Robo Cops: They Only Shoot People Who Really Deserve It.", new UnlockRequirement(true, "Androids!"), 13, FULL_TOOLS, 10, ['rbbbrrbr'], null, function _out_(input:String):String { return input.slice(0,input.length/2) + 'y' + input.slice(input.length/2, input.length); }, Level.evenMalevoTest )); levels.push(new Level( "Judiciary!", "ACCEPT: (Even-length) strings that repeat midway through!", "Robotic judges! Completely incorruptible, and utterly infallible! You'll never need HUMAN justices again!", new UnlockRequirement(true, "Police!"), 13, FULL_TOOLS, 10, ['bbbrbbbr', 'rbbbrb'], function _acc_(input:String, output:String):Boolean { return (input.slice(0,input.length/2) == input.slice(input.length/2, input.length)) == (output != 'x'); }, null, Level.evenMalevoTest )); levels.push(new Level( "Teachers!", "ACCEPT: X blue, then X red, then X more blue, for any X!", //"Robots in the shape of women! Suitable for cooking, cleaning, secretarial work, or computer programming.", "Classes taught by robot teachers have, on average, 68% higher standardized test scores. They're simply superior!", new UnlockRequirement(true, "Androids!"), 13, FULL_TOOLS, 12, ['bbrrbb', 'bbbrrrbb'], function _acc_(input:String, output:String):Boolean { if (input.length % 3) return output == 'x'; for (var j:int = 0; j < input.length / 3; j++) if (input.charAt(j) == 'r') return output == 'x'; for (; j < input.length * 2 / 3; j++) if (input.charAt(j) == 'b') return output == 'x'; for (; j < input.length; j++) if (input.charAt(j) == 'r') return output == 'x'; return output != 'x'; } )); levels.push(new Level( "Politicians!", "ACCEPT: If there are exactly twice as many blues as red!", "Robo-politicians: built so carefully, test models have replaced their targets with a detection rate below 1%!", new UnlockRequirement(true, "Teachers!"), 13, FULL_TOOLS, 12, ['rbbrbr', 'bbbrbrb'], function _acc_(input:String, output:String):Boolean { var red:int = 0; var blue:int = 0; for (var j:int = 0; j < input.length; j++) { var char:String = input.charAt(j); if (char == 'b') blue++; else red++; } return ((red << 1) == blue) == (output != 'x'); } )); levels.push(new Level( "Academics!", "OUTPUT: Reverse the input string!", "Robot professors! The robot race can now debate Derrida, satire Socrates, and control the academic world!", new UnlockRequirement(true, "Teachers!"), 13, FULL_TOOLS, 9, ['rrrrbbbb'], null, function _out_(input:String):String { return input.split("").reverse().join(""); } )); levels.push(new Level( "Engineers!", "ACCEPT: Perfectly symmetrical strings!", "Robot engineers. Designed to build testing machines.\n\nHarmless.", new UnlockRequirement(true, "Academics!"), 13, FULL_TOOLS, 9, ['brbrb', 'rrbrbrbr'], function _acc_(input:String, output:String):Boolean { return (input.split("").reverse().join("") == input) == (output != 'x'); } )); levels.push(new Level( "Roborockets!", "OUTPUT: Swap blue for red, and red for blue!", "Guided by a clever robotic navigation capsule, these rockets can carry nearly thirty tons of cargo into low Earth orbit!", new UnlockRequirement(true, "Robostilts!"), 7, FULL_TOOLS, 12, ['bbrbrr'], null, function _out_(input:String):String { var output:String = ''; for (var j:int = 0; j < input.length; j++) output += (input.charAt(j) == 'b') ? 'r' : 'b'; return output; } )); levels.push(new Level( "Roboplanes!", "OUTPUT: All of the blue, but none of the red!", "Using new, advanced 'jet engines', our automated planes will take you from here to there in half the time!", new UnlockRequirement(true, "Robostilts!"), 7, FULL_TOOLS, 9, ['rrbrrbbbr'], null, function _out_(input:String):String { var output:String = ''; for (var j:int = 0; j < input.length; j++) if (input.charAt(j) == 'b') output += 'b'; return output; } )); levels.push(new Level( "Rocket Planes!", "OUTPUT: The input, but with all blues moved to the front!", "'The earth is the cradle of the mind - but one cannot live forever in a cradle.' Man's devices sojourn out to the stars.", new UnlockRequirement(true, "Roborockets!,Roboplanes!"), 9, FULL_TOOLS, 9, ['rbrbrbrrbr'], null, function _out_(input:String):String { var output:String = ''; for (var j:int = 0; j < input.length; j++) if (input.charAt(j) == 'b') output = 'b' + output; else output += 'r'; return output; } )); levels.push(new Level( "Robomecha!", "OUTPUT: The input, but with the last symbol moved to the front!", //also kinda easy "Stilts are fine. But what's better - robot STILTS, or a GIANT WALKING ROBOT SUIT? We think you already know!", new UnlockRequirement(true, "Robostilts!"), 11, FULL_TOOLS, 12, ['rrrbbrb'], null, function _out_(input:String):String { return input.charAt(input.length - 1) + input.slice(0, input.length - 1); } )); BONUS_OFFSET = levels.length; levels.push(new Level( "Seraphim", "ACCEPT: Two identical strings, separated by a green!", " - ", new UnlockRequirement(true, "Engineers!"), 11, FULL_TOOLS, 9, ['brrgrbr', 'rbbgbrb'], function _acc_(input:String, output:String):Boolean { var mid:int = input.indexOf('g'); return (input.slice(0,mid) == input.slice(mid + 1, input.length)) == (output != 'x'); }, null, Level.multiMalevoTest)); levels.push(new Level( "Ophanim", "ACCEPT: Read the tape as two numbers, A and B, split by a green: accept if A>B!", " -- ", new UnlockRequirement(true, "Seraphim"), 13, FULL_TOOLS, 6, ['bbrgbrb', 'brrgbrb'], function _acc_(input:String, output:String):Boolean { var A:int = BinaryHelper.toBinary(input.slice(0,input.indexOf('g')))[0]; var B:int = BinaryHelper.toBinary(input.slice(input.indexOf('g') + 1))[0]; return (A > B) == (output != 'x'); }, null, Level.multiMalevoTest, true)); levels.push(new Level( "Metatron", "OUTPUT: Read the tape as two numbers, A and B, split by a green: output A + B!", " ---- ", new UnlockRequirement(true, "Ophanim"), 13, FULL_TOOLS, 6, ['bbgbr'], null, function _out_(input:String):String { var mid:int = input.indexOf('g'); var A:int = BinaryHelper.toBinary(input.slice(0,mid))[0]; var B:int = BinaryHelper.toBinary(input.slice(mid + 1, input.length))[0]; return BinaryHelper.fromBinary([A + B, 0]); }, Level.multiMalevoTest, true)); CUSTOM_OFFSET = levels.length; //tack new levels on after the end levelsByName = new Array(); for (i = 0; i < levels.length; i++) { levelsByName[levels[i].name] = i; } FINAL_LEVEL = levelsByName["Engineers!"]; buttonLayout = new Array(); unlocked = new Array(levels.length); var row:Array; var finished:Boolean = false; while (!finished) { for (i = 0; i < BONUS_OFFSET; i++) { if (!unlocked[i] && levels[i].unlock.unlocked()) unlocked[i] = UNLOCKED; } row = new Array(); finished = true; for (i = 0; i < BONUS_OFFSET; i++) if (unlocked[i] == UNLOCKED) { unlocked[i] = BEATEN; row.push(i); finished = false; } if (!finished) buttonLayout.push(row); } return levels; } protected function loadCustomLevels(levels:Array, custom:Array):void { //CUSTOM CUSTOM CUSTOM if (custom == null) { return; } for (var i:int = 0; i < CUSTOM_MAX; i++) { levels[CUSTOM_OFFSET + i] = Level.fromString(custom[i]); } } private static function loadRecords(savedTime:Array, savedComponents:Array):void { if (savedTime == null || savedTime[0] is Array) { timeRecords = new Array(CUSTOM_OFFSET); savedComponents = null; //hax } else timeRecords = savedTime; if (savedComponents == null) componentRecords = new Array(CUSTOM_OFFSET); else componentRecords = savedComponents; } public static function saveCustomLevels(levels:Array = null):void { if (!levels) levels = FlxG.levels; var customs:Array = levels.slice(CUSTOM_OFFSET) for (var i:int = 0; i < CUSTOM_MAX; i++) { if (customs[i]) customs[i] = customs[i].toString(); else customs[i] = ''; } save.write("custom", customs); } private function compensateForVersion(oldVersion:String):void { if (oldVersion == VERSION || !oldVersion) return; var versionNumber:int = int(oldVersion.substr(2, 2)); if (versionNumber < 15) { loadRecords(null, null); //fresh start! } save.write("version", VERSION); //don't ever repeat! } protected function loadFromURL(levels:Array):int { var path:QueryString = new QueryString(); var level:int = Number(path._params["lvl"]); //1 to LEVEL_COUNT if (level > 0 && level <= CUSTOM_OFFSET && unlocked[level-1]) { linkCode = path._params["code"]; overwrite = false; return level - 1; } else if (path._params["ctm"]) { //CUSTOM CUSTOM CUSTOM var customIndex:int = LevelSelectState.loadNewCustom(path._params["ctm"], levels); if (customIndex > -1) { linkCode = path._params["code"]; Manufactoria.levelEntry = LevelSelectState; return customIndex; } } return -1; } public static function onKongLoad(e:Event):void { FlxG.kong.API.sharedContent.addLoadListener('Level', SaveLoadState.onLoadKongLevel); FlxG.kong.API.sharedContent.addLoadListener('Custom Level', LevelSelectState.onLoadKongCustom); } public static function onLoadKongCustom(e:Event):void { FlxG.log("Hello!"); } override protected function onFocusLost(event:Event = null):void { } //Don't pause when alt-tabbed! override protected function onFocus(event:Event = null):void { } //Haha - and don't unpause. public static function get totalUnlocked():int { var total:int = 0; for (var i:int = 0; i < unlocked.length; i++) if (unlocked[i] == BEATEN) total++; return total; } public static function updateUnlocked():void { for (var i:int = 0; i < CUSTOM_OFFSET; i++) { if (!unlocked[i] && FlxG.levels[i].unlock.unlocked()) unlocked[i] = UNLOCKED; } if (KONG && FlxG.kong && FlxG.kong.API) { var kongStatsArray:Array = []; //kongStatsArray["LevelsBeaten"] = totalUnlocked; kongStatsArray.push( { name:"LevelsBeaten", value:totalUnlocked } ); //kongStatsArray["GameBeaten"] = unlocked[FINAL_LEVEL] == BEATEN; kongStatsArray.push( { name:"GameBeaten", value:(unlocked[FINAL_LEVEL] == BEATEN) } ); //kongStatsArray["BonusLevelsBeaten"] = unlocked[BONUS_OFFSET + 2] == BEATEN; kongStatsArray.push( { name:"BonusLevelsBeaten", value:(unlocked[BONUS_OFFSET + 2] == BEATEN) } ); //kongStatsArray["GameComplete"] = totalUnlocked == CUSTOM_OFFSET; kongStatsArray.push( { name:"GameComplete", value:(totalUnlocked >= CUSTOM_OFFSET) } ); FlxG.kong.API.stats.submitArray(kongStatsArray); } save.write("unlocked", unlocked); } public static function saveLevel():void { //autosave save.write("mute", FlxG.mute); save.write("volume", FlxG.volume); save.write("version", VERSION); if (!overwrite || FlxG.level == -1) return; savedLevels[FlxG.level] = SaveLoadState.levelString; save.write("levels", savedLevels); } public static function saveRecords(totalTime:int, componentTally:int):void { FlxG.log("Saving records!"); if (!timeRecords[FlxG.level] || timeRecords[FlxG.level] > totalTime) timeRecords[FlxG.level] = totalTime; if (!componentRecords[FlxG.level] || componentRecords[FlxG.level] > componentTally) componentRecords[FlxG.level] = componentTally; save.write("time", timeRecords); save.write("components", componentRecords); if (KONG && FlxG.kong && FlxG.kong.API && totalUnlocked >= CUSTOM_OFFSET) { FlxG.log("Uploading to Kongregate!"); var timeSum:int = 0; for (var i:int = 0; i < CUSTOM_OFFSET && timeSum != int.MAX_VALUE; i++) timeSum = timeRecords[i] ? timeSum + timeRecords[i] : int.MAX_VALUE; if (timeSum == int.MAX_VALUE) { FlxG.log("Invalid time record at index: " + (i - 1)); return; } var partsSum:int = 0; for (i = 0; i < CUSTOM_OFFSET && partsSum != int.MAX_VALUE; i++) partsSum = componentRecords[i] ? partsSum + componentRecords[i] : int.MAX_VALUE; if (partsSum == int.MAX_VALUE) { FlxG.log("Invalid parts record at index: " + (i - 1)); return; } var kongStatsArray:Array = []; //kongStatsArray["Parts Used"] = partsSum; kongStatsArray.push( { name:"Parts Used", value:partsSum } ); //kongStatsArray["Level Times"] = timeSum; kongStatsArray.push( { name:"Level Times", value:timeSum } ); FlxG.kong.API.stats.submitArray(kongStatsArray); } } public static function reset():void { unlocked = new Array(Manufactoria.CUSTOM_OFFSET); unlocked[PROTO1] = UNLOCKED; savedLevels = new Array(FlxG.levels.length); IntroState.viewedScenes = new Array(IntroState.viewedScenes.length); loadRecords(null, null); save.write("unlocked", unlocked); save.write("levels", savedLevels); save.write("scenes", IntroState.viewedScenes); save.write("time", timeRecords); save.write("components", componentRecords); } public static function gridOccupant(X:int, Y:int):TileComponent { return grid[gridToArray(realToGrid(X, Y))]; } public static function realToGrid(x:int, y:int):FlxPoint { return new FlxPoint(Math.floor((x - 80) / GRID_SIZE - inv_offset), Math.floor(y / GRID_SIZE) - inv_offset); } public static function gridToArray(p:FlxPoint):int { return p.y * GRID_DIM + p.x; } public static function xInGrid(x:Number):Boolean { return x >= 80 + inv_offset * GRID_SIZE && x < 200 + GRID_DIM * GRID_SIZE / 2; } public static function yInGrid(y:Number):Boolean { return y >= inv_offset * GRID_SIZE && y < 120 + GRID_DIM * GRID_SIZE / 2; } public static function updateMusic():void { /*if ((FlxG.mute || !FlxG.volume) && FlxG.music && FlxG.music.playing) FlxG.music.pause(); else if ((!FlxG.mute && FlxG.volume) && FlxG.music && !FlxG.music.playing) FlxG.music.fadeIn(1); else */ if (FlxG.keys.justPressed('ZERO') && !(FlxG.state is BuildState)) { FlxG.mute = !FlxG.mute; _self.showSoundTray(); if (AudioButton.instance) AudioButton.instance.refresh(); } else if (FlxG.keys.justReleased('MINUS')) { FlxG.mute = false; FlxG.volume = FlxG.volume - 0.1; _self.showSoundTray(); if (AudioButton.instance) AudioButton.instance.refresh(); } else if (FlxG.keys.justReleased('PLUS')) { FlxG.mute = false; FlxG.volume = FlxG.volume + 0.1; _self.showSoundTray(); if (AudioButton.instance) AudioButton.instance.refresh(); } //else if (FlxG.keys.justReleased("P")) //FlxG.pause = !FlxG.pause; if (/*!OFFLINE && */!FlxG.mute && FlxG.volume) { if (!FlxG.music) { /*try { FlxG.music = new FlxSound().loadStream(MUSIC[0]); } catch (_:Event) { OFFLINE = true; } */ music_timer = 60; //seconds FlxG.music = new FlxSound().loadEmbedded(MUSIC); FlxG.music.volume = .6; FlxG.music.survive = true; FlxG.music.play(); } else if (!FlxG.music.playing) { music_timer -= FlxG.elapsed / FlxG.timeScale; if (music_timer <= 0) FlxG.music.play(); /*music_index = (++music_index) % MUSIC.length; try { FlxG.music.loadStream(MUSIC[music_index]).play(); } catch (_:Event) { OFFLINE = true; } */ } } } /*private function onExit(_:Event):void { trace("roru"); saveLevel(); } */ public static const LOCKED:int = 0; public static const UNLOCKED:int = 1; public static const BEATEN:int = 2; public static const PROTO1:int = 0; public static const PROTO2:int = 1; public static var FINAL_LEVEL:int; public static var BONUS_OFFSET:int; public static var CUSTOM_OFFSET:int; public static var CUSTOM_MAX:int = 32; public static const BELT:int = 0; public static const BPUSH:int = 3; public static const RPUSH:int = 4; public static const BRPULL:int = 5; public static const GPUSH:int = 6; public static const YPUSH:int = 7; public static const GYPULL:int = 8; public static const PROTO_TOOLS:int = -1; public static const BASIC_TOOLS:int = 0; public static const WRITING_TOOLS:int = 1; public static const COLOR_TOOLS:int = 2; public static const FULL_TOOLS:int = 3; public static const GRID_SIZE:int = 16; public static const COMPONENT_TYPES:Array = new Array( ConveyorBelt, ConveyorBridge, null, BluePusher, RedPusher, BlueRedPuller, GreenPusher, YellowPusher, GreenYellowPuller); public static const WRITTEN_NUMBERS:Array = new Array( "ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"); public static const COMPONENTS_BY_ID:Array = new Array( 'c', 'i', null, 'b', 'r', 'p', 'g', 'y', 'q'); public static const CONTROL_TIPS:Array = new Array( "Click or drag to place; shift-click to bridge!", "Bridge!", "Garbage!", "Click to place!", "Click to place!", "Click to place; space to flip!", "Click to place!", "Click to place!", "Click to place; space to flip!"); /*public static const MENU_STATE:int = 0; public static const BUILD_STATE:int = 1; public static const MENU_STATE:int = 2; public static const MENU_STATE:int = 3; public static const MENU_STATE:int = 4; public static const MENU_STATE:int = 5; public static const STATES:Array = new Array(MenuState, BuildState, HelpState, RunState, SaveLoadState, CreditsState); */ } }
/* * VERSION:3.0 * DATE:2014-10-15 * ACTIONSCRIPT VERSION: 3.0 * UPDATES AND DOCUMENTATION AT: http://www.wdmir.net * MAIL:mir3@163.com */ package com.greensock.plugins { import flash.display.*; import com.greensock.*; /** * Some components require resizing with setSize() instead of standard tweens of width/height in * order to scale properly. The SetSizePlugin accommodates this easily. You can define the width, * height, or both. <br /><br /> * * <b>USAGE:</b><br /><br /> * <code> * import com.greensock.TweenLite; <br /> * import com.greensock.plugins.TweenPlugin; <br /> * import com.greensock.plugins.SetSizePlugin; <br /> * TweenPlugin.activate([SetSizePlugin]); //activation is permanent in the SWF, so this line only needs to be run once.<br /><br /> * * TweenLite.to(myComponent, 1, {setSize:{width:200, height:30}}); <br /><br /> * </code> * * <b>Copyright 2010, GreenSock. All rights reserved.</b> This work is subject to the terms in <a href="http://www.greensock.com/terms_of_use.html">http://www.greensock.com/terms_of_use.html</a> or for corporate Club GreenSock members, the software agreement that was issued with the corporate membership. * * @author Jack Doyle, jack@greensock.com */ public class SetSizePlugin extends TweenPlugin { /** @private **/ public static const API:Number = 1.0; //If the API/Framework for plugins changes in the future, this number helps determine compatibility /** @private **/ public var width:Number; /** @private **/ public var height:Number; /** @private **/ protected var _target:Object; /** @private **/ protected var _setWidth:Boolean; /** @private **/ protected var _setHeight:Boolean; /** @private **/ protected var _hasSetSize:Boolean; /** @private **/ public function SetSizePlugin() { super(); this.propName = "setSize"; this.overwriteProps = ["setSize","setActualSize","width","height","scaleX","scaleY"]; this.round = true; } /** @private **/ override public function onInitTween(target:Object, value:*, tween:TweenLite):Boolean { _target = target; _hasSetSize = Boolean("setSize" in _target); if ("width" in value && _target.width != value.width) { addTween((_hasSetSize) ? this : _target, "width", _target.width, value.width, "width"); _setWidth = _hasSetSize; } if ("height" in value && _target.height != value.height) { addTween((_hasSetSize) ? this : _target, "height", _target.height, value.height, "height"); _setHeight = _hasSetSize; } if (_tweens.length == 0) { _hasSetSize = false; //protects from situations where the start and end values are the same, thus we're not really tweening anything. } return true; } /** @private **/ override public function killProps(lookup:Object):void { super.killProps(lookup); if (_tweens.length == 0 || "setSize" in lookup) { this.overwriteProps = []; } } /** @private **/ override public function set changeFactor(n:Number):void { updateTweens(n); if (_hasSetSize) { _target.setSize((_setWidth) ? this.width : _target.width, (_setHeight) ? this.height : _target.height); } } } }
/* * Copyright (c) 2018 Marcel Piestansky * * 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.marpies.ane.facebook.events { /** * Internal base class for events which represent cancellable action, e.g. login. */ public class AIRFacebookCancellableEvent extends AIRFacebookEvent { private var mCancelled:Boolean; public function AIRFacebookCancellableEvent( type:String, bubbles:Boolean = false, cancelable:Boolean = false ) { super( type, bubbles, cancelable ); } /** * * * Getters / Setters * * */ /** * Returns <code>true</code> if the action represented by the event was cancelled, * <code>false</code> otherwise. */ public function get wasCancelled():Boolean { return mCancelled; } /** * @private */ ns_airfacebook_internal function set wasCancelled( value:Boolean ):void { mCancelled = value; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.core { import flash.display.SimpleButton; import mx.utils.NameUtil; /** * FlexSimpleButton is a subclass of the Player's SimpleButton class. * It overrides the <code>toString()</code> method * to return a string indicating the location of the object * within the hierarchy of DisplayObjects in the application. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class FlexSimpleButton extends SimpleButton { include "../core/Version.as"; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * <p>Sets the <code>name</code> property to a string * returned by the <code>createUniqueName()</code> * method of the mx.utils.NameUtils class.</p> * * <p>This string is the name of the object's class concatenated * with an integer that is unique within the application, * such as <code>"FlexSimpleButton16"</code>.</p> * * @see flash.display.DisplayObject#name * @see mx.utils.NameUtil#createUniqueName() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function FlexSimpleButton() { super(); try { name = NameUtil.createUniqueName(this); } catch(e:Error) { // The name assignment above can cause the RTE // Error #2078: The name property of a Timeline-placed // object cannot be modified. // if this class has been associated with an asset // that was created in the Flash authoring tool. // The only known case where this is a problem is when // an asset has another asset PlaceObject'd onto it and // both are embedded separately into a Flex application. // In this case, we ignore the error and toString() will // use the name assigned in the Flash authoring tool. } } //-------------------------------------------------------------------------- // // Overridden methods // //-------------------------------------------------------------------------- /** * Returns a string indicating the location of this object * within the hierarchy of DisplayObjects in the Application. * This string, such as <code>"MyApp0.HBox5.FlexSimpleButton16"</code>, * is built by the <code>displayObjectToString()</code> method * of the mx.utils.NameUtils class from the <code>name</code> * property of the object and its ancestors. * * @return A String indicating the location of this object * within the DisplayObject hierarchy. * * @see flash.display.DisplayObject#name * @see mx.utils.NameUtil#displayObjectToString() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ override public function toString():String { return NameUtil.displayObjectToString(this); } } }
#define _DAC_B0 24 ' #define _DAC_B1 25 ' #define _DAC_B2 26 ' #define _DAC_B3 27 ' MAIN: PRINT "STARTING APP ..." OUTPUT(_DAC_B0) OUTPUT(_DAC_B1) OUTPUT(_DAC_B2) OUTPUT(_DAC_B3) DO ' an inlined approach to fire off a nibble of gpio, as a binary counter (in a fast manner) ' Print AD(0), AD(7), AD(8) ' trying nxp's naming, historical AB approach, and even the package pin # - no joy. Pkg pin 8 tied to pin 40 (3v3 Vdd) OUT(_DAC_B0) = 0 OUT(_DAC_B1) = 0 OUT(_DAC_B2) = 0 OUT(_DAC_B3) = 0 OUT(_DAC_B0) = 1 OUT(_DAC_B0) = 0 OUT(_DAC_B1) = 1 OUT(_DAC_B0) = 1 OUT(_DAC_B0) = 0 OUT(_DAC_B1) = 0 OUT(_DAC_B2) = 1 OUT(_DAC_B0) = 1 OUT(_DAC_B0) = 0 OUT(_DAC_B1) = 1 OUT(_DAC_B0) = 1 OUT(_DAC_B0) = 0 OUT(_DAC_B1) = 0 OUT(_DAC_B2) = 0 OUT(_DAC_B3) = 1 OUT(_DAC_B0) = 1 OUT(_DAC_B0) = 0 OUT(_DAC_B1) = 1 OUT(_DAC_B0) = 1 OUT(_DAC_B0) = 0 OUT(_DAC_B1) = 0 OUT(_DAC_B2) = 1 OUT(_DAC_B0) = 1 OUT(_DAC_B0) = 0 OUT(_DAC_B1) = 1 OUT(_DAC_B0) = 1 LOOP END
/* * -*- Mode: Actionscript -*- * ************************************************************************* * * Copyright 2007-2009 Juice, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ************************************************************************* */ package org.juicekit.events { import flash.events.Event; import flash.events.IEventDispatcher; /** * The InactivityEvent class defines an event to signal a period of * inactivity occurred. * * @author Jon Buffington * * @see InactivityMonitor */ public class InactivityEvent extends Event { /** * The <code>InactivityEvent.INACTIVITY_PERIOD</code> constant * defines the value of the <code>type</code> property of the event * object for a <code>jkInactivityPeriod</code> event. */ public static const INACTIVITY_PERIOD:String = "jkInactivityPeriod"; /** * Constructor. * * @param type The event type; indicates the action that caused the event. * * @param bubbles Specifies whether the event can bubble up the * display list hierarchy. * * @param cancelable Specifies whether the behavior associated with * the event can be prevented. * * @param monitored References the watched object that became inactive. * * @param idleTime Contains the time in milliseconds elapsed since * the last activity was observed. */ public function InactivityEvent(type:String, bubbles:Boolean, cancelable:Boolean, monitored:IEventDispatcher, idleTime:Number) { super(type, bubbles, cancelable); this.monitored = monitored; this.idleTime = idleTime; } /** * References the watched object that became inactive. */ public var monitored:IEventDispatcher; /** * Contains the time in milliseconds elapsed since the last * activity was observed. */ public var idleTime:Number; /** * @inheritDoc */ override public function clone():Event { return new InactivityEvent(type, bubbles, cancelable, monitored, idleTime); } } }
/* Copyright (c) 2011 Taro Hanamura See LICENSE.txt for full license information. */ /* using BetweenAS3: http://www.libspark.org/wiki/BetweenAS3/en */ package org.typefest.transitions.keytween.tweens { import org.libspark.betweenas3.BetweenAS3; import org.libspark.betweenas3.core.easing.IEasing; import org.libspark.betweenas3.easing.Linear; import org.libspark.betweenas3.tweens.IObjectTween; import org.libspark.betweenas3.tweens.ITween; import org.typefest.transitions.keytween.KeyTween; import org.typefest.transitions.keytween.KeyTweenEvent; public class BetweenAS3Tween extends KeyTween { ///// tween protected var _tween:IObjectTween = null; ///// properties protected var _time:Number = 1; protected var _easing:IEasing = Linear.easeNone; public function get time():Number { return _time } public function set time(_:Number):void { _time = _ } public function get easing():IEasing { return _easing } public function set easing(_:IEasing):void { _easing = _ } //--------------------------------------- // constructor //--------------------------------------- public function BetweenAS3Tween( target:*, key:*, time:Number = 1, easing:IEasing = null, filter:Function = null ) { _time = time; _easing = easing || Linear.easeNone; super(target, key, filter); } //--------------------------------------- // check //--------------------------------------- override protected function _check():void { if (_value === _dest) { if (_tween) { _tween.stop(); _tween = null; dispatchEvent(new KeyTweenEvent(KeyTweenEvent.END)); } } else { var _:ITween = _tween; _tween = BetweenAS3.to({_:_value}, {_:_dest}, _time, _easing); _tween.onUpdate = _tweenUpdate; _tween.onComplete = _tweenComplete; _tween.play(); if (_) { _.stop(); } else { dispatchEvent(new KeyTweenEvent(KeyTweenEvent.START)); } } } ///// tween update protected function _tweenUpdate():void { _value = _tween.target["_"]; _target[_key] = _filter is Function ? _filter(_value) : _value; dispatchEvent(new KeyTweenEvent(KeyTweenEvent.UPDATE)); } ///// tween complete protected function _tweenComplete():void { _tween = null; dispatchEvent(new KeyTweenEvent(KeyTweenEvent.END)); } } }
/* * FLINT PARTICLE SYSTEM * ..................... * * Author: Richard Lord * Copyright (c) Richard Lord 2008-2011 * http://flintparticles.org/ * * Licence Agreement * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.flintparticles.common.easing { /** * A set of easing equations that start and end at the end value and reach the start value * at the half-time point. They are designed for modifying the particle energy such that it * starts and ends at zero and peaks at half way through the particle's lifetime. * * @see org.flintparticles.common.actions.Age */ public class TwoWay { /** * Gives a linear increase and decrease in energy either side of the centre point. */ public static function linear( t : Number, b : Number, c : Number, d : Number ):Number { if( ( t = 2 * t / d ) <= 1 ) { return ( 1 - t ) * c + b; } return ( t - 1 ) * c + b; } /** * Energy increases and then decreases as if following the top half of a circle. */ public static function circular( t : Number, b : Number, c : Number, d : Number ):Number { t = 1 - (2 * t / d); return ( 1 - Math.sqrt( 1 - t * t ) ) * c + b; } /** * Energy follows the first half of a sine wave. */ public static function sine( t : Number, b : Number, c : Number, d : Number ):Number { return ( 1 - Math.sin( Math.PI * t / d ) ) * c + b; } /** * Eases towards the middle using a quadratic curve. */ public static function quadratic( t : Number, b : Number, c : Number, d : Number ):Number { t = 1 - (2 * t / d); return t * t * c + b; } /** * Eases towards the middle using a cubic curve. */ public static function cubic( t : Number, b : Number, c : Number, d : Number ):Number { t = 1 - (2 * t / d); if( t < 0 ) t = -t; return t * t * t * c + b; } /** * Eases towards the middle using a quartic curve. */ public static function quartic( t : Number, b : Number, c : Number, d : Number ):Number { t = 1 - (2 * t / d); return t * t * t * t * c + b; } /** * Eases towards the middle using a quintic curve. */ public static function quintic( t : Number, b : Number, c : Number, d : Number ):Number { t = 1 - (2 * t / d); if( t < 0 ) t = -t; return t * t * t * t * t * c + b; } } }
package serverProto.player { import com.netease.protobuf.Message; import com.netease.protobuf.fieldDescriptors.FieldDescriptor$TYPE_MESSAGE; import com.netease.protobuf.WireType; import serverProto.inc.ProtoRetInfo; import com.netease.protobuf.WritingBuffer; import com.netease.protobuf.WriteUtils; import flash.utils.IDataInput; import com.netease.protobuf.ReadUtils; import flash.errors.IOError; public final class ProtoGetPlayerTopsInfoRsp extends Message { public static const RET:FieldDescriptor$TYPE_MESSAGE = new FieldDescriptor$TYPE_MESSAGE("serverProto.player.ProtoGetPlayerTopsInfoRsp.ret","ret",1 << 3 | WireType.LENGTH_DELIMITED,ProtoRetInfo); public static const PLAYER_TIPS:FieldDescriptor$TYPE_MESSAGE = new FieldDescriptor$TYPE_MESSAGE("serverProto.player.ProtoGetPlayerTopsInfoRsp.player_tips","playerTips",2 << 3 | WireType.LENGTH_DELIMITED,ProtoPlayerTipsInfo); private var ret$field:ProtoRetInfo; private var player_tips$field:serverProto.player.ProtoPlayerTipsInfo; public function ProtoGetPlayerTopsInfoRsp() { super(); } public function clearRet() : void { this.ret$field = null; } public function get hasRet() : Boolean { return this.ret$field != null; } public function set ret(param1:ProtoRetInfo) : void { this.ret$field = param1; } public function get ret() : ProtoRetInfo { return this.ret$field; } public function clearPlayerTips() : void { this.player_tips$field = null; } public function get hasPlayerTips() : Boolean { return this.player_tips$field != null; } public function set playerTips(param1:serverProto.player.ProtoPlayerTipsInfo) : void { this.player_tips$field = param1; } public function get playerTips() : serverProto.player.ProtoPlayerTipsInfo { return this.player_tips$field; } override final function writeToBuffer(param1:WritingBuffer) : void { var _loc2_:* = undefined; if(this.hasRet) { WriteUtils.writeTag(param1,WireType.LENGTH_DELIMITED,1); WriteUtils.write$TYPE_MESSAGE(param1,this.ret$field); } if(this.hasPlayerTips) { WriteUtils.writeTag(param1,WireType.LENGTH_DELIMITED,2); WriteUtils.write$TYPE_MESSAGE(param1,this.player_tips$field); } for(_loc2_ in this) { super.writeUnknown(param1,_loc2_); } } override final function readFromSlice(param1:IDataInput, param2:uint) : void { /* * Decompilation error * Code may be obfuscated * Tip: You can try enabling "Automatic deobfuscation" in Settings * Error type: IndexOutOfBoundsException (Index: 2, Size: 2) */ throw new flash.errors.IllegalOperationError("Not decompiled due to error"); } } }
/** * __ __ __ * ____/ /_ ____/ /______ _ ___ / /_ * / __ / / ___/ __/ ___/ / __ `/ __/ * / /_/ / (__ ) / / / / / /_/ / / * \__,_/_/____/_/ /_/ /_/\__, /_/ * / / * \/ * http://distriqt.com * * @author Michael (https://github.com/marchbold) * @created 18/5/21 */ package { import com.apm.client.APM; import com.apm.client.events.APMEvent; import flash.desktop.NativeApplication; import flash.desktop.SystemIdleMode; import flash.display.Sprite; import flash.events.InvokeEvent; import flash.system.System; import flash.utils.setInterval; public class APMConsoleApp extends Sprite { //////////////////////////////////////////////////////// // CONSTANTS // private static const TAG:String = "APMConsoleApp"; //////////////////////////////////////////////////////// // VARIABLES // protected var apmContext:APM; //////////////////////////////////////////////////////// // FUNCTIONALITY // public function APMConsoleApp() { apmContext = new APM(); NativeApplication.nativeApplication.executeInBackground = true; NativeApplication.nativeApplication.systemIdleMode = SystemIdleMode.KEEP_AWAKE; NativeApplication.nativeApplication.idleThreshold = 86400; NativeApplication.nativeApplication.addEventListener( InvokeEvent.INVOKE, invokeHandler ); } private function invokeHandler( event:InvokeEvent ):void { apmContext.main( event.arguments ); } } }
/** * User: MerlinDS * Date: 13.07.2014 * Time: 3:22 */ package com.merlinds.miracle_tool.views.logger { import com.bit101.components.HBox; import com.bit101.components.IndicatorLight; import com.bit101.components.Label; import com.bit101.components.Panel; import com.merlinds.miracle_tool.views.interfaces.IResizable; import flash.display.DisplayObjectContainer; public class StatusBar extends Panel implements IResizable { private static const _label:Label = new Label(); private static const _indicator:IndicatorLight = new IndicatorLight(null, 0, 4, 0xFF00FF00); private static var _errorWasOcure:Boolean; //============================================================================== //{region PUBLIC METHODS public function StatusBar(parent:DisplayObjectContainer) { super(parent, 0, 0); var body:HBox = new HBox(this); body.x = 10; body.addChild(_indicator); body.addChild(_label); _indicator.isLit = true; } //} endregion PUBLIC METHODS =================================================== //============================================================================== //{region PRIVATE\PROTECTED METHODS override public function setSize(w:Number, h:Number):void { this.y = h; super.setSize(w, _label.height); } public static function log(...message):void { if(!_errorWasOcure){ _label.text = "Log: " + message.join(" "); _indicator.color = 0xFF00FF00; _indicator.isLit = true; } } public static function warning(...message):void { if(!_errorWasOcure){ _indicator.color = 0xFFFF9900; _indicator.flash(500); _label.text = "Warning: " + message.join(" ") + "!"; } } public static function error(...message):void { _indicator.color = 0xFFFF0000; _indicator.flash(200); _label.text = "Error: " + message.join(" ") + "!"; _errorWasOcure = true; } public static function fixed():void { _errorWasOcure = false; log("Ok!"); } //} endregion PRIVATE\PROTECTED METHODS ======================================== //============================================================================== //{region EVENTS HANDLERS //} endregion EVENTS HANDLERS ================================================== //============================================================================== //{region GETTERS/SETTERS public static function get height():int { return _label.height; } //} endregion GETTERS/SETTERS ================================================== } }
package org.as3wavsound { import flash.events.SampleDataEvent; import flash.media.Sound; import flash.media.SoundChannel; import flash.media.SoundLoaderContext; import flash.media.SoundTransform; import flash.net.URLRequest; import flash.utils.ByteArray; import org.as3wavsound.sazameki.core.AudioSamples; import org.as3wavsound.sazameki.core.AudioSetting; import org.as3wavsound.sazameki.format.wav.Wav; /* * -------------------------------------- * b.bottema [Codemonkey] -- WavSound Sound adaption * http://blog.projectnibble.org/ * -------------------------------------- * sazameki -- audio manipulating library * http://sazameki.org/ * -------------------------------------- * * - developed by: * Benny Bottema (Codemonkey) * blog.projectnibble.org * hosted by: * Google Code (code.google.com) * code.google.com/p/as3wavsound/ * * - audio library in its original state developed by: * Takaaki Yamazaki * www.zkdesign.jp * hosted by: * Spark project (www.libspark.org) * www.libspark.org/svn/as3/sazameki/branches/fp10/ */ /* * Licensed under the MIT License * * Copyright (c) 2008 Takaaki Yamazaki * * 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. */ /** * Sound extension that directly plays WAVE data. Also backwards compatible with * MP3's played through the load() method. * * Simply embed .wav files as you would mp3's and play with this Sound class. * Make sure you provide mimetype 'application/octet-stream' when embedding to * ensure Flash embeds the data as ByteArray. * * Example: * [Embed(source = "drumloop.wav", mimeType = "application/octet-stream")] * public const DrumLoop:Class; * public const rain:Sound = new WavSound(new DrumLoop() as ByteArray); * * * @author b.bottema [Codemonkey] */ public class WavSound extends Sound { // used to switch the runtime behavior of this Sound object, for backwards compatibility private var legacyMode:Boolean; // the master Sound player, which mixes all playing WavSound samples on any given moment private static const player:WavSoundPlayer = new WavSoundPlayer(); // length of the original encoded wav data private var _bytesTotal:Number; // extracted sound data for mixing private var _samples:AudioSamples; // each sound can be configured to be played mono/stereo using AudioSetting private var _playbackSettings:AudioSetting; // calculated length of the entire sound in milliseconds, made global to avoid recalculating all the time private var _length:Number; /** * Constructor: loads wavdata using loadWav(). * * @param wavData A ByteArray containing uncmopressed wav data. * @param audioSettings An optional playback configuration (mono/stereo, * sample rate and bit rate). */ public function WavSound(wavData:ByteArray, audioSettings:AudioSetting = null) { loadWav(wavData, audioSettings); } /** * Loads WAVE data. * * Resets this WavSound and turns off legacy mode to act as a WavSound object. * * @param wavData * @param audioSettings */ public function loadWav(wavData:ByteArray, audioSettings:AudioSetting = null): void { legacyMode = false; this._bytesTotal = wavData.length; this._samples = new Wav().decode(wavData); this._playbackSettings = (audioSettings != null) ? audioSettings : new AudioSetting(); this._length = samples.length / samples.setting.sampleRate * 1000; } /** * Loads MP3 data. * * Resets this WavSound and turns on legacy mode to act as if it were a basic Sound object. * Also stops all playing channels for this WavSound. */ public override function load(stream:URLRequest, context:SoundLoaderContext = null) : void { legacyMode = true; player.stopAll(this); super.load(stream, context); } /** * Playback function that performs the following tasks: * * - calculates the startingPhase, bases on startTime in ms. * - initializes loopsLeft variable * - registers a dummy function for SampleDataEvent.SAMPLE_DATA to avoid 'invalid Sound' error * - adds the playing channel in combination with its originating WavSound to the playingWavSounds * * @param startTime The starting time in milliseconds, applies to each loop (as with regular MP3 Sounds). * @param loops The number of loops to take in *addition* to the default playback (loops == 2 -> 3 playthroughs). * @param sndTransform An optional soundtransform to apply for playback that controls volume and panning. * @return The SoundChannel used for playing back the sound. */ public override function play(startTime:Number = 0, loops:int = 0, sndTransform:SoundTransform = null) : SoundChannel { if (legacyMode) { return super.play(startTime, loops, sndTransform); } else { addEventListener(SampleDataEvent.SAMPLE_DATA, function():void{}); var channel:SoundChannel = super.play(0, loops, sndTransform); player.playingWavSounds.push(new WavSoundChannel(this, startTime, loops, channel)); return channel; } } /** * No idea if this works. Alpha state. Read up on Sound.extract(): * http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/media/Sound.html#extract() */ public override function extract(target:ByteArray, length:Number, startPosition:Number = -1): Number { if (legacyMode) { return super.extract(target, length, startPosition); } else { var start:Number = Math.max(startPosition, 0); var end:Number = Math.min(length, samples.length); for (var i:Number = start; i < end; i++) { target.writeFloat(samples.left[i]); if (samples.setting.channels == 2) { target.writeFloat(samples.right[i]); } else { target.writeFloat(samples.left[i]); } } return samples.length; } } /** * Returns the total bytes of the wavData the current WavSound was created with. */ public override function get bytesLoaded () : uint { return (legacyMode) ? super.bytesLoaded : _bytesTotal; } /** * Returns the total bytes of the wavData the current WavSound was created with. */ public override function get bytesTotal () : int { return (legacyMode) ? super.bytesTotal : _bytesTotal; } /** * Returns the total length of the sound in milliseconds. */ public override function get length() : Number { return (legacyMode) ? super.length : _length; } internal function get samples():AudioSamples { return _samples; } internal function get playbackSettings():AudioSetting { return _playbackSettings; } } }
package com.destroytoday.menu { import flash.display.NativeMenuItem; import flash.ui.Keyboard; import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; public class MenuItemTest { //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- protected var item:MenuItem; //-------------------------------------------------------------------------- // // Prep // //-------------------------------------------------------------------------- [Before] public function setUp():void { } [After] public function tearDown():void { item = null; } //-------------------------------------------------------------------------- // // Tests // //-------------------------------------------------------------------------- [Test] public function item_is_native_menu_item():void { item = new MenuItem("Item"); assertThat(item is NativeMenuItem); } [Test] public function item_sets_label_with_constructor_argument():void { item = new MenuItem("Item"); assertThat(item.label, equalTo("Item")); } [Test] public function item_sets_key_modifiers_with_constructor_argument():void { var keyModifierList:Array = [Keyboard.COMMAND, Keyboard.SHIFT]; item = new MenuItem("Item", keyModifierList); assertThat(item.keyEquivalentModifiers, equalTo(keyModifierList)); } [Test] public function item_sets_key_equivalent_with_constructor_argument():void { item = new MenuItem("Item", null, "@"); assertThat(item.keyEquivalent, equalTo("@")); } } }
/* * Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ package Box2D.Dynamics.Joints{ import Box2D.Common.*; import Box2D.Common.Math.*; import Box2D.Dynamics.*; // Linear constraint (point-to-line) // d = p2 - p1 = x2 + r2 - x1 - r1 // C = dot(ay1, d) // Cdot = dot(d, cross(w1, ay1)) + dot(ay1, v2 + cross(w2, r2) - v1 - cross(w1, r1)) // = -dot(ay1, v1) - dot(cross(d + r1, ay1), w1) + dot(ay1, v2) + dot(cross(r2, ay1), v2) // J = [-ay1 -cross(d+r1,ay1) ay1 cross(r2,ay1)] // // Angular constraint // C = a2 - a1 + a_initial // Cdot = w2 - w1 // J = [0 0 -1 0 0 1] // Motor/Limit linear constraint // C = dot(ax1, d) // Cdot = = -dot(ax1, v1) - dot(cross(d + r1, ax1), w1) + dot(ax1, v2) + dot(cross(r2, ax1), v2) // J = [-ax1 -cross(d+r1,ax1) ax1 cross(r2,ax1)] public class b2PrismaticJoint extends b2Joint { public override function GetAnchor1():b2Vec2{ return m_body1.GetWorldPoint(m_localAnchor1); } public override function GetAnchor2():b2Vec2{ return m_body2.GetWorldPoint(m_localAnchor2); } public override function GetReactionForce() : b2Vec2 { var tMat:b2Mat22 = m_body1.m_xf.R; //b2Vec2 ax1 = b2Mul(m_body1->m_xf.R, m_localXAxis1); var ax1X:Number = m_limitForce* (tMat.col1.x * m_localXAxis1.x + tMat.col2.x * m_localXAxis1.y); var ax1Y:Number = m_limitForce* (tMat.col1.y * m_localXAxis1.x + tMat.col2.y * m_localXAxis1.y); //b2Vec2 ay1 = b2Mul(m_body1->m_xf.R, m_localYAxis1); var ay1X:Number = m_force* (tMat.col1.x * m_localYAxis1.x + tMat.col2.x * m_localYAxis1.y); var ay1Y:Number = m_force* (tMat.col1.y * m_localYAxis1.x + tMat.col2.y * m_localYAxis1.y); //return m_limitForce * ax1 + m_force * ay1; return new b2Vec2( m_limitForce*ax1X + m_force*ay1X, m_limitForce*ax1Y + m_force*ay1Y); } public override function GetReactionTorque() : Number { return m_torque; } /// Get the current joint translation, usually in meters. public function GetJointTranslation():Number{ var b1:b2Body = m_body1; var b2:b2Body = m_body2; var tMat:b2Mat22; var p1:b2Vec2 = b1.GetWorldPoint(m_localAnchor1); var p2:b2Vec2 = b2.GetWorldPoint(m_localAnchor2); //var d:b2Vec2 = b2Math.SubtractVV(p2, p1); var dX:Number = p2.x - p1.x; var dY:Number = p2.y - p1.y; //b2Vec2 axis = b1->GetWorldVector(m_localXAxis1); var axis:b2Vec2 = b1.GetWorldVector(m_localXAxis1); //float32 translation = b2Dot(d, axis); var translation:Number = axis.x*dX + axis.y*dY; return translation; } /// Get the current joint translation speed, usually in meters per second. public function GetJointSpeed():Number{ var b1:b2Body = m_body1; var b2:b2Body = m_body2; var tMat:b2Mat22; //b2Vec2 r1 = b2Mul(b1->m_xf.R, m_localAnchor1 - b1->GetLocalCenter()); tMat = b1.m_xf.R; var r1X:Number = m_localAnchor1.x - b1.m_sweep.localCenter.x; var r1Y:Number = m_localAnchor1.y - b1.m_sweep.localCenter.y; var tX:Number = (tMat.col1.x * r1X + tMat.col2.x * r1Y); r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y); r1X = tX; //b2Vec2 r2 = b2Mul(b2->m_xf.R, m_localAnchor2 - b2->GetLocalCenter()); tMat = b2.m_xf.R; var r2X:Number = m_localAnchor2.x - b2.m_sweep.localCenter.x; var r2Y:Number = m_localAnchor2.y - b2.m_sweep.localCenter.y; tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y); r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y); r2X = tX; //b2Vec2 p1 = b1->m_sweep.c + r1; var p1X:Number = b1.m_sweep.c.x + r1X; var p1Y:Number = b1.m_sweep.c.y + r1Y; //b2Vec2 p2 = b2->m_sweep.c + r2; var p2X:Number = b2.m_sweep.c.x + r2X; var p2Y:Number = b2.m_sweep.c.y + r2Y; //var d:b2Vec2 = b2Math.SubtractVV(p2, p1); var dX:Number = p2X - p1X; var dY:Number = p2Y - p1Y; //b2Vec2 axis = b1->GetWorldVector(m_localXAxis1); var axis:b2Vec2 = b1.GetWorldVector(m_localXAxis1); var v1:b2Vec2 = b1.m_linearVelocity; var v2:b2Vec2 = b2.m_linearVelocity; var w1:Number = b1.m_angularVelocity; var w2:Number = b2.m_angularVelocity; //var speed:Number = b2Math.b2Dot(d, b2Math.b2CrossFV(w1, ax1)) + b2Math.b2Dot(ax1, b2Math.SubtractVV( b2Math.SubtractVV( b2Math.AddVV( v2 , b2Math.b2CrossFV(w2, r2)) , v1) , b2Math.b2CrossFV(w1, r1))); //var b2D:Number = (dX*(-w1 * ax1Y) + dY*(w1 * ax1X)); //var b2D2:Number = (ax1X * ((( v2.x + (-w2 * r2Y)) - v1.x) - (-w1 * r1Y)) + ax1Y * ((( v2.y + (w2 * r2X)) - v1.y) - (w1 * r1X))); var speed:Number = (dX*(-w1 * axis.y) + dY*(w1 * axis.x)) + (axis.x * ((( v2.x + (-w2 * r2Y)) - v1.x) - (-w1 * r1Y)) + axis.y * ((( v2.y + (w2 * r2X)) - v1.y) - (w1 * r1X))); return speed; } /// Is the joint limit enabled? public function IsLimitEnabled() : Boolean { return m_enableLimit; } /// Enable/disable the joint limit. public function EnableLimit(flag:Boolean) : void { m_enableLimit = flag; } /// Get the lower joint limit, usually in meters. public function GetLowerLimit() : Number { return m_lowerTranslation; } /// Get the upper joint limit, usually in meters. public function GetUpperLimit() : Number { return m_upperTranslation; } /// Set the joint limits, usually in meters. public function SetLimits(lower:Number, upper:Number) : void { //b2Settings.b2Assert(lower <= upper); m_lowerTranslation = lower; m_upperTranslation = upper; } /// Is the joint motor enabled? public function IsMotorEnabled() : Boolean { return m_enableMotor; } /// Enable/disable the joint motor. public function EnableMotor(flag:Boolean) : void { m_enableMotor = flag; } /// Set the motor speed, usually in meters per second. public function SetMotorSpeed(speed:Number) : void { m_motorSpeed = speed; } /// Get the motor speed, usually in meters per second. public function GetMotorSpeed() :Number { return m_motorSpeed; } /// Set the maximum motor force, usually in N. public function SetMaxMotorForce(force:Number) : void { m_maxMotorForce = force; } /// Get the current motor force, usually in N. public function GetMotorForce() : Number { return m_motorForce; } //--------------- Internals Below ------------------- public function b2PrismaticJoint(def:b2PrismaticJointDef){ super(def); var tMat:b2Mat22; var tX:Number; var tY:Number; m_localAnchor1.SetV(def.localAnchor1); m_localAnchor2.SetV(def.localAnchor2); m_localXAxis1.SetV(def.localAxis1); //m_localYAxis1 = b2Cross(1.0f, m_localXAxis1); m_localYAxis1.x = -m_localXAxis1.y; m_localYAxis1.y = m_localXAxis1.x; m_refAngle = def.referenceAngle; m_linearJacobian.SetZero(); m_linearMass = 0.0; m_force = 0.0; m_angularMass = 0.0; m_torque = 0.0; m_motorJacobian.SetZero(); m_motorMass = 0.0; m_motorForce = 0.0; m_limitForce = 0.0; m_limitPositionImpulse = 0.0; m_lowerTranslation = def.lowerTranslation; m_upperTranslation = def.upperTranslation; m_maxMotorForce = def.maxMotorForce; m_motorSpeed = def.motorSpeed; m_enableLimit = def.enableLimit; m_enableMotor = def.enableMotor; } public override function InitVelocityConstraints(step:b2TimeStep) : void{ var b1:b2Body = m_body1; var b2:b2Body = m_body2; var tMat:b2Mat22; var tX:Number; // Compute the effective masses. //b2Vec2 r1 = b2Mul(b1->m_xf.R, m_localAnchor1 - b1->GetLocalCenter()); tMat = b1.m_xf.R; var r1X:Number = m_localAnchor1.x - b1.m_sweep.localCenter.x; var r1Y:Number = m_localAnchor1.y - b1.m_sweep.localCenter.y; tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y); r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y); r1X = tX; //b2Vec2 r2 = b2Mul(b2->m_xf.R, m_localAnchor2 - b2->GetLocalCenter()); tMat = b2.m_xf.R; var r2X:Number = m_localAnchor2.x - b2.m_sweep.localCenter.x; var r2Y:Number = m_localAnchor2.y - b2.m_sweep.localCenter.y; tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y); r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y); r2X = tX; //float32 invMass1 = b1->m_invMass, invMass2 = b2->m_invMass; var invMass1:Number = b1.m_invMass; var invMass2:Number = b2.m_invMass; //float32 invI1 = b1->m_invI, invI2 = b2->m_invI; var invI1:Number = b1.m_invI; var invI2:Number = b2.m_invI; // Compute point to line constraint effective mass. // J = [-ay1 -cross(d+r1,ay1) ay1 cross(r2,ay1)] //b2Vec2 ay1 = b2Mul(b1->m_xf.R, m_localYAxis1); tMat = b1.m_xf.R; var ay1X:Number = tMat.col1.x * m_localYAxis1.x + tMat.col2.x * m_localYAxis1.y; var ay1Y:Number = tMat.col1.y * m_localYAxis1.x + tMat.col2.y * m_localYAxis1.y; //b2Vec2 e = b2->m_sweep.c + r2 - b1->m_sweep.c; // e = d + r1 var eX:Number = b2.m_sweep.c.x + r2X - b1.m_sweep.c.x; var eY:Number = b2.m_sweep.c.y + r2Y - b1.m_sweep.c.y; //m_linearJacobian.Set(-ay1, -b2Math.b2Cross(e, ay1), ay1, b2Math.b2Cross(r2, ay1)); m_linearJacobian.linear1.x = -ay1X; m_linearJacobian.linear1.y = -ay1Y; m_linearJacobian.linear2.x = ay1X; m_linearJacobian.linear2.y = ay1Y; m_linearJacobian.angular1 = -(eX * ay1Y - eY * ay1X); m_linearJacobian.angular2 = r2X * ay1Y - r2Y * ay1X; m_linearMass = invMass1 + invI1 * m_linearJacobian.angular1 * m_linearJacobian.angular1 + invMass2 + invI2 * m_linearJacobian.angular2 * m_linearJacobian.angular2; //b2Settings.b2Assert(m_linearMass > Number.MIN_VALUE); m_linearMass = 1.0 / m_linearMass; // Compute angular constraint effective mass. m_angularMass = invI1 + invI2; if (m_angularMass > Number.MIN_VALUE) { m_angularMass = 1.0 / m_angularMass; } // Compute motor and limit terms. if (m_enableLimit || m_enableMotor) { // The motor and limit share a Jacobian and effective mass. //b2Vec2 ax1 = b2Mul(b1->m_xf.R, m_localXAxis1); tMat = b1.m_xf.R; var ax1X:Number = tMat.col1.x * m_localXAxis1.x + tMat.col2.x * m_localXAxis1.y; var ax1Y:Number = tMat.col1.y * m_localXAxis1.x + tMat.col2.y * m_localXAxis1.y; //m_motorJacobian.Set(-ax1, -b2Cross(e, ax1), ax1, b2Cross(r2, ax1)); m_motorJacobian.linear1.x = -ax1X; m_motorJacobian.linear1.y = -ax1Y; m_motorJacobian.linear2.x = ax1X; m_motorJacobian.linear2.y = ax1Y; m_motorJacobian.angular1 = -(eX * ax1Y - eY * ax1X); m_motorJacobian.angular2 = r2X * ax1Y - r2Y * ax1X; m_motorMass = invMass1 + invI1 * m_motorJacobian.angular1 * m_motorJacobian.angular1 + invMass2 + invI2 * m_motorJacobian.angular2 * m_motorJacobian.angular2; //b2Settings.b2Assert(m_motorMass > Number.MIN_VALUE); m_motorMass = 1.0 / m_motorMass; if (m_enableLimit) { //b2Vec2 d = e - r1; // p2 - p1 var dX:Number = eX - r1X; var dY:Number = eY - r1Y; //float32 jointTranslation = b2Dot(ax1, d); var jointTranslation:Number = ax1X * dX + ax1Y * dY; if (b2Math.b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0 * b2Settings.b2_linearSlop) { m_limitState = e_equalLimits; } else if (jointTranslation <= m_lowerTranslation) { if (m_limitState != e_atLowerLimit) { m_limitForce = 0.0; } m_limitState = e_atLowerLimit; } else if (jointTranslation >= m_upperTranslation) { if (m_limitState != e_atUpperLimit) { m_limitForce = 0.0; } m_limitState = e_atUpperLimit; } else { m_limitState = e_inactiveLimit; m_limitForce = 0.0; } } } if (m_enableMotor == false) { m_motorForce = 0.0; } if (m_enableLimit == false) { m_limitForce = 0.0; } if (step.warmStarting) { //b2Vec2 P1 = step.dt * (m_force * m_linearJacobian.linear1 + (m_motorForce + m_limitForce) * m_motorJacobian.linear1); var P1X:Number = step.dt * (m_force * m_linearJacobian.linear1.x + (m_motorForce + m_limitForce) * m_motorJacobian.linear1.x); var P1Y:Number = step.dt * (m_force * m_linearJacobian.linear1.y + (m_motorForce + m_limitForce) * m_motorJacobian.linear1.y); //b2Vec2 P2 = step.dt * (m_force * m_linearJacobian.linear2 + (m_motorForce + m_limitForce) * m_motorJacobian.linear2); var P2X:Number = step.dt * (m_force * m_linearJacobian.linear2.x + (m_motorForce + m_limitForce) * m_motorJacobian.linear2.x); var P2Y:Number = step.dt * (m_force * m_linearJacobian.linear2.y + (m_motorForce + m_limitForce) * m_motorJacobian.linear2.y); //float32 L1 = step.dt * (m_force * m_linearJacobian.angular1 - m_torque + (m_motorForce + m_limitForce) * m_motorJacobian.angular1); var L1:Number = step.dt * (m_force * m_linearJacobian.angular1 - m_torque + (m_motorForce + m_limitForce) * m_motorJacobian.angular1); //float32 L2 = step.dt * (m_force * m_linearJacobian.angular2 + m_torque + (m_motorForce + m_limitForce) * m_motorJacobian.angular2); var L2:Number = step.dt * (m_force * m_linearJacobian.angular2 + m_torque + (m_motorForce + m_limitForce) * m_motorJacobian.angular2); //b1->m_linearVelocity += invMass1 * P1; b1.m_linearVelocity.x += invMass1 * P1X; b1.m_linearVelocity.y += invMass1 * P1Y; //b1->m_angularVelocity += invI1 * L1; b1.m_angularVelocity += invI1 * L1; //b2->m_linearVelocity += invMass2 * P2; b2.m_linearVelocity.x += invMass2 * P2X; b2.m_linearVelocity.y += invMass2 * P2Y; //b2->m_angularVelocity += invI2 * L2; b2.m_angularVelocity += invI2 * L2; } else { m_force = 0.0; m_torque = 0.0; m_limitForce = 0.0; m_motorForce = 0.0; } m_limitPositionImpulse = 0.0; } public override function SolveVelocityConstraints(step:b2TimeStep) : void{ var b1:b2Body = m_body1; var b2:b2Body = m_body2; var invMass1:Number = b1.m_invMass; var invMass2:Number = b2.m_invMass; var invI1:Number = b1.m_invI; var invI2:Number = b2.m_invI; var oldLimitForce:Number; // Solve linear constraint. var linearCdot:Number = m_linearJacobian.Compute(b1.m_linearVelocity, b1.m_angularVelocity, b2.m_linearVelocity, b2.m_angularVelocity); var force:Number = -step.inv_dt * m_linearMass * linearCdot; m_force += force; var P:Number = step.dt * force; //b1->m_linearVelocity += (invMass1 * P) * m_linearJacobian.linear1; b1.m_linearVelocity.x += (invMass1 * P) * m_linearJacobian.linear1.x; b1.m_linearVelocity.y += (invMass1 * P) * m_linearJacobian.linear1.y; //b1->m_angularVelocity += invI1 * P * m_linearJacobian.angular1; b1.m_angularVelocity += invI1 * P * m_linearJacobian.angular1; //b2->m_linearVelocity += (invMass2 * P) * m_linearJacobian.linear2; b2.m_linearVelocity.x += (invMass2 * P) * m_linearJacobian.linear2.x; b2.m_linearVelocity.y += (invMass2 * P) * m_linearJacobian.linear2.y; //b2.m_angularVelocity += invI2 * P * m_linearJacobian.angular2; b2.m_angularVelocity += invI2 * P * m_linearJacobian.angular2; // Solve angular constraint. var angularCdot:Number = b2.m_angularVelocity - b1.m_angularVelocity; var torque:Number = -step.inv_dt * m_angularMass * angularCdot; m_torque += torque; var L:Number = step.dt * torque; b1.m_angularVelocity -= invI1 * L; b2.m_angularVelocity += invI2 * L; // Solve linear motor constraint. if (m_enableMotor && m_limitState != e_equalLimits) { var motorCdot:Number = m_motorJacobian.Compute(b1.m_linearVelocity, b1.m_angularVelocity, b2.m_linearVelocity, b2.m_angularVelocity) - m_motorSpeed; var motorForce:Number = -step.inv_dt * m_motorMass * motorCdot; var oldMotorForce:Number = m_motorForce; m_motorForce = b2Math.b2Clamp(m_motorForce + motorForce, -m_maxMotorForce, m_maxMotorForce); motorForce = m_motorForce - oldMotorForce; P = step.dt * motorForce; //b1.m_linearVelocity += (invMass1 * P) * m_motorJacobian.linear1; b1.m_linearVelocity.x += (invMass1 * P) * m_motorJacobian.linear1.x; b1.m_linearVelocity.y += (invMass1 * P) * m_motorJacobian.linear1.y; //b1.m_angularVelocity += invI1 * P * m_motorJacobian.angular1; b1.m_angularVelocity += invI1 * P * m_motorJacobian.angular1; //b2->m_linearVelocity += (invMass2 * P) * m_motorJacobian.linear2; b2.m_linearVelocity.x += (invMass2 * P) * m_motorJacobian.linear2.x; b2.m_linearVelocity.y += (invMass2 * P) * m_motorJacobian.linear2.y; //b2->m_angularVelocity += invI2 * P * m_motorJacobian.angular2; b2.m_angularVelocity += invI2 * P * m_motorJacobian.angular2; } // Solve linear limit constraint. if (m_enableLimit && m_limitState != e_inactiveLimit) { var limitCdot:Number = m_motorJacobian.Compute(b1.m_linearVelocity, b1.m_angularVelocity, b2.m_linearVelocity, b2.m_angularVelocity); var limitForce:Number = -step.inv_dt * m_motorMass * limitCdot; if (m_limitState == e_equalLimits) { m_limitForce += limitForce; } else if (m_limitState == e_atLowerLimit) { oldLimitForce = m_limitForce; m_limitForce = b2Math.b2Max(m_limitForce + limitForce, 0.0); limitForce = m_limitForce - oldLimitForce; } else if (m_limitState == e_atUpperLimit) { oldLimitForce = m_limitForce; m_limitForce = b2Math.b2Min(m_limitForce + limitForce, 0.0); limitForce = m_limitForce - oldLimitForce; } P = step.dt * limitForce; //b1->m_linearVelocity += (invMass1 * P) * m_motorJacobian.linear1; b1.m_linearVelocity.x += (invMass1 * P) * m_motorJacobian.linear1.x; b1.m_linearVelocity.y += (invMass1 * P) * m_motorJacobian.linear1.y; //b1->m_angularVelocity += invI1 * P * m_motorJacobian.angular1; b1.m_angularVelocity += invI1 * P * m_motorJacobian.angular1; //b2->m_linearVelocity += (invMass2 * P) * m_motorJacobian.linear2; b2.m_linearVelocity.x += (invMass2 * P) * m_motorJacobian.linear2.x; b2.m_linearVelocity.y += (invMass2 * P) * m_motorJacobian.linear2.y; //b2->m_angularVelocity += invI2 * P * m_motorJacobian.angular2; b2.m_angularVelocity += invI2 * P * m_motorJacobian.angular2; } } public override function SolvePositionConstraints():Boolean{ var limitC:Number; var oldLimitImpulse:Number; var b1:b2Body = m_body1; var b2:b2Body = m_body2; var invMass1:Number = b1.m_invMass; var invMass2:Number = b2.m_invMass; var invI1:Number = b1.m_invI; var invI2:Number = b2.m_invI; var tMat:b2Mat22; var tX:Number; //b2Vec2 r1 = b2Mul(b1->m_xf.R, m_localAnchor1 - b1->GetLocalCenter()); tMat = b1.m_xf.R; var r1X:Number = m_localAnchor1.x - b1.m_sweep.localCenter.x; var r1Y:Number = m_localAnchor1.y - b1.m_sweep.localCenter.y; tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y); r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y); r1X = tX; //b2Vec2 r2 = b2Mul(b2->m_xf.R, m_localAnchor2 - b2->GetLocalCenter()); tMat = b2.m_xf.R; var r2X:Number = m_localAnchor2.x - b2.m_sweep.localCenter.x; var r2Y:Number = m_localAnchor2.y - b2.m_sweep.localCenter.y; tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y); r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y); r2X = tX; //b2Vec2 p1 = b1->m_sweep.c + r1; var p1X:Number = b1.m_sweep.c.x + r1X; var p1Y:Number = b1.m_sweep.c.y + r1Y; //b2Vec2 p2 = b2->m_sweep.c + r2; var p2X:Number = b2.m_sweep.c.x + r2X; var p2Y:Number = b2.m_sweep.c.y + r2Y; //b2Vec2 d = p2 - p1; var dX:Number = p2X - p1X; var dY:Number = p2Y - p1Y; //b2Vec2 ay1 = b2Mul(b1->m_xf.R, m_localYAxis1); tMat = b1.m_xf.R; var ay1X:Number = tMat.col1.x * m_localYAxis1.x + tMat.col2.x * m_localYAxis1.y; var ay1Y:Number = tMat.col1.y * m_localYAxis1.x + tMat.col2.y * m_localYAxis1.y; // Solve linear (point-to-line) constraint. //float32 linearC = b2Dot(ay1, d); var linearC:Number = ay1X*dX + ay1Y*dY; // Prevent overly large corrections. linearC = b2Math.b2Clamp(linearC, -b2Settings.b2_maxLinearCorrection, b2Settings.b2_maxLinearCorrection); var linearImpulse:Number = -m_linearMass * linearC; //b1->m_sweep.c += (invMass1 * linearImpulse) * m_linearJacobian.linear1; b1.m_sweep.c.x += (invMass1 * linearImpulse) * m_linearJacobian.linear1.x; b1.m_sweep.c.y += (invMass1 * linearImpulse) * m_linearJacobian.linear1.y; //b1->m_sweep.a += invI1 * linearImpulse * m_linearJacobian.angular1; b1.m_sweep.a += invI1 * linearImpulse * m_linearJacobian.angular1; //b1->SynchronizeTransform(); // updated by angular constraint //b2->m_sweep.c += (invMass2 * linearImpulse) * m_linearJacobian.linear2; b2.m_sweep.c.x += (invMass2 * linearImpulse) * m_linearJacobian.linear2.x; b2.m_sweep.c.y += (invMass2 * linearImpulse) * m_linearJacobian.linear2.y; //b2->m_sweep.a += invI2 * linearImpulse * m_linearJacobian.angular2; b2.m_sweep.a += invI2 * linearImpulse * m_linearJacobian.angular2; //b2->SynchronizeTransform(); // updated by angular constraint var positionError:Number = b2Math.b2Abs(linearC); // Solve angular constraint. var angularC:Number = b2.m_sweep.a - b1.m_sweep.a - m_refAngle; // Prevent overly large corrections. angularC = b2Math.b2Clamp(angularC, -b2Settings.b2_maxAngularCorrection, b2Settings.b2_maxAngularCorrection); var angularImpulse:Number = -m_angularMass * angularC; b1.m_sweep.a -= b1.m_invI * angularImpulse; b2.m_sweep.a += b2.m_invI * angularImpulse; b1.SynchronizeTransform(); b2.SynchronizeTransform(); var angularError:Number = b2Math.b2Abs(angularC); // Solve linear limit constraint. if (m_enableLimit && m_limitState != e_inactiveLimit) { //b2Vec2 r1 = b2Mul(b1->m_xf.R, m_localAnchor1 - b1->GetLocalCenter()); tMat = b1.m_xf.R; r1X = m_localAnchor1.x - b1.m_sweep.localCenter.x; r1Y = m_localAnchor1.y - b1.m_sweep.localCenter.y; tX = (tMat.col1.x * r1X + tMat.col2.x * r1Y); r1Y = (tMat.col1.y * r1X + tMat.col2.y * r1Y); r1X = tX; //b2Vec2 r2 = b2Mul(b2->m_xf.R, m_localAnchor2 - b2->GetLocalCenter()); tMat = b2.m_xf.R; r2X = m_localAnchor2.x - b2.m_sweep.localCenter.x; r2Y = m_localAnchor2.y - b2.m_sweep.localCenter.y; tX = (tMat.col1.x * r2X + tMat.col2.x * r2Y); r2Y = (tMat.col1.y * r2X + tMat.col2.y * r2Y); r2X = tX; //b2Vec2 p1 = b1->m_sweep.c + r1; p1X = b1.m_sweep.c.x + r1X; p1Y = b1.m_sweep.c.y + r1Y; //b2Vec2 p2 = b2->m_sweep.c + r2; p2X = b2.m_sweep.c.x + r2X; p2Y = b2.m_sweep.c.y + r2Y; //b2Vec2 d = p2 - p1; dX = p2X - p1X; dY = p2Y - p1Y; //b2Vec2 ax1 = b2Mul(b1->m_xf.R, m_localXAxis1); tMat = b1.m_xf.R; var ax1X:Number = tMat.col1.x * m_localXAxis1.x + tMat.col2.x * m_localXAxis1.y; var ax1Y:Number = tMat.col1.y * m_localXAxis1.x + tMat.col2.y * m_localXAxis1.y; //float32 translation = b2Dot(ax1, d); var translation:Number = (ax1X*dX + ax1Y*dY); var limitImpulse:Number = 0.0; if (m_limitState == e_equalLimits) { // Prevent large angular corrections limitC = b2Math.b2Clamp(translation, -b2Settings.b2_maxLinearCorrection, b2Settings.b2_maxLinearCorrection); limitImpulse = -m_motorMass * limitC; positionError = b2Math.b2Max(positionError, b2Math.b2Abs(angularC)); } else if (m_limitState == e_atLowerLimit) { limitC = translation - m_lowerTranslation; positionError = b2Math.b2Max(positionError, -limitC); // Prevent large linear corrections and allow some slop. limitC = b2Math.b2Clamp(limitC + b2Settings.b2_linearSlop, -b2Settings.b2_maxLinearCorrection, 0.0); limitImpulse = -m_motorMass * limitC; oldLimitImpulse = m_limitPositionImpulse; m_limitPositionImpulse = b2Math.b2Max(m_limitPositionImpulse + limitImpulse, 0.0); limitImpulse = m_limitPositionImpulse - oldLimitImpulse; } else if (m_limitState == e_atUpperLimit) { limitC = translation - m_upperTranslation; positionError = b2Math.b2Max(positionError, limitC); // Prevent large linear corrections and allow some slop. limitC = b2Math.b2Clamp(limitC - b2Settings.b2_linearSlop, 0.0, b2Settings.b2_maxLinearCorrection); limitImpulse = -m_motorMass * limitC; oldLimitImpulse = m_limitPositionImpulse; m_limitPositionImpulse = b2Math.b2Min(m_limitPositionImpulse + limitImpulse, 0.0); limitImpulse = m_limitPositionImpulse - oldLimitImpulse; } //b1->m_sweep.c += (invMass1 * limitImpulse) * m_motorJacobian.linear1; b1.m_sweep.c.x += (invMass1 * limitImpulse) * m_motorJacobian.linear1.x; b1.m_sweep.c.y += (invMass1 * limitImpulse) * m_motorJacobian.linear1.y; //b1->m_sweep.a += invI1 * limitImpulse * m_motorJacobian.angular1; b1.m_sweep.a += invI1 * limitImpulse * m_motorJacobian.angular1; //b2->m_sweep.c += (invMass2 * limitImpulse) * m_motorJacobian.linear2; b2.m_sweep.c.x += (invMass2 * limitImpulse) * m_motorJacobian.linear2.x; b2.m_sweep.c.y += (invMass2 * limitImpulse) * m_motorJacobian.linear2.y; //b2->m_sweep.a += invI2 * limitImpulse * m_motorJacobian.angular2; b2.m_sweep.a += invI2 * limitImpulse * m_motorJacobian.angular2; b1.SynchronizeTransform(); b2.SynchronizeTransform(); } return positionError <= b2Settings.b2_linearSlop && angularError <= b2Settings.b2_angularSlop; } public var m_localAnchor1:b2Vec2 = new b2Vec2(); public var m_localAnchor2:b2Vec2 = new b2Vec2(); public var m_localXAxis1:b2Vec2 = new b2Vec2(); public var m_localYAxis1:b2Vec2 = new b2Vec2(); public var m_refAngle:Number; public var m_linearJacobian:b2Jacobian = new b2Jacobian(); public var m_linearMass:Number; // effective mass for point-to-line constraint. public var m_force:Number; public var m_angularMass:Number; // effective mass for angular constraint. public var m_torque:Number; public var m_motorJacobian:b2Jacobian = new b2Jacobian(); public var m_motorMass:Number; // effective mass for motor/limit translational constraint. public var m_motorForce:Number; public var m_limitForce:Number; public var m_limitPositionImpulse:Number; public var m_lowerTranslation:Number; public var m_upperTranslation:Number; public var m_maxMotorForce:Number; public var m_motorSpeed:Number; public var m_enableLimit:Boolean; public var m_enableMotor:Boolean; public var m_limitState:int; }; }
//////////////////////////////////////////////////////////////////////////////// // // 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.html.beads { import org.apache.royale.core.IBead; import org.apache.royale.core.IItemRendererClassFactory; import org.apache.royale.core.IItemRendererParent; import org.apache.royale.core.ISelectionModel; import org.apache.royale.core.IStrand; import org.apache.royale.core.IStrandWithModelView; import org.apache.royale.core.ValuesManager; import org.apache.royale.events.Event; import org.apache.royale.events.EventDispatcher; import org.apache.royale.events.IEventDispatcher; import org.apache.royale.events.ItemRendererEvent; import org.apache.royale.html.beads.IListView; import org.apache.royale.utils.loadBeadFromValuesManager; [Event(name="itemRendererCreated",type="org.apache.royale.events.ItemRendererEvent")] /** * The TextItemRendererFactoryForStringVectorData class is the * IDataProviderItemRendererMapper for creating * ITextItemRenderers and assigning them data from an vector * of Strings. Other IDataProviderItemRendererMapper implementations * assign specific array or vector types to item * renderers expecting those types. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.0 */ public class TextItemRendererFactoryForStringVectorData extends EventDispatcher implements IBead { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.0 */ public function TextItemRendererFactoryForStringVectorData(target:Object=null) { super(target); } private var selectionModel:ISelectionModel; 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.0 */ public function set strand(value:IStrand):void { _strand = value; IEventDispatcher(value).addEventListener("initComplete",finishSetup); } private function finishSetup(event:Event):void { selectionModel = _strand.getBeadByType(ISelectionModel) as ISelectionModel; selectionModel.addEventListener("dataProviderChanged", dataProviderChangeHandler); // if the host component inherits from DataContainerBase, the itemRendererClassFactory will // already have been loaded by DataContainerBase.addedToParent function. if (!_itemRendererFactory) { _itemRendererFactory = loadBeadFromValuesManager(IItemRendererClassFactory, "iItemRendererClassFactory", _strand) as IItemRendererClassFactory; } dataProviderChangeHandler(null); } private var _itemRendererFactory:IItemRendererClassFactory; /** * An IItemRendererClassFactory that should generate ITextItemRenderers * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.0 */ public function get itemRendererFactory():IItemRendererClassFactory { if(!_itemRendererFactory) _itemRendererFactory = loadBeadFromValuesManager(IItemRendererClassFactory, "iItemRendererClassFactory", _strand) as IItemRendererClassFactory; return _itemRendererFactory } /** * @private */ public function set itemRendererFactory(value:IItemRendererClassFactory):void { _itemRendererFactory = value; } /** * The IItemRendererParent that should parent the ITextItemRenderers * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.0 */ protected var dataGroup:IItemRendererParent; /** * @royaleignorecoercion org.apache.royale.core.IStrandWithModelView * @royaleignorecoercion org.apache.royale.core.IListView */ private function dataProviderChangeHandler(event:Event):void { var dp:Vector.<String> = selectionModel.dataProvider as Vector.<String>; var view:IListView = (_strand as IStrandWithModelView).view as IListView; var dataGroup:IItemRendererParent = view.dataGroup; dataGroup.removeAllItemRenderers(); var n:int = dp.length; for (var i:int = 0; i < n; i++) { var tf:ITextItemRenderer = itemRendererFactory.createItemRenderer(dataGroup) as ITextItemRenderer; tf.index = i; //TODO There is no itemsCreated event being dispatched once all the item renderers are added. // Not sure why, but that would require dispatching events as they are added. This should probably be fixed. dataGroup.addItemRenderer(tf, true); tf.text = dp[i]; var newEvent:ItemRendererEvent = new ItemRendererEvent(ItemRendererEvent.CREATED); newEvent.itemRenderer = tf; dispatchEvent(newEvent); } } } }
/* 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/. */ var DESC = "'do' loop, comparable to 'for-1' and 'while-1'"; include "driver.as" function doloop():uint { var i:uint=0; do { i++; } while (i <= 100000); return i; } TEST(doloop, "do-1");
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.royale.net.remoting.messages { COMPILE::SWF{ import flash.utils.IDataInput; import flash.utils.IDataOutput; } COMPILE::JS{ import org.apache.royale.net.utils.IDataInput; import org.apache.royale.net.utils.IDataOutput; } [RemoteClass(alias="flex.messaging.messages.CommandMessage")] /** * The CommandMessage class provides a mechanism for sending commands to the * server infrastructure, such as commands related to publish/subscribe * messaging scenarios, ping operations, and cluster operations. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 * * @royalesuppresspublicvarwarning */ public class CommandMessage extends AsyncMessage { //-------------------------------------------------------------------------- // // Static Constants // //-------------------------------------------------------------------------- /** * This operation is used to subscribe to a remote destination. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const SUBSCRIBE_OPERATION:uint = 0; /** * This operation is used to unsubscribe from a remote destination. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const UNSUBSCRIBE_OPERATION:uint = 1; /** * This operation is used to poll a remote destination for pending, * undelivered messages. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const POLL_OPERATION:uint = 2; /** * This operation is used by a remote destination to sync missed or cached messages * back to a client as a result of a client issued poll command. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const CLIENT_SYNC_OPERATION:uint = 4; /** * This operation is used to test connectivity over the current channel to * the remote endpoint. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const CLIENT_PING_OPERATION:uint = 5; /** * This operation is used to request a list of failover endpoint URIs * for the remote destination based on cluster membership. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const CLUSTER_REQUEST_OPERATION:uint = 7; /** * This operation is used to send credentials to the endpoint so that * the user can be logged in over the current channel. * The credentials need to be Base64 encoded and stored in the <code>body</code> * of the message. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const LOGIN_OPERATION:uint = 8; /** * This operation is used to log the user out of the current channel, and * will invalidate the server session if the channel is HTTP based. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const LOGOUT_OPERATION:uint = 9; /** * Endpoints can imply what features they support by reporting the * latest version of messaging they are capable of during the handshake of * the initial ping CommandMessage. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const MESSAGING_VERSION:String = "DSMessagingVersion"; /** * This operation is used to indicate that the client's subscription with a * remote destination has timed out. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const SUBSCRIPTION_INVALIDATE_OPERATION:uint = 10; /** * Used by the MultiTopicConsumer to subscribe/unsubscribe for more * than one topic in the same message. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const MULTI_SUBSCRIBE_OPERATION:uint = 11; /** * This operation is used to indicate that a channel has disconnected. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const DISCONNECT_OPERATION:uint = 12; /** * This operation is used to trigger a ChannelSet to connect. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const TRIGGER_CONNECT_OPERATION:uint = 13; /** * This is the default operation for new CommandMessage instances. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const UNKNOWN_OPERATION:uint = 10000; /** * The server message type for authentication commands. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const AUTHENTICATION_MESSAGE_REF_TYPE:String = "flex.messaging.messages.AuthenticationMessage"; /** * Subscribe commands issued by a Consumer pass the Consumer's <code>selector</code> * expression in this header. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const SELECTOR_HEADER:String = "DSSelector"; /** * Durable JMS subscriptions are preserved when an unsubscribe message * has this parameter set to true in its header. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const PRESERVE_DURABLE_HEADER:String = "DSPreserveDurable"; /** * Header to indicate that the Channel needs the configuration from the * server. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const NEEDS_CONFIG_HEADER:String = "DSNeedsConfig"; /** * Header used in a MULTI_SUBSCRIBE message to specify an Array of subtopic/selector * pairs to add to the existing set of subscriptions. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const ADD_SUBSCRIPTIONS:String = "DSAddSub"; /** * Like the above, but specifies the subtopic/selector array of to remove * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const REMOVE_SUBSCRIPTIONS:String = "DSRemSub"; /** * The separator string used for separating subtopic and selectors in the * add and remove subscription headers. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const SUBTOPIC_SEPARATOR:String = "_;_"; /** * Header to drive an idle wait time before the next client poll request. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const POLL_WAIT_HEADER:String = "DSPollWait"; /** * Header to suppress poll response processing. If a client has a long-poll * parked on the server and issues another poll, the response to this subsequent poll * should be tagged with this header in which case the response is treated as a * no-op and the next poll will not be scheduled. Without this, a subsequent poll * will put the channel and endpoint into a busy polling cycle. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const NO_OP_POLL_HEADER:String = "DSNoOpPoll"; /** * Header to specify which character set encoding was used while encoding * login credentials. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const CREDENTIALS_CHARSET_HEADER:String = "DSCredentialsCharset"; /** * Header to indicate the maximum number of messages a Consumer wants to * receive per second. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const MAX_FREQUENCY_HEADER:String = "DSMaxFrequency"; /** * Header that indicates the message is a heartbeat. */ public static const HEARTBEAT_HEADER:String = "DS<3"; //-------------------------------------------------------------------------- // // Private Static Constants for Serialization // //-------------------------------------------------------------------------- private static const OPERATION_FLAG:uint = 1; //-------------------------------------------------------------------------- // // Static Variables // //-------------------------------------------------------------------------- /** * @private * Map of operations to semi-descriptive operation text strings. */ private static var operationTexts:Object = null; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructs an instance of a CommandMessage with an empty body and header * and a default <code>operation</code> of <code>UNKNOWN_OPERATION</code>. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public function CommandMessage() { super(); operation = UNKNOWN_OPERATION; } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * Provides access to the operation/command for the CommandMessage. * Operations indicate how this message should be processed by the remote * destination. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public var operation:uint; //-------------------------------------------------------------------------- // // Overridden Methods // //-------------------------------------------------------------------------- /** * @private */ override public function getSmallMessage():IMessage { // We shouldn't use small messages for PING or LOGIN operations as the // messaging version handshake would not yet be complete... for now just // optimize POLL operations. if (operation == POLL_OPERATION) { return new CommandMessageExt(this); } return null; } /** * @private */ /* override protected function addDebugAttributes(attributes:Object):void { super.addDebugAttributes(attributes); attributes["operation"] = getOperationAsString(operation); } */ /** * Returns a string representation of the message. * * @return String representation of the message. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ /* override public function toString():String { return getDebugString(); } */ //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * Provides a description of the operation specified. * This method is used in <code>toString()</code> operations on this * message. * * @param op One of the CommandMessage operation constants. * * @return Short name for the operation. * * @example * <code><pre> * var msg:CommandMessage = CommandMessage(event.message); * trace("Current operation -'"+ * CommandMessage.getOperationAsString(msg.operation)+ "'."); * </pre></code> * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ /* public static function getOperationAsString(op:uint):String { if (operationTexts == null) { operationTexts = {}; operationTexts[SUBSCRIBE_OPERATION] = "subscribe"; operationTexts[UNSUBSCRIBE_OPERATION] = "unsubscribe"; operationTexts[POLL_OPERATION] = "poll"; operationTexts[CLIENT_SYNC_OPERATION] = "client sync"; operationTexts[CLIENT_PING_OPERATION] = "client ping"; operationTexts[CLUSTER_REQUEST_OPERATION] = "cluster request"; operationTexts[LOGIN_OPERATION] = "login"; operationTexts[LOGOUT_OPERATION] = "logout"; operationTexts[SUBSCRIPTION_INVALIDATE_OPERATION] = "subscription invalidate"; operationTexts[MULTI_SUBSCRIBE_OPERATION] = "multi-subscribe"; operationTexts[DISCONNECT_OPERATION] = "disconnect"; operationTexts[TRIGGER_CONNECT_OPERATION] = "trigger connect"; operationTexts[UNKNOWN_OPERATION] = "unknown"; } var result:* = operationTexts[op]; return result == undefined ? op.toString() : String(result); } */ /** * @private */ override public function readExternal(input:IDataInput):void { super.readExternal(input); var flagsArray:Array = readFlags(input); for (var i:uint = 0; i < flagsArray.length; i++) { var flags:uint = flagsArray[i] as uint; var reservedPosition:uint = 0; if (i == 0) { if ((flags & OPERATION_FLAG) != 0) operation = input.readObject() as uint; reservedPosition = 1; } // For forwards compatibility, read in any other flagged objects // to preserve the integrity of the input stream... if ((flags >> reservedPosition) != 0) { for (var j:uint = reservedPosition; j < 6; j++) { if (((flags >> j) & 1) != 0) { input.readObject(); } } } } } /** * @private */ override public function writeExternal(output:IDataOutput):void { super.writeExternal(output); var flags:uint = 0; if (operation != 0) flags |= OPERATION_FLAG; output.writeByte(flags); if (operation != 0) output.writeObject(operation); } } }
package org.openapitools.client.api { import org.openapitools.common.ApiInvoker; import org.openapitools.exception.ApiErrorCodes; import org.openapitools.exception.ApiError; import org.openapitools.common.ApiUserCredentials; import org.openapitools.event.Response; import org.openapitools.common.OpenApi; import org.openapitools.client.model.Body; import org.openapitools.client.model.BranchImpl; import org.openapitools.client.model.FavoriteImpl; import org.openapitools.client.model.GithubScm; import org.openapitools.client.model.MultibranchPipeline; import org.openapitools.client.model.Organisation; import org.openapitools.client.model.Organisations; import org.openapitools.client.model.Pipeline; import org.openapitools.client.model.PipelineActivities; import org.openapitools.client.model.PipelineFolderImpl; import org.openapitools.client.model.PipelineImpl; import org.openapitools.client.model.PipelineQueue; import org.openapitools.client.model.PipelineRun; import org.openapitools.client.model.PipelineRunNode; import org.openapitools.client.model.PipelineRunNodeSteps; import org.openapitools.client.model.PipelineRunNodes; import org.openapitools.client.model.PipelineRuns; import org.openapitools.client.model.PipelineStepImpl; import org.openapitools.client.model.Pipelines; import org.openapitools.client.model.QueueItemImpl; import org.openapitools.client.model.ScmOrganisations; import org.openapitools.client.model.User; import org.openapitools.client.model.UserFavorites; import mx.rpc.AsyncToken; import mx.utils.UIDUtil; import flash.utils.Dictionary; import flash.events.EventDispatcher; public class BlueOceanApi extends OpenApi { /** * Constructor for the BlueOceanApi api client * @param apiCredentials Wrapper object for tokens and hostName required towards authentication * @param eventDispatcher Optional event dispatcher that when provided is used by the SDK to dispatch any Response */ public function BlueOceanApi(apiCredentials: ApiUserCredentials, eventDispatcher: EventDispatcher = null) { super(apiCredentials, eventDispatcher); } public static const event_delete_pipeline_queue_item: String = "delete_pipeline_queue_item"; public static const event_get_authenticated_user: String = "get_authenticated_user"; public static const event_get_classes: String = "get_classes"; public static const event_get_json_web_key: String = "get_json_web_key"; public static const event_get_json_web_token: String = "get_json_web_token"; public static const event_get_organisation: String = "get_organisation"; public static const event_get_organisations: String = "get_organisations"; public static const event_get_pipeline: String = "get_pipeline"; public static const event_get_pipeline_activities: String = "get_pipeline_activities"; public static const event_get_pipeline_branch: String = "get_pipeline_branch"; public static const event_get_pipeline_branch_run: String = "get_pipeline_branch_run"; public static const event_get_pipeline_branches: String = "get_pipeline_branches"; public static const event_get_pipeline_folder: String = "get_pipeline_folder"; public static const event_get_pipeline_folder_pipeline: String = "get_pipeline_folder_pipeline"; public static const event_get_pipeline_queue: String = "get_pipeline_queue"; public static const event_get_pipeline_run: String = "get_pipeline_run"; public static const event_get_pipeline_run_log: String = "get_pipeline_run_log"; public static const event_get_pipeline_run_node: String = "get_pipeline_run_node"; public static const event_get_pipeline_run_node_step: String = "get_pipeline_run_node_step"; public static const event_get_pipeline_run_node_step_log: String = "get_pipeline_run_node_step_log"; public static const event_get_pipeline_run_node_steps: String = "get_pipeline_run_node_steps"; public static const event_get_pipeline_run_nodes: String = "get_pipeline_run_nodes"; public static const event_get_pipeline_runs: String = "get_pipeline_runs"; public static const event_get_pipelines: String = "get_pipelines"; public static const event_get_scm: String = "get_scm"; public static const event_get_scm_organisation_repositories: String = "get_scm_organisation_repositories"; public static const event_get_scm_organisation_repository: String = "get_scm_organisation_repository"; public static const event_get_scm_organisations: String = "get_scm_organisations"; public static const event_get_user: String = "get_user"; public static const event_get_user_favorites: String = "get_user_favorites"; public static const event_get_users: String = "get_users"; public static const event_post_pipeline_run: String = "post_pipeline_run"; public static const event_post_pipeline_runs: String = "post_pipeline_runs"; public static const event_put_pipeline_favorite: String = "put_pipeline_favorite"; public static const event_put_pipeline_run: String = "put_pipeline_run"; public static const event_search: String = "search"; public static const event_search_classes: String = "search_classes"; /* * Returns void */ public function delete_pipeline_queue_item (organization: String, pipeline: String, queue: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/pipelines/{pipeline}/queue/{queue}".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "pipeline" + "}", getApiInvoker().escapeString(pipeline)).replace("{" + "queue" + "}", getApiInvoker().escapeString(queue)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "DELETE", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "delete_pipeline_queue_item"; token.returnType = null ; return requestId; } /* * Returns User */ public function get_authenticated_user (organization: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/user/".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if() { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_authenticated_user"; token.returnType = User; return requestId; } /* * Returns String */ public function get_classes (class: String): String { // create path and map variables var path: String = "/blue/rest/classes/{class}".replace(/{format}/g,"xml").replace("{" + "class" + "}", getApiInvoker().escapeString(class)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if() { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_classes"; token.returnType = String; return requestId; } /* * Returns String */ public function get_json_web_key (key: Number): String { // create path and map variables var path: String = "/jwt-auth/jwks/{key}".replace(/{format}/g,"xml").replace("{" + "key" + "}", getApiInvoker().escapeString(key)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if() { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_json_web_key"; token.returnType = String; return requestId; } /* * Returns String */ public function get_json_web_token (expiryTimeInMins: Number, maxExpiryTimeInMins: Number): String { // create path and map variables var path: String = "/jwt-auth/token".replace(/{format}/g,"xml"); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } if("null" != String(expiryTimeInMins)) queryParams["expiryTimeInMins"] = toPathValue(expiryTimeInMins); if("null" != String(maxExpiryTimeInMins)) queryParams["maxExpiryTimeInMins"] = toPathValue(maxExpiryTimeInMins); var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_json_web_token"; token.returnType = String; return requestId; } /* * Returns Organisation */ public function get_organisation (organization: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if() { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_organisation"; token.returnType = Organisation; return requestId; } /* * Returns Organisations */ public function get_organisations (): String { // create path and map variables var path: String = "/blue/rest/organizations/".replace(/{format}/g,"xml"); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_organisations"; token.returnType = Organisations; return requestId; } /* * Returns Pipeline */ public function get_pipeline (organization: String, pipeline: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/pipelines/{pipeline}".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "pipeline" + "}", getApiInvoker().escapeString(pipeline)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_pipeline"; token.returnType = Pipeline; return requestId; } /* * Returns PipelineActivities */ public function get_pipeline_activities (organization: String, pipeline: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/pipelines/{pipeline}/activities".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "pipeline" + "}", getApiInvoker().escapeString(pipeline)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_pipeline_activities"; token.returnType = PipelineActivities; return requestId; } /* * Returns BranchImpl */ public function get_pipeline_branch (organization: String, pipeline: String, branch: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/pipelines/{pipeline}/branches/{branch}/".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "pipeline" + "}", getApiInvoker().escapeString(pipeline)).replace("{" + "branch" + "}", getApiInvoker().escapeString(branch)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_pipeline_branch"; token.returnType = BranchImpl; return requestId; } /* * Returns PipelineRun */ public function get_pipeline_branch_run (organization: String, pipeline: String, branch: String, run: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/pipelines/{pipeline}/branches/{branch}/runs/{run}".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "pipeline" + "}", getApiInvoker().escapeString(pipeline)).replace("{" + "branch" + "}", getApiInvoker().escapeString(branch)).replace("{" + "run" + "}", getApiInvoker().escapeString(run)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if( // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_pipeline_branch_run"; token.returnType = PipelineRun; return requestId; } /* * Returns MultibranchPipeline */ public function get_pipeline_branches (organization: String, pipeline: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/pipelines/{pipeline}/branches".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "pipeline" + "}", getApiInvoker().escapeString(pipeline)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_pipeline_branches"; token.returnType = MultibranchPipeline; return requestId; } /* * Returns PipelineFolderImpl */ public function get_pipeline_folder (organization: String, folder: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/pipelines/{folder}/".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "folder" + "}", getApiInvoker().escapeString(folder)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_pipeline_folder"; token.returnType = PipelineFolderImpl; return requestId; } /* * Returns PipelineImpl */ public function get_pipeline_folder_pipeline (organization: String, pipeline: String, folder: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/pipelines/{folder}/pipelines/{pipeline}".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "pipeline" + "}", getApiInvoker().escapeString(pipeline)).replace("{" + "folder" + "}", getApiInvoker().escapeString(folder)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_pipeline_folder_pipeline"; token.returnType = PipelineImpl; return requestId; } /* * Returns PipelineQueue */ public function get_pipeline_queue (organization: String, pipeline: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/pipelines/{pipeline}/queue".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "pipeline" + "}", getApiInvoker().escapeString(pipeline)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_pipeline_queue"; token.returnType = PipelineQueue; return requestId; } /* * Returns PipelineRun */ public function get_pipeline_run (organization: String, pipeline: String, run: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/pipelines/{pipeline}/runs/{run}".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "pipeline" + "}", getApiInvoker().escapeString(pipeline)).replace("{" + "run" + "}", getApiInvoker().escapeString(run)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_pipeline_run"; token.returnType = PipelineRun; return requestId; } /* * Returns String */ public function get_pipeline_run_log (organization: String, pipeline: String, run: String, start: Number, download: Boolean): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/pipelines/{pipeline}/runs/{run}/log".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "pipeline" + "}", getApiInvoker().escapeString(pipeline)).replace("{" + "run" + "}", getApiInvoker().escapeString(run)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if( // verify required params are set if( // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } if("null" != String(start)) queryParams["start"] = toPathValue(start); if("null" != String(download)) queryParams["download"] = toPathValue(download); var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_pipeline_run_log"; token.returnType = String; return requestId; } /* * Returns PipelineRunNode */ public function get_pipeline_run_node (organization: String, pipeline: String, run: String, node: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/pipelines/{pipeline}/runs/{run}/nodes/{node}".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "pipeline" + "}", getApiInvoker().escapeString(pipeline)).replace("{" + "run" + "}", getApiInvoker().escapeString(run)).replace("{" + "node" + "}", getApiInvoker().escapeString(node)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if( // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_pipeline_run_node"; token.returnType = PipelineRunNode; return requestId; } /* * Returns PipelineStepImpl */ public function get_pipeline_run_node_step (organization: String, pipeline: String, run: String, node: String, step: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/pipelines/{pipeline}/runs/{run}/nodes/{node}/steps/{step}".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "pipeline" + "}", getApiInvoker().escapeString(pipeline)).replace("{" + "run" + "}", getApiInvoker().escapeString(run)).replace("{" + "node" + "}", getApiInvoker().escapeString(node)).replace("{" + "step" + "}", getApiInvoker().escapeString(step)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if( // verify required params are set if( // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_pipeline_run_node_step"; token.returnType = PipelineStepImpl; return requestId; } /* * Returns String */ public function get_pipeline_run_node_step_log (organization: String, pipeline: String, run: String, node: String, step: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/pipelines/{pipeline}/runs/{run}/nodes/{node}/steps/{step}/log".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "pipeline" + "}", getApiInvoker().escapeString(pipeline)).replace("{" + "run" + "}", getApiInvoker().escapeString(run)).replace("{" + "node" + "}", getApiInvoker().escapeString(node)).replace("{" + "step" + "}", getApiInvoker().escapeString(step)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if( // verify required params are set if( // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_pipeline_run_node_step_log"; token.returnType = String; return requestId; } /* * Returns PipelineRunNodeSteps */ public function get_pipeline_run_node_steps (organization: String, pipeline: String, run: String, node: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/pipelines/{pipeline}/runs/{run}/nodes/{node}/steps".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "pipeline" + "}", getApiInvoker().escapeString(pipeline)).replace("{" + "run" + "}", getApiInvoker().escapeString(run)).replace("{" + "node" + "}", getApiInvoker().escapeString(node)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if( // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_pipeline_run_node_steps"; token.returnType = PipelineRunNodeSteps; return requestId; } /* * Returns PipelineRunNodes */ public function get_pipeline_run_nodes (organization: String, pipeline: String, run: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/pipelines/{pipeline}/runs/{run}/nodes".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "pipeline" + "}", getApiInvoker().escapeString(pipeline)).replace("{" + "run" + "}", getApiInvoker().escapeString(run)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_pipeline_run_nodes"; token.returnType = PipelineRunNodes; return requestId; } /* * Returns PipelineRuns */ public function get_pipeline_runs (organization: String, pipeline: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/pipelines/{pipeline}/runs".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "pipeline" + "}", getApiInvoker().escapeString(pipeline)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_pipeline_runs"; token.returnType = PipelineRuns; return requestId; } /* * Returns Pipelines */ public function get_pipelines (organization: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/pipelines/".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if() { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_pipelines"; token.returnType = Pipelines; return requestId; } /* * Returns GithubScm */ public function get_scm (organization: String, scm: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/scm/{scm}".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "scm" + "}", getApiInvoker().escapeString(scm)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_scm"; token.returnType = GithubScm; return requestId; } /* * Returns ScmOrganisations */ public function get_scm_organisation_repositories (organization: String, scm: String, scmOrganisation: String, credentialId: String, pageSize: Number, pageNumber: Number): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/scm/{scm}/organizations/{scmOrganisation}/repositories".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "scm" + "}", getApiInvoker().escapeString(scm)).replace("{" + "scmOrganisation" + "}", getApiInvoker().escapeString(scmOrganisation)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if( // verify required params are set if( // verify required params are set if( // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } if("null" != String(credentialId)) queryParams["credentialId"] = toPathValue(credentialId); if("null" != String(pageSize)) queryParams["pageSize"] = toPathValue(pageSize); if("null" != String(pageNumber)) queryParams["pageNumber"] = toPathValue(pageNumber); var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_scm_organisation_repositories"; token.returnType = ScmOrganisations; return requestId; } /* * Returns ScmOrganisations */ public function get_scm_organisation_repository (organization: String, scm: String, scmOrganisation: String, repository: String, credentialId: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/scm/{scm}/organizations/{scmOrganisation}/repositories/{repository}".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "scm" + "}", getApiInvoker().escapeString(scm)).replace("{" + "scmOrganisation" + "}", getApiInvoker().escapeString(scmOrganisation)).replace("{" + "repository" + "}", getApiInvoker().escapeString(repository)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if( // verify required params are set if( // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } if("null" != String(credentialId)) queryParams["credentialId"] = toPathValue(credentialId); var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_scm_organisation_repository"; token.returnType = ScmOrganisations; return requestId; } /* * Returns ScmOrganisations */ public function get_scm_organisations (organization: String, scm: String, credentialId: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/scm/{scm}/organizations".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "scm" + "}", getApiInvoker().escapeString(scm)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } if("null" != String(credentialId)) queryParams["credentialId"] = toPathValue(credentialId); var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_scm_organisations"; token.returnType = ScmOrganisations; return requestId; } /* * Returns User */ public function get_user (organization: String, user: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/users/{user}".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "user" + "}", getApiInvoker().escapeString(user)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_user"; token.returnType = User; return requestId; } /* * Returns UserFavorites */ public function get_user_favorites (user: String): String { // create path and map variables var path: String = "/blue/rest/users/{user}/favorites".replace(/{format}/g,"xml").replace("{" + "user" + "}", getApiInvoker().escapeString(user)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if() { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_user_favorites"; token.returnType = UserFavorites; return requestId; } /* * Returns User */ public function get_users (organization: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/users/".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if() { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_users"; token.returnType = User; return requestId; } /* * Returns QueueItemImpl */ public function post_pipeline_run (organization: String, pipeline: String, run: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/pipelines/{pipeline}/runs/{run}/replay".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "pipeline" + "}", getApiInvoker().escapeString(pipeline)).replace("{" + "run" + "}", getApiInvoker().escapeString(run)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "post_pipeline_run"; token.returnType = QueueItemImpl; return requestId; } /* * Returns QueueItemImpl */ public function post_pipeline_runs (organization: String, pipeline: String): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/pipelines/{pipeline}/runs".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "pipeline" + "}", getApiInvoker().escapeString(pipeline)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "post_pipeline_runs"; token.returnType = QueueItemImpl; return requestId; } /* * Returns FavoriteImpl */ public function put_pipeline_favorite (organization: String, pipeline: String, body: Body): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/pipelines/{pipeline}/favorite".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "pipeline" + "}", getApiInvoker().escapeString(pipeline)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } var token:AsyncToken = getApiInvoker().invokeAPI(path, "PUT", queryParams, body, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "put_pipeline_favorite"; token.returnType = FavoriteImpl; return requestId; } /* * Returns PipelineRun */ public function put_pipeline_run (organization: String, pipeline: String, run: String, blocking: String, timeOutInSecs: Number): String { // create path and map variables var path: String = "/blue/rest/organizations/{organization}/pipelines/{pipeline}/runs/{run}/stop".replace(/{format}/g,"xml").replace("{" + "organization" + "}", getApiInvoker().escapeString(organization)).replace("{" + "pipeline" + "}", getApiInvoker().escapeString(pipeline)).replace("{" + "run" + "}", getApiInvoker().escapeString(run)); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if( // verify required params are set if( // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } if("null" != String(blocking)) queryParams["blocking"] = toPathValue(blocking); if("null" != String(timeOutInSecs)) queryParams["timeOutInSecs"] = toPathValue(timeOutInSecs); var token:AsyncToken = getApiInvoker().invokeAPI(path, "PUT", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "put_pipeline_run"; token.returnType = PipelineRun; return requestId; } /* * Returns String */ public function search (q: String): String { // create path and map variables var path: String = "/blue/rest/search/".replace(/{format}/g,"xml"); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if() { throw new ApiError(400, "missing required params"); } if("null" != String(q)) queryParams["q"] = toPathValue(q); var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "search"; token.returnType = String; return requestId; } /* * Returns String */ public function search_classes (q: String): String { // create path and map variables var path: String = "/blue/rest/classes/".replace(/{format}/g,"xml"); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if() { throw new ApiError(400, "missing required params"); } if("null" != String(q)) queryParams["q"] = toPathValue(q); var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "search_classes"; token.returnType = String; return requestId; } } }
package { import flash.display.MovieClip; public dynamic class SentinelMarker extends MovieClip { public function SentinelMarker() { super(); addFrameScript(0,this.frame1,1,this.frame2); } function frame1() : * { stop(); } function frame2() : * { stop(); } } }
package as_src { import system.data.maps.MultiValueMap; import system.data.Collection; /** * ... * @author i */ public class TODODataBase implements ITODODataBase { public function TODODataBase() { _todoMap = new MultiValueMap(); } /* INTERFACE as_src.ITODODataBase */ private var _todoMap : MultiValueMap; public function CreateEntry(assumedKey:String, entity:TODOMapPairValue):int { // сохраняем полученный ключ var workAssumedKey:String = assumedKey; // проверяем есть ли еще записи по переданному ключу var slice:Collection = _todoMap.getCollection( workAssumedKey ); if( slice != null ) { // если записей больше одной, то получаем старшее значение номера if (slice.size() > 0) { var pair:TODOMapPairValue = slice.get(slice.size() - 1); // и вставляемому присваиваем номер, увеличенный на единицу entity._numberEntry = pair._numberEntry + 1; } } // Вставляем компанент _todoMap.put( workAssumedKey, entity ); // Показываем всю структуру ( debug ) var mapArray:Array = _todoMap.getValues(); for (var i:int = 0; i < mapArray.length; i++ ) { trace(mapArray[i]._numberEntry); } trace(mapArray); // проверяем границы индексов return 0; } // public function GetEntry( Key:String ) : Array { // проверить бы входные данные // извлекаем var slice:Collection = _todoMap.get( Key ); return slice.toArray(); } // удаление элемента public function DeleteEntry(Key:String):void { } public function test(assumedKey:String):void { // показать содержимое } } }
package org.bigbluebutton.air.voice.views { import flash.events.MouseEvent; import org.bigbluebutton.lib.main.models.IUserSession; import org.bigbluebutton.lib.user.models.User; import org.bigbluebutton.lib.user.models.UserList; import org.bigbluebutton.lib.voice.commands.MicrophoneMuteSignal; import robotlegs.bender.bundles.mvcs.Mediator; public class MicButtonMediator extends Mediator { [Inject] public var userSession:IUserSession; [Inject] public var microphoneMuteSignal:MicrophoneMuteSignal; [Inject] public var view:IMicButton; /** * Initialize listeners and Mediator initial state */ override public function initialize():void { view.addEventListener(MouseEvent.CLICK, mouseEventClickHandler); userSession.userList.userChangeSignal.add(userChangeHandler); view.setVisibility(userSession.userList.me.voiceJoined); view.muted = userSession.userList.me.muted; } /** * Destroy view and listeners */ override public function destroy():void { view.removeEventListener(MouseEvent.CLICK, mouseEventClickHandler); userSession.userList.userChangeSignal.remove(userChangeHandler); super.destroy(); view.dispose(); view = null; } /** * Handle events to turnOn microphone */ private function mouseEventClickHandler(e:MouseEvent):void { microphoneMuteSignal.dispatch(userSession.userList.me); } /** * Update the view when there is a chenge in the model */ private function userChangeHandler(user:User, type:int):void { if (user.me) { if (type == UserList.JOIN_AUDIO) { view.setVisibility(user.voiceJoined); } else if (type == UserList.MUTE) { view.muted = user.muted; } } } } }
//////////////////////////////////////////////////////////////////////////////// // // 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.core { /** * The IDataGridModel interface describes the minimum set of properties * available to an DataGrid control. More sophisticated DataGrid controls * could have models that extend IDataGridModel. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.10.0 */ public interface ITableModel extends IColumns, ISelectionModel, IRollOverModel { /** * The selected item property * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.10.0 */ function get selectedItemProperty():Object function set selectedItemProperty(value:Object):void /** * Get the index for the selected item property * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.10.0 */ function getIndexForSelectedItemProperty():Number } }
/******************************************************************************* * PushButton Engine * Copyright (C) 2009 PushButton Labs, LLC * For more information see http://www.pushbuttonengine.com * * This file is licensed under the terms of the MIT license, which is included * in the License.html file at the root directory of this SDK. ******************************************************************************/ package com.pblabs.animation { import com.pblabs.engine.serialization.Enumerable; import flash.utils.Dictionary; /** * An enumeration that holds all the possible values for a type of animation. * * @see Animator */ public class AnimatorType extends Enumerable { /** * The value to use for animations that aren't currently animating. */ public static const NO_ANIMATION:AnimatorType = new AnimatorType(); /** * The value to use for animations that should play once and then stop. */ public static const PLAY_ANIMATION_ONCE:AnimatorType = new AnimatorType(); /** * The value to use for animations that should play once, and then start over. */ public static const LOOP_ANIMATION:AnimatorType = new AnimatorType(); /** * The value to use for animations that should play once, then reverse and animate back * to the start value. */ public static const PING_PONG_ANIMATION:AnimatorType = new AnimatorType(); private static var _typeMap:Dictionary = null; /** * @inheritDoc */ override public function get typeMap():Dictionary { if (!_typeMap) { _typeMap = new Dictionary(); _typeMap["NO_ANIMATION"] = NO_ANIMATION; _typeMap["PLAY_ANIMATION_ONCE"] = PLAY_ANIMATION_ONCE; _typeMap["LOOP_ANIMATION"] = LOOP_ANIMATION; _typeMap["PING_PONG_ANIMATION"] = PING_PONG_ANIMATION; } return _typeMap; } /** * @inheritDoc */ override public function get defaultType():Enumerable { return NO_ANIMATION; } } }
/* * Licensed under the MIT License * * Copyright 2010 (c) Flávio Silva, http://flsilva.com * * 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. * * http://www.opensource.org/licenses/mit-license.php */ package org.as3collections.queues { import org.as3collections.ICollection; import org.as3collections.ISortedQueue; import org.as3coreaddendum.system.IComparator; import org.as3utils.ReflectionUtil; /** * A queue that provides a <em>total ordering</em> on its elements. * The queue is ordered according to the <em>natural ordering</em> of its elements, by a <em>IComparator</em> typically provided at sorted queue creation time, or by the arguments provided to the <code>sort</code> or <code>sortOn</code> methods. * <p>For each change that occurs the queue is automatically ordered using the <code>comparator</code> and <code>options</code>. * If none was provided the default behavior of the <code>sort</code> method is used.</p> * <p>The user of this queue may change their order at any time by calling the <code>sort</code> or <code>sortOn</code> method and imposing others arguments to change the sort behaviour.</p> * <p>It's possible to create unique sorted queues, typed sorted queues and even unique typed sorted queues. * You just sends the <code>SortedQueue</code> object to the wrappers <code>UniqueQueue</code> or <code>TypedQueue</code> or uses the <code>QueueUtil.getUniqueTypedQueue</code>. * But there's a problem here: the return type will be <code>UniqueQueue</code> or <code>TypedQueue</code>. * Thus you will can no longer use the <code>sort</code> and <code>sortOn</code> methods directly. * The wrapped <code>SortedQueue</code> will be only automatically ordered, with the provided <code>comparator</code> and <code>options</code> constructor's arguments. * Check the examples at the bottom of the page.</p> * * @example * * <listing version="3.0"> * import org.as3collections.ISortedQueue; * import org.as3collections.queues.SortedQueue; * * var queue1:ISortedQueue = new SortedQueue([3, 5, 1, 7], null, Array.NUMERIC | Array.DESCENDING); * * queue1 // [7,5,3,1] * queue1.size() // 4 * * queue1.add(-1) // true * queue1 // [7,5,3,1,-1] * queue1.size() // 5 * * queue1.add(4) // true * queue1 // [7,5,4,3,1,-1] * queue1.size() // 6 * * queue1.add(5) // true * queue1 // [7,5,5,4,3,1,-1] * queue1.size() // 7 * * queue1.poll() // 7 * queue1 // [5,5,4,3,1,-1] * queue1.size() // 6 * * queue1.sort(null, Array.NUMERIC) * queue1 // [-1,1,3,4,5,5] * * queue1.poll() // -1 * queue1 // [5,5,4,3,1] * queue1.size() // 5 * * queue1.add(2) // true * queue1 // [5,5,4,3,2,1] * queue1.size() // 6 * * queue1.add(10) // true * queue1 // [10,5,5,4,3,2,1] * </listing> * * @author Flávio Silva */ public class SortedQueue extends LinearQueue implements ISortedQueue { private var _comparator: IComparator; private var _options: uint; /** * Defines the comparator object to be used automatically to sort. * <p>If this value change the queue is automatically reordered with the new value.</p> */ public function get comparator(): IComparator { return _comparator; } public function set comparator(value:IComparator): void { _comparator = value; _sort(); } /** * Defines the options to be used automatically to sort. * <p>If this value change the queue is automatically reordered with the new value.</p> */ public function get options(): uint { return _options; } public function set options(value:uint): void { _options = value; _sort(); } /** * Constructor, creates a new <code>SortedQueue</code> object. * * @param source an array to fill the queue. * @param comparator the comparator object to be used internally to sort. * @param options the options to be used internally to sort. */ public function SortedQueue(source:Array = null, comparator:IComparator = null, options:uint = 0) { super(source); _comparator = comparator; _options = options; _sort(); } /** * Creates and return a new <code>SortedQueue</code> object containing all elements in this queue (in the same order). * * @return a new <code>SortedQueue</code> object containing all elements in this queue (in the same order). */ override public function clone(): * { return new SortedQueue(data, _comparator, _options); } /** * Performs an arbitrary, specific evaluation of equality between this object and the <code>other</code> object. * <p>This implementation considers two differente objects equal if:</p> * <p> * <ul><li>object A and object B are instances of the same class (i.e. if they have <b>exactly</b> the same type)</li> * <li>object A contains all elements of object B</li> * <li>object B contains all elements of object A</li> * <li>elements have exactly the same order</li> * <li>object A and object B has the same type of comparator</li> * <li>object A and object B has the same options</li> * </ul></p> * <p>This implementation takes care of the order of the elements in the queue. * So, for two queues are equal the order of elements returned by the iterator object must be equal.</p> * * @param other the object to be compared for equality. * @return <code>true</code> if the arbitrary evaluation considers the objects equal. */ override public function equals(other:*): Boolean { if (this == other) return true; if (!ReflectionUtil.classPathEquals(this, other)) return false; var l:ISortedQueue = other as ISortedQueue; if (_options != l.options) return false; if (!_comparator && l.comparator) return false; if (_comparator && !l.comparator) return false; if (!ReflectionUtil.classPathEquals(_comparator, l.comparator)) return false; return super.equals(other); } /** * Inserts the specified element into this queue if it is possible to do so immediately without violating restrictions. * When using a restricted queue (like <code>TypedQueue</code> and <code>UniqueQueue</code>), this method is generally preferable to <code>add</code>, which can fail to insert an element only by throwing an error. * <p>Before returning, the queue is reordered.</p> * * @param element the element to add. * @return <code>true</code> if the element was added to this queue, else <code>false</code>. */ override public function offer(element:*): Boolean { var b:Boolean = super.offer(element); if (b) _sort(); return b; } /** * Retrieves and removes the head of this queue, or returns <code>null</code> if this queue is empty. * <p>Before returning, the queue is reordered.</p> * * @return the head of this queue, or <code>null</code> if this queue is empty. */ override public function poll(): * { var e:* = super.poll(); if (e) _sort(); return e; } /** * Removes a single instance (only one occurrence) of the specified object from this queue, if it is present. * <p>Before returning, the queue is reordered.</p> * * @param o the object to be removed from this collection, if present. * @return <code>true</code> if an object was removed as a result of this call. */ override public function remove(o:*): Boolean { var b:Boolean = super.remove(o); if (b) _sort(); return b; } /** * Removes all of this queue's elements that are also contained in the specified collection. After this call returns, this queue will contain no elements in common with the specified collection. * <p>Before returning, the queue is reordered.</p> * * @param collection the collection containing elements to be removed from this queue. * @return <code>true</code> if this queue changed as a result of the call. */ override public function removeAll(collection:ICollection): Boolean { var b:Boolean = super.removeAll(collection); if (b) _sort(); return b; } /** * Sorts the objects within this class. * <p>For more info see <code>org.as3coreaddendum.system.ISortable.sort()</code> in the link below.</p> * * @param compare * @param options * @return */ public function sort(compare:Function = null, options:uint = 0): Array { if (compare != null) { return data.sort(compare, options); } else { return data.sort(options); } } /** * @inheritDoc * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#sortOn() */ public function sortOn(fieldName:*, options:* = null): Array { return data.sortOn(fieldName, options); } /** * @private */ protected function _sort(): void { if (_comparator) { sort(_comparator.compare, _options); } else { sort(null, _options); } } } }
package tetragon.view.render2d.extensions.graphics.shaders.fragment { import tetragon.view.render2d.extensions.graphics.shaders.AbstractShader2D; import flash.display3D.Context3DProgramType; /* * A pixel shader that multiplies a single texture with constants (the color transform) * and vertex color. */ public class TextureVertexColorFragmentShader2D extends AbstractShader2D { public function TextureVertexColorFragmentShader2D() { compileAGAL(Context3DProgramType.FRAGMENT, "tex ft1, v1, fs0 <2d, repeat, linear> \n" + "mul ft2, v0, fc0 \n" + "mul oc, ft1, ft2 "); } } }
package fightLib.view { import com.pickgliss.toplevel.StageReferance; import com.pickgliss.ui.ComponentFactory; import com.pickgliss.ui.LayerManager; import com.pickgliss.ui.controls.BaseButton; import com.pickgliss.ui.controls.Frame; import com.pickgliss.ui.controls.TextButton; import com.pickgliss.ui.text.FilterFrameText; import com.pickgliss.utils.ObjectUtils; import ddt.manager.FightLibManager; import ddt.manager.GameInSocketOut; import ddt.manager.LanguageMgr; import ddt.manager.SoundManager; import flash.display.Bitmap; import flash.events.Event; import flash.events.MouseEvent; import flash.geom.Point; import flash.utils.getTimer; public class FightLibQuestionFrame extends Frame { private static const MarkRate:int = 1000; private var _reAnswerBtn:TextButton; private var _viewTutorialBtn:TextButton; private var _answerBtn1:BaseButton; private var _answerBtn2:BaseButton; private var _answerBtn3:BaseButton; private var _hasAnswered:int; private var _needAnswer:int; private var _totalQuestion:int; private var _question:String; private var _answer1:String; private var _answer2:String; private var _answer3:String; private var _timeLimit:int; private var _questionInfoField:FilterFrameText; private var _questionField:FilterFrameText; private var _timeField:FilterFrameText; private var _answerBack:Bitmap; private var _answerField1:FilterFrameText; private var _answerField2:FilterFrameText; private var _answerField3:FilterFrameText; private var _answerPosField1:FilterFrameText; private var _answerPosField2:FilterFrameText; private var _answerPosField3:FilterFrameText; private var _markStart:Boolean = false; private var _elapsed:int = 0; private var _markBlank:int = 0; private var _startTime:int = 0; public function FightLibQuestionFrame(param1:int, param2:String = "", param3:int = 0, param4:int = 0, param5:int = 0, param6:String = "", param7:String = "", param8:String = "", param9:String = "", param10:int = 30) { super(); _id = param1; titleText = param2; this._hasAnswered = param3; this._needAnswer = param4; this._totalQuestion = param5; this._question = param6; this._answer1 = param7; this._answer2 = param8; this._answer3 = param9; this._timeLimit = param10 + 1; this.updateInfo(); } private function updateInfo() : void { var _loc1_:Point = null; this._questionInfoField.text = LanguageMgr.GetTranslation("tank.fightLib.questionInfo",this._totalQuestion,this._needAnswer,this._hasAnswered,this._totalQuestion - id); this._questionField.text = this._question; this._answerField1.text = this._answer1; this._answerField2.text = this._answer2; this._answerField3.text = this._answer3; _loc1_ = ComponentFactory.Instance.creatCustomObject("fightLib.Question.Time.TopRight"); this._timeField.text = String(this._timeLimit) + LanguageMgr.GetTranslation("second"); this._timeField.x = _loc1_.x - this._timeField.width; this._timeField.y = _loc1_.y; } private function configUI() : void { this._answerBack = ComponentFactory.Instance.creatBitmap("tank.view.fightLib.AnswerBack"); _container.addChild(this._answerBack); this._questionInfoField = ComponentFactory.Instance.creatComponentByStylename("fightLib.Question.InfoField"); _container.addChild(this._questionInfoField); this._questionField = ComponentFactory.Instance.creatComponentByStylename("fightLib.Question.QuestionField"); _container.addChild(this._questionField); this._timeField = ComponentFactory.Instance.creatComponentByStylename("fightLib.Question.TimeField"); _container.addChild(this._timeField); this._reAnswerBtn = ComponentFactory.Instance.creatComponentByStylename("fightLib.Question.ReAnswerButton"); this._reAnswerBtn.text = LanguageMgr.GetTranslation("tank.fightLib.FightLibQuestionFrame.reAnswer"); _container.addChild(this._reAnswerBtn); this._viewTutorialBtn = ComponentFactory.Instance.creatComponentByStylename("fightLib.Question.ViewTutorialButton"); this._viewTutorialBtn.text = LanguageMgr.GetTranslation("tank.fightLib.FightLibQuestionFrame.viewTutorial"); _container.addChild(this._viewTutorialBtn); this._answerBtn1 = ComponentFactory.Instance.creatComponentByStylename("fightLib.Question.Answer1"); _container.addChild(this._answerBtn1); this._answerPosField1 = ComponentFactory.Instance.creatComponentByStylename("fightLib.Question.Answer.PositionField"); this._answerPosField1.text = "A"; this._answerBtn1.addChild(this._answerPosField1); this._answerField1 = ComponentFactory.Instance.creatComponentByStylename("fightLib.Question.AnswerField"); this._answerBtn1.addChild(this._answerField1); this._answerBtn2 = ComponentFactory.Instance.creatComponentByStylename("fightLib.Question.Answer2"); _container.addChild(this._answerBtn2); this._answerPosField2 = ComponentFactory.Instance.creatComponentByStylename("fightLib.Question.Answer.PositionField"); this._answerPosField2.text = "B"; this._answerBtn2.addChild(this._answerPosField2); this._answerField2 = ComponentFactory.Instance.creatComponentByStylename("fightLib.Question.AnswerField"); this._answerBtn2.addChild(this._answerField2); this._answerBtn3 = ComponentFactory.Instance.creatComponentByStylename("fightLib.Question.Answer3"); _container.addChild(this._answerBtn3); this._answerPosField3 = ComponentFactory.Instance.creatComponentByStylename("fightLib.Question.Answer.PositionField"); this._answerPosField3.text = "C"; this._answerBtn3.addChild(this._answerPosField3); this._answerField3 = ComponentFactory.Instance.creatComponentByStylename("fightLib.Question.AnswerField"); this._answerBtn3.addChild(this._answerField3); } override protected function init() : void { super.init(); this.configUI(); this.addEvent(); } private function addEvent() : void { addEventListener(Event.ADDED_TO_STAGE,this.__addedToStage); this._answerBtn1.addEventListener(MouseEvent.CLICK,this.__selectAnswer); this._answerBtn2.addEventListener(MouseEvent.CLICK,this.__selectAnswer); this._answerBtn3.addEventListener(MouseEvent.CLICK,this.__selectAnswer); this._reAnswerBtn.addEventListener(MouseEvent.CLICK,this.__reAnswer); this._viewTutorialBtn.addEventListener(MouseEvent.CLICK,this.__viewTutorial); } private function removeEvent() : void { removeEventListener(Event.ADDED_TO_STAGE,this.__addedToStage); if(this._answerBtn1) { this._answerBtn1.removeEventListener(MouseEvent.CLICK,this.__selectAnswer); } if(this._answerBtn2) { this._answerBtn2.removeEventListener(MouseEvent.CLICK,this.__selectAnswer); } if(this._answerBtn3) { this._answerBtn3.removeEventListener(MouseEvent.CLICK,this.__selectAnswer); } if(this._reAnswerBtn) { this._reAnswerBtn.removeEventListener(MouseEvent.CLICK,this.__reAnswer); } if(this._viewTutorialBtn) { this._viewTutorialBtn.removeEventListener(MouseEvent.CLICK,this.__viewTutorial); } } private function __addedToStage(param1:Event) : void { removeEventListener(Event.ADDED_TO_STAGE,this.__addedToStage); this.startupMark(); } private function startupMark() : void { if(!this._markStart) { this._startTime = getTimer(); this._elapsed = 0; this._markBlank = 0; StageReferance.stage.addEventListener(Event.ENTER_FRAME,this.__enterFrame); this._markStart = true; } } private function shutdownMark() : void { StageReferance.stage.removeEventListener(Event.ENTER_FRAME,this.__enterFrame); this._markStart = false; } private function __enterFrame(param1:Event) : void { var _loc2_:int = getTimer(); var _loc3_:int = _loc2_ - this._elapsed; this._elapsed = _loc2_ - this._startTime; if(this._elapsed >= this._timeLimit * 1000) { this.shutdownMark(); this.markComplete(); } else { this._markBlank = this._markBlank + _loc3_; if(this._markBlank >= MarkRate) { if(this._timeField) { this._timeField.text = String(int(this._timeLimit - this._elapsed / 1000)) + LanguageMgr.GetTranslation("second"); } this._markBlank = 0; } } } private function markComplete() : void { GameInSocketOut.sendFightLibAnswer(_id,-1); GameInSocketOut.sendGameSkipNext(int(this._elapsed / 1000)); this.close(); } private function __selectAnswer(param1:MouseEvent) : void { SoundManager.instance.play("008"); this._answerBtn1.enable = this._answerBtn2.enable = this._answerBtn3.enable = false; if(param1.currentTarget == this._answerBtn1) { GameInSocketOut.sendFightLibAnswer(_id,0); } else if(param1.currentTarget == this._answerBtn2) { GameInSocketOut.sendFightLibAnswer(_id,1); } else { GameInSocketOut.sendFightLibAnswer(_id,2); } GameInSocketOut.sendGameSkipNext(int(this._elapsed / 1000)); this.close(); } private function __reAnswer(param1:MouseEvent) : void { SoundManager.instance.play("008"); GameInSocketOut.sendFightLibReanswer(); FightLibManager.Instance.reAnswerNum--; } private function __viewTutorial(param1:MouseEvent) : void { SoundManager.instance.play("008"); FightLibManager.Instance.script.restart(); GameInSocketOut.sendClientScriptStart(); this.close(); } override public function dispose() : void { this.removeEvent(); if(this._reAnswerBtn) { this._reAnswerBtn.dispose(); this._reAnswerBtn = null; } if(this._viewTutorialBtn) { this._viewTutorialBtn.dispose(); this._viewTutorialBtn = null; } if(this._answerField1) { ObjectUtils.disposeObject(this._answerField1); } this._answerField1 = null; if(this._answerField2) { ObjectUtils.disposeObject(this._answerField2); } this._answerField2 = null; if(this._answerField3) { ObjectUtils.disposeObject(this._answerField3); } this._answerField3 = null; if(this._answerPosField1) { ObjectUtils.disposeObject(this._answerPosField1); } this._answerPosField1 = null; if(this._answerPosField2) { ObjectUtils.disposeObject(this._answerPosField2); } this._answerPosField2 = null; if(this._answerPosField3) { ObjectUtils.disposeObject(this._answerPosField3); } this._answerPosField3 = null; if(this._answerBack) { ObjectUtils.disposeObject(this._answerBack); } this._answerBack = null; if(this._timeField) { ObjectUtils.disposeObject(this._timeField); } this._timeField = null; super.dispose(); } public function close() : void { if(this._markStart) { this.shutdownMark(); } ObjectUtils.disposeObject(this); } public function show() : void { LayerManager.Instance.addToLayer(this,LayerManager.GAME_UI_LAYER,true); } } }
package services.vo.reports { [RemoteClass(alias="MapProductionProfile")] public class ProfileProductionReportVO { public var bIsShowDetail:Boolean = false; public var sGuestName:String = ""; public var sGuestSurName:String = ""; public var sArrivalFrom:String = ''; public var sArrivalTo:String = ''; public var bIsShowCompany:Boolean = false; // company or individual public var sCompanyName:String = ""; } }
package net.psykosoft.psykopaint2.core.rendering { import flash.display3D.Context3D; import flash.display3D.Context3DProgramType; import flash.display3D.textures.TextureBase; public class CopyTextureWithAlpha extends FullTextureFilter { private var copyAlpha:Number; private static var _instance : CopyTextureWithAlpha; public function CopyTextureWithAlpha() { } // use a static method because this is so universally used. (still bleh, tho) public static function copy(source : TextureBase, context3D : Context3D, alpha:Number = 1) : void { if (!_instance) throw new Error("CopyTextureWithAlpha::init must be called first!"); _instance.copyAlpha = alpha; _instance.draw(source, context3D); } public static function init(context3D : Context3D) : void { _instance ||= new CopyTextureWithAlpha(); _instance.init(context3D); } public static function dispose() : void { if (_instance) _instance.dispose(); } override protected function getFragmentCode() : String { // source image is always in fs0 return "tex ft0, v0, fs0 <2d, nearest, mipnone>\n"+ "mul oc, ft0, fc0\n"; } override public function draw(source : TextureBase, context3D : Context3D) : void { init(context3D); _vertexShaderData[4] = 2; _vertexShaderData[5] = 2; _vertexShaderData[8] = 1; _vertexShaderData[9] = 1; _context3D.setProgram(_program); _context3D.setProgramConstantsFromVector(Context3DProgramType.VERTEX, 0, _vertexShaderData, 4); _context3D.setProgramConstantsFromVector(Context3DProgramType.FRAGMENT, 0, Vector.<Number>([copyAlpha,copyAlpha,copyAlpha,copyAlpha]), 1); setRenderState(source); _context3D.drawTriangles(_quadIndices,0,2); clearRenderState(); } } }
/* * MIT License * * Copyright (c) 2017 Digital Strawberry LLC * * 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 breezedb.queries { internal namespace breezedb_internal = "https://getbreeze.io/breezedb"; }
package com.company.util { import flash.display.CapsStyle; import flash.display.GraphicsEndFill; import flash.display.GraphicsPath; import flash.display.GraphicsPathCommand; import flash.display.GraphicsSolidFill; import flash.display.GraphicsStroke; import flash.display.JointStyle; import flash.display.LineScaleMode; import flash.geom.Matrix; public class GraphicsUtil { public static const END_FILL:GraphicsEndFill = new GraphicsEndFill(); public static const QUAD_COMMANDS:Vector.<int> = new <int>[GraphicsPathCommand.MOVE_TO, GraphicsPathCommand.LINE_TO, GraphicsPathCommand.LINE_TO, GraphicsPathCommand.LINE_TO]; public static const DEBUG_STROKE:GraphicsStroke = new GraphicsStroke(1, false, LineScaleMode.NORMAL, CapsStyle.NONE, JointStyle.ROUND, 3, new GraphicsSolidFill(0xFF0000)); public static const END_STROKE:GraphicsStroke = new GraphicsStroke(); private static const TWO_PI:Number = (2 * Math.PI);//6.28318530717959 public static const ALL_CUTS:Array = [true, true, true, true]; public static function clearPath(_arg_1:GraphicsPath):void { _arg_1.commands.length = 0; _arg_1.data.length = 0; } public static function getRectPath(_arg_1:int, _arg_2:int, _arg_3:int, _arg_4:int):GraphicsPath { return (new GraphicsPath(QUAD_COMMANDS, new <Number>[_arg_1, _arg_2, (_arg_1 + _arg_3), _arg_2, (_arg_1 + _arg_3), (_arg_2 + _arg_4), _arg_1, (_arg_2 + _arg_4)])); } public static function getGradientMatrix(_arg_1:Number, _arg_2:Number, _arg_3:Number = 0, _arg_4:Number = 0, _arg_5:Number = 0):Matrix { var _local_6:Matrix = new Matrix(); _local_6.createGradientBox(_arg_1, _arg_2, _arg_3, _arg_4, _arg_5); return (_local_6); } public static function drawRect(_arg_1:int, _arg_2:int, _arg_3:int, _arg_4:int, _arg_5:GraphicsPath):void { _arg_5.moveTo(_arg_1, _arg_2); _arg_5.lineTo((_arg_1 + _arg_3), _arg_2); _arg_5.lineTo((_arg_1 + _arg_3), (_arg_2 + _arg_4)); _arg_5.lineTo(_arg_1, (_arg_2 + _arg_4)); } public static function drawCircle(_arg_1:Number, _arg_2:Number, _arg_3:Number, _arg_4:GraphicsPath, _arg_5:int = 8):void { var _local_8:Number; var _local_9:Number; var _local_10:Number; var _local_11:Number; var _local_12:Number; var _local_13:Number; var _local_6:Number = (1 + (1 / (_arg_5 * 1.75))); _arg_4.moveTo((_arg_1 + _arg_3), _arg_2); var _local_7:int = 1; while (_local_7 <= _arg_5) { _local_8 = ((TWO_PI * _local_7) / _arg_5); _local_9 = ((TWO_PI * (_local_7 - 0.5)) / _arg_5); _local_10 = (_arg_1 + (_arg_3 * Math.cos(_local_8))); _local_11 = (_arg_2 + (_arg_3 * Math.sin(_local_8))); _local_12 = (_arg_1 + ((_arg_3 * _local_6) * Math.cos(_local_9))); _local_13 = (_arg_2 + ((_arg_3 * _local_6) * Math.sin(_local_9))); _arg_4.curveTo(_local_12, _local_13, _local_10, _local_11); _local_7++; } } public static function drawCutEdgeRect(_arg_1:int, _arg_2:int, _arg_3:int, _arg_4:int, _arg_5:int, _arg_6:Array, _arg_7:GraphicsPath):void { if (_arg_6[0] != 0) { _arg_7.moveTo(_arg_1, (_arg_2 + _arg_5)); _arg_7.lineTo((_arg_1 + _arg_5), _arg_2); } else { _arg_7.moveTo(_arg_1, _arg_2); } if (_arg_6[1] != 0) { _arg_7.lineTo(((_arg_1 + _arg_3) - _arg_5), _arg_2); _arg_7.lineTo((_arg_1 + _arg_3), (_arg_2 + _arg_5)); } else { _arg_7.lineTo((_arg_1 + _arg_3), _arg_2); } if (_arg_6[2] != 0) { _arg_7.lineTo((_arg_1 + _arg_3), ((_arg_2 + _arg_4) - _arg_5)); _arg_7.lineTo(((_arg_1 + _arg_3) - _arg_5), (_arg_2 + _arg_4)); } else { _arg_7.lineTo((_arg_1 + _arg_3), (_arg_2 + _arg_4)); } if (_arg_6[3] != 0) { _arg_7.lineTo((_arg_1 + _arg_5), (_arg_2 + _arg_4)); _arg_7.lineTo(_arg_1, ((_arg_2 + _arg_4) - _arg_5)); } else { _arg_7.lineTo(_arg_1, (_arg_2 + _arg_4)); } if (_arg_6[0] != 0) { _arg_7.lineTo(_arg_1, (_arg_2 + _arg_5)); } else { _arg_7.lineTo(_arg_1, _arg_2); } } public static function drawDiamond(_arg_1:Number, _arg_2:Number, _arg_3:Number, _arg_4:GraphicsPath):void { _arg_4.moveTo(_arg_1, (_arg_2 - _arg_3)); _arg_4.lineTo((_arg_1 + _arg_3), _arg_2); _arg_4.lineTo(_arg_1, (_arg_2 + _arg_3)); _arg_4.lineTo((_arg_1 - _arg_3), _arg_2); } } }//package com.company.util
package org.aswing.components.tabbedpanes{ import org.aswing.plaf.basic.BasicClosableTabbedPaneUI; /** * Dispatched when a tab clos button is clicked. * @eventType org.aswing.event.TabCloseEvent.TAB_CLOSING */ [Event(name="tabClosing", type="org.aswing.event.TabCloseEvent")] /** * A TabbedPane with each tab a close button, you must listen the TabCloseEvent * and then remove the related tab component if you want. * By default, any thing will happen for close button click. * @author iiley */ public class JClosableTabbedPane extends JTabbedPane{ protected var closeEnables:Array; public function JClosableTabbedPane(){ super(); closeEnables = new Array(); setName("JClosableTabbedPane"); } override public function getDefaultBasicUIClass():Class{ return org.aswing.plaf.basic.BasicClosableTabbedPaneUI; } override public function getUIClassID():String{ return "ClosableTabbedPaneUI"; } /** * Sets whether or not the tab close button at index is enabled. * Nothing will happen if there is no tab at that index. * @param index the tab index which should be enabled/disabled * @param enabled whether or not the tab close button should be enabled */ public function setCloseEnabledAt(index:int, enabled:Boolean):void{ if(closeEnables[index] != enabled){ closeEnables[index] = enabled; revalidate(); repaint(); } } /** * Returns whether or not the tab close button at index is currently enabled. * false will be returned if there is no tab at that index. * @param index the index of the item being queried * @return if the tab close button at index is enabled; false otherwise. */ public function isCloseEnabledAt(index:int):Boolean{ return closeEnables[index] == true; } override protected function insertProperties(i:int, title:String="", icon:Icon=null, tip:String=null):void{ super.insertProperties(i, title, icon, tip); insertToArray(closeEnables, i, true); } override protected function removeProperties(i:int):void{ super.removeProperties(i); removeFromArray(closeEnables, i); } } }
/** * Created by newkrok on 29/12/15. */ package src.game.library.crates { import Box2D.Collision.Shapes.b2PolygonShape; import Box2D.Common.Math.b2Vec2; import Box2D.Dynamics.b2World; import flash.geom.Point; import net.fpp.common.starling.StaticAssetManager; import src.constant.CBox2D; import starling.display.Image; public class RampCrate extends BaseCrate { private const WIDTH:uint = 75; private const HEIGHT:uint = 37; public function RampCrate( world:b2World, position:Point, scale:Number ) { super( world, position, scale ); } override protected function createShape():b2PolygonShape { var polygonShape:b2PolygonShape = new b2PolygonShape(); var vertices:Vector.<b2Vec2>; if( this._scale == 1 ) { vertices = new <b2Vec2>[ new b2Vec2( WIDTH / 2 / CBox2D.PIXELS_TO_METRE * -1, HEIGHT / 2 / CBox2D.PIXELS_TO_METRE * -1 ), new b2Vec2( WIDTH / 2 / CBox2D.PIXELS_TO_METRE, HEIGHT / 2 / CBox2D.PIXELS_TO_METRE ), new b2Vec2( WIDTH / 2 / CBox2D.PIXELS_TO_METRE * -1, HEIGHT / 2 / CBox2D.PIXELS_TO_METRE ) ]; } else { vertices = new <b2Vec2>[ new b2Vec2( WIDTH / 2 / CBox2D.PIXELS_TO_METRE, HEIGHT / 2 / CBox2D.PIXELS_TO_METRE * -1 ), new b2Vec2( WIDTH / 2 / CBox2D.PIXELS_TO_METRE, HEIGHT / 2 / CBox2D.PIXELS_TO_METRE ), new b2Vec2( WIDTH / 2 / CBox2D.PIXELS_TO_METRE * -1, HEIGHT / 2 / CBox2D.PIXELS_TO_METRE ) ]; } polygonShape.SetAsVector( vertices, 3 ); return polygonShape; } override protected function createImage():void { this._image = new Image( StaticAssetManager.instance.getTexture( 'crate_4' ) ); } } }
package flash.events { public class ActivityEvent extends Event { public function get activating():Boolean; public function set activating(value:Boolean):void; public function ActivityEvent(type:String, bubbles:Boolean = false, cancelable:Boolean = false, activating:Boolean = false); public override function clone():Event; public override function toString():String; public static const ACTIVITY:String = "activity"; } }
package idv.cjcat.stardustextended.actions { import idv.cjcat.stardustextended.emitters.Emitter; import idv.cjcat.stardustextended.particles.Particle; import idv.cjcat.stardustextended.xml.XMLBuilder; /** * Causes a particle's position to change according to its velocity. * * <p> * Default priority = -4; * </p> */ public class Move extends Action { /** * The multiplier of movement, 1 by default. * * <p> * For instance, a multiplier value of 2 causes a particle to move twice as fast as normal. * </p> */ public var multiplier : Number; private var factor : Number; public function Move(multiplier : Number = 1) { priority = -4; this.multiplier = multiplier; } override public function preUpdate(emitter : Emitter, time : Number) : void { factor = time * multiplier; } override public function update(emitter : Emitter, particle : Particle, timeDelta : Number, currentTime : Number) : void { particle.x += particle.vx * factor; particle.y += particle.vy * factor; } //XML //------------------------------------------------------------------------------------------------ override public function getXMLTagName() : String { return "Move"; } override public function toXML() : XML { var xml : XML = super.toXML(); xml.@multiplier = multiplier; return xml; } override public function parseXML(xml : XML, builder : XMLBuilder = null) : void { super.parseXML(xml, builder); if (xml.@multiplier.length()) multiplier = parseFloat(xml.@multiplier); } //------------------------------------------------------------------------------------------------ //end of XML } }
/************************************************************************** Filename : DemoController.as Copyright : Copyright 2011 Autodesk, Inc. All Rights reserved. Use of this software is subject to the terms of the Autodesk license agreement provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. **************************************************************************/ package com.scaleform.clikbrowser.controllers { import scaleform.clik.interfaces.IDataProvider; public class DemoController extends Object { // Constants: // Public Properties: // Protected Properties: protected var _tabData:IDataProvider; // UI Elements: // Initialization: public function DemoController() { super(); } // Public getter / setters: public function getTabData():IDataProvider { return _tabData; } // Public Methods: public function toString():String { return "[DemoController Base]"; } // Protected Methods: } }
//////////////////////////////////////////////////////////////////////////////// // // 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 // // No warranty of merchantability or fitness of any kind. // Use this software at your own risk. // //////////////////////////////////////////////////////////////////////////////// package actionScripts.utils { import flash.display.DisplayObject; import flash.events.Event; import flash.geom.Point; import flash.system.Capabilities; import mx.collections.ArrayCollection; import mx.collections.ICollectionView; import mx.collections.IList; import mx.collections.Sort; import mx.collections.SortField; import mx.controls.Alert; import mx.core.FlexGlobals; import mx.core.UIComponent; import mx.events.CloseEvent; import mx.events.ToolTipEvent; import mx.managers.PopUpManager; import mx.resources.ResourceManager; import mx.utils.UIDUtil; import actionScripts.events.GlobalEventDispatcher; import actionScripts.events.ProjectEvent; import actionScripts.factory.FileLocation; import actionScripts.locator.IDEModel; import actionScripts.plugin.actionscript.as3project.vo.AS3ProjectVO; import actionScripts.plugin.actionscript.as3project.vo.SWFOutputVO; import actionScripts.plugin.groovy.grailsproject.vo.GrailsProjectVO; import actionScripts.plugin.haxe.hxproject.vo.HaxeOutputVO; import actionScripts.plugin.haxe.hxproject.vo.HaxeProjectVO; import actionScripts.plugin.java.javaproject.vo.JavaProjectVO; import actionScripts.plugin.ondiskproj.vo.OnDiskProjectVO; import actionScripts.plugin.settings.SettingsView; import actionScripts.ui.IContentWindow; import actionScripts.ui.IFileContentWindow; import actionScripts.ui.menu.vo.MenuItem; import actionScripts.ui.menu.vo.ProjectMenuTypes; import actionScripts.ui.tabview.CloseTabEvent; import actionScripts.valueObjects.ConstantsCoreVO; import actionScripts.valueObjects.DataHTMLType; import actionScripts.valueObjects.FileWrapper; import actionScripts.valueObjects.ProjectReferenceVO; import actionScripts.valueObjects.ProjectVO; import actionScripts.valueObjects.ResourceVO; import actionScripts.valueObjects.SDKReferenceVO; import actionScripts.valueObjects.SDKTypes; import components.popup.ModifiedFileListPopup; import components.renderers.CustomToolTipGBA; import components.views.splashscreen.SplashScreen; import feathers.data.ArrayCollection; //import flash.filesystem.File; public class UtilsCore { public static var wrappersFoundThroughFindingAWrapper:Vector.<FileWrapper>; private static var model:IDEModel = IDEModel.getInstance(); /** * Get data agent error type */ public static function getDataType(value:String):DataHTMLType { var dataType:DataHTMLType = new DataHTMLType(); var message:String; // true if it's a login agent call if ((value.indexOf("/Grails4NotesBroker/admin/auth") != -1) || (value.indexOf("Please Login") != -1)) { // error is a login error var indexToStart:int = value.indexOf("<div class='login_message'>"); if (indexToStart > 0) message = value.substring(indexToStart+27, value.indexOf("</div>", indexToStart)); else message = "Please, check your username or password."; dataType.message = message; dataType.type = DataHTMLType.LOGIN_ERROR; dataType.isError = true; } else if ((value.toLowerCase().indexOf("authenticated") != -1) || (value.toLowerCase().indexOf("welcome to grails") != -1)) { dataType.isError = false; dataType.type = DataHTMLType.LOGIN_SUCCESS; } else { dataType.message = "Your session has expired. Please, re-login."; dataType.type = DataHTMLType.SESSION_ERROR; dataType.isError = true; } return dataType; } /** * Checks through opened project list against * a given path value * @return * BOOL */ public static function checkProjectIfAlreadyOpened(value:String):Boolean { for each (var file:ProjectVO in model.projects) { if (file.folderLocation.fileBridge.nativePath == value) { return true; } } return false; } /** * Creates custom tooltip */ public static function createCustomToolTip(event:ToolTipEvent):void { var cTT : CustomToolTipGBA = new CustomToolTipGBA(); event.toolTip = cTT; } /** * Checks content of files to determine between * binary and text */ public static function isBinary(fileContent:String):Boolean { return (/[\x00-\x08\x0E-\x1F]/.test(fileContent)); } /** * Positions the toolTip */ public static function positionTip(event:ToolTipEvent):void { var tmpPoint : Point = getContentToGlobalXY( event.currentTarget as UIComponent ); event.toolTip.y = tmpPoint.y + 20; //event.toolTip.x = event.toolTip.x - 20; event.toolTip.x = ( event.currentTarget as UIComponent ).mouseX; } /** * Determines if a project is AIR type */ public static function isAIR(project:AS3ProjectVO):Boolean { // giving precedence to the as3proj value if (project.swfOutput.platform == SWFOutputVO.PLATFORM_AIR || project.swfOutput.platform == SWFOutputVO.PLATFORM_MOBILE) return true; if (project.targets.length > 0) { // considering that application descriptor file should exists in the same // root where application source file is exist var appFileName:String = project.targets[0].fileBridge.name.split(".")[0]; if (project.targets[0].fileBridge.parent.fileBridge.resolvePath("application.xml").fileBridge.exists) return true; else if (project.targets[0].fileBridge.parent.fileBridge.resolvePath(appFileName +"-app.xml").fileBridge.exists) return true; } if (project.isLibraryProject && project.testMovie == AS3ProjectVO.TEST_MOVIE_AIR) return true; return false; } /** * Determines if a project is mobile type */ public static function isMobile(project:AS3ProjectVO):Boolean { // giving precedence to the as3proj value if (project.swfOutput.platform == SWFOutputVO.PLATFORM_MOBILE) return true; if (project.isLibraryProject) { if (project.buildOptions.additional && project.buildOptions.additional.indexOf("airmobile") != -1) return true; } else if (project.sourceFolder && project.sourceFolder.fileBridge.exists) { var appFileName:String = project.targets[0].fileBridge.name.split(".")[0]; var descriptor:FileLocation = project.sourceFolder.fileBridge.resolvePath(appFileName +"-app.xml"); if (descriptor.fileBridge.exists) { var descriptorData:XML = XML(descriptor.fileBridge.read()); var tmpNameSearchString:String = ""; for each (var i:XML in descriptorData.children()) { tmpNameSearchString += i.localName()+" "; } return (tmpNameSearchString.indexOf("android") != -1) || (tmpNameSearchString.indexOf("iPhone") != -1); } } return false; } /** * Determines if a project is Lime type */ public static function isLime(project:HaxeProjectVO):Boolean { return project.haxeOutput.platform == HaxeOutputVO.PLATFORM_LIME; } /** * Getting a component co-ordinate * in respect of global stage */ public static function getContentToGlobalXY(dObject:UIComponent):Point { var thisHolderPoint : Point = UIComponent(dObject.owner).contentToGlobal( new Point( dObject.x, dObject.y ) ); var newP : Point = FlexGlobals.topLevelApplication.globalToContent( thisHolderPoint ); return newP; } public static function fixSlashes(path:String):String { if (!path) return null; //path = path.replace(/\//g, IDEModel.getInstance().fileCore.separator); if (ConstantsCoreVO.IS_MACOS) path = path.replace(/\\/g, model.fileCore.separator); return path; } public static function convertString(path:String):String { if (!ConstantsCoreVO.IS_MACOS) { path= path.split(" ").join("^ "); path= path.split("(").join("^("); path= path.split(")").join("^)"); path= path.split("&").join("^&"); } else { path= path.split(" ").join("\\ "); path= path.split("(").join("\\("); path= path.split(")").join("\\)"); path= path.split("&").join("\\&"); } return path; } public static function getUserDefinedSDK(searchByValue:String, searchByField:String):SDKReferenceVO { for each (var i:SDKReferenceVO in model.userSavedSDKs) { if (!ConstantsCoreVO.IS_MACOS) searchByValue = searchByValue.replace(/(\/)/g, "\\"); if (i[searchByField] == searchByValue) { return i; } } // if not found return null; } public static function sortCollection(collection:mx.collections.ArrayCollection, fields:Array):void { var sortFields:Array = []; fields.forEach(function(field:String, index:int, arr:Array):void { if (field != "") { sortFields.push(new SortField(field, true)); } }); collection.sort = new Sort(sortFields); collection.refresh(); } /** * Returns project based on its path */ public static function getProjectByPath(value:String):ProjectVO { for each (var project:ProjectVO in model.projects) { if (project.folderLocation.fileBridge.nativePath == value) { return project; } } return null; } /** * Returns project if given path match any project's path */ public static function getProjectByAnyFilePath(value:String):ProjectVO { for each (var project:ProjectVO in model.projects) { if (value.toLowerCase().indexOf(project.folderLocation.fileBridge.nativePath.toLowerCase()) != -1) { return project; } } return null; } /** * Returns project based on its name */ public static function getProjectByName(projectName:String):ProjectVO { for each (var project:ProjectVO in model.projects) { if (project.projectName == projectName) { return project; } } return null; } /** * Returns projectVO against fileWrapper */ public static function getProjectFromProjectFolder(projectFolder:FileWrapper):ProjectVO { if (!projectFolder) return null; for each (var p:ProjectVO in model.projects) { if (p.folderPath == projectFolder.projectReference.path) return p; } return null; } /** * Returns the probable SDK against a project */ public static function getCurrentSDK(pvo:AS3ProjectVO):FileLocation { return pvo.buildOptions.customSDK ? pvo.buildOptions.customSDK : model.defaultSDK; } /** * Returns path reference separated with * file separator */ public static function getPackageReferenceByProjectPath(classPaths:Vector.<FileLocation>, filePath:String=null, fileWrapper:FileWrapper=null, fileLocation:FileLocation=null, appendProjectNameAsPrefix:Boolean=true):String { var path:String = getPathStringByProjectPath(classPaths, filePath, fileWrapper, fileLocation, appendProjectNameAsPrefix); var pattern:RegExp = new RegExp(ConstantsCoreVO.IS_MACOS ? model.fileCore.separator : "\\" + model.fileCore.separator, "g"); path = path.replace(pattern, "."); return path; } /** * Returns dotted package references * against a project path */ public static function getPathStringByProjectPath(classPaths:Vector.<FileLocation>, filePath:String=null, fileWrapper:FileWrapper=null, fileLocation:FileLocation=null, appendProjectNameAsPrefix:Boolean=true):String { if (fileWrapper) { filePath = fileWrapper.nativePath; } else if (fileLocation) { filePath = fileLocation.fileBridge.nativePath; } var separator:String = model.fileCore.separator; var classPathCount:int = classPaths.length; var projectPathSplit:Array = null; for (var i:int = 0; i < classPathCount; i++) { var location:FileLocation = classPaths[i]; if (filePath.indexOf(location.fileBridge.nativePath) > -1) { projectPathSplit = location.fileBridge.nativePath.split(separator); filePath = filePath.replace(location.fileBridge.nativePath, ""); break; } } //var projectPathSplit:Array = projectPath.split(separator); //filePath = filePath.replace(projectPath, ""); if (appendProjectNameAsPrefix && projectPathSplit) { return projectPathSplit[projectPathSplit.length-1] + filePath.split(separator).join(model.fileCore.separator); } return filePath.split(separator).join(model.fileCore.separator); } /** * Fine a fileWrapper object * by a fileLocation object */ public static function findFileWrapperAgainstFileLocation(current:FileWrapper, target:FileLocation):FileWrapper { // Recurse-find filewrapper child for each (var child:FileWrapper in current.children) { if (target.fileBridge.nativePath == child.nativePath || target.fileBridge.nativePath.indexOf(child.nativePath + target.fileBridge.separator) == 0) { if (wrappersFoundThroughFindingAWrapper) wrappersFoundThroughFindingAWrapper.push(child); if (target.fileBridge.nativePath == child.nativePath) { return child; } if (child.children) { return findFileWrapperAgainstFileLocation(child, target); } } } return current; } /** * Find a fileWrapper object * against a project object */ public static function findFileWrapperAgainstProject(current:FileWrapper, project:ProjectVO, orInFileWrapper:FileWrapper=null):FileWrapper { var projectChildren:FileWrapper = project ? project.projectFolder : orInFileWrapper; // Probable termination if (!projectChildren) return current; // Recurse-find filewrapper child wrappersFoundThroughFindingAWrapper = new Vector.<FileWrapper>(); for each (var ownerWrapper:FileWrapper in projectChildren.children) { if (current.file.fileBridge.nativePath == ownerWrapper.nativePath || current.file.fileBridge.nativePath.indexOf(ownerWrapper.nativePath + current.file.fileBridge.separator) == 0) { wrappersFoundThroughFindingAWrapper.push(ownerWrapper); if (current.file.fileBridge.nativePath == ownerWrapper.nativePath) { return ownerWrapper; } if (ownerWrapper.children && ownerWrapper.children.length > 0) { var tmpMultiReturn:FileWrapper = findFileWrapperAgainstFileLocation(ownerWrapper, current.file); if (tmpMultiReturn != ownerWrapper) return tmpMultiReturn; } } } return current; } /** * Another way of finding fileWrapper * inside the project hierarchy */ public static function findFileWrapperInDepth(wrapper:FileWrapper, searchPath:String, project:ProjectVO=null):FileWrapper { var projectChildren:FileWrapper = project ? project.projectFolder : wrapper; for each (var child:FileWrapper in projectChildren.children) { if (searchPath == child.nativePath || searchPath.indexOf(child.nativePath + child.file.fileBridge.separator) == 0) { wrappersFoundThroughFindingAWrapper.push(child); if (searchPath == child.nativePath) { return child; } if (child.children && child.children.length > 0) return findFileWrapperInDepth(child, searchPath); } } return wrapper; } public static function findDominoFileWrapperInDepth(wrapper:FileWrapper, searchPath:String):FileWrapper { //Alert.show("searchPath:"+searchPath); for each (var child:FileWrapper in wrapper.children) { if (searchPath == child.nativePath || searchPath.indexOf(child.nativePath + child.file.fileBridge.separator) == 0) { wrappersFoundThroughFindingAWrapper.push(child); if (searchPath == child.nativePath) { return child; } if (child.children && child.children.length > 0) return findFileWrapperInDepth(child, searchPath); } if(child.children && child.children.length > 0){ if(endsWith(child.nativePath,"nsfs")|| endsWith(child.nativePath,"nsf-moonshine")||endsWith(child.nativePath,"odp")){ findDominoFileWrapperInDepth(child, searchPath); } // } } return wrapper; } public static function endsWith(str:String, ending:String):Boolean { var index:int = str.lastIndexOf(ending) return index > -1 && index == str.length - ending.length; } /** * Finding fileWrapper by its UDID */ public static function findFileWrapperIndexByID(wrapperToSearch:FileWrapper, searchIn:ICollectionView):int { var uidToSearch:String = UIDUtil.getUID(wrapperToSearch); for (var i:String in searchIn) { if (UIDUtil.getUID(searchIn[i]) == uidToSearch) return int(i); } return -1; } /** * Validate a given path compared with a project's * default source path and class path */ public static function validatePathAgainstSources(project:ProjectVO, wrapperToCompare:FileWrapper):Boolean { var pathToCompare:String = wrapperToCompare.nativePath + project.folderLocation.fileBridge.separator; // if no sourceFolder exists at all let add file anywhere if (!project["sourceFolder"]) { return true; } if (project.hasOwnProperty("classpaths") && project["classpaths"]) { var classPaths:Vector.<FileLocation> = project["classpaths"]; var hasPath:Boolean = classPaths.some(function(item:FileLocation, index:int, vector:Vector.<FileLocation>):Boolean{ return pathToCompare.indexOf(item.fileBridge.nativePath) != -1; }); if (hasPath) { return true; } } if (pathToCompare.indexOf(project["sourceFolder"].fileBridge.nativePath + project.folderLocation.fileBridge.separator) == -1) { return false; } return true; } /** * Checks if code-completion requisite FlexJS * available or not and returns */ public static function checkCodeCompletionFlexJSSDK():String { var hasFlex:Boolean = false; var FLEXJS_NAME_PREFIX:String = "Apache Flex (FlexJS) "; var path:String; var bestVersionValue:int = 0; for each (var i:SDKReferenceVO in model.userSavedSDKs) { var sdkName:String = i.name; if (sdkName.indexOf(FLEXJS_NAME_PREFIX) != -1) { var sdkVersion:String = sdkName.substr(FLEXJS_NAME_PREFIX.length, sdkName.indexOf(" ", FLEXJS_NAME_PREFIX.length) - FLEXJS_NAME_PREFIX.length); var versionParts:Array = sdkVersion.split("-")[0].split("."); var major:int = 0; var minor:int = 0; var revision:int = 0; if (versionParts.length >= 3) { major = parseInt(versionParts[0], 10); minor = parseInt(versionParts[1], 10); revision = parseInt(versionParts[2], 10); } //FlexJS 0.7.0 is the minimum version supported by the //language server. this may change in the future. if (major > 0 || minor >= 7) { //convert the three parts of the version number //into a single value to compare to other versions. var currentValue:int = major * 1e6 + minor * 1000 + revision; if(bestVersionValue < currentValue) { //pick the newest available version of FlexJS //to power the language server. hasFlex = true; path = i.path; bestVersionValue = currentValue; model.isCodeCompletionJavaPresent = true; } } } } return path; } /** * Returns BOOL if version is newer than * given version * * Basically requires for FlexJS version check where * 0.8.0 added new compiler argument which do not works * in older versions */ public static function isNewerVersionSDKThan(olderVersion:int, sdkPath:String):Boolean { if (!sdkPath) return false; // we need some extra work to determine if FlexJS version is lower than 0.8.0 // to ensure addition of new compiler argument '-compiler.targets' // which do not works with SDK < 0.8.0 var sdkFullName:String; for each (var project:SDKReferenceVO in model.userSavedSDKs) { if (sdkPath == project.path) { sdkFullName = project.name; break; } } if (!sdkFullName) return false; var flexJSPrefixName:String = "Apache Flex (FlexJS) "; var royalePrefixName:String = "Apache Royale "; var isValidSdk:Boolean = false; if (sdkFullName.indexOf(flexJSPrefixName) > -1) { isValidSdk = true; } else if (sdkFullName.indexOf(royalePrefixName) > -1) { return true; } if (isValidSdk) { var sdkNamePrefixLength:int = flexJSPrefixName.length; var sdkVersion:String = sdkFullName.substr(sdkNamePrefixLength, sdkFullName.indexOf(" ", sdkNamePrefixLength) - sdkNamePrefixLength); var versionParts:Array = sdkVersion.split("-")[0].split("."); var major:int = 0; var minor:int = 0; if (versionParts.length >= 3) { major = parseInt(versionParts[0], 10); minor = parseInt(versionParts[1], 10); } if (major > 0 || minor > olderVersion) { return true; } } return false; } /** * Sets requisite flags based on application file's tag * Required - AS3ProjectVO */ public static function checkIfRoyaleApplication(project:AS3ProjectVO):void { if (project.isRoyale) return; // probable termination if (project.targets.length == 0 || !project.targets[0].fileBridge.exists) return; var mainAppContent:String = project.targets[0].fileBridge.read() as String; var isBasicApp:Boolean = mainAppContent.indexOf("js:Application") > -1; var isMdlApp:Boolean = mainAppContent.indexOf("mdl:Application") > -1; var isJewelApp:Boolean = mainAppContent.indexOf("j:Application") > -1; var isMXApp:Boolean = mainAppContent.indexOf("mx:Application") > -1; var hasExpressNamespace:Boolean = mainAppContent.indexOf("library://ns.apache.org/royale/express") > -1; var hasRoyaleNamespace:Boolean = mainAppContent.indexOf("library://ns.apache.org/royale/basic") > -1 || hasExpressNamespace; var hasFlexJSNamespace:Boolean = mainAppContent.indexOf("library://ns.apache.org/flexjs/basic") > -1; var hasJewelNamespace:Boolean = mainAppContent.indexOf("library://ns.apache.org/royale/jewel") > -1; var hasMXNamespace:Boolean = mainAppContent.indexOf("library://ns.apache.org/royale/mx") > -1; var isRoyaleModule:Boolean = mainAppContent.indexOf("s:Module") > -1 || mainAppContent.indexOf("mx:Module") || mainAppContent.indexOf("js:UIModule"); var isRoyaleNamespace:Boolean = hasRoyaleNamespace || hasJewelNamespace || hasMXNamespace || hasExpressNamespace; if ((isBasicApp || isMdlApp || isJewelApp || isMXApp || isRoyaleModule) && (hasFlexJSNamespace || isRoyaleNamespace)) { // FlexJS Application project.isFlexJS = true; project.isRoyale = isRoyaleNamespace; // FlexJS MDL applicaiton project.isMDLFlexJS = isMdlApp; } else { project.isFlexJS = project.isMDLFlexJS = project.isRoyale = false; } } /** * Returns possible Java exeuctable in system */ public static function getExecutableJavaLocation():FileLocation { var executableFile:FileLocation; var separator:String = model.fileCore.separator; if (ConstantsCoreVO.IS_MACOS) { if (model.javaPathForTypeAhead && model.javaPathForTypeAhead.fileBridge.exists) { executableFile = new FileLocation(model.javaPathForTypeAhead.fileBridge.nativePath.concat(separator, "bin", separator, "java")); } else { executableFile = new FileLocation(separator.concat("usr", separator, "bin", separator, "java")); } } else { if (model.javaPathForTypeAhead && model.javaPathForTypeAhead.fileBridge.exists) { executableFile = new FileLocation(model.javaPathForTypeAhead.fileBridge.nativePath.concat(separator, "bin", separator, "javaw.exe")); if (!executableFile.fileBridge.exists) { executableFile = new FileLocation(model.javaPathForTypeAhead.fileBridge.nativePath.concat(separator, "javaw.exe")); } // in case of user setup by 'javaPath/bin' } else { var javaFolder:String = Capabilities.supports64BitProcesses ? "Program Files (x86)" : "Program Files"; var tmpJavaLocation:FileLocation = new FileLocation("C:".concat(separator, javaFolder, separator, "Java")); if (tmpJavaLocation.fileBridge.exists) { var javaFiles:Array = tmpJavaLocation.fileBridge.getDirectoryListing(); for each (var j:Object in javaFiles) { if (j.nativePath.indexOf("jre") != -1) { executableFile = new FileLocation(j.nativePath + separator + "bin" + separator + "javaw.exe"); break; } } } } } // finally return executableFile; } /** * Closes all the opened editors relative to a certain project path */ public static function closeAllRelativeEditors(projectOrWrapper:Object, isSkipSaveConfirmation:Boolean=false, completionHandler:Function=null, isCloseWhenDone:Boolean=true, exceptEditor:IContentWindow=null):void { var projectReferencePath:String; var editorsCount:int = model.editors.length; var hasChangesEditors:mx.collections.ArrayCollection = new mx.collections.ArrayCollection(); var editorsToClose:Array = []; // closes all opened file editor instances belongs to the deleted project // closing is IMPORTANT // if projectOrWrapper==null, it'll close all opened editors irrespective of // any particular project (example usage in 'Close All' option in File menu) if (projectOrWrapper) { if (projectOrWrapper is ProjectVO) { projectReferencePath = (projectOrWrapper as ProjectVO).folderLocation.fileBridge.nativePath; } else if (projectOrWrapper is FileWrapper && (projectOrWrapper as FileWrapper).projectReference) { projectReferencePath = (projectOrWrapper as FileWrapper).projectReference.path; } } for (var i:int = 0; i < editorsCount; i++) { if (model.editors[i] == exceptEditor) { continue; } if ((model.editors[i] is IFileContentWindow) && model.editors[i].currentFile && (!projectReferencePath || (model.editors[i].hasOwnProperty("projectPath") && model.editors[i].projectPath == projectReferencePath))) { var editor:IContentWindow = model.editors[i]; if (editor) { editorsToClose.push(editor); if (!isSkipSaveConfirmation && editor.isChanged()) { hasChangesEditors.addItem({file:editor, isSelected:true}); } } } else if (model.editors[i] is SettingsView && model.editors[i].associatedData && (!projectReferencePath || ProjectVO(model.editors[i].associatedData).folderLocation.fileBridge.nativePath == projectReferencePath)) { editorsToClose.push(model.editors[i]); if (!isSkipSaveConfirmation && model.editors[i].isChanged()) { hasChangesEditors.addItem({file:model.editors[i], isSelected:true}); } } else if (model.editors[i].hasOwnProperty("label") && ConstantsCoreVO.NON_CLOSEABLE_TABS.indexOf(model.editors[i].label) == -1) { if (!isSkipSaveConfirmation && model.editors[i].isChanged()) { hasChangesEditors.addItem({file:model.editors[i], isSelected:true}); } else if (projectOrWrapper == null && completionHandler == null && model.editors[i] != SplashScreen) { editorsToClose.push(model.editors[i]); } } } // check if the editors has any changes if (!isSkipSaveConfirmation && hasChangesEditors.length > 0) { var modListPopup:ModifiedFileListPopup = PopUpManager.createPopUp(FlexGlobals.topLevelApplication as DisplayObject, ModifiedFileListPopup, true) as ModifiedFileListPopup; modListPopup.collection = hasChangesEditors; modListPopup.addEventListener(CloseEvent.CLOSE, onModListClosed); PopUpManager.centerPopUp(modListPopup); } else { onModListClosed(null); } /* * @local */ function onModListClosed(event:CloseEvent):void { if (event) event.target.removeEventListener(CloseEvent.CLOSE, onModListClosed); // in case we just want save process to the unsaved editors // but not to close the editors when done // default - true if (isCloseWhenDone) { // close all the tabs without waiting for anything further for each (var j:IContentWindow in editorsToClose) { GlobalEventDispatcher.getInstance().dispatchEvent( new CloseTabEvent(CloseTabEvent.EVENT_CLOSE_TAB, j as DisplayObject, true) ); } } // notify the caller if (completionHandler != null) completionHandler(); } } /** * Parse all acceptable files in a given project */ public static function parseFilesList(flexCollection:IList=null, feathersCollection:feathers.data.ArrayCollection=null, project:ProjectVO=null, readableExtensions:Array=null, isSourceFolderOnly:Boolean=false):void { if (project) { if (isSourceFolderOnly && (project as AS3ProjectVO).sourceFolder) { // lets search for the probable existing fileWrapper object // instead of creating a new one - that could be expensive var sourceWrapper:FileWrapper = findFileWrapperAgainstFileLocation(project.projectFolder, (project as AS3ProjectVO).sourceFolder); if (sourceWrapper) { initiateFilesParsingByPath(sourceWrapper.file.fileBridge.nativePath); return; } } initiateFilesParsingByPath(project.projectFolder.nativePath); } else { for each (var i:ProjectVO in model.projects) { initiateFilesParsingByPath(i.projectFolder.nativePath); } } /* * @local */ function initiateFilesParsingByPath(value:String):void { var tmpFSP:FileSystemParser = new FileSystemParser(); tmpFSP.addEventListener(FileSystemParser.EVENT_PARSE_COMPLETED, onFilesListParseCompleted); tmpFSP.parseFilesPaths(value, "", readableExtensions); } function onFilesListParseCompleted(event:Event):void { event.currentTarget.removeEventListener(FileSystemParser.EVENT_PARSE_COMPLETED, onFilesListParseCompleted); var parsedFilesList:Array = (event.target as FileSystemParser).resultsArrayFormat; var fileCount:int = parsedFilesList.length; var separator:String = model.fileCore.separator; var tmpNameLabel:String; var tmpNameExtension:String; for each (var i:String in parsedFilesList) { //var resource:ResourceVO = ResourceVO(parsedFilesList.getItemAt(i)); //resources.add(resource); if (i != "") { tmpNameLabel = i.substr(i.lastIndexOf(separator)+1, i.length); tmpNameExtension = tmpNameLabel.substr(tmpNameLabel.lastIndexOf(".")+1, tmpNameLabel.length); if (!readableExtensions || (readableExtensions && isAcceptableResource(tmpNameExtension, readableExtensions))) { if (flexCollection) flexCollection.addItem({name:tmpNameLabel, extension: tmpNameExtension, resourcePath: i}); if (feathersCollection) feathersCollection.add({name:tmpNameLabel, extension: tmpNameExtension, resourcePath: i}); } } } } } /** * Returns menu options on current * recent opened projects */ public static function getRecentProjectsMenu():MenuItem { var openRecentLabel:String = ResourceManager.getInstance().getString('resources','OPEN_RECENT_PROJECTS'); var openProjectMenu:MenuItem = new MenuItem(openRecentLabel); openProjectMenu.parents = ["File", openRecentLabel]; openProjectMenu.items = new Vector.<MenuItem>(); for each (var i:ProjectReferenceVO in model.recentlyOpenedProjects) { if (i.name) { var menuItem:MenuItem = new MenuItem(i.name, null, null, "eventOpenRecentProject"); menuItem.data = i; openProjectMenu.items.push(menuItem); } } openProjectMenu.items.sort(menuComparer); return openProjectMenu; } /** * Returns menu options on current * recent opened projects */ public static function getRecentFilesMenu():MenuItem { var openRecentLabel:String = ResourceManager.getInstance().getString('resources','OPEN_RECENT_FILES'); var openFileMenu:MenuItem = new MenuItem(openRecentLabel); openFileMenu.parents = ["File", openRecentLabel]; openFileMenu.items = new Vector.<MenuItem>(); for each (var i:ProjectReferenceVO in model.recentlyOpenedFiles) { if (i.name) { var menuItem:MenuItem = new MenuItem(i.name, null, null, "eventOpenRecentFile"); menuItem.data = i; openFileMenu.items.push(menuItem); } } openFileMenu.items.sort(menuComparer); return openFileMenu; } /** * Set project menu type based on possible field */ public static function setProjectMenuType(value:ProjectVO):void { var currentMenuType:String; // the type-check ordering are important if (value is AS3ProjectVO) { if ((value as AS3ProjectVO).isFlexJS || (value as AS3ProjectVO).isRoyale || (value as AS3ProjectVO).isMDLFlexJS) { currentMenuType = ProjectMenuTypes.JS_ROYALE; } else if ((value as AS3ProjectVO).isLibraryProject) { currentMenuType = ProjectMenuTypes.LIBRARY_FLEX_AS; } else if ((value as AS3ProjectVO).isPrimeFacesVisualEditorProject) { currentMenuType = ProjectMenuTypes.VISUAL_EDITOR_PRIMEFACES; }else if ((value as AS3ProjectVO).isDominoVisualEditorProject) { currentMenuType = ProjectMenuTypes.VISUAL_EDITOR_DOMINO; } else if ((value as AS3ProjectVO).isVisualEditorProject) { currentMenuType = ProjectMenuTypes.VISUAL_EDITOR_FLEX; } else if ((value as AS3ProjectVO).isActionScriptOnly) { currentMenuType = ProjectMenuTypes.PURE_AS; } else { currentMenuType = ProjectMenuTypes.FLEX_AS; } } else if (value is GrailsProjectVO) { currentMenuType = ProjectMenuTypes.GRAILS; } else if (value is JavaProjectVO) { currentMenuType = ProjectMenuTypes.JAVA; } else if (value is HaxeProjectVO) { currentMenuType = ProjectMenuTypes.HAXE; } else if (value is OnDiskProjectVO) { currentMenuType = ProjectMenuTypes.ON_DISK; } if (!value.menuType) { value.menuType = currentMenuType; } else if (value.menuType && value.menuType.indexOf(currentMenuType) == -1) { value.menuType += ","+ currentMenuType; } // version-control check if (!value.hasVersionControlType) { // git check GlobalEventDispatcher.getInstance().dispatchEvent(new ProjectEvent(ProjectEvent.CHECK_GIT_PROJECT, value)); // svn check GlobalEventDispatcher.getInstance().dispatchEvent(new ProjectEvent(ProjectEvent.CHECK_SVN_PROJECT, value)); } } /** * Returns encoded string to run on Windows' shell */ public static function getEncodedForShell(value:String, forceOSXEncode:Boolean=false, forceWindowsEncode:Boolean=false):String { var tmpValue:String = ""; if (ConstantsCoreVO.IS_MACOS || forceOSXEncode) { // @note // in case of /bash one should send the value surrounded by $'' // i.e. $' +encodedValue+ ' tmpValue = value.replace(/(\\)/g, '\\\\"'); tmpValue = value.replace(/(")/g, '\\"'); tmpValue = value.replace(/(')/g, "\\'"); } else if (!ConstantsCoreVO.IS_MACOS || forceWindowsEncode) { for (var i:int; i < value.length; i++) { tmpValue += "^"+ value.charAt(i); } } return tmpValue; } /** * Reads through project configuration and * returns the project name */ public static function getProjectNameFromConfiguration(file:FileLocation=null, path:String=null):String { if (!file && !path) return null; if (!file && path) file = new FileLocation(path); var configurationXML:XML = new XML(file.fileBridge.read() as String); if (file.fileBridge.extension == "project") { // flash-builder projec return String(configurationXML.name); } else { // moonshine projects return file.fileBridge.nameWithoutExtension; } return null; } public static function getConsolePath():String { var separator:String = model.fileCore.separator; if (!ConstantsCoreVO.IS_MACOS) { // in windows return "c:".concat(separator, "Windows", separator, "System32", separator, "cmd.exe"); } else { // in mac return separator.concat("bin", separator, "bash"); } } public static function isMavenAvailable():Boolean { if (!model.mavenPath || model.mavenPath == "") { return false; } var component:Object = model.flexCore.getComponentByType(SDKTypes.MAVEN); if (component && component.pathValidation) { return model.fileCore.isPathExists(model.mavenPath + model.fileCore.separator + component.pathValidation); } return true; } public static function isGradleAvailable():Boolean { if (!model.gradlePath || model.gradlePath == "") { return false; } var component:Object = model.flexCore.getComponentByType(SDKTypes.GRADLE); if (component && component.pathValidation) { return model.fileCore.isPathExists(model.gradlePath + model.fileCore.separator + component.pathValidation); } return true; } public static function isGrailsAvailable():Boolean { if (!model.grailsPath || model.grailsPath == "") { return false; } var component:Object = model.flexCore.getComponentByType(SDKTypes.GRAILS); if (component && component.pathValidation) { return model.fileCore.isPathExists(model.grailsPath + model.fileCore.separator + component.pathValidation); } return true; } public static function isNodeAvailable():Boolean { if (!model.nodePath || model.nodePath == "") { return false; } var component:Object = model.flexCore.getComponentByType(SDKTypes.NODEJS); if (component && component.pathValidation) { if (model.fileCore.isPathExists(model.nodePath + model.fileCore.separator + component.pathValidation)) return true; else if (model.fileCore.isPathExists(model.nodePath + model.fileCore.separator + "node")) return true; return false; } return true; } public static function isHaxeAvailable():Boolean { if (!model.haxePath || model.haxePath == "") { return false; } //TODO: use path validation with SDKTypes var haxeName:String = ConstantsCoreVO.IS_MACOS ? "haxe" : "haxe.exe"; return model.fileCore.isPathExists(model.haxePath + model.fileCore.separator + haxeName); } public static function isNekoAvailable():Boolean { if (!model.nekoPath || model.nekoPath == "") { return false; } //TODO: use path validation with SDKTypes var nekoName:String = ConstantsCoreVO.IS_MACOS ? "neko" : "neko.exe"; return model.fileCore.isPathExists(model.nekoPath + model.fileCore.separator + nekoName); } public static function getMavenBinPath():String { if (!model.mavenPath || model.mavenPath == "") { return null; } var separator:String = model.fileCore.separator; var mavenLocation:FileLocation = new FileLocation(model.mavenPath); var mavenBin:String = "bin" + separator; if (mavenLocation.fileBridge.nativePath.lastIndexOf(model.fileCore.separator +"bin") > -1) { mavenBin = ""; } if (!mavenLocation.fileBridge.exists) { return null; } else if (!ConstantsCoreVO.IS_MACOS) { return mavenLocation.resolvePath(mavenBin + "mvn.cmd").fileBridge.nativePath; } else { return UtilsCore.convertString(mavenLocation.resolvePath(mavenBin + "mvn").fileBridge.nativePath); } return null; } public static function getGradleBinPath():String { if (!model.gradlePath || model.gradlePath == "") { return null; } var gradleLocation:FileLocation = new FileLocation(model.gradlePath); var gradleBin:String = "bin" + model.fileCore.separator; if (gradleLocation.fileBridge.nativePath.lastIndexOf(model.fileCore.separator +"bin") > -1) { gradleBin = ""; } if (!gradleLocation.fileBridge.exists) { return null; } else if (!ConstantsCoreVO.IS_MACOS) { return gradleLocation.resolvePath(gradleBin + "gradle.bat").fileBridge.nativePath; } else { return UtilsCore.convertString(gradleLocation.resolvePath(gradleBin + "gradle").fileBridge.nativePath); } return null; } public static function getGrailsBinPath():String { if (!model.grailsPath || model.grailsPath == "") { return null; } var separator:String = model.fileCore.separator; var grailsLocation:FileLocation = new FileLocation(model.grailsPath); var grailsBin:String = "bin" + separator; if (grailsLocation.fileBridge.nativePath.lastIndexOf(model.fileCore.separator +"bin") > -1) { grailsBin = ""; } if (!grailsLocation.fileBridge.exists) { return null; } else if (!ConstantsCoreVO.IS_MACOS) { return grailsLocation.resolvePath(grailsBin + "grails.bat").fileBridge.nativePath; } else { return UtilsCore.convertString(grailsLocation.resolvePath(grailsBin + "grails").fileBridge.nativePath); } return null; } public static function getNodeBinPath():String { if (!model.nodePath || model.nodePath == "") { return null; } var nodeLocation:FileLocation = new FileLocation(model.nodePath); if (!nodeLocation.fileBridge.exists) { return null; } else if (!ConstantsCoreVO.IS_MACOS) { return nodeLocation.resolvePath("node.exe").fileBridge.nativePath; } else { if (nodeLocation.resolvePath("node").fileBridge.exists) { return UtilsCore.convertString(nodeLocation.resolvePath("node").fileBridge.nativePath); } else if (nodeLocation.resolvePath("bin/node").fileBridge.exists) { return UtilsCore.convertString(nodeLocation.resolvePath("bin/node").fileBridge.nativePath); } } return null; } public static function isDefaultSDKAvailable():Boolean { if (!model.defaultSDK || !model.defaultSDK.fileBridge.exists) { return false; } return true; } public static function isJavaForTypeaheadAvailable():Boolean { if (!model.javaPathForTypeAhead || !model.javaPathForTypeAhead.fileBridge.exists) { return false; } var component:Object = model.flexCore.getComponentByType(SDKTypes.OPENJAVA); if (component && component.pathValidation) { return model.javaPathForTypeAhead.fileBridge.resolvePath(component.pathValidation).fileBridge.exists; } return true; } public static function isJava8Present():Boolean { if (model.java8Path && model.java8Path.fileBridge.exists) { return true; } return false; } public static function isAntAvailable():Boolean { if (!model.antHomePath || !model.antHomePath.fileBridge.exists) { return false; } var component:Object = model.flexCore.getComponentByType(SDKTypes.ANT); if (component && component.pathValidation) { return model.antHomePath.fileBridge.resolvePath(component.pathValidation).fileBridge.exists; } return true; } public static function isSVNPresent():Boolean { if (!model.svnPath || !model.fileCore.isPathExists(model.svnPath)) { return false; } var component:Object = model.flexCore.getComponentByType(SDKTypes.SVN); if (component && component.pathValidation) { return model.flexCore.isValidExecutableBy(SDKTypes.SVN, model.svnPath, component.pathValidation); } return true; } public static function isGitPresent():Boolean { if (!model.gitPath || !model.fileCore.isPathExists(model.gitPath)) { return false; } var component:Object = model.flexCore.getComponentByType(SDKTypes.GIT); if (component && component.pathValidation) { return model.flexCore.isValidExecutableBy(SDKTypes.GIT, model.gitPath, component.pathValidation); } return true; } public static function isVagrantAvailable():Boolean { if (!model.vagrantPath || !model.fileCore.isPathExists(model.vagrantPath)) { return false; } var component:Object = model.flexCore.getComponentByType(SDKTypes.VAGRANT); if (component && component.pathValidation) { return model.flexCore.isValidExecutableBy(SDKTypes.VAGRANT, model.vagrantPath, component.pathValidation); } return false; } public static function getVagrantBinPath():String { if (!model.vagrantPath || !model.fileCore.isPathExists(model.vagrantPath)) { return null; } var vagrantExecutable:String = ConstantsCoreVO.IS_MACOS ? "vagrant" : "vagrant.exe"; if (model.fileCore.isPathExists([model.vagrantPath, vagrantExecutable].join(model.fileCore.separator))) { return [model.vagrantPath, vagrantExecutable].join(model.fileCore.separator); } if (model.fileCore.isPathExists([model.vagrantPath, "bin", vagrantExecutable].join(model.fileCore.separator))) { return [model.vagrantPath, "bin", vagrantExecutable].join(model.fileCore.separator); } return null; } public static function isMacPortsAvailable():Boolean { if (!model.macportsPath || !model.fileCore.isPathExists(model.macportsPath)) { return false; } var component:Object = model.flexCore.getComponentByType(SDKTypes.MACPORTS); if (component && component.pathValidation) { return model.flexCore.isValidExecutableBy(SDKTypes.MACPORTS, model.macportsPath, component.pathValidation); } return false; } public static function getMacPortsBinPath():String { if (!model.macportsPath || !model.fileCore.isPathExists(model.macportsPath)) { return null; } var mportsExecutable:String = "port"; if (model.fileCore.isPathExists([model.macportsPath, mportsExecutable].join(model.fileCore.separator))) { return [model.macportsPath, mportsExecutable].join(model.fileCore.separator); } if (model.fileCore.isPathExists([model.macportsPath, "bin", mportsExecutable].join(model.fileCore.separator))) { return [model.macportsPath, "bin", mportsExecutable].join(model.fileCore.separator); } return null; } public static function isNotesDominoAvailable():Boolean { if (!model.notesPath || !model.fileCore.isPathExists(model.notesPath)) { return false; } var component:Object = model.flexCore.getComponentByType(SDKTypes.NOTES); if (component && component.pathValidation) { return model.fileCore.resolvePath(model.notesPath +"/"+ component.pathValidation).fileBridge.exists; //return model.flexCore.isValidExecutableBy(SDKTypes.NOTES, model.notesPath, component.pathValidation); } return true; } public static function getLineBreakEncoding():String { return (ConstantsCoreVO.IS_MACOS ? "\n" : "\r\n"); } public static function getVisualEditorSourceFile(fw:FileWrapper):FileLocation { var as3ProjectVO:AS3ProjectVO = UtilsCore.getProjectFromProjectFolder(fw) as AS3ProjectVO; if (as3ProjectVO && as3ProjectVO.isVisualEditorProject) { var veSourcePathFile:String = fw.file.fileBridge.nativePath .replace(as3ProjectVO.sourceFolder.fileBridge.nativePath, as3ProjectVO.visualEditorSourceFolder.fileBridge.nativePath) .replace(/.mxml$|.xhtml$|.form/, ".xml"); return new FileLocation(veSourcePathFile); } return null; } private static function parseChildrens(value:FileWrapper, collection:IList, readableExtensions:Array=null):void { if (!value) return; var extension:String = value.file.fileBridge.extension; if (!value.file.fileBridge.isDirectory && (extension != null) && isAcceptableResource(extension)) { collection.addItem(new ResourceVO(value.file.fileBridge.name, value)); return; } if ((value.children is Array) && (value.children as Array).length > 0) { for each (var c:FileWrapper in value.children) { extension = c.file.fileBridge.extension; if (!c.file.fileBridge.isDirectory && (extension != null) && isAcceptableResource(extension, readableExtensions)) { collection.addItem(new ResourceVO(c.file.fileBridge.name, c)); } else if (c.file.fileBridge.isDirectory) { parseChildrens(c, collection, readableExtensions); } } } } private static function isAcceptableResource(extension:String, readableExtensions:Array=null):Boolean { readableExtensions ||= ConstantsCoreVO.READABLE_FILES; return readableExtensions.some( function isValidExtension(item:Object, index:int, arr:Array):Boolean { return item == extension; }); } private static function menuComparer(itemA:MenuItem, itemB:MenuItem):Number { if (itemA.label.toLowerCase() < itemB.label.toLowerCase()) return -1; else if (itemA.label.toLowerCase() > itemB.label.toLowerCase()) return 1; else return 0; } } }
package org.w3c.css.sac { // http://www.w3.org/Style/CSS/SAC/doc/org/w3c/css/sac/NegativeCondition.html /** * @see ConditionTypes#SAC_NEGATIVE_CONDITION * @copy ConditionTypes#SAC_NEGATIVE_CONDITION */ public interface INegativeCondition extends ICondition { /** * Returns the condition. */ function get condition():ICondition; } }
package { import flash.display.BitmapData; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.Event; import flash.events.StatusEvent; import flash.media.Camera; import flash.media.Video; import flash.utils.setTimeout; public class FileAPI_flash_camera extends Sprite { private var video:Video; private var camera:Camera; public function FileAPI_flash_camera() { if (stage) init(); else addEventListener(Event.ADDED_TO_STAGE, init); } public function init(e:Event = null):void { if(e) removeEventListener(Event.ADDED_TO_STAGE, init); stage.scaleMode = StageScaleMode.SHOW_ALL; stage.align = StageAlign.TOP_LEFT; // init camera camera = Camera.getCamera(); if (camera != null) { camera.addEventListener(StatusEvent.STATUS, onCameraStatus); // we need to show settings dialog, so we attach camera to a video video = new Video(); video.attachCamera(camera); if (!camera.muted) { onCameraStatus(new StatusEvent(StatusEvent.STATUS, false, false, 'Camera.Unmuted')); } else { setTimeout(function ():void { if (securityPanelIsClosed()) { onCameraStatus(new StatusEvent(StatusEvent.STATUS, false, false, 'Camera.Muted')); } }, 1000); } } else { // callback with error } } public function toggleCamera(on:Boolean):void { trace('toggleCamera',on); if (on) { if (video != null) { // turn current video off toggleCamera(false); } trace('stage width',stage.stageWidth,'stage w',stage.width,'camera width',camera.width); var w:Number = stage.stageWidth; var h:Number = stage.stageHeight; //stage.stageWidth * camera.height / camera.width; camera.setMode(w, h, camera.fps); video = new Video(w, h); video.attachCamera(camera); video.addEventListener(Event.ADDED_TO_STAGE, function(event:Event):void { trace('video addedToStage'); // now the camera is visible dispatchEvent(new Event('Camera.On')); }); addChildAt(video,0); } else { if(video) removeChild(video); video = null; } } public function shot():BitmapData { if (video) { trace('click!', video.width, stage.stageWidth); try{ var bm:BitmapData = new BitmapData(video.width,video.height); bm.draw(video); return bm; } catch(error:Error) { trace('error',error.toString() ); return null; } } return null; } private function onCameraStatus(event:StatusEvent):void { trace('status event:',event.toString() ); video = null; // turn off video // redispatch dispatchEvent(event.clone()); } /** * This code checks one time if the security panel is closed. * When you open the security panel, you should run this test * repeatedly with a timer (every 500ms seems to work well). * If the security panel is closed, you can then clean up your timers */ private function securityPanelIsClosed():Boolean { // Why not just wait for an event from the SettingsPanel to know that it's closed? Because there isn't one. // See http://bugs.adobe.com/jira/browse/FP-41 var closed:Boolean = true; var hack:BitmapData = new BitmapData(1,1); try { // Trying to capture the stage triggers a Security error when the settings dialog box is open. hack.draw(stage); } catch (error:Error) { closed = false; } hack.dispose(); hack = null; return (closed); } } }