CombinedText stringlengths 4 3.42M |
|---|
/*
* Copyright (c) 2014-2017 Object Builder <https://github.com/ottools/ObjectBuilder>
*
* 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 otlib.things
{
import nail.errors.AbstractClassError;
/**
* The ThingTypeFlags6 class defines the valid constant values for the client versions 10.10+
*/
public final class ThingTypeFlags6
{
//--------------------------------------------------------------------------
// CONSTRUCTOR
//--------------------------------------------------------------------------
public function ThingTypeFlags6()
{
throw new AbstractClassError(ThingTypeFlags6);
}
//--------------------------------------------------------------------------
// STATIC
//--------------------------------------------------------------------------
public static const GROUND:uint = 0x00;
public static const GROUND_BORDER:uint = 0x01;
public static const ON_BOTTOM:uint = 0x02;
public static const ON_TOP:uint = 0x03;
public static const CONTAINER:uint = 0x04;
public static const STACKABLE:uint = 0x05;
public static const FORCE_USE:uint = 0x06;
public static const MULTI_USE:uint = 0x07;
public static const WRITABLE:uint = 0x08;
public static const WRITABLE_ONCE:uint = 0x09;
public static const FLUID_CONTAINER:uint = 0x0A;
public static const FLUID:uint = 0x0B;
public static const UNPASSABLE:uint = 0x0C;
public static const UNMOVEABLE:uint = 0x0D;
public static const BLOCK_MISSILE:uint = 0x0E;
public static const BLOCK_PATHFIND:uint = 0x0F;
public static const NO_MOVE_ANIMATION:uint = 0x10;
public static const PICKUPABLE:uint = 0x11;
public static const HANGABLE:uint = 0x12;
public static const VERTICAL:uint = 0x13;
public static const HORIZONTAL:uint = 0x14;
public static const ROTATABLE:uint = 0x15;
public static const HAS_LIGHT:uint = 0x16;
public static const DONT_HIDE:uint = 0x17;
public static const TRANSLUCENT:uint = 0x18;
public static const HAS_OFFSET:uint = 0x19;
public static const HAS_ELEVATION:uint = 0x1A;
public static const LYING_OBJECT:uint = 0x1B;
public static const ANIMATE_ALWAYS:uint = 0x1C;
public static const MINI_MAP:uint = 0x1D;
public static const LENS_HELP:uint = 0x1E;
public static const FULL_GROUND:uint = 0x1F;
public static const IGNORE_LOOK:uint = 0x20;
public static const CLOTH:uint = 0x21;
public static const MARKET_ITEM:uint = 0x22;
public static const DEFAULT_ACTION:uint = 0x23;
public static const USABLE:uint = 0xFE;
}
}
|
/*
* The MIT License
*
* Copyright (c) 2008
* United Nations Office at Geneva
* Center for Advanced Visual Analytics
* http://cava.unog.ch
*
* 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.un.cava.birdeye.ravis.components.renderers.nodes {
import flash.events.Event;
import mx.containers.Box;
import mx.core.UIComponent;
import org.un.cava.birdeye.ravis.graphLayout.visual.IVisualNode;
import org.un.cava.birdeye.ravis.utils.events.VGraphEvent;
/**
* This is a simple renderer, similar to the filtered circle
* but renders a rectangle which is rotated according to the
* angle of the corresponding visualNode
* */
public class RotatedRectNodeRenderer extends EffectBaseNodeRenderer {
private var _rc:UIComponent;
public var boxWidth:Number = 20;
/**
* Default constructor
* */
public function RotatedRectNodeRenderer() {
super();
this.addEventListener(VGraphEvent.VNODE_UPDATED,updateRotation);
}
/**
* @inheritDoc
* */
override protected function initComponent(e:Event):void {
/* initialize the upper part of the renderer */
initTopPart();
/* add a primitive rectangle
* as well the XML should be checked before */
/*
rc = RendererIconFactory.createIcon("primitive::rectangle",
this.data.data.@nodeSize,
this.data.data.@nodeColor);
*/
_rc = new Box;
_rc.width = this.data.data.@nodeSize;
_rc.height = boxWidth;
_rc.setStyle("backgroundColor",this.data.data.@nodeColor);
_rc.setStyle("borderStyle","solid");
_rc.toolTip = this.data.data.@name; // needs check
/* rotate. Note that this will only rotate on init
* i.e. all will be triggered only on creation complete
* this was the same in the original vgExplorer
* maybe it was not intended */
if(this.data is IVisualNode) {
_rc.rotation = (this.data as IVisualNode).orientAngle;
}
this.addChild(_rc);
/* now add the filters to the circle */
reffects.addDSFilters(_rc);
/* now the link button */
initLinkButton();
}
/**
* Event handler to turn the box if the orientation
* in a node changes *
* */
public function updateRotation(e:Event):void {
if(_rc != null) {
//trace("updating rotation");
if(this.data is IVisualNode) {
_rc.rotation = (this.data as IVisualNode).orientAngle;
}
}
}
}
} |
/* 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 = "15.5.4.3-1";
// var VERSION = "ECMA_1";
// var TITLE = "String.prototype.valueOf";
var testcases = getTestCases();
function getTestCases() {
var array = new Array();
var item = 0;
array[item++] = Assert.expectEq( "String.prototype.valueOf.length", 0, String.prototype.valueOf.length );
array[item++] = Assert.expectEq( "String.prototype.valueOf()", "", String.prototype.valueOf() );
array[item++] = Assert.expectEq( "(new String()).valueOf()", "", (new String()).valueOf() );
array[item++] = Assert.expectEq( "(new String(\"\")).valueOf()", "", (new String("")).valueOf() );
array[item++] = Assert.expectEq( "(new String( String() )).valueOf()","", (new String(String())).valueOf() );
array[item++] = Assert.expectEq( "(new String( \"h e l l o\" )).valueOf()", "h e l l o", (new String("h e l l o")).valueOf() );
array[item++] = Assert.expectEq( "(new String( 0 )).valueOf()", "0", (new String(0)).valueOf() );
return ( array );
}
|
/**
* Hex
*
* Utility class to convert Hex strings to ByteArray or String types.
* Copyright (c) 2007 Henri Torgemane
*
* See LICENSE.txt for full license information.
*/
/*[IF-FLASH]*/package com.hurlant.util
{
import flash.utils.ByteArray;
public class Hex
{
/**
* Support straight hex, or colon-laced hex.
* (that means 23:03:0e:f0, but *NOT* 23:3:e:f0)
* Whitespace characters are ignored.
*/
public static function toArray(hex:String):ByteArray {
hex = hex.replace(/\s|:/gm,'');
var a:ByteArray = new ByteArray;
if ((hex.length&1)==1) hex="0"+hex;
for (var i:uint=0;i<hex.length;i+=2) {
a[i/2] = parseInt(hex.substr(i,2),16);
}
return a;
}
public static function fromArray(array:ByteArray, colons:Boolean=false):String {
var s:String = "";
for (var i:uint=0;i<array.length;i++) {
s+=("0"+array[i].toString(16)).substr(-2,2);
if (colons) {
if (i<array.length-1) s+=":";
}
}
return s;
}
/**
*
* @param hex
* @return a UTF-8 string decoded from hex
*
*/
public static function toString(hex:String):String {
var a:ByteArray = toArray(hex);
return a.readUTFBytes(a.length);
}
/**
*
* @param str
* @return a hex string encoded from the UTF-8 string str
*
*/
public static function fromString(str:String, colons:Boolean=false):String {
var a:ByteArray = new ByteArray;
a.writeUTFBytes(str);
return fromArray(a, colons);
}
}
} |
////////////////////////////////////////////////////////////////////////////////
//
// 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.crux.beads
{
import org.apache.royale.core.ApplicationBase;
import org.apache.royale.core.IBead;
import org.apache.royale.core.IStrand;
import org.apache.royale.crux.ICrux;
import org.apache.royale.crux.utils.buildCrux;
import org.apache.royale.events.IEventDispatcher;
/**
* CruxHelper generate a Crux for an Application or a Module
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.9.8
*/
public class CruxHelper implements IBead
{
public function CruxHelper() {
super();
}
private var host:IEventDispatcher;
/**
* @copy org.apache.royale.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.9.8
*
* @royaleignorecoercion org.apache.royale.core.ElementWrapper
* @royaleignorecoercion org.apache.royale.events.IEventDispatcher
*/
public function set strand(value:IStrand):void
{
host = value as IEventDispatcher;
if(host is ApplicationBase)
{
var jsStageEvents:JSStageEvents = new JSStageEvents();
jsStageEvents.packageExclusionFilter = _packageExclusionFilter;
value.addBead(jsStageEvents);
}
crux = buildCrux(host, beanProviders, eventPackages, viewPackages);
if(parentCrux)
crux.parentCrux = parentCrux;
value.addBead(crux);
}
private var _crux:ICrux;
/**
* The generated crux instance
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.9.8
*/
public function get crux():ICrux
{
return _crux;
}
public function set crux(value:ICrux):void
{
_crux = value;
}
private var _beanProviders:Array;
/**
* The Array of bean providers
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.9.8
*/
public function get beanProviders():Array
{
return _beanProviders;
}
public function set beanProviders(value:*):void
{
_beanProviders = value;
}
private var _eventPackages:Array;
/**
* The Array of event packages
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.9.8
*/
public function get eventPackages():Array
{
return _eventPackages;
}
public function set eventPackages(value:*):void
{
_eventPackages = value;
}
private var _viewPackages:Array;
/**
* The Array of view packages
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.9.8
*/
public function get viewPackages():Array
{
return _viewPackages;
}
public function set viewPackages(value:*):void
{
_viewPackages = value;
}
private var _packageExclusionFilter:String = "_default_";
/**
* The package exclusion filter to use in JSStageEvents
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.9.8
*/
public function get packageExclusionFilter():String
{
return _packageExclusionFilter;
}
public function set packageExclusionFilter(value:String):void
{
_packageExclusionFilter = value;
}
private var _parentCrux:ICrux;
/**
* The parent crux
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.9.8
*/
public function get parentCrux():ICrux
{
return _parentCrux;
}
public function set parentCrux(value:ICrux):void
{
_parentCrux = 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.charts
{
// import mx.binding.BindingManager;
import mx.charts.chartClasses.ChartBase;
import mx.charts.events.LegendMouseEvent;
import mx.collections.ArrayCollection;
import mx.collections.ICollectionView;
import mx.collections.IList;
import mx.collections.ListCollectionView;
// import mx.containers.utilityClasses.PostScaleAdapter;
// import mx.core.ComponentDescriptor;
import mx.core.ContainerCreationPolicy;
// import mx.core.ContainerGlobals;
import mx.core.EdgeMetrics;
import mx.core.FlexGlobals;
// import mx.core.FlexSprite;
import mx.core.FlexVersion;
import mx.core.IChildList;
// import mx.core.IContainer;
// import mx.core.IDeferredInstantiationUIComponent;
import mx.core.IFlexDisplayObject;
import mx.core.IFlexModuleFactory;
import mx.core.IInvalidating;
// import mx.core.ILayoutDirectionElement;
// import mx.core.IRectangularBorder;
// import mx.core.IRepeater;
// import mx.core.IRepeaterClient;
import mx.core.IUIComponent;
import mx.core.IUITextField;
import mx.core.IVisualElement;
import mx.core.Keyboard;
import mx.core.ScrollPolicy;
import mx.core.UIComponent;
import mx.core.mx_internal;
import mx.display.Graphics;
// import mx.events.ChildExistenceChangedEvent;
import mx.events.FlexEvent;
import mx.events.IndexChangedEvent;
// import mx.geom.RoundedRectangle;
import mx.managers.ILayoutManagerClient;
import mx.managers.ISystemManager;
import mx.styles.CSSStyleDeclaration;
import mx.styles.ISimpleStyleClient;
import mx.styles.IStyleClient;
// import mx.styles.StyleProtoChain;
import org.apache.royale.core.IUIBase;
import org.apache.royale.events.Event;
import mx.events.KeyboardEvent;
import org.apache.royale.events.MouseEvent;
import org.apache.royale.geom.Point;
import org.apache.royale.geom.Rectangle;
import org.apache.royale.reflection.getDefinitionByName;
use namespace mx_internal;
//--------------------------------------
// Events
//--------------------------------------
/**
* Dispatched when the user clicks on a LegendItem in the Legend control.
*
* @eventType mx.charts.events.LegendMouseEvent.ITEM_CLICK
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="itemClick", type="mx.charts.events.LegendMouseEvent")]
/**
* Dispatched when the user presses the mouse button
* while over a LegendItem in the Legend control.
*
* @eventType mx.charts.events.LegendMouseEvent.ITEM_MOUSE_DOWN
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="itemMouseDown", type="mx.charts.events.LegendMouseEvent")]
/**
* Dispatched when the user moves the mouse off of a LegendItem in the Legend.
*
* @eventType mx.charts.events.LegendMouseEvent.ITEM_MOUSE_OUT
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="itemMouseOut", type="mx.charts.events.LegendMouseEvent")]
/**
* Dispatched when the user moves the mouse over a LegendItem in the Legend control.
*
* @eventType mx.charts.events.LegendMouseEvent.ITEM_MOUSE_OVER
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="itemMouseOver", type="mx.charts.events.LegendMouseEvent")]
/**
* Dispatched when the user releases the mouse button
* while over a LegendItem in the Legend.
*
* @eventType mx.charts.events.LegendMouseEvent.ITEM_MOUSE_UP
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="itemMouseUp", type="mx.charts.events.LegendMouseEvent")]
/**
* Dispatched after a child has been added to a legend.
*
* <p>The childAdd event is dispatched when the <code>addChild()</code>
* or <code>addChildAt()</code> method is called.
* When a container is first created, the <code>addChild()</code>
* method is automatically called for each child component declared
* in the MXML file.
* The <code>addChildAt()</code> method is automatically called
* whenever a Repeater object adds or removes child objects.
* The application developer may also manually call these
* methods to add new children.</p>
*
* <p>At the time when this event is sent, the child object has been
* initialized, but its width and height have not yet been calculated,
* and the child has not been drawn on the screen.
* If you want to be notified when the child has been fully initialized
* and rendered, then register as a listener for the child's
* <code>creationComplete</code> event.</p>
*
* @eventType mx.events.ChildExistenceChangedEvent.CHILD_ADD
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="childAdd", type="mx.events.ChildExistenceChangedEvent")]
/**
* Dispatched after the index (among the legend children)
* of a legend child changes.
* This event is only dispatched for the child specified as the argument to
* the <code>setChildIndex()</code> method; it is not dispatched
* for any other child whose index changes as a side effect of the call
* to the <code>setChildIndex()</code> method.
*
* <p>The child's index is changed when the
* <code>setChildIndex()</code> method is called.</p>
*
* @eventType mx.events.IndexChangedEvent.CHILD_INDEX_CHANGE
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="childIndexChange", type="mx.events.IndexChangedEvent")]
/**
* Dispatched before a child of a legend is removed.
*
* <p>This event is delivered when any of the following methods is called:
* <code>removeChild()</code>, <code>removeChildAt()</code>,
* or <code>removeAllChildren()</code>.</p>
*
* @eventType mx.events.ChildExistenceChangedEvent.CHILD_REMOVE
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="childRemove", type="mx.events.ChildExistenceChangedEvent")]
/**
* Dispatched when the <code>data</code> property changes.
*
* <p>When a legend is used as a renderer in a List or other components,
* the <code>data</code> property is used pass to the legend
* the data to display.</p>
*
* @eventType mx.events.FlexEvent.DATA_CHANGE
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="dataChange", type="mx.events.FlexEvent")]
//--------------------------------------
// Styles
//--------------------------------------
// include "../styles/metadata/BorderStyles.as"
// include "../styles/metadata/PaddingStyles.as"
// include "../styles/metadata/TextStyles.as"
// include "../styles/metadata/GapStyles.as"
//--------------------------------------
// Styles
//--------------------------------------
/**
* Accent color used by component skins. The default button skin uses this color
* to tint the background. Slider track highlighting uses this color.
*
* @default #0099FF
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
[Style(name="accentColor", type="uint", format="Color", inherit="yes", theme="spark")]
/**
* If a background image is specified, this style specifies
* whether it is fixed with regard to the viewport (<code>"fixed"</code>)
* or scrolls along with the content (<code>"scroll"</code>).
*
* @default "scroll"
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Style(name="backgroundAttachment", type="String", inherit="no")]
/**
* Alpha level of the color defined by the <code>backgroundColor</code>
* property, of the image or SWF file defined by the <code>backgroundImage</code>
* style.
* Valid values range from 0.0 to 1.0. For most controls, the default value is 1.0,
* but for ToolTip controls, the default value is 0.95 and for Alert controls, the default value is 0.9.
*
* @default 1.0
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Style(name="backgroundAlpha", type="Number", inherit="no", theme="halo, spark")]
/**
* Background color of a component.
* You can have both a <code>backgroundColor</code> and a
* <code>backgroundImage</code> set.
* Some components do not have a background.
* The DataGrid control ignores this style.
* The default value is <code>undefined</code>, which means it is not set.
* If both this style and the <code>backgroundImage</code> style
* are <code>undefined</code>, the component has a transparent background.
*
* <p>For the Application container, this style specifies the background color
* while the application loads, and a background gradient while it is running.
* Flex calculates the gradient pattern between a color slightly darker than
* the specified color, and a color slightly lighter than the specified color.</p>
*
* <p>The default skins of most Flex controls are partially transparent. As a result, the background color of
* a container partially "bleeds through" to controls that are in that container. You can avoid this by setting the
* alpha values of the control's <code>fillAlphas</code> property to 1, as the following example shows:
* <pre>
* <mx:<i>Container</i> backgroundColor="0x66CC66"/>
* <mx:<i>ControlName</i> ... fillAlphas="[1,1]"/>
* </mx:<i>Container</i>></pre>
* </p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Style(name="backgroundColor", type="uint", format="Color", inherit="no", theme="halo, spark")]
/**
* Determines the color of a ProgressBar.
* A ProgressBar is filled with a vertical gradient between this color
* and a brighter color computed from it.
* This style has no effect on other components, but can be set on a container
* to control the appearance of all progress bars found within.
* The default value is <code>undefined</code>, which means it is not set.
* In this case, the <code>themeColor</code> style property is used.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Style(name="barColor", type="uint", format="Color", inherit="yes", theme="halo")]
/**
* The alpha of the content background for this component.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
[Style(name="contentBackgroundAlpha", type="Number", inherit="yes", theme="spark")]
/**
* Color of the content area of the component.
*
* @default 0xFFFFFF
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
[Style(name="contentBackgroundColor", type="uint", format="Color", inherit="yes", theme="spark")]
/**
* Radius of component corners.
* The default value depends on the component class;
* if not overridden for the class, the default value
* is 0.
* The default value for ApplicationControlBar is 5.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Style(name="cornerRadius", type="Number", format="Length", inherit="no", theme="halo, spark")]
/**
* The alpha value for the overlay that is placed on top of the
* container when it is disabled.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Style(name="disabledOverlayAlpha", type="Number", inherit="no")]
/**
* Color of focus ring when the component is in focus
*
* @default 0x70B2EE
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
[Style(name="focusColor", type="uint", format="Color", inherit="yes", theme="spark")]
/**
* Horizontal alignment of each child inside its tile cell.
* Possible values are <code>"left"</code>, <code>"center"</code>, and
* <code>"right"</code>.
* If the value is <code>"left"</code>, the left edge of each child
* is at the left edge of its cell.
* If the value is <code>"center"</code>, each child is centered horizontally
* within its cell.
* If the value is <code>"right"</code>, the right edge of each child
* is at the right edge of its cell.
*
* @default "left"
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Style(name="horizontalAlign", type="String", enumeration="left,center,right", inherit="no")]
/**
* Specifies the label placement of the legend element.
* Valid values are <code>"top"</code>, <code>"bottom"</code>,
* <code>"right"</code>, and <code>"left"</code>.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Style(name="labelPlacement", type="String", enumeration="top,bottom,right,left", inherit="yes")]
/**
* Specifies the height of the legend element.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Style(name="markerHeight", type="Number", format="Length", inherit="yes")]
/**
* Specifies the width of the legend element.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Style(name="markerWidth", type="Number", format="Length", inherit="yes")]
/**
* Number of pixels between the legend's bottom border
* and the bottom of its content area.
*
* @default 0
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Style(name="paddingBottom", type="Number", format="Length", inherit="no")]
/**
* Number of pixels between the legend's top border
* and the top of its content area.
*
* @default 0
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Style(name="paddingTop", type="Number", format="Length", inherit="no")]
/**
* Color of any symbol of a component. Examples include the check mark of a CheckBox or
* the arrow of a ScrollBar button.
*
* @default 0x000000
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
[Style(name="symbolColor", type="uint", format="Color", inherit="yes", theme="spark")]
/**
* Specifies the line stroke for the legend element.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Style(name="stroke", type="Object", inherit="no")]
/**
* Vertical alignment of each child inside its tile cell.
* Possible values are <code>"top"</code>, <code>"middle"</code>, and
* <code>"bottom"</code>.
* If the value is <code>"top"</code>, the top edge of each child
* is at the top edge of its cell.
* If the value is <code>"middle"</code>, each child is centered vertically
* within its cell.
* If the value is <code>"bottom"</code>, the bottom edge of each child
* is at the bottom edge of its cell.
*
* @default "top"
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Style(name="verticalAlign", type="String", enumeration="bottom,middle,top", inherit="no")]
// [ResourceBundle("core")]
//--------------------------------------
// Excluded APIs
//--------------------------------------
[Exclude(name="defaultButton", kind="property")]
[Exclude(name="horizontalScrollPolicy", kind="property")]
[Exclude(name="icon", kind="property")]
[Exclude(name="label", kind="property")]
[Exclude(name="tileHeight", kind="property")]
[Exclude(name="tileWidth", kind="property")]
[Exclude(name="verticalScrollPolicy", kind="property")]
[Exclude(name="focusIn", kind="event")]
[Exclude(name="focusOut", kind="event")]
[Exclude(name="focusBlendMode", kind="style")]
[Exclude(name="focusSkin", kind="style")]
[Exclude(name="focusThickness", kind="style")]
[Exclude(name="focusInEffect", kind="effect")]
[Exclude(name="focusOutEffect", kind="effect")]
//--------------------------------------
// Other metadata
//--------------------------------------
[DefaultBindingProperty(destination="dataProvider")]
[DefaultTriggerEvent("itemClick")]
// [IconFile("Legend.png")]
/**
* The Legend control adds a legend to your charts,
* where the legend displays the label for each data series in the chart
* and a key showing the chart element for the series.
*
* <p>You can initialize a Legend control by binding a chart control
* identifier to the Legend control's <code>dataProvider</code> property,
* or you can define an Array of LegendItem objects.</p>
*
* @mxml
*
* <p>The <code><mx:Legend></code> tag inherits all the properties
* of its parent classes and adds the following properties:</p>
*
* <pre>
* <mx:Legend
* <strong>Properties</strong>
* autoLayout="true|false"
* clipContent="true|false"
* creationIndex="undefined"
* creationPolicy="auto|all|queued|none"
* dataProvider="<i>No default</i>"
* direction="horizontal|vertical"
* horizontalScrollPosition="0"
* legendItemClass="<i>No default</i>"
* verticalScrollPosition="0"
*
* <strong>Styles</strong>
* backgroundAlpha="1.0"
* backgroundAttachment="scroll"
* backgroundColor="undefined"
* backgroundDisabledColor="undefined"
* backgroundImage="undefined"
* backgroundSize="auto"
* barColor="undefined"
* borderColor="0xAAB3B3"
* borderSides="left top right bottom"
* borderSkin="mx.skins.halo.HaloBorder"
* borderStyle="inset|none|solid|outset"
* borderThickness="1"
* color="0x0B333C"
* cornerRadius="0"
* disabledColor="0xAAB3B3"
* disbledOverlayAlpha="undefined"
* dropShadowColor="0x000000"
* dropShadowEnabled="false"
* fontAntiAliasType="advanced"
* fontfamily="Verdana"
* fontGridFitType="pixel"
* fontSharpness="0""
* fontSize="10"
* fontStyle="normal"
* fontThickness="0"
* fontWeight="normal"
* horizontalAlign="left|center|right"
* horizontalGap="<i>8</i>"
* labelPlacement="right|left|top|bottom"
* markerHeight="15"
* markerWidth="10"
* paddingBottom="0"
* paddingLeft="0"
* paddingRight="0"
* paddingTop="0"
* shadowDirection="center"
* shadowDistance="2"
* stroke="<i>IStroke; no default</i>"
* textAlign="left"
* textDecoration="none|underline"
* textIndent="0"
* verticalAlign="top|middle|bottom"
* verticalGap="<i>6</i>"
*
* <strong>Events</strong>
* childAdd="<i>No default</i>"
* childIndexChange="<i>No default</i>"
* childRemove="<i>No default</i>"
* dataChange="<i>No default</i>"
* itemClick="<i>Event; no default</i>"
* itemMouseDown="<i>Event; no default</i>"
* itemMouseOut="<i>Event; no default</i>"
* itemMouseOver="<i>Event; no default</i>"
* itemMouseUp="<i>Event; no default</i>"
* />
* </pre>
*
* @see mx.charts.LegendItem
*
* @includeExample examples/PlotChartExample.mxml
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public class Legend extends UIComponent// implements IContainer
{
// include "../core/Version.as"
//--------------------------------------------------------------------------
//
// Notes: Child management
//
//--------------------------------------------------------------------------
/*
Although at the level of a Flash DisplayObjectContainer, all
children are equal, in a Flex Container some children are "more
equal than others". (George Orwell, "Animal Farm")
In particular, Flex distinguishes between content children and
non-content (or "chrome") children. Content children are the kind
that can be specified in MXML. If you put several controls
into a VBox, those are its content children. Non-content children
are the other ones that you get automatically, such as a
background/border, scrollbars, the titlebar of a Panel,
AccordionHeaders, etc.
Most application developers are uninterested in non-content children,
so Container overrides APIs such as numChildren and getChildAt()
to deal only with content children. For example, Container, keeps
its own _numChildren counter.
Container assumes that content children are contiguous, and that
non-content children come before or after the content children.
In order words, Container partitions DisplayObjectContainer's
index range into three parts:
A B C D E F G H I
0 1 2 3 4 5 6 7 8 <- index for all children
0 1 2 3 <- index for content children
The content partition contains the content children D E F G.
The pre-content partition contains the non-content children
A B C that always stay before the content children.
The post-content partition contains the non-content children
H I that always stay after the content children.
Container maintains two state variables, _firstChildIndex
and _numChildren, which keep track of the partitioning.
In this example, _firstChildIndex would be 3 and _numChildren
would be 4.
*/
//--------------------------------------------------------------------------
//
// Class constants
//
//--------------------------------------------------------------------------
/**
* @private
* See changedStyles, below
*/
private static const MULTIPLE_PROPERTIES:String = "<MULTIPLE>";
//--------------------------------------------------------------------------
//
// Class methods
//
//--------------------------------------------------------------------------
mx_internal function getLayoutChildAt(index:int):IUIComponent
{
return /*PostScaleAdapter.getCompatibleIUIComponent(*/getChildAt(index)/*)*/;
}
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function Legend()
{
super();
tabEnabled = false;
tabFocusEnabled = false;
//showInAutomationHierarchy = false;
// If available, get soft-link to the RichEditableText class
// to use in keyDownHandler().
try
{
richEditableTextClass =
Class(getDefinitionByName(
"spark.components.RichEditableText"));
}
catch (e:Error)
{
}
direction = "vertical";
addEventListener(MouseEvent.CLICK, childMouseEventHandler);
addEventListener(MouseEvent.MOUSE_OVER, childMouseEventHandler);
addEventListener(MouseEvent.MOUSE_OUT, childMouseEventHandler);
addEventListener(MouseEvent.MOUSE_UP, childMouseEventHandler);
addEventListener(MouseEvent.MOUSE_DOWN, childMouseEventHandler);
_dataProvider = new ArrayCollection();
}
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
//----------------------------------
// Child creation vars
//----------------------------------
/**
* The creation policy of this container.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
protected var actualCreationPolicy:String;
/**
* @private
*/
private var numChildrenBefore:int;
/**
* @private
* @royalesuppresspublicvarwarning
*/
public var recursionFlag:Boolean = true;
//----------------------------------
// Layout vars
//----------------------------------
/**
* @private
* Remember when a child has been added or removed.
* When that occurs, we want to run the LayoutManager
* (even if autoLayout is false).
*/
private var forceLayout:Boolean = false;
/**
* @private
*/
mx_internal var doingLayout:Boolean = false;
//----------------------------------
// Style vars
//----------------------------------
/**
* @private
* If this value is non-null, then we need to recursively notify children
* that a style property has changed. If one style property has changed,
* this field holds the name of the style that changed. If multiple style
* properties have changed, then the value of this field is
* Container.MULTIPLE_PROPERTIES.
*/
private var changedStyles:String = null;
//----------------------------------
// Scrolling vars
//----------------------------------
/**
* @private
*/
private var _creatingContentPane:Boolean = false;
/**
* Containers use an internal content pane to control scrolling.
* The <code>creatingContentPane</code> is <code>true</code> while the container is creating
* the content pane so that some events can be ignored or blocked.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get creatingContentPane():Boolean
{
return _creatingContentPane;
}
public function set creatingContentPane(value:Boolean):void
{
_creatingContentPane = value;
}
/**
* @private
* A box that takes up space in the lower right corner,
* between the horizontal and vertical scrollbars.
*/
protected var whiteBox:UIComponent;
/**
* @private
*/
mx_internal var contentPane:UIComponent = null;
/**
* @private
* Flags that remember what work to do during the next updateDisplayList().
*/
private var scrollPositionChanged:Boolean = true;
private var horizontalScrollPositionPending:Number;
private var verticalScrollPositionPending:Number;
/**
* @private
* Cached values describing the total size of the content being scrolled
* and the size of the area in which the scrolled content is displayed.
*/
private var scrollableWidth:Number = 0;
private var scrollableHeight:Number = 0;
private var viewableWidth:Number = 0;
private var viewableHeight:Number = 0;
//----------------------------------
// Other vars
//----------------------------------
/**
* @private
* The border/background object.
*/
mx_internal var border:IFlexDisplayObject;
/**
* @private
* Sprite used to block user input when the container is disabled.
*/
mx_internal var blocker:UIComponent;
/**
* @private
* Keeps track of the number of mouse events we are listening for
*/
private var mouseEventReferenceCount:int = 0;
/**
* @private
* Soft-link to RichEditableText class object, if available.
*/
private var richEditableTextClass:Class;
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
/**
* @private
* Cached value from findCellSize() call in measure(),
* so that updateDisplayList() doesn't also have to call findCellSize().
*/
mx_internal var cellWidth:Number;
/**
* @private
* Cached value from findCellSize() call in measure(),
* so that updateDisplaylist() doesn't also have to call findCellSize().
*/
mx_internal var cellHeight:Number;
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
//----------------------------------
// direction
//----------------------------------
/**
* @private
* Storage for the direction property.
*/
private var _direction:String = "horizontal";
[Bindable("directionChanged")]
[Inspectable(category="General", enumeration="vertical,horizontal", defaultValue="horizontal")]
/**
* Determines how children are placed in the container.
* Possible MXML values are <code>"horizontal"</code> and
* <code>"vertical"</code>.
* In ActionScript, you can set the direction using the values
* TileDirection.HORIZONTAL or TileDirection.VERTICAL.
* The default value is <code>"horizontal"</code>.
* (If the container is a Legend container, which is a subclass of Tile,
* the default value is <code>"vertical"</code>.)
*
* <p>The first child is always placed at the upper-left of the
* Tile container.
* If the <code>direction</code> is <code>"horizontal"</code>,
* the children are placed left-to-right in the topmost row,
* and then left-to-right in the second row, and so on.
* If the value is <code>"vertical"</code>, the children are placed
* top-to-bottom in the leftmost column, and then top-to-bottom
* in the second column, and so on.</p>
*
* @default "horizontal"
*
* @see TileDirection
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get direction():String
{
return _direction;
}
/**
* @private
*/
public function set direction(value:String):void
{
_direction = value;
invalidateSize();
invalidateDisplayList();
dispatchEvent(new Event("directionChanged"));
}
//----------------------------------
// tileHeight
//----------------------------------
/**
* @private
* Storage for the tileHeight property.
*/
private var _tileHeight:Number;
[Bindable("resize")]
[Inspectable(category="General")]
/**
* Height of each tile cell, in pixels.
* If this property is <code>NaN</code>, the default, the height
* of each cell is determined by the height of the tallest child.
* If you set this property, the specified value overrides
* this calculation.
*
* @default NaN
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get tileHeight():Number
{
return _tileHeight;
}
/**
* @private
*/
public function set tileHeight(value:Number):void
{
_tileHeight = value;
invalidateSize();
}
//----------------------------------
// tileWidth
//----------------------------------
/**
* @private
* Storage for the tileWidth property.
*/
private var _tileWidth:Number;
[Bindable("resize")]
[Inspectable(category="General")]
/**
* Width of each tile cell, in pixels.
* If this property is <code>NaN</code>, the defualt, the width
* of each cell is determined by the width of the widest child.
* If you set this property, the specified value overrides
* this calculation.
*
* @default NaN
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get tileWidth():Number
{
return _tileWidth;
}
/**
* @private
*/
public function set tileWidth(value:Number):void
{
_tileWidth = value;
invalidateSize();
}
/**
* @private
*/
private var _preferredMajorAxisLength:Number;
/**
* @private
*/
private var _actualMajorAxisLength:Number;
/**
* @private
*/
private var _childrenDirty:Boolean = false;
/**
* @private
*/
private var _unscaledWidth:Number;
/**
* @private
*/
private var _unscaledHeight:Number;
/**
* @private
*/
private static var legendItemLinkage:LegendItem = null;
/**
* @private
*/
private var _dataProviderChanged:Boolean = false;
//--------------------------------------------------------------------------
//
// Overridden properties
//
//--------------------------------------------------------------------------
//----------------------------------
// baselinePosition
//----------------------------------
/**
* @private
* The baselinePosition of a Container is calculated
* as if there was a UITextField using the Container's styles
* whose top is at viewMetrics.top.
*/
override public function get baselinePosition():Number
{
//if (!validateBaselinePosition())
// return NaN;
// Unless the height is very small, the baselinePosition
// of a generic Container is calculated as if there was
// a UITextField using the Container's styles
// whose top is at viewMetrics.top.
// If the height is small, the baselinePosition is calculated
// as if there were text within whose ascent the Container
// is vertically centered.
// At the crossover height, these two calculations
// produce the same result.
/*
var lineMetrics:TextLineMetrics = measureText("Wj");
if (height < 2 * viewMetrics.top + 4 + lineMetrics.ascent)
return int(height + (lineMetrics.ascent - height) / 2);
*/
return viewMetrics.top/* + 2 + lineMetrics.ascent*/;
}
//----------------------------------
// contentMouseX
//----------------------------------
/**
* @copy mx.core.UIComponent#contentMouseX
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
override public function get contentMouseX():Number
{
if (contentPane)
return contentPane.mouseX;
return super.contentMouseX;
}
//----------------------------------
// contentMouseY
//----------------------------------
/**
* @copy mx.core.UIComponent#contentMouseY
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
override public function get contentMouseY():Number
{
if (contentPane)
return contentPane.mouseY;
return super.contentMouseY;
}
//----------------------------------
// doubleClickEnabled
//----------------------------------
/**
* @private
* Propagate to children.
*/
override public function set doubleClickEnabled(value:Boolean):void
{
super.doubleClickEnabled = value;
if (contentPane)
{
var n:int = contentPane.numChildren;
for (var i:int = 0; i < n; i++)
{
var child:UIComponent =
contentPane.getChildAt(i) as UIComponent;
if (child)
child.doubleClickEnabled = value;
}
}
}
//----------------------------------
// enabled
//----------------------------------
[Inspectable(category="General", enumeration="true,false", defaultValue="true")]
/**
* @private
*/
override public function set enabled(value:Boolean):void
{
super.enabled = value;
invalidateProperties();
/*if (border && border is IInvalidating)
IInvalidating(border).invalidateDisplayList();*/
}
//----------------------------------
// focusPane
//----------------------------------
/**
* @private
* Storage for the focusPane property.
*/
private var _focusPane:UIComponent;
/**
* @private
* Focus pane associated with this object.
* An object has a focus pane when one of its children has got focus.
override public function get focusPane():UIComponent
{
return _focusPane;
}
*/
/**
* @private
override public function set focusPane(o:UIComponent):void
{
// The addition or removal of the focus sprite should not trigger
// a measurement/layout pass. Temporarily set the invalidation flags,
// so that calls to invalidateSize() and invalidateDisplayList() have
// no effect.
var oldInvalidateSizeFlag:Boolean = invalidateSizeFlag;
var oldInvalidateDisplayListFlag:Boolean = invalidateDisplayListFlag;
invalidateSizeFlag = true;
invalidateDisplayListFlag = true;
if (o)
{
rawChildren.addChild(o);
o.x = 0;
o.y = 0;
o.scrollRect = null;
_focusPane = o;
}
else
{
rawChildren.removeChild(_focusPane);
_focusPane = null;
}
if (o && contentPane)
{
o.x = contentPane.x;
o.y = contentPane.y;
o.scrollRect = contentPane.scrollRect;
}
invalidateSizeFlag = oldInvalidateSizeFlag;
invalidateDisplayListFlag = oldInvalidateDisplayListFlag;
}
*/
//----------------------------------
// moduleFactory
//----------------------------------
/**
* @private
override public function set moduleFactory(moduleFactory:IFlexModuleFactory):void
{
super.moduleFactory = moduleFactory;
// Register the _creationPolicy style as inheriting. See the creationPolicy
// getter for details on usage of this style.
styleManager.registerInheritingStyle("_creationPolicy");
}
*/
//----------------------------------
// $numChildren
//----------------------------------
/**
* @private
* This property allows access to the Player's native implementation
* of the numChildren property, which can be useful since components
* can override numChildren and thereby hide the native implementation.
* Note that this "base property" is final and cannot be overridden,
* so you can count on it to reflect what is happening at the player level.
*/
COMPILE::JS
mx_internal final function get $sprite_numChildren():int
{
return super.numChildren;
}
//----------------------------------
// numChildren
//----------------------------------
/**
* @private
* Storage for the numChildren property.
*/
mx_internal var _numChildren:int = 0;
/**
* Number of child components in this container.
*
* <p>The number of children is initially equal
* to the number of children declared in MXML.
* At runtime, new children may be added by calling
* <code>addChild()</code> or <code>addChildAt()</code>,
* and existing children may be removed by calling
* <code>removeChild()</code>, <code>removeChildAt()</code>,
* or <code>removeAllChildren()</code>.</p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
override public function get numChildren():int
{
return contentPane ? contentPane.numChildren : _numChildren;
}
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
//----------------------------------
// dataProvider
//----------------------------------
/**
* @private
* Storage for the dataProvider property.
*/
private var _dataProvider:Object;
[Bindable("collectionChange")]
[Inspectable(category="Data")]
/**
* Set of data to be used in the Legend.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get dataProvider():Object
{
return _dataProvider;
}
/**
* @private
*/
public function set dataProvider(
value:Object /* String, ViewStack or Array */):void
{
if (_dataProvider is ChartBase)
{
_dataProvider.removeEventListener("legendDataChanged",
legendDataChangedHandler);
}
_dataProvider = value ? value : [];
if (_dataProvider is ChartBase)
{
// weak listeners to collections and dataproviders
_dataProvider.addEventListener("legendDataChanged",
legendDataChangedHandler, false, 0, true);
}
else if (_dataProvider is ICollectionView)
{
}
else if (_dataProvider is IList)
{
_dataProvider = new ListCollectionView(IList(_dataProvider));
}
else if (_dataProvider is Array)
{
_dataProvider = new ArrayCollection(_dataProvider as Array);
}
else if (_dataProvider != null)
{
_dataProvider = new ArrayCollection([_dataProvider]);
}
else
{
_dataProvider = new ArrayCollection();
}
invalidateProperties();
invalidateSize();
_childrenDirty = true;
if (parent)
{
commitProperties();
measure();
// layoutVertical cares about width/height (via UIComponent unscaledWidth/Height)
setActualSize(getExplicitOrMeasuredWidth(), getExplicitOrMeasuredHeight());
updateDisplayList(width, height);
}
dispatchEvent(new Event("collectionChange"));
}
//----------------------------------
// legendItemClass
//----------------------------------
/**
* The class used to instantiate LegendItem objects.
* When a legend's content is derived from the chart or data,
* it instantiates one instance of <code>legendItemClass</code>
* for each item described by the <code>dataProvider</code>.
* If you want custom behavior in your legend items,
* you can assign a subclass of LegendItem to this property
* to have the Legend create instances of their derived type instead.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*
* @royalesuppresspublicvarwarning
*/
public var legendItemClass:Class = LegendItem;
//----------------------------------
// autoLayout
//----------------------------------
/**
* @private
* Storage for the autoLayout property.
*/
private var _autoLayout:Boolean = true;
[Inspectable(defaultValue="true")]
/**
* If <code>true</code>, measurement and layout are done
* when the position or size of a child is changed.
* If <code>false</code>, measurement and layout are done only once,
* when children are added to or removed from the container.
*
* <p>When using the Move effect, the layout around the component that
* is moving does not readjust to fit that the Move effect animates.
* Setting a container's <code>autoLayout</code> property to
* <code>true</code> has no effect on this behavior.</p>
*
* <p>The Zoom effect does not work when the <code>autoLayout</code>
* property is <code>false</code>.</p>
*
* <p>The <code>autoLayout</code> property does not apply to
* Accordion or ViewStack containers.</p>
*
* @default true
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get autoLayout():Boolean
{
return _autoLayout;
}
/**
* @private
*/
public function set autoLayout(value:Boolean):void
{
_autoLayout = value;
// If layout is being turned back on, trigger a layout to occur now.
if (value)
{
invalidateSize();
invalidateDisplayList();
var p:IInvalidating = parent as IInvalidating;
if (p)
{
p.invalidateSize();
p.invalidateDisplayList();
}
}
}
//----------------------------------
// borderMetrics
//----------------------------------
/**
* Returns an EdgeMetrics object that has four properties:
* <code>left</code>, <code>top</code>, <code>right</code>,
* and <code>bottom</code>.
* The value of each property is equal to the thickness of one side
* of the border, expressed in pixels.
*
* <p>Unlike <code>viewMetrics</code>, this property is not
* overridden by subclasses of Container.</p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get borderMetrics():EdgeMetrics
{
/*return border && border is IRectangularBorder ?
IRectangularBorder(border).borderMetrics :
EdgeMetrics.EMPTY;*/
return EdgeMetrics.EMPTY;
}
//----------------------------------
// childDescriptors
//----------------------------------
/**
* @private
* Storage for the childDescriptors property.
* This variable is initialized in the construct() method
* using the childDescriptors in the initObj, which is autogenerated.
* If this Container was not created by createComponentFromDescriptor(),
* its childDescriptors property is null.
*/
private var _childDescriptors:Array /* of UIComponentDescriptor */;
/**
* Array of UIComponentDescriptor objects produced by the MXML compiler.
*
* <p>Each UIComponentDescriptor object contains the information
* specified in one child MXML tag of the container's MXML tag.
* The order of the UIComponentDescriptor objects in the Array
* is the same as the order of the child tags.
* During initialization, the child descriptors are used to create
* the container's child UIComponent objects and its Repeater objects,
* and to give them the initial property values, event handlers, effects,
* and so on, that were specified in MXML.</p>
*
* @see mx.core.UIComponentDescriptor
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get childDescriptors():Array /* of UIComponentDescriptor */
{
return _childDescriptors;
}
public function set childDescriptors(value:Array):void /* of UIComponentDescriptor */
{
_childDescriptors = value;
}
//----------------------------------
// childRepeaters
//----------------------------------
/**
* @private
* Storage for the childRepeaters property.
*/
private var _childRepeaters:Array;
/**
* @private
* An array of the Repeater objects found within this container.
*/
mx_internal function get childRepeaters():Array
{
return _childRepeaters;
}
/**
* @private
*/
mx_internal function set childRepeaters(value:Array):void
{
_childRepeaters = value;
}
//----------------------------------
// clipContent
//----------------------------------
/**
* @private
* Storage for the clipContent property.
*/
private var _clipContent:Boolean = true;
[Inspectable(defaultValue="true")]
/**
* Whether to apply a clip mask if the positions and/or sizes
* of this container's children extend outside the borders of
* this container.
* If <code>false</code>, the children of this container
* remain visible when they are moved or sized outside the
* borders of this container.
* If <code>true</code>, the children of this container are clipped.
*
* <p>If <code>clipContent</code> is <code>false</code>, then scrolling
* is disabled for this container and scrollbars will not appear.
* If <code>clipContent</code> is true, then scrollbars will usually
* appear when the container's children extend outside the border of
* the container.
* For additional control over the appearance of scrollbars,
* see <code>horizontalScrollPolicy</code> and <code>verticalScrollPolicy</code>.</p>
*
* @default true
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get clipContent():Boolean
{
return _clipContent;
}
/**
* @private
*/
public function set clipContent(value:Boolean):void
{
if (_clipContent != value)
{
_clipContent = value;
invalidateDisplayList();
}
}
//----------------------------------
// createdComponents
//----------------------------------
/**
* @private
* Internal variable used to keep track of the components created
* by this Container. This is different than the list maintained
* by DisplayObjectContainer, because it includes Repeaters.
*/
private var _createdComponents:Array;
/**
* @private
* An array of all components created by this container including
* Repeater components.
*/
mx_internal function get createdComponents():Array
{
return _createdComponents;
}
/**
* @private
*/
mx_internal function set createdComponents(value:Array):void
{
_createdComponents = value;
}
//----------------------------------
// creationIndex
//----------------------------------
/**
* @private
* Storage for the creationIndex property.
*/
private var _creationIndex:int = -1;
[Inspectable(defaultValue="undefined")]
/**
* Specifies the order to instantiate and draw the children
* of the container.
*
* <p>This property can only be used when the <code>creationPolicy</code>
* property is set to <code>ContainerCreationPolicy.QUEUED</code>.
* Otherwise, it is ignored.</p>
*
* @default -1
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Deprecated]
public function get creationIndex():int
{
return _creationIndex;
}
/**
* @private
*/
public function set creationIndex(value:int):void
{
_creationIndex = value;
}
//----------------------------------
// creationPolicy
//----------------------------------
// Internal flag used when creationPolicy="none".
// When set, the value of the backing store _creationPolicy
// style is "auto" so descendants inherit the correct value.
private var creationPolicyNone:Boolean = false;
[Inspectable(enumeration="all,auto,none")]
/**
* The child creation policy for this MX Container.
* ActionScript values can be <code>ContainerCreationPolicy.AUTO</code>,
* <code>ContainerCreationPolicy.ALL</code>,
* or <code>ContainerCreationPolicy.NONE</code>.
* MXML values can be <code>auto</code>, <code>all</code>,
* or <code>none</code>.
*
* <p>If no <code>creationPolicy</code> is specified for a container,
* that container inherits its parent's <code>creationPolicy</code>.
* If no <code>creationPolicy</code> is specified for the Application,
* it defaults to <code>ContainerCreationPolicy.AUTO</code>.</p>
*
* <p>A <code>creationPolicy</code> of <code>ContainerCreationPolicy.AUTO</code> means
* that the container delays creating some or all descendants
* until they are needed, a process which is known as <i>deferred
* instantiation</i>.
* This policy produces the best startup time because fewer
* UIComponents are created initially.
* However, this introduces navigation delays when a user navigates
* to other parts of the application for the first time.
* Navigator containers such as Accordion, TabNavigator, and ViewStack
* implement the <code>ContainerCreationPolicy.AUTO</code> policy by creating all their
* children immediately, but wait to create the deeper descendants
* of a child until it becomes the selected child of the navigator
* container.</p>
*
* <p>A <code>creationPolicy</code> of <code>ContainerCreationPolicy.ALL</code> means
* that the navigator containers immediately create deeper descendants
* for each child, rather than waiting until that child is
* selected. For single-view containers such as a VBox container,
* there is no difference between the <code>ContainerCreationPolicy.AUTO</code> and
* <code>ContainerCreationPolicy.ALL</code> policies.</p>
*
* <p>A <code>creationPolicy</code> of <code>ContainerCreationPolicy.NONE</code> means
* that the container creates none of its children.
* In that case, it is the responsibility of the MXML author
* to create the children by calling the
* <code>createComponentsFromDescriptors()</code> method.</p>
*
* @default ContainerCreationPolicy.AUTO
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
public function get creationPolicy():String
{
// Use an inheriting style as the backing storage for this property.
// This allows the property to be inherited by either mx or spark
// containers, and also to correctly cascade through containers that
// don't have this property (ie Group).
// This style is an implementation detail and should be considered
// private. Do not set it from CSS.
if (creationPolicyNone)
return ContainerCreationPolicy.NONE;
return getStyle("_creationPolicy");
}
*/
/**
* @private
public function set creationPolicy(value:String):void
{
var styleValue:String = value;
if (value == ContainerCreationPolicy.NONE)
{
// creationPolicy of none is not inherited by descendants.
// In this case, set the style to "auto" and set a local
// flag for subsequent access to the creationPolicy property.
creationPolicyNone = true;
styleValue = ContainerCreationPolicy.AUTO;
}
else
{
creationPolicyNone = false;
}
setStyle("_creationPolicy", styleValue);
setActualCreationPolicies(value);
}
*/
//----------------------------------
// defaultButton
//----------------------------------
/**
* @private
* Storage for the defaultButton property.
*/
private var _defaultButton:IFlexDisplayObject;
[Inspectable(category="General")]
/**
* The Button control designated as the default button
* for the container.
* When controls in the container have focus, pressing the
* Enter key is the same as clicking this Button control.
*
* @default null
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
public function get defaultButton():IFlexDisplayObject
{
return _defaultButton;
}
*/
/**
* @private
public function set defaultButton(value:IFlexDisplayObject):void
{
_defaultButton = value;
ContainerGlobals.focusedContainer = null;
}
*/
//----------------------------------
// deferredContentCreated
//----------------------------------
/**
* IDeferredContentOwner equivalent of processedDescriptors
*
* @see UIComponent#processedDescriptors
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
public function get deferredContentCreated():Boolean
{
return processedDescriptors;
}
*/
//----------------------------------
// data
//----------------------------------
/**
* @private
* Storage for the data property.
*/
private var _data:Object;
[Bindable("dataChange")]
[Inspectable(environment="none")]
/**
* The <code>data</code> property lets you pass a value
* to the component when you use it in an item renderer or item editor.
* You typically use data binding to bind a field of the <code>data</code>
* property to a property of this component.
*
* <p>You do not set this property in MXML.</p>
*
* @default null
* @see mx.core.IDataRenderer
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get data():Object
{
return _data;
}
/**
* @private
*/
public function set data(value:Object):void
{
_data = value;
dispatchEvent(new FlexEvent(FlexEvent.DATA_CHANGE));
invalidateDisplayList();
}
//----------------------------------
// firstChildIndex
//----------------------------------
/**
* @private
* Storage for the firstChildIndex property.
*/
private var _firstChildIndex:int = 0;
/**
* @private
* The index of the first content child,
* when dealing with both content and non-content children.
*/
mx_internal function get firstChildIndex():int
{
return _firstChildIndex;
}
//----------------------------------
// horizontalScrollPosition
//----------------------------------
/**
* @private
* Storage for the horizontalScrollPosition property.
*/
private var _horizontalScrollPosition:Number = 0;
[Bindable("scroll")]
[Bindable("viewChanged")]
[Inspectable(defaultValue="0")]
/**
* The current position of the horizontal scroll bar.
* This is equal to the distance in pixels between the left edge
* of the scrollable surface and the leftmost piece of the surface
* that is currently visible.
*
* @default 0
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get horizontalScrollPosition():Number
{
if (!isNaN(horizontalScrollPositionPending))
return horizontalScrollPositionPending;
return _horizontalScrollPosition;
}
/**
* @private
*/
public function set horizontalScrollPosition(value:Number):void
{
if (_horizontalScrollPosition == value)
return;
// Note: We can't use maxHorizontalScrollPosition to clamp the value here.
// The horizontalScrollBar may not exist yet,
// or its maxPos might change during layout.
// (For example, you could set the horizontalScrollPosition of a childless container,
// then add a child which causes it to have a scrollbar.)
// The horizontalScrollPosition gets clamped to the range 0 through maxHorizontalScrollPosition
// late, in the updateDisplayList() method, just before the scrollPosition
// of the horizontalScrollBar is set.
_horizontalScrollPosition = value;
scrollPositionChanged = true;
if (!initialized)
horizontalScrollPositionPending = value;
invalidateDisplayList();
dispatchEvent(new Event("viewChanged"));
}
//----------------------------------
// horizontalScrollPolicy
//----------------------------------
/**
* @private
* Storage for the horizontalScrollPolicy property.
*/
mx_internal var _horizontalScrollPolicy:String = ScrollPolicy.AUTO;
[Bindable("horizontalScrollPolicyChanged")]
[Inspectable(category="General", enumeration="off,on,auto", defaultValue="auto")]
/**
* Specifies whether the horizontal scroll bar is always present,
* always absent, or automatically added when needed.
* ActionScript values can be <code>ScrollPolicy.ON</code>, <code>ScrollPolicy.OFF</code>,
* and <code>ScrollPolicy.AUTO</code>.
* MXML values can be <code>"on"</code>, <code>"off"</code>,
* and <code>"auto"</code>.
*
* <p>Setting this property to <code>ScrollPolicy.OFF</code> also prevents the
* <code>horizontalScrollPosition</code> property from having an effect.</p>
*
* <p>Note: This property does not apply to the ControlBar container.</p>
*
* <p>If the <code>horizontalScrollPolicy</code> is <code>ScrollPolicy.AUTO</code>,
* the horizontal scroll bar appears when all of the following
* are true:</p>
* <ul>
* <li>One of the container's children extends beyond the left
* edge or right edge of the container.</li>
* <li>The <code>clipContent</code> property is <code>true</code>.</li>
* <li>The width and height of the container are large enough to
* reasonably accommodate a scroll bar.</li>
* </ul>
*
* @default ScrollPolicy.AUTO
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get horizontalScrollPolicy():String
{
return ScrollPolicy.OFF;
}
/**
* @private
*/
public function set horizontalScrollPolicy(value:String):void
{
}
//----------------------------------
// icon
//----------------------------------
/**
* @private
* Storage for the icon property.
*/
private var _icon:Class = null;
[Bindable("iconChanged")]
[Inspectable(category="General", defaultValue="", format="EmbeddedFile")]
/**
* The Class of the icon displayed by some navigator
* containers to represent this Container.
*
* <p>For example, if this Container is a child of a TabNavigator,
* this icon appears in the corresponding tab.
* If this Container is a child of an Accordion,
* this icon appears in the corresponding header.</p>
*
* <p>To embed the icon in the SWF file, use the @Embed()
* MXML compiler directive:</p>
*
* <pre>
* icon="@Embed('filepath')"
* </pre>
*
* <p>The image can be a JPEG, GIF, PNG, SVG, or SWF file.</p>
*
* @default null
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get icon():Class
{
return _icon;
}
/**
* @private
*/
public function set icon(value:Class):void
{
_icon = value;
dispatchEvent(new Event("iconChanged"));
}
//----------------------------------
// label
//----------------------------------
/**
* @private
* Storage for the label property.
*/
private var _label:String = "";
[Bindable("labelChanged")]
[Inspectable(category="General", defaultValue="")]
/**
* The text displayed by some navigator containers to represent
* this Container.
*
* <p>For example, if this Container is a child of a TabNavigator,
* this string appears in the corresponding tab.
* If this Container is a child of an Accordion,
* this string appears in the corresponding header.</p>
*
* @default ""
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get label():String
{
return _label;
}
/**
* @private
*/
public function set label(value:String):void
{
_label = value;
dispatchEvent(new Event("labelChanged"));
}
//----------------------------------
// maxHorizontalScrollPosition
//----------------------------------
/**
* The largest possible value for the
* <code>horizontalScrollPosition</code> property.
* Defaults to 0 if the horizontal scrollbar is not present.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get maxHorizontalScrollPosition():Number
{
return Math.max(scrollableWidth - viewableWidth, 0);
}
//----------------------------------
// maxVerticalScrollPosition
//----------------------------------
/**
* The largest possible value for the
* <code>verticalScrollPosition</code> property.
* Defaults to 0 if the vertical scrollbar is not present.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get maxVerticalScrollPosition():Number
{
return Math.max(scrollableHeight - viewableHeight, 0);
}
//----------------------------------
// numChildrenCreated
//----------------------------------
/**
* @private
*/
private var _numChildrenCreated:int = -1;
/**
* @private
* The number of children created inside this container.
* The default value is 0.
*/
mx_internal function get numChildrenCreated():int
{
return _numChildrenCreated;
}
/**
* @private
*/
mx_internal function set numChildrenCreated(value:int):void
{
_numChildrenCreated = value;
}
//----------------------------------
// numRepeaters
//----------------------------------
/**
* @private
* The number of Repeaters in this Container.
*
* <p>This number includes Repeaters that are immediate children of this
* container and Repeaters that are nested inside other Repeaters.
* Consider the following example:</p>
*
* <pre>
* <mx:HBox>
* <mx:Repeater dataProvider="[1, 2]">
* <mx:Repeater dataProvider="...">
* <mx:Button/>
* </mx:Repeater>
* </mx:Repeater>
* <mx:HBox>
* </pre>
*
* <p>In this example, the <code>numRepeaters</code> property
* for the HBox would be set equal to 3 -- one outer Repeater
* and two inner repeaters.</p>
*
* <p>The <code>numRepeaters</code> property does not include Repeaters
* that are nested inside other containers.
* Consider this example:</p>
*
* <pre>
* <mx:HBox>
* <mx:Repeater dataProvider="[1, 2]">
* <mx:VBox>
* <mx:Repeater dataProvider="...">
* <mx:Button/>
* </mx:Repeater>
* </mx:VBox>
* </mx:Repeater>
* <mx:HBox>
* </pre>
*
* <p>In this example, the <code>numRepeaters</code> property
* for the outer HBox would be set equal to 1 -- just the outer repeater.
* The two inner VBox containers would also have a
* <code>numRepeaters</code> property equal to 1 -- one Repeater
* per VBox.</p>
*/
mx_internal function get numRepeaters():int
{
return childRepeaters ? childRepeaters.length : 0;
}
//----------------------------------
// rawChildren
//----------------------------------
/**
* @private
* The single IChildList object that's always returned
* from the rawChildren property, below.
*/
private var _rawChildren:LegendRawChildrenList;
/**
* A container typically contains child components, which can be enumerated
* using the <code>Container.getChildAt()</code> method and
* <code>Container.numChildren</code> property. In addition, the container
* may contain style elements and skins, such as the border and background.
* Flash Player and AIR do not draw any distinction between child components
* and skins. They are all accessible using the player's
* <code>getChildAt()</code> method and
* <code>numChildren</code> property.
* However, the Container class overrides the <code>getChildAt()</code> method
* and <code>numChildren</code> property (and several other methods)
* to create the illusion that
* the container's children are the only child components.
*
* <p>If you need to access all of the children of the container (both the
* content children and the skins), then use the methods and properties
* on the <code>rawChildren</code> property instead of the regular Container methods.
* For example, use the <code>Container.rawChildren.getChildAt())</code> method.
* However, if a container creates a ContentPane Sprite object for its children,
* the <code>rawChildren</code> property value only counts the ContentPane, not the
* container's children.
* It is not always possible to determine when a container will have a ContentPane.</p>
*
* <p><b>Note:</b>If you call the <code>addChild</code> or
* <code>addChildAt</code> method of the <code>rawChildren</code> object,
* set <code>tabFocusEnabled = false</code> on the component that you have added.
* Doing so prevents users from tabbing to the visual-only component
* that you have added.</p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get rawChildren():IChildList
{
if (!_rawChildren)
_rawChildren = new LegendRawChildrenList(this);
return _rawChildren;
}
//----------------------------------
// usePadding
//----------------------------------
/**
* @private
*/
mx_internal function get usePadding():Boolean
{
// Containers, by default, always use padding.
return true;
}
//----------------------------------
// verticalScrollPosition
//----------------------------------
/**
* @private
* Storage for the verticalScrollPosition property.
*/
private var _verticalScrollPosition:Number = 0;
[Bindable("scroll")]
[Bindable("viewChanged")]
[Inspectable(defaultValue="0")]
/**
* The current position of the vertical scroll bar.
* This is equal to the distance in pixels between the top edge
* of the scrollable surface and the topmost piece of the surface
* that is currently visible.
*
* @default 0
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get verticalScrollPosition():Number
{
if (!isNaN(verticalScrollPositionPending))
return verticalScrollPositionPending;
return _verticalScrollPosition;
}
/**
* @private
*/
public function set verticalScrollPosition(value:Number):void
{
if (_verticalScrollPosition == value)
return;
// Note: We can't use maxVerticalScrollPosition to clamp the value here.
// The verticalScrollBar may not exist yet,
// or its maxPos might change during layout.
// (For example, you could set the verticalScrollPosition of a childless container,
// then add a child which causes it to have a scrollbar.)
// The verticalScrollPosition gets clamped to the range 0 through maxVerticalScrollPosition
// late, in the updateDisplayList() method, just before the scrollPosition
// of the verticalScrollBar is set.
_verticalScrollPosition = value;
scrollPositionChanged = true;
if (!initialized)
verticalScrollPositionPending = value;
invalidateDisplayList();
dispatchEvent(new Event("viewChanged"));
}
//----------------------------------
// verticalScrollPolicy
//----------------------------------
/**
* @private
* Storage for the verticalScrollPolicy property.
*/
mx_internal var _verticalScrollPolicy:String = ScrollPolicy.AUTO;
[Bindable("verticalScrollPolicyChanged")]
[Inspectable(category="General", enumeration="off,on,auto", defaultValue="auto")]
/**
* Specifies whether the vertical scroll bar is always present,
* always absent, or automatically added when needed.
* Possible values are <code>ScrollPolicy.ON</code>, <code>ScrollPolicy.OFF</code>,
* and <code>ScrollPolicy.AUTO</code>.
* MXML values can be <code>"on"</code>, <code>"off"</code>,
* and <code>"auto"</code>.
*
* <p>Setting this property to <code>ScrollPolicy.OFF</code> also prevents the
* <code>verticalScrollPosition</code> property from having an effect.</p>
*
* <p>Note: This property does not apply to the ControlBar container.</p>
*
* <p>If the <code>verticalScrollPolicy</code> is <code>ScrollPolicy.AUTO</code>,
* the vertical scroll bar appears when all of the following
* are true:</p>
* <ul>
* <li>One of the container's children extends beyond the top
* edge or bottom edge of the container.</li>
* <li>The <code>clipContent</code> property is <code>true</code>.</li>
* <li>The width and height of the container are large enough to
* reasonably accommodate a scroll bar.</li>
* </ul>
*
* @default ScrollPolicy.AUTO
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get verticalScrollPolicy():String
{
return ScrollPolicy.OFF;
}
/**
* @private
*/
public function set verticalScrollPolicy(value:String):void
{
}
//----------------------------------
// viewMetrics
//----------------------------------
/**
* @private
* Offsets including borders and scrollbars
*/
private var _viewMetrics:EdgeMetrics;
/**
* Returns an object that has four properties: <code>left</code>,
* <code>top</code>, <code>right</code>, and <code>bottom</code>.
* The value of each property equals the thickness of the chrome
* (visual elements) around the edge of the container.
*
* <p>The chrome includes the border thickness.
* If the <code>horizontalScrollPolicy</code> or <code>verticalScrollPolicy</code>
* property value is <code>ScrollPolicy.ON</code>, the
* chrome also includes the thickness of the corresponding
* scroll bar. If a scroll policy is <code>ScrollPolicy.AUTO</code>,
* the chrome measurement does not include the scroll bar thickness,
* even if a scroll bar is displayed.</p>
*
* <p>Subclasses of Container should override this method, so that
* they include other chrome to be taken into account when positioning
* the Container's children.
* For example, the <code>viewMetrics</code> property for the
* Panel class should return an object whose <code>top</code> property
* includes the thickness of the Panel container's title bar.</p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get viewMetrics():EdgeMetrics
{
var bm:EdgeMetrics = borderMetrics;
// If scrollPolicy is ScrollPolicy.ON, then the scrollbars are accounted for
// during both measurement and layout.
//
// If scrollPolicy is ScrollPolicy.AUTO, then scrollbars are ignored during
// measurement. Otherwise, the entire layout of the app could change
// everytime that the scrollbars turn on or off.
//
// However, we do take the width of scrollbars into account when laying
// out our children. That way, children that have a percentage width or
// percentage height will only expand to consume space that's left over
// after leaving room for the scrollbars.
var verticalScrollBarIncluded:Boolean = false;
/*verticalScrollBar != null &&
(doingLayout || verticalScrollPolicy == ScrollPolicy.ON);*/
var horizontalScrollBarIncluded:Boolean = false;
/*horizontalScrollBar != null &&
(doingLayout || horizontalScrollPolicy == ScrollPolicy.ON);*/
if (!verticalScrollBarIncluded && !horizontalScrollBarIncluded)
return bm;
// The viewMetrics property needs to return its own object.
// Rather than allocating a new one each time, we'll allocate one once
// and then hold a reference to it.
if (!_viewMetrics)
{
_viewMetrics = bm.clone();
}
else
{
_viewMetrics.left = bm.left;
_viewMetrics.right = bm.right;
_viewMetrics.top = bm.top;
_viewMetrics.bottom = bm.bottom;
}
if (verticalScrollBarIncluded)
_viewMetrics.right;// += verticalScrollBar.minWidth;
if (horizontalScrollBarIncluded)
_viewMetrics.bottom;// += horizontalScrollBar.minHeight;
return _viewMetrics;
}
//----------------------------------
// viewMetricsAndPadding
//----------------------------------
/**
* @private
* Cached value containing the view metrics plus the object's margins.
*/
private var _viewMetricsAndPadding:EdgeMetrics;
/**
* Returns an object that has four properties: <code>left</code>,
* <code>top</code>, <code>right</code>, and <code>bottom</code>.
* The value of each property is equal to the thickness of the chrome
* (visual elements)
* around the edge of the container plus the thickness of the object's margins.
*
* <p>The chrome includes the border thickness.
* If the <code>horizontalScrollPolicy</code> or <code>verticalScrollPolicy</code>
* property value is <code>ScrollPolicy.ON</code>, the
* chrome also includes the thickness of the corresponding
* scroll bar. If a scroll policy is <code>ScrollPolicy.AUTO</code>,
* the chrome measurement does not include the scroll bar thickness,
* even if a scroll bar is displayed.</p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get viewMetricsAndPadding():EdgeMetrics
{
// If this object has scrollbars, and if the verticalScrollPolicy
// is not ScrollPolicy.ON, then the view metrics change
// depending on whether we're doing layout or not.
// In that case, we can't use a cached value.
// In all other cases, use the cached value if it exists.
if (_viewMetricsAndPadding &&
(horizontalScrollPolicy == ScrollPolicy.ON) &&
(verticalScrollPolicy == ScrollPolicy.ON))
{
return _viewMetricsAndPadding;
}
if (!_viewMetricsAndPadding)
_viewMetricsAndPadding = new EdgeMetrics();
var o:EdgeMetrics = _viewMetricsAndPadding;
var vm:EdgeMetrics = viewMetrics;
o.left = vm.left + getStyle("paddingLeft");
o.right = vm.right + getStyle("paddingRight");
o.top = vm.top + getStyle("paddingTop");
o.bottom = vm.bottom + getStyle("paddingBottom");
return o;
}
//--------------------------------------------------------------------------
//
// Overridden methods: EventDispatcher
//
//--------------------------------------------------------------------------
/**
* @private
* If we add a mouse event, then we need to add a mouse shield
* to us and to all our children
* The mouseShield style is a non-inheriting style
* that is used by the view.
* The mouseShieldChildren style is an inherting style
* that is used by the children views.
override public function addEventListener(
type:String, listener:Function,
useCapture:Boolean = false,
priority:int = 0,
useWeakReference:Boolean = false):void
{
super.addEventListener(type, listener, useCapture,
priority, useWeakReference);
// If we are a mouse event, then create a mouse shield.
if (type == MouseEvent.CLICK ||
type == MouseEvent.DOUBLE_CLICK ||
type == MouseEvent.MOUSE_DOWN ||
type == MouseEvent.MOUSE_MOVE ||
type == MouseEvent.MOUSE_OVER ||
type == MouseEvent.MOUSE_OUT ||
type == MouseEvent.MOUSE_UP ||
type == MouseEvent.MOUSE_WHEEL)
{
if (mouseEventReferenceCount < 0x7FFFFFFF // int_max
&& mouseEventReferenceCount++ == 0)
{
setStyle("mouseShield", true);
setStyle("mouseShieldChildren", true);
}
}
}
*/
/**
* @private
* We're doing special behavior on addEventListener to make sure that
* we successfully capture mouse events, even when there's no background.
* However, this means adding an event listener changes the behavior
* a little, and this can be troublesome for overlapping components
* that now don't get any mouse events. This is acceptable normally;
* however, automation adds certain events to the Container, and
* it'd be better if automation support didn't modify the behavior of
* the component. For this reason, especially, we have an mx_internal
* $addEventListener to add event listeners without affecting the behavior
* of the component.
mx_internal function $addEventListener(
type:String, listener:Function,
useCapture:Boolean = false,
priority:int = 0,
useWeakReference:Boolean = false):void
{
super.addEventListener(type, listener, useCapture,
priority, useWeakReference);
}
*/
/**
* @private
* Remove the mouse shield if we no longer listen to any mouse events
override public function removeEventListener(
type:String, listener:Function,
useCapture:Boolean = false):void
{
super.removeEventListener(type, listener, useCapture);
// If we are a mouse event,
// then decrement the mouse shield reference count.
if (type == MouseEvent.CLICK ||
type == MouseEvent.DOUBLE_CLICK ||
type == MouseEvent.MOUSE_DOWN ||
type == MouseEvent.MOUSE_MOVE ||
type == MouseEvent.MOUSE_OVER ||
type == MouseEvent.MOUSE_OUT ||
type == MouseEvent.MOUSE_UP ||
type == MouseEvent.MOUSE_WHEEL)
{
if (mouseEventReferenceCount > 0 &&
--mouseEventReferenceCount == 0)
{
setStyle("mouseShield", false);
setStyle("mouseShieldChildren", false);
}
}
}
*/
/**
* @private
* We're doing special behavior on removeEventListener to make sure that
* we successfully capture mouse events, even when there's no background.
* However, this means removing an event listener changes the behavior
* a little, and this can be troublesome for overlapping components
* that now don't get any mouse events. This is acceptable normally;
* however, automation adds certain events to the Container, and
* it'd be better if automation support didn't modify the behavior of
* the component. For this reason, especially, we have an mx_internal
* $removeEventListener to remove event listeners without affecting the behavior
* of the component.
mx_internal function $removeEventListener(
type:String, listener:Function,
useCapture:Boolean = false):void
{
super.removeEventListener(type, listener, useCapture);
}
*/
//--------------------------------------------------------------------------
//
// Overridden methods: DisplayObjectContainer
//
//--------------------------------------------------------------------------
/**
* Adds a child DisplayObject to this Container.
* The child is added after other existing children,
* so that the first child added has index 0,
* the next has index 1, an so on.
*
* <p><b>Note: </b>While the <code>child</code> argument to the method
* is specified as of type DisplayObject, the argument must implement
* the IUIComponent interface to be added as a child of a container.
* All Flex components implement this interface.</p>
*
* <p>Children are layered from back to front.
* In other words, if children overlap, the one with index 0
* is farthest to the back, and the one with index
* <code>numChildren - 1</code> is frontmost.
* This means the newly added children are layered
* in front of existing children.</p>
*
* @param child The DisplayObject to add as a child of this Container.
* It must implement the IUIComponent interface.
*
* @return The added child as an object of type DisplayObject.
* You typically cast the return value to UIComponent,
* or to the type of the added component.
*
* @see mx.core.IUIComponent
*
* @tiptext Adds a child object to this container.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[SWFOverride(params="flash.display.DisplayObject", altparams="mx.core.UIComponent", returns="flash.display.DisplayObject"))]
override public function addChild(child:IUIComponent):IUIComponent
{
return addChildAt(child, numChildren);
/* Application and Panel are depending on addChild calling addChildAt */
/*
addingChild(child);
if (contentPane)
contentPane.addChild(child);
else
$addChild(child);
childAdded(child);
return child;
*/
}
/**
* Adds a child DisplayObject to this Container.
* The child is added at the index specified.
*
* <p><b>Note: </b>While the <code>child</code> argument to the method
* is specified as of type DisplayObject, the argument must implement
* the IUIComponent interface to be added as a child of a container.
* All Flex components implement this interface.</p>
*
* <p>Children are layered from back to front.
* In other words, if children overlap, the one with index 0
* is farthest to the back, and the one with index
* <code>numChildren - 1</code> is frontmost.
* This means the newly added children are layered
* in front of existing children.</p>
*
* <p>When you add a new child at an index that is already occupied
* by an old child, it doesn't replace the old child; instead the
* old child and the ones after it "slide over" and have their index
* incremented by one.
* For example, suppose a Container contains the children
* (A, B, C) and you add D at index 1.
* Then the container will contain (A, D, B, C).
* If you want to replace an old child, you must first remove it
* before adding the new one.</p>
*
* @param child The DisplayObject to add as a child of this Container.
* It must implement the IUIComponent interface.
*
* @param index The index to add the child at.
*
* @return The added child as an object of type DisplayObject.
* You typically cast the return value to UIComponent,
* or to the type of the added component.
*
* @see mx.core.IUIComponent
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[SWFOverride(params="flash.display.DisplayObject,int", altparams="mx.core.UIComponent,int", returns="flash.display.DisplayObject"))]
override public function addChildAt(child:IUIComponent,
index:int):IUIComponent
{
var formerParent:UIComponent = child.parent as UIComponent;
if (formerParent /* && !(formerParent is Loader)*/)
{
// Adjust index if necessary when former parent happens
// to be the same container.
if (formerParent == this)
index = (index == numChildren) ? index - 1 : index;
formerParent.removeChild(child);
}
addingChild(child);
// Add the child to either this container or its contentPane.
// The player will dispatch an "added" event from the child
// after it has been added, so all "added" handlers execute here.
if (contentPane)
contentPane.addChildAt(child, index);
else
$uibase_addChildAt(child, _firstChildIndex + index);
childAdded(child);
//if ((child is UIComponent) && UIComponent(child).isDocument)
// BindingManager.setEnabled(child, true);
return child;
}
/**
* Removes a child DisplayObject from the child list of this Container.
* The removed child will have its <code>parent</code>
* property set to null.
* The child will still exist unless explicitly destroyed.
* If you add it to another container,
* it will retain its last known state.
*
* @param child The DisplayObject to remove.
*
* @return The removed child as an object of type DisplayObject.
* You typically cast the return value to UIComponent,
* or to the type of the removed component.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[SWFOverride(params="flash.display.DisplayObject", altparams="mx.core.UIComponent", returns="flash.display.DisplayObject"))]
override public function removeChild(child:IUIComponent):IUIComponent
{
/*
if (child is IDeferredInstantiationUIComponent &&
IDeferredInstantiationUIComponent(child).descriptor)
{
// if child's descriptor is present, it means child was created
// with MXML. Need to go through and remove component in
// createdComponents so there is no memory leak by keeping
// a reference to the removed child (SDK-12506)
if (createdComponents)
{
var n:int = createdComponents.length;
for (var i:int = 0; i < n; i++)
{
if (createdComponents[i] === child)
{
// delete this reference
createdComponents.splice(i, 1);
}
}
}
}
*/
removingChild(child);
//if ((child is UIComponent) && UIComponent(child).isDocument)
// BindingManager.setEnabled(child, false);
// Remove the child from either this container or its contentPane.
// The player will dispatch a "removed" event from the child
// before it is removed, so all "removed" handlers execute here.
if (contentPane)
contentPane.removeChild(child);
else
$uibase_removeChild(child);
childRemoved(child);
return child;
}
/**
* Removes a child DisplayObject from the child list of this Container
* at the specified index.
* The removed child will have its <code>parent</code>
* property set to null.
* The child will still exist unless explicitly destroyed.
* If you add it to another container,
* it will retain its last known state.
*
* @param index The child index of the DisplayObject to remove.
*
* @return The removed child as an object of type DisplayObject.
* You typically cast the return value to UIComponent,
* or to the type of the removed component.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[SWFOverride(returns="flash.display.DisplayObject"))]
override public function removeChildAt(index:int):IUIComponent
{
return removeChild(getChildAt(index));
/*
Shouldn't implement removeChildAt() in terms of removeChild().
If we change this ViewStack IList, Application, and Panel are depending on it
*/
}
/**
* Gets the <i>n</i>th child component object.
*
* <p>The children returned from this method include children that are
* declared in MXML and children that are added using the
* <code>addChild()</code> or <code>addChildAt()</code> method.</p>
*
* @param childIndex Number from 0 to (numChildren - 1).
*
* @return Reference to the child as an object of type DisplayObject.
* You typically cast the return value to UIComponent,
* or to the type of a specific Flex control, such as ComboBox or TextArea.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[SWFOverride(returns="flash.display.DisplayObject"))]
override public function getChildAt(index:int):IUIComponent
{
if (contentPane)
{
return contentPane.getChildAt(index);
}
else
{
// The DisplayObjectContainer implementation of getChildAt()
// in the Player throws this error if the index is bad,
// so we should too.
// if (index < 0 || index >= _numChildren)
// throw new RangeError("The supplied index is out of bounds");
return super.getChildAt(_firstChildIndex + index);
}
}
/**
* Returns the child whose <code>name</code> property is the specified String.
*
* @param name The identifier of the child.
*
* @return The DisplayObject representing the child as an object of type DisplayObject.
* You typically cast the return value to UIComponent,
* or to the type of a specific Flex control, such as ComboBox or TextArea.
* Throws a run-time error if the child of the specified name does not exist.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[SWFOverride(returns="flash.display.DisplayObject"))]
override public function getChildByName(name:String):IUIComponent
{
if (contentPane)
{
return contentPane.getChildByName(name);
}
else
{
var child:IUIComponent = super.getChildByName(name);
if (!child)
return null;
// Check if the child is in the index range for content children.
var index:int = super.getChildIndex(child) - _firstChildIndex;
if (index < 0 || index >= _numChildren)
return null;
return child;
}
}
/**
* Gets the zero-based index of a specific child.
*
* <p>The first child of the container (i.e.: the first child tag
* that appears in the MXML declaration) has an index of 0,
* the second child has an index of 1, and so on.
* The indexes of a container's children determine
* the order in which they get laid out.
* For example, in a VBox the child with index 0 is at the top,
* the child with index 1 is below it, etc.</p>
*
* <p>If you add a child by calling the <code>addChild()</code> method,
* the new child's index is equal to the largest index among existing
* children plus one.
* You can insert a child at a specified index by using the
* <code>addChildAt()</code> method; in that case the indices of the
* child previously at that index, and the children at higher indices,
* all have their index increased by 1 so that all indices fall in the
* range from 0 to <code>(numChildren - 1)</code>.</p>
*
* <p>If you remove a child by calling <code>removeChild()</code>
* or <code>removeChildAt()</code> method, then the indices of the
* remaining children are adjusted so that all indices fall in the
* range from 0 to <code>(numChildren - 1)</code>.</p>
*
* <p>If <code>myView.getChildIndex(myChild)</code> returns 5,
* then <code>myView.getChildAt(5)</code> returns myChild.</p>
*
* <p>The index of a child may be changed by calling the
* <code>setChildIndex()</code> method.</p>
*
* @param child Reference to child whose index to get.
*
* @return Number between 0 and (numChildren - 1).
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[SWFOverride(params="flash.display.DisplayObject", altparams="mx.core.UIComponent"))]
override public function getChildIndex(child:IUIComponent):int
{
if (contentPane)
{
return contentPane.getChildIndex(child);
}
else
{
var index:int = super.getChildIndex(child) - _firstChildIndex;
// The DisplayObjectContainer implementation of getChildIndex()
// in the Player throws this error if the child isn't a child,
// so we should too.
// if (index < 0 || index >= _numChildren)
// throw new /*Argument*/Error("The DisplayObject supplied must be a child of the caller.");
return index;
}
}
/**
* Sets the index of a particular child.
* See the <code>getChildIndex()</code> method for a
* description of the child's index.
*
* @param child Reference to child whose index to set.
*
* @param newIndex Number that indicates the new index.
* Must be an integer between 0 and (numChildren - 1).
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[SWFOverride(params="flash.display.DisplayObject,int", altparams="mx.core.UIComponent,int"))]
override public function setChildIndex(child:IUIComponent, newIndex:int):void
{
var oldIndex:int;
var eventOldIndex:int = oldIndex;
var eventNewIndex:int = newIndex;
if (contentPane)
{
contentPane.setChildIndex(child, newIndex);
if (_autoLayout || forceLayout)
invalidateDisplayList();
}
else
{
oldIndex = super.getChildIndex(child);
// Offset the index, to leave room for skins before the list of children
newIndex += _firstChildIndex;
if (newIndex == oldIndex)
return;
// Change the child's index, shifting around other children to make room
super.setChildIndex(child, newIndex);
invalidateDisplayList();
eventOldIndex = oldIndex - _firstChildIndex;
eventNewIndex = newIndex - _firstChildIndex;
}
// Notify others that the child index has changed
var event:IndexChangedEvent = new IndexChangedEvent(IndexChangedEvent.CHILD_INDEX_CHANGE);
event.relatedObject = child;
event.oldIndex = eventOldIndex;
event.newIndex = eventNewIndex;
dispatchEvent(event);
dispatchEvent(new Event("childrenChanged"));
}
/**
* @private
*/
[SWFOverride(params="flash.display.DisplayObject", altparams="mx.core.UIComponent"))]
override public function contains(child:IUIBase):Boolean
{
if (contentPane)
return contentPane.contains(child);
else
return super.contains(child);
}
//--------------------------------------------------------------------------
//
// Methods: IVisualElementContainer
//
//--------------------------------------------------------------------------
/**
* @copy mx.core.IVisualElementContainer#numElements
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
public function get numElements():int
{
return numChildren;
}
*/
/**
* @copy mx.core.IVisualElementContainer#getElementAt()
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
public function getElementAt(index:int):IVisualElement
{
return getChildAt(index) as IVisualElement;
}
*/
/**
* @copy mx.core.IVisualElementContainer#getElementIndex()
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
public function getElementIndex(element:IVisualElement):int
{
if (! (element is IUIComponent) )
throw Error(element + " is not found in this Container");
// throw Error(element + " is not found in this Container");
return getChildIndex(element as IUIComponent);
}
*/
/**
* @copy mx.core.IVisualElementContainer#addElement()
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
public function addElement(element:IVisualElement):IVisualElement
{
if (! (element is IUIComponent) )
throw Error(element + " is not supported in this Container");
// throw Error(element + " is not supported in this Container");
return addChild(element as IUIComponent) as IVisualElement;
}
*/
/**
* @copy mx.core.IVisualElementContainer#addElementAt()
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
public function addElementAt(element:IVisualElement, index:int):IVisualElement
{
if (! (element is IUIComponent) )
throw Error(element + " is not supported in this Container");
// throw Error(element + " is not supported in this Container");
return addChildAt(element as IUIComponent, index) as IVisualElement;
}
*/
/**
* @copy mx.core.IVisualElementContainer#removeElement()
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
public function removeElement(element:IVisualElement):IVisualElement
{
throw Error(element + " is not found in this Container");
// throw Error(element + " is not found in this Container");
return removeChild(element as IUIComponent) as IVisualElement;
}
*/
/**
* @copy mx.core.IVisualElementContainer#removeElementAt()
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
public function removeElementAt(index:int):IVisualElement
{
return removeChildAt(index) as IVisualElement;
}
*/
/**
* @copy mx.core.IVisualElementContainer#removeAllElements()
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
public function removeAllElements():void
{
for (var i:int = numElements - 1; i >= 0; i--)
{
removeElementAt(i);
}
}
*/
/**
* @copy mx.core.IVisualElementContainer#setElementIndex()
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function setElementIndex(element:IVisualElement, index:int):void
{
if (! (element is IUIComponent) )
throw /*Argument*/Error(element + " is not found in this Container");
return setChildIndex(element as IUIComponent, index);
}
/**
* @copy mx.core.IVisualElementContainer#swapElements()
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function swapElements(element1:IVisualElement, element2:IVisualElement):void
{
if (! (element1 is IUIComponent) )
throw /*Argument*/Error(element1 + " is not found in this Container");
if (! (element2 is IUIComponent) )
throw /*Argument*/Error(element2 + " is not found in this Container");
//swapChildren(element1 as IUIComponent, element2 as IUIComponent);
}
/**
* @copy mx.core.IVisualElementContainer#swapElementsAt()
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function swapElementsAt(index1:int, index2:int):void
{
trace("Legend:swapElemetsAt not implemented");
//swapChildrenAt(index1, index2);
}
//--------------------------------------------------------------------------
//
// Overridden methods: UIComponent
//
//--------------------------------------------------------------------------
/**
* @private
override public function initialize():void
{
// Until component templating is implemented, the childDescriptors
// come either from the top-level descriptor in the component itself
// (i.e., the defined children) or from a descriptor for an instance
// of that component in some other component or app (i.e., the
// instance children). At this point _childDescriptors already
// contains the instance children if there are any; but if the
// document defines any children, we have to use them instead.
if (documentDescriptor && !processedDescriptors)
{
// NOTE: documentDescriptor.properties is a potentially
// expensive function call, so do it only once.
var props:* = documentDescriptor.properties;
if (props && props.childDescriptors)
{
if (_childDescriptors)
{
var message:String = resourceManager.getString(
"core", "multipleChildSets_ClassAndInstance");
throw new Error(message);
}
else
{
_childDescriptors = props.childDescriptors;
}
}
}
super.initialize();
}
*/
/**
* @private
* Create components that are children of this Container.
override protected function createChildren():void
{
super.createChildren();
// Create the border/background object.
createBorder();
// Determine the child-creation policy (ContainerCreationPolicy.AUTO,
// ContainerCreationPolicy.ALL, or ContainerCreationPolicy.NONE).
// If the author has specified a policy, use it.
// Otherwise, use the parent's policy.
// This must be set before createChildren() gets called.
if (actualCreationPolicy == null)
{
if (creationPolicy != null)
actualCreationPolicy = creationPolicy;
if (actualCreationPolicy == ContainerCreationPolicy.QUEUED)
actualCreationPolicy = ContainerCreationPolicy.AUTO;
}
// It is ok for actualCreationPolicy to be null. Popups require it.
if (actualCreationPolicy == ContainerCreationPolicy.NONE)
{
actualCreationPolicy = ContainerCreationPolicy.AUTO;
}
else if (actualCreationPolicy == ContainerCreationPolicy.QUEUED)
{
var mainApp:* = parentApplication ?
parentApplication :
FlexGlobals.topLevelApplication;
if ("addToCreationQueue" in mainApp)
mainApp.addToCreationQueue(this, _creationIndex, null, this);
else // If the app doesn't support queued creation, create our components now
createComponentsFromDescriptors();
}
else if (recursionFlag)
{
// Create whatever children are appropriate. If any were
// previously created, they don't get re-created.
createComponentsFromDescriptors();
}
// If autoLayout is initially false, we still want to do
// measurement once (even if we don't have any children)
if (autoLayout == false)
forceLayout = true;
// weak references
//UIComponentGlobals.layoutManager.addEventListener(
// FlexEvent.UPDATE_COMPLETE, layoutCompleteHandler, false, 0, true);
}
*/
/**
* @private
* Override to NOT set precessedDescriptors.
*/
override protected function initializationComplete():void
{
// Don't call super.initializationComplete().
}
/**
* @private
override public function invalidateLayoutDirection():void
{
super.invalidateLayoutDirection();
// We have to deal with non-styled raw children here.
if (_rawChildren)
{
const rawNumChildren:int = _rawChildren.numChildren;
for (var i:int = 0; i < rawNumChildren; i++)
{
var child:IUIComponent = _rawChildren.getChildAt(i);
if (!(child is IStyleClient) && child is ILayoutDirectionElement)
ILayoutDirectionElement(child).invalidateLayoutDirection();
}
}
}
*/
/**
* @private
*/
override protected function commitProperties():void
{
super.commitProperties();
if (changedStyles)
{
// If multiple properties have changed, set styleProp to null.
// Otherwise, set it to the name of the style that has changed.
var styleProp:String = changedStyles == MULTIPLE_PROPERTIES ?
null :
changedStyles;
//super.notifyStyleChangeInChildren(styleProp, true);
changedStyles = null;
}
createOrDestroyBlocker();
if (_childrenDirty)
{
populateFromArray(_dataProvider);
_childrenDirty = false;
}
}
/**
* @private
*/
override public function validateSize(recursive:Boolean = false):void
{
// If autoLayout is turned off and we haven't recently created
// or destroyed any children, then we're not doing any
// measurement or layout.
// Return false indicating that the measurements haven't changed.
if (autoLayout == false && forceLayout == false)
{
if (recursive)
{
var n:int = super.numChildren;
for (var i:int = 0; i < n; i++)
{
var child:IUIComponent = super.getChildAt(i);
if (child is ILayoutManagerClient )
ILayoutManagerClient (child).validateSize(true);
}
}
//adjustSizesForScaleChanges();
}
else
{
super.validateSize(recursive);
}
}
/**
* @private
*/
override public function validateDisplayList():void
{
// trace(">>Container validateLayoutPhase " + this);
var vm:EdgeMetrics;
// If autoLayout is turned off and we haven't recently created or
// destroyed any children, then don't do any layout
if (_autoLayout || forceLayout)
{
doingLayout = true;
super.validateDisplayList();
doingLayout = false;
}
else
{
// Layout borders, Panel headers, and other border chrome.
layoutChrome(unscaledWidth, unscaledHeight);
}
// Set this to block requeuing when sizing children.
//invalidateDisplayListFlag = true;
// Based on the positions of the children, determine
// whether a clip mask and scrollbars are needed.
if (createContentPaneAndScrollbarsIfNeeded())
{
// Redo layout if scrollbars just got created or destroyed (because
// now we may have more or less space).
if (_autoLayout || forceLayout)
{
doingLayout = true;
super.validateDisplayList();
doingLayout = false;
}
// If a scrollbar was created, that may precipitate the need
// for a second scrollbar, so run it a second time.
createContentPaneAndScrollbarsIfNeeded();
}
// The relayout performed by the above calls
// to super.validateDisplayList() may result
// in new max scroll positions that are less
// than previously-set scroll positions.
// For example, when a maximally-scrolled container
// is resized to be larger, the new max scroll positions
// are reduced and the current scroll positions
// will be invalid unless we clamp them.
if (clampScrollPositions())
scrollChildren();
if (contentPane)
{
vm = viewMetrics;
/*
// Set the position and size of the overlay .
if (effectOverlay)
{
effectOverlay.x = 0;
effectOverlay.y = 0;
effectOverlay.width = unscaledWidth;
effectOverlay.height = unscaledHeight;
}
*/
// Set the positions and sizes of the scrollbars.
/*if (horizontalScrollBar || verticalScrollBar)
{
// Get the view metrics and remove the thickness
// of the scrollbars from the view metrics.
// We can't simply get the border metrics,
// because some subclass (e.g.: Window)
// might add to the metrics.
if (verticalScrollBar &&
verticalScrollPolicy == ScrollPolicy.ON)
{
vm.right -= verticalScrollBar.minWidth;
}
if (horizontalScrollBar &&
horizontalScrollPolicy == ScrollPolicy.ON)
{
vm.bottom -= horizontalScrollBar.minHeight;
}
if (horizontalScrollBar)
{
var w:Number = unscaledWidth - vm.left - vm.right;
if (verticalScrollBar)
w -= verticalScrollBar.minWidth;
horizontalScrollBar.setActualSize(
w, horizontalScrollBar.minHeight);
horizontalScrollBar.move(vm.left,
unscaledHeight - vm.bottom -
horizontalScrollBar.minHeight);
}
if (verticalScrollBar)
{
var h:Number = unscaledHeight - vm.top - vm.bottom;
if (horizontalScrollBar)
h -= horizontalScrollBar.minHeight;
verticalScrollBar.setActualSize(
verticalScrollBar.minWidth, h);
verticalScrollBar.move(unscaledWidth - vm.right -
verticalScrollBar.minWidth,
vm.top);
}
// Set the position of the box
// that covers the gap between the scroll bars.
if (whiteBox)
{
whiteBox.x = verticalScrollBar.x;
whiteBox.y = horizontalScrollBar.y;
}
}*/
contentPane.x = vm.left;
contentPane.y = vm.top;
/*
if (focusPane)
{
focusPane.x = vm.left
focusPane.y = vm.top;
}
*/
scrollChildren();
}
//invalidateDisplayListFlag = false;
// that blocks UI input as well as draws an alpha overlay.
// Make sure the blocker is correctly positioned and sized here.
if (blocker)
{
vm = viewMetrics;
//if (FlexVersion.compatibilityVersion >= FlexVersion.VERSION_4_0)
vm = EdgeMetrics.EMPTY;
var bgColor:Object = enabled ?
null :
getStyle("backgroundDisabledColor");
if (bgColor === null || isNaN(Number(bgColor)))
bgColor = getStyle("backgroundColor");
if (bgColor === null || isNaN(Number(bgColor)))
bgColor = 0xFFFFFF;
var blockerAlpha:Number = getStyle("disabledOverlayAlpha");
if (isNaN(blockerAlpha))
blockerAlpha = 0.6;
blocker.x = vm.left;
blocker.y = vm.top;
var widthToBlock:Number = unscaledWidth - (vm.left + vm.right);
var heightToBlock:Number = unscaledHeight - (vm.top + vm.bottom);
blocker.graphics.clear();
blocker.graphics.beginFill(uint(bgColor), blockerAlpha);
blocker.graphics.drawRect(0, 0, widthToBlock, heightToBlock);
blocker.graphics.endFill();
// Blocker must be in front of everything
rawChildren.setChildIndex(blocker, rawChildren.numChildren - 1);
}
// trace("<<Container internalValidateDisplayList " + this);
}
/**
* Respond to size changes by setting the positions and sizes
* of this container's children.
*
* <p>See the <code>UIComponent.updateDisplayList()</code> method for more information
* about the <code>updateDisplayList()</code> method.</p>
*
* <p>The <code>Container.updateDisplayList()</code> method sets the position
* and size of the Container container's border.
* In every subclass of Container, the subclass's <code>updateDisplayList()</code>
* method should call the <code>super.updateDisplayList()</code> method,
* so that the border is positioned properly.</p>
*
* @param unscaledWidth Specifies the width of the component, in pixels,
* in the component's coordinates, regardless of the value of the
* <code>scaleX</code> property of the component.
*
* @param unscaledHeight Specifies the height of the component, in pixels,
* in the component's coordinates, regardless of the value of the
* <code>scaleY</code> property of the component.
*
* @see mx.core.UIComponent
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
override protected function updateDisplayList(unscaledWidth:Number,
unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
layoutChrome(unscaledWidth, unscaledHeight);
if (scrollPositionChanged)
{
clampScrollPositions();
scrollChildren();
scrollPositionChanged = false;
}
/*
if (contentPane && contentPane.scrollRect)
{
// Draw content pane
var backgroundColor:Object = enabled ?
null :
getStyle("backgroundDisabledColor");
if (backgroundColor === null || isNaN(Number(backgroundColor)))
backgroundColor = getStyle("backgroundColor");
var backgroundAlpha:Number = getStyle("backgroundAlpha");
if (!_clipContent ||
isNaN(Number(backgroundColor)) ||
backgroundColor === "" ||
(!cacheAsBitmap))
{
backgroundColor = null;
}
// If there's a backgroundImage or background, unset
// opaqueBackground.
else if (getStyle("backgroundImage") ||
getStyle("background"))
{
backgroundColor = null;
}
// If the background is not opaque, unset opaqueBackground.
else if (backgroundAlpha != 1)
{
backgroundColor = null;
}
contentPane.opaqueBackground = backgroundColor;
// Set cacheAsBitmap only if opaqueBackground is also set (to avoid
// text anti-aliasing issue with device text on Windows).
contentPane.cacheAsBitmap = (backgroundColor != null);
}
*/
// The measure function isn't called if the width and height of
// the Tile are hard-coded. In that case, we compute the cellWidth
// and cellHeight now.
if (isNaN(cellWidth) || isNaN(cellHeight))
findCellSize();
var vm:EdgeMetrics = viewMetricsAndPadding;
var paddingLeft:Number = getStyle("paddingLeft");
var paddingTop:Number = getStyle("paddingTop");
var horizontalGap:Number = getStyle("horizontalGap");
var verticalGap:Number = getStyle("verticalGap");
var horizontalAlign:String = getStyle("horizontalAlign");
var verticalAlign:String = getStyle("verticalAlign");
var xPos:Number = paddingLeft;
var yPos:Number = paddingTop;
var xOffset:Number;
var yOffset:Number;
var n:int = numChildren;
var i:int;
var child:IUIComponent;
if (direction == "horizontal")
{
var xEnd:Number = Math.ceil(unscaledWidth) - vm.right;
for (i = 0; i < n; i++)
{
child = getLayoutChildAt(i);
if (!child.includeInLayout)
continue;
// Start a new row?
if (xPos + cellWidth > xEnd)
{
// Only if we have not just started one...
if (xPos != paddingLeft)
{
yPos += (cellHeight + verticalGap);
xPos = paddingLeft;
}
}
setChildSize(child); // calls child.setActualSize()
// Calculate the offsets to align the child in the cell.
xOffset = Math.floor(calcHorizontalOffset(
child.width, horizontalAlign));
yOffset = Math.floor(calcVerticalOffset(
child.height, verticalAlign));
child.move(xPos + xOffset, yPos + yOffset);
xPos += (cellWidth + horizontalGap);
}
}
else
{
var yEnd:Number = Math.ceil(unscaledHeight) - vm.bottom;
for (i = 0; i < n; i++)
{
child = getLayoutChildAt(i);
if (!child.includeInLayout)
continue;
// Start a new column?
if (yPos + cellHeight > yEnd)
{
// Only if we have not just started one...
if (yPos != paddingTop)
{
xPos += (cellWidth + horizontalGap);
yPos = paddingTop;
}
}
setChildSize(child); // calls child.setActualSize()
// Calculate the offsets to align the child in the cell.
xOffset = Math.floor(calcHorizontalOffset(
child.width, horizontalAlign));
yOffset = Math.floor(calcVerticalOffset(
child.height, verticalAlign));
child.move(xPos + xOffset, yPos + yOffset);
yPos += (cellHeight + verticalGap);
}
}
// Clear the cached cell size, because if a child's size changes
// it will be invalid. These cached values are only used to
// avoid recalculating in updateDisplayList() the same values
// that were just calculated in measure().
// They should not persist across invalidation/validation cycles.
// (An alternative approach we tried was to clear these
// values in an override of invalidateSize(), but this gets called
// called indirectly by setChildSize() and child.move() inside
// the loops above. So we had to save and restore cellWidth
// and cellHeight around these calls in the loops, which is ugly.)
cellWidth = NaN;
cellHeight = NaN;
_unscaledWidth = unscaledWidth;
_unscaledHeight = unscaledHeight;
// The measure function isn't called if the width and height of
// the Tile are hard-coded. In that case, we compute the cellWidth
// and cellHeight now.
if (isNaN(cellWidth))
findCellSize();
if (direction == "vertical")
layoutVertical();
else
layoutHorizontal();
}
/**
* @copy mx.core.UIComponent#contentToGlobal()
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
override public function contentToGlobal(point:Point):Point
{
if (contentPane)
return contentPane.localToGlobal(point);
return localToGlobal(point);
}
*/
/**
* @copy mx.core.UIComponent#globalToContent()
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
override public function globalToContent(point:Point):Point
{
if (contentPane)
return contentPane.globalToLocal(point);
return globalToLocal(point);
}
*/
/**
* @copy mx.core.UIComponent#contentToLocal()
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
override public function contentToLocal(point:Point):Point
{
if (!contentPane)
return point;
point = contentToGlobal(point);
return globalToLocal(point);
}
*/
/**
* @copy mx.core.UIComponent#localToContent()
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
override public function localToContent(point:Point):Point
{
if (!contentPane)
return point;
point = localToGlobal(point);
return globalToContent(point);
}
*/
/**
* @private
override public function styleChanged(styleProp:String):void
{
var allStyles:Boolean = styleProp == null || styleProp == "styleName";
// Check to see if this is one of the style properties that is known
// to affect page layout.
if (allStyles || styleManager.isSizeInvalidatingStyle(styleProp))
{
// Some styles, such as horizontalAlign and verticalAlign,
// affect the layout of this object's children without changing the
// view's size. This function forces the view to be remeasured
// and layed out.
invalidateDisplayList();
}
// Replace the borderSkin
if (allStyles || styleProp == "borderSkin")
{
if (border)
{
rawChildren.removeChild(IUIComponent(border));
border = null;
createBorder();
}
}
// Create a border object, if none previously existed and
// one is needed now.
if (allStyles ||
styleProp == "borderStyle" ||
styleProp == "backgroundColor" ||
styleProp == "backgroundImage" ||
styleProp == "mouseShield" ||
styleProp == "mouseShieldChildren")
{
createBorder();
}
super.styleChanged(styleProp);
// Check to see if this is one of the style properties that is known.
// to affect page layout.
if (allStyles ||
styleManager.isSizeInvalidatingStyle(styleProp))
{
invalidateViewMetricsAndPadding();
}
}
*/
/**
* @private
* Call the styleChanged method on children of this container
*
* Notify chrome children immediately, and recursively call this
* function for all descendants of the chrome children. We recurse
* regardless of the recursive flag because one of the descendants
* might have a styleName property that points to this object.
*
* If recursive is true, then also notify content children ... but
* do it later. Notification is deferred so that multiple calls to
* setStyle can be batched up into one traversal.
override public function notifyStyleChangeInChildren(
styleProp:String, recursive:Boolean):void
{
// Notify chrome children immediately, recursively calling this
// this function
var n:int = super.numChildren;
for (var i:int = 0; i < n; i++)
{
// Is this a chrome child?
if (contentPane ||
i < _firstChildIndex ||
i >= _firstChildIndex + _numChildren)
{
var child:ISimpleStyleClient = super.getChildAt(i) as ISimpleStyleClient;
if (child)
{
child.styleChanged(styleProp);
if (child is IStyleClient)
IStyleClient(child).notifyStyleChangeInChildren(styleProp, recursive);
}
}
}
// If recursive, then remember to notify the content children later
if (recursive)
{
// If multiple styleProps have changed, set changedStyles to
// MULTIPLE_PROPERTIES. Otherwise, set it to the name of the
// changed property.
changedStyles = (changedStyles != null || styleProp == null) ?
MULTIPLE_PROPERTIES : styleProp;
invalidateProperties();
}
}
*/
/**
* @private
override public function regenerateStyleCache(recursive:Boolean):void
{
super.regenerateStyleCache(recursive);
if (contentPane)
{
// Do the same thing as UIComponent, but don't check the child's index to
// ascertain that it's a content child (we already know that here).
var n:int = contentPane.numChildren;
for (var i:int = 0; i < n; i++)
{
var child:IUIComponent = getChildAt(i);
if (child is UIComponent)
{
// Does this object already have a proto chain? If not,
// there's no need to regenerate a new one.
if (UIComponent(child).inheritingStyles != StyleProtoChain.STYLE_UNINITIALIZED)
UIComponent(child).regenerateStyleCache(recursive);
}
else if (child is IUITextField && IUITextField(child).inheritingStyles)
{
StyleProtoChain.initTextField(IUITextField(child));
}
}
}
}
*/
/**
* Used internally by the Dissolve Effect to add the overlay to the chrome of a container.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
override protected function attachOverlay():void
{
rawChildren_addChild(effectOverlay);
}
*/
/**
* Fill an overlay object which is always the topmost child in the container.
* This method is used
* by the Dissolve effect; never call it directly. It is called
* internally by the <code>addOverlay()</code> method.
*
* The Container fills the overlay object so it covers the viewable area returned
* by the <code>viewMetrics</code> property and uses the <code>cornerRadius</code> style.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
override mx_internal function fillOverlay(overlay:UIComponent, color:uint,
targetArea:RoundedRectangle = null):void
{
var vm:EdgeMetrics = viewMetrics;
var cornerRadius:Number = 0; //getStyle("cornerRadius");
if (!targetArea)
{
targetArea = new RoundedRectangle(
vm.left, vm.top,
unscaledWidth - vm.right - vm.left,
unscaledHeight - vm.bottom - vm.top,cornerRadius);
}
if (isNaN(targetArea.x) || isNaN(targetArea.y) ||
isNaN(targetArea.width) || isNaN(targetArea.height) ||
isNaN(targetArea.cornerRadius))
return;
var g:Graphics = overlay.graphics;
g.clear();
g.beginFill(color);
g.drawRoundRect(targetArea.x, targetArea.y,
targetArea.width, targetArea.height,
targetArea.cornerRadius * 2,
targetArea.cornerRadius * 2);
g.endFill();
}
*/
/**
* Executes all the data bindings on this Container. Flex calls this method
* automatically once a Container has been created to cause any data bindings that
* have destinations inside of it to execute.
*
* Workaround for MXML container/bindings problem (177074):
* override Container.executeBindings() to prefer descriptor.document over parentDocument in the
* call to BindingManager.executeBindings().
*
* This should always provide the correct behavior for instances created by descriptor, and will
* provide the original behavior for procedurally-created instances. (The bug may or may not appear
* in the latter case.)
*
* A more complete fix, guaranteeing correct behavior in both non-DI and reparented-component
* scenarios, is anticipated for updater 1.
*
* @param recurse If <code>false</code>, then only execute the bindings
* on this Container.
* If <code>true</code>, then also execute the bindings on this
* container's children, grandchildren,
* great-grandchildren, and so on.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
override public function executeBindings(recurse:Boolean = false):void
{
var bindingsHost:Object = descriptor && descriptor.document ? descriptor.document : parentDocument;
BindingManager.executeBindings(bindingsHost, id, this);
if (recurse)
executeChildBindings(recurse);
}
*/
/**
* @private
* Prepare the Object for printing
*
* @see mx.printing.FlexPrintJob
override public function prepareToPrint(target:IFlexDisplayObject):Object
{
var rect:Rectangle = (contentPane && contentPane.scrollRect) ? contentPane.scrollRect : null;
if (rect)
contentPane.scrollRect = null;
super.prepareToPrint(target);
return rect;
}
*/
/**
* @private
* After printing is done
*
* @see mx.printing.FlexPrintJob
override public function finishPrint(obj:Object, target:IFlexDisplayObject):void
{
if (obj)
contentPane.scrollRect = Rectangle(obj);
super.finishPrint(obj,target);
}
*/
//--------------------------------------------------------------------------
//
// Methods: Child management
//
//--------------------------------------------------------------------------
/**
* @private
*/
override mx_internal function addingChild(child:IUIComponent):void
{
// Throw an RTE if child is not an IUIComponent.
var uiChild:IUIComponent = IUIComponent(child);
// Set the child's virtual parent, nestLevel, document, etc.
super.addingChild(child);
invalidateSize();
invalidateDisplayList();
if (!contentPane)
{
// If this is the first content child, then any chrome
// that already exists is positioned in front of it.
// If other content children already existed, then set the
// depth of this object to be just behind the existing
// content children.
if (_numChildren == 0)
_firstChildIndex = super.numChildren;
// Increment the number of content children.
_numChildren++;
}
if (contentPane && !autoLayout)
{
forceLayout = true;
// weak reference
//UIComponentGlobals.layoutManager.addEventListener(
// FlexEvent.UPDATE_COMPLETE, layoutCompleteHandler, false, 0, true);
}
}
/**
* @private
*/
override mx_internal function childAdded(child:IUIComponent):void
{
/*
if (hasEventListener("childrenChanged"))
dispatchEvent(new Event("childrenChanged"));
if (hasEventListener(ChildExistenceChangedEvent.CHILD_ADD))
{
var event:ChildExistenceChangedEvent =
new ChildExistenceChangedEvent(
ChildExistenceChangedEvent.CHILD_ADD);
event.relatedObject = child;
dispatchEvent(event);
}
if (hasEventListener(FlexEvent.ADD))
child.dispatchEvent(new FlexEvent(FlexEvent.ADD));
super.childAdded(child); // calls createChildren()
*/
}
/**
* @private
*/
override mx_internal function removingChild(child:IUIComponent):void
{
/*
super.removingChild(child);
if (hasEventListener(FlexEvent.REMOVE))
child.dispatchEvent(new FlexEvent(FlexEvent.REMOVE));
if (hasEventListener(ChildExistenceChangedEvent.CHILD_REMOVE))
{
var event:ChildExistenceChangedEvent =
new ChildExistenceChangedEvent(
ChildExistenceChangedEvent.CHILD_REMOVE);
event.relatedObject = child;
dispatchEvent(event);
}
*/
}
/**
* @private
*/
override mx_internal function childRemoved(child:IUIComponent):void
{
super.childRemoved(child);
invalidateSize();
invalidateDisplayList();
if (!contentPane)
{
_numChildren--;
if (_numChildren == 0)
_firstChildIndex = super.numChildren;
}
if (contentPane && !autoLayout)
{
forceLayout = true;
// weak reference
//UIComponentGlobals.layoutManager.addEventListener(
// FlexEvent.UPDATE_COMPLETE, layoutCompleteHandler, false, 0, true);
}
if (hasEventListener("childrenChanged"))
dispatchEvent(new Event("childrenChanged"));
}
[Bindable("childrenChanged")]
/**
* Returns an Array of DisplayObject objects consisting of the content children
* of the container.
* This array does <b>not</b> include the DisplayObjects that implement
* the container's display elements, such as its border and
* the background image.
*
* @return Array of DisplayObject objects consisting of the content children
* of the container.
*
* @see #rawChildren
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function getChildren():Array
{
var results:Array = [];
var n:int = numChildren;
for (var i:int = 0; i < n; i++)
{
results.push(getChildAt(i));
}
return results;
}
/**
* Removes all children from the child list of this container.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function removeAllChildren():void
{
while (numChildren > 0)
{
removeChildAt(0);
}
}
//--------------------------------------------------------------------------
//
// Methods: Deferred instantiation
//
//--------------------------------------------------------------------------
/**
* @private
* For containers, we need to ensure that at most one set of children
* has been specified for the component.
* There are two ways to specify multiple sets of children:
* a) the component itself, as well as an instance of the component,
* might specify children;
* b) both a base and derived component might specify children.
* Case (a) is handled in initialize(), above.
* Case (b) is handled here.
* This method is called in overrides of initialize()
* that are generated for MXML components.
*/
mx_internal function setDocumentDescriptor(/*desc:UIComponentDescriptor*/):void
{
/*
if (processedDescriptors)
return;
if (_documentDescriptor && _documentDescriptor.properties.childDescriptors)
{
if (desc.properties.childDescriptors)
{
var message:String = resourceManager.getString(
"core", "multipleChildSets_ClassAndSubclass");
throw new Error(message);
}
}
else
{
_documentDescriptor = desc;
_documentDescriptor.document = this;
}
*/
}
/**
* @private
* Used by subclasses, so must be public.
*/
mx_internal function setActualCreationPolicies(policy:String):void
{
/*
actualCreationPolicy = policy;
// Recursively set the actualCreationPolicy of all descendant
// containers which have an undefined creationPolicy.
var childPolicy:String = policy;
if (policy == ContainerCreationPolicy.QUEUED)
childPolicy = ContainerCreationPolicy.AUTO;
//trace("setActualCreationPolicies policy", policy, "childPolicy", childPolicy);
var n:int = numChildren;
for (var i:int = 0; i < n; i++)
{
var child:IFlexDisplayObject = IFlexDisplayObject(getChildAt(i));
*//*if (child is Container)
{
var childContainer:Container = Container(child);
if (childContainer.creationPolicy == null)
childContainer.setActualCreationPolicies(childPolicy);
}*//*
}*/
}
/**
* Iterate through the Array of <code>childDescriptors</code>,
* and call the <code>createComponentFromDescriptor()</code> method for each one.
*
* <p>If the value of the container's <code>creationPolicy</code> property is
* <code>ContainerCreationPolicy.ALL</code>, then this method is called
* automatically during the initialization sequence.</p>
*
* <p>If the value of the container's <code>creationPolicy</code> is
* <code>ContainerCreationPolicy.AUTO</code>,
* then this method is called automatically when the
* container's children are about to become visible.</p>
*
* <p>If the value of the container's <code>creationPolicy</code> property is
* <code>ContainerCreationPolicy.NONE</code>,
* then you should call this function
* when you want to create this container's children.</p>
*
* @param recurse If <code>true</code>, recursively
* create components.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
public function createComponentsFromDescriptors(
recurse:Boolean = true):void
{
numChildrenBefore = numChildren;
createdComponents = [];
var n:int = childDescriptors ? childDescriptors.length : 0;
for (var i:int = 0; i < n; i++)
{
var component:IFlexDisplayObject =
createComponentFromDescriptor(childDescriptors[i], recurse);
createdComponents.push(component);
}
if (creationPolicy == ContainerCreationPolicy.QUEUED ||
creationPolicy == ContainerCreationPolicy.NONE)
{
UIComponentGlobals.layoutManager.usePhasedInstantiation = false;
}
numChildrenCreated = numChildren - numChildrenBefore;
processedDescriptors = true;
dispatchEvent(new FlexEvent(FlexEvent.CONTENT_CREATION_COMPLETE));
}
*/
/**
* Performs the equivalent action of calling
* the <code>createComponentsFromDescriptors(true)</code> method for containers
* that implement the IDeferredContentOwner interface to support deferred instantiation.
*
* @see #createComponentsFromDescriptors()
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function createDeferredContent():void
{
//createComponentsFromDescriptors(true);
}
/**
* Given a single UIComponentDescriptor, create the corresponding
* component and add the component as a child of this container.
*
* <p>This method instantiates the new object but does not add it to the display list, so the object does not
* appear on the screen by default. To add the new object to the display list, call the <code>validateNow()</code>
* method on the container after calling the <code>createComponentFromDescriptor()</code> method,
* as the following example shows:
* <pre>
* myVBox.createComponentFromDescriptor(myVBox.childDescriptors[0],false);
* myVBox.validateNow();
* </pre>
* </p>
*
* <p>Alternatively, you can call the <code>createComponentsFromDescriptors()</code> method on the
* container to create all components at one time. You are not required to call the <code>validateNow()</code>
* method after calling the <code>createComponentsFromDescriptors()</code> method.</p>
*
* @param descriptor The UIComponentDescriptor for the
* component to be created. This argument is either a
* UIComponentDescriptor object or the index of one of the container's
* children (an integer between 0 and n-1, where n is the total
* number of children of this container).
*
* @param recurse If <code>false</code>, create this component
* but none of its children.
* If <code>true</code>, after creating the component, Flex calls
* the <code>createComponentsFromDescriptors()</code> method to create all or some
* of its children, based on the value of the component's <code>creationPolicy</code> property.
*
* @return The component that is created.
*
* @see mx.core.UIComponentDescriptor
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
public function createComponentFromDescriptor(
descriptor:ComponentDescriptor,
recurse:Boolean):IFlexDisplayObject
{
// If recurse is 'false', we create this component but none
// of its children.
// If recurse is 'true', after creating the component we call
// createComponentsFromDescriptors() to create all or some
// of its children, based on the component's
// actualContainerCreationPolicy.
var childDescriptor:UIComponentDescriptor =
UIComponentDescriptor(descriptor);
var childProperties:Object = childDescriptor.properties;
// This function could be asked to create the same child component
// twice. That's fine if the child component is inside a repeater.
// In other cases, though, we want to avoid creating the same child
// twice.
//
// The hasChildMatchingDescriptor function is a bit expensive, so
// we try to avoid calling it if we know we're inside the first call
// to createComponents.
if ((numChildrenBefore != 0 || numChildrenCreated != -1) &&
childDescriptor.instanceIndices == null &&
hasChildMatchingDescriptor(childDescriptor))
{
return null;
}
// Turn on the three-frame instantiation scheme.
UIComponentGlobals.layoutManager.usePhasedInstantiation = true;
// Create the new child object and give it a unique name
var childType:Class = childDescriptor.type;
var child:IDeferredInstantiationUIComponent = new childType();
child.id = childDescriptor.id;
if (child.id && child.id != "")
child.name = child.id;
// Copy property values from the descriptor
// to the newly created component.
child.descriptor = childDescriptor;
if (childProperties.childDescriptors && child is IContainer && (child as Object).hasOwnProperty("_childDescriptors"))
{
(child as Object)._childDescriptors =
childProperties.childDescriptors;
delete childProperties.childDescriptors;
}
for (var p:String in childProperties)
{
child[p] = childProperties[p];
}
// Set a flag indicating whether we should call
// this function recursively.
if (child is IContainer && (child as Object).hasOwnProperty("recursionFlag"))
(child as Object).recursionFlag = recurse;
if (childDescriptor.instanceIndices)
{
if (child is IRepeaterClient)
{
var rChild:IRepeaterClient = IRepeaterClient(child);
rChild.instanceIndices = childDescriptor.instanceIndices;
rChild.repeaters = childDescriptor.repeaters;
rChild.repeaterIndices = childDescriptor.repeaterIndices;
}
}
if (child is IStyleClient)
{
var scChild:IStyleClient = IStyleClient(child);
// Initialize the CSSStyleDeclaration.
// It is used by initProtoChain(), which is called by addChild().
if (childDescriptor.stylesFactory != null)
{
if (!scChild.styleDeclaration)
scChild.styleDeclaration = new CSSStyleDeclaration(null, styleManager);
scChild.styleDeclaration.factory =
childDescriptor.stylesFactory;
}
}
// For each event, register the handle method, which is specified in
// the descriptor by name, as one of the child's event listeners.
var childEvents:Object = childDescriptor.events;
if (childEvents)
{
for (var eventName:String in childEvents)
{
var eventHandler:String = childEvents[eventName];
child.addEventListener(eventName,
childDescriptor.document[eventHandler]);
}
}
// For each effect, register the EffectManager as an event listener
var childEffects:Array = childDescriptor.effects;
if (childEffects)
child.registerEffects(childEffects);
if (child is IRepeaterClient)
IRepeaterClient(child).initializeRepeaterArrays(this);
// If an MXML id was specified, create a property with this name on
// the MXML document object whose value references the child.
// This should be the last step in initializing the child, so that
// it can't be referenced until initialization is complete.
// However, it must be done before executing executeBindings().
child.createReferenceOnParentDocument(
IFlexDisplayObject(childDescriptor.document));
if (!child.document)
child.document = childDescriptor.document;
// Repeaters don't get added as children of the Container,
// so they have their own initialization sequence.
if (child is IRepeater)
{
// Add this repeater to the list maintained by the parent
// container
if (!childRepeaters)
childRepeaters = [];
childRepeaters.push(child);
// The Binding Manager may have some data that it wants to bind to
// various properties of the newly created repeater.
child.executeBindings();
IRepeater(child).initializeRepeater(this, recurse);
}
else
{
// This needs to run before child.executeBindings(), because
// executeBindings() depends on the parent being set.
addChild(IUIComponent(child));
child.executeBindings();
if (creationPolicy == ContainerCreationPolicy.QUEUED ||
creationPolicy == ContainerCreationPolicy.NONE)
{
child.addEventListener(FlexEvent.CREATION_COMPLETE,
creationCompleteHandler);
}
}
// Return a reference to the child UIComponent that was just created.
return child;
}
*/
/**
* @private
private function hasChildMatchingDescriptor(
descriptor:UIComponentDescriptor):Boolean
{
// Optimization: If the descriptor has an id but no such id
// reference exists on the document, then there are no children
// in this container with that descriptor.
// (On the other hand, if there IS an id reference on the document,
// we can't be sure that it is for a child of this container. It
// could be an indexed reference in which some instances are
// in other containers. This happens when you have
// <Repeater>
// <VBox>
// <Button>
var id:String = descriptor.id;
if (id != null && (id in document) && document[id] == null)
return false;
var n:int = numChildren;
var i:int;
// Iterate over this container's children, looking for one
// that matches this descriptor
for (i = 0; i < n; i++)
{
var child:IUIComponent = IUIComponent(getChildAt(i));
if (child is IDeferredInstantiationUIComponent &&
IDeferredInstantiationUIComponent(child)
.descriptor == descriptor)
{
return true;
}
}
// Also check this container's Repeaters, if there are any.
if (childRepeaters)
{
n = childRepeaters.length;
for (i = 0; i < n; i++)
{
if (IDeferredInstantiationUIComponent(childRepeaters[i])
.descriptor == descriptor)
{
return true;
}
}
}
return false;
}
*/
//--------------------------------------------------------------------------
//
// Methods: Support for rawChildren access
//
//--------------------------------------------------------------------------
/**
* @private
* This class overrides addChild() to deal with only content children,
* so in order to implement the rawChildren property we need
* a parallel method that deals with all children.
*/
mx_internal function rawChildren_addChild(child:IUIComponent):IUIComponent
{
// This method is only used to implement rawChildren.addChild(),
// so the child being added is assumed to be a non-content child.
// (You would use just addChild() to add a content child.)
// If there are no content children, the new child is placed
// in the pre-content partition.
// If there are content children, the new child is placed
// in the post-content partition.
if (_numChildren == 0)
_firstChildIndex++;
super.addingChild(child);
$uibase_addChild(child);
super.childAdded(child);
dispatchEvent(new Event("childrenChanged"));
return child;
}
/**
* @private
* This class overrides addChildAt() to deal with only content children,
* so in order to implement the rawChildren property we need
* a parallel method that deals with all children.
*/
mx_internal function rawChildren_addChildAt(child:IUIComponent,
index:int):IUIComponent
{
if (_firstChildIndex < index &&
index < _firstChildIndex + _numChildren + 1)
{
_numChildren++;
}
else if (index <= _firstChildIndex)
{
_firstChildIndex++;
}
super.addingChild(child);
$uibase_addChildAt(child, index);
super.childAdded(child);
dispatchEvent(new Event("childrenChanged"));
return child;
}
/**
* @private
* This class overrides removeChild() to deal with only content children,
* so in order to implement the rawChildren property we need
* a parallel method that deals with all children.
*/
mx_internal function rawChildren_removeChild(
child:IUIComponent):IUIComponent
{
var index:int = rawChildren_getChildIndex(child);
return rawChildren_removeChildAt(index);
}
/**
* @private
* This class overrides removeChildAt() to deal with only content children,
* so in order to implement the rawChildren property we need
* a parallel method that deals with all children.
*/
mx_internal function rawChildren_removeChildAt(index:int):IUIComponent
{
var child:IUIComponent = super.getChildAt(index);
super.removingChild(child);
$uibase_removeChildAt(index);
super.childRemoved(child);
if (_firstChildIndex < index &&
index < _firstChildIndex + _numChildren)
{
_numChildren--;
}
else if (_numChildren == 0 || index < _firstChildIndex)
{
_firstChildIndex--;
}
invalidateSize();
invalidateDisplayList();
dispatchEvent(new Event("childrenChanged"));
return child;
}
/**
* @private
* This class overrides getChildAt() to deal with only content children,
* so in order to implement the rawChildren property we need
* a parallel method that deals with all children.
*/
mx_internal function rawChildren_getChildAt(index:int):IUIComponent
{
return super.getChildAt(index);
}
/**
* @private
* This class overrides getChildByName() to deal with only content children,
* so in order to implement the rawChildren property we need
* a parallel method that deals with all children.
*/
mx_internal function rawChildren_getChildByName(name:String):IUIComponent
{
return super.getChildByName(name);
}
/**
* @private
* This class overrides getChildIndex() to deal with only content children,
* so in order to implement the rawChildren property we need
* a parallel method that deals with all children.
*/
mx_internal function rawChildren_getChildIndex(child:IUIComponent):int
{
return super.getChildIndex(child);
}
/**
* @private
* This class overrides setChildIndex() to deal with only content children,
* so in order to implement the rawChildren property we need
* a parallel method that deals with all children.
*/
mx_internal function rawChildren_setChildIndex(child:IUIComponent,
newIndex:int):void
{
var oldIndex:int = super.getChildIndex(child);
super.setChildIndex(child, newIndex);
// Is this a piece of chrome that was previously before
// the content children and is now after them in the list?
if (oldIndex < _firstChildIndex && newIndex >= _firstChildIndex)
{
_firstChildIndex--;
}
// Is this a piece of chrome that was previously after
// the content children and is now before them in the list?
else if (oldIndex >= _firstChildIndex && newIndex <= _firstChildIndex)
{
_firstChildIndex++
}
dispatchEvent(new Event("childrenChanged"));
}
/**
* @private
* This class overrides getObjectsUnderPoint() to deal with only content children,
* so in order to implement the rawChildren property we need
* a parallel method that deals with all children.
*/
mx_internal function rawChildren_getObjectsUnderPoint(pt:Point):Array
{
return null; //super.getObjectsUnderPoint(pt);
}
/**
* @private
* This class overrides contains() to deal with only content children,
* so in order to implement the rawChildren property we need
* a parallel method that deals with all children.
*/
mx_internal function rawChildren_contains(child:IUIBase):Boolean
{
return super.contains(child);
}
//--------------------------------------------------------------------------
//
// Methods: Chrome management
//
//--------------------------------------------------------------------------
/**
* Respond to size changes by setting the positions and sizes
* of this container's borders.
* This is an advanced method that you might override
* when creating a subclass of Container.
*
* <p>Flex calls the <code>layoutChrome()</code> method when the
* container is added to a parent container using the <code>addChild()</code> method,
* and when the container's <code>invalidateDisplayList()</code> method is called.</p>
*
* <p>The <code>Container.layoutChrome()</code> method is called regardless of the
* value of the <code>autoLayout</code> property.</p>
*
* <p>The <code>Container.layoutChrome()</code> method sets the
* position and size of the Container container's border.
* In every subclass of Container, the subclass's <code>layoutChrome()</code>
* method should call the <code>super.layoutChrome()</code> method,
* so that the border is positioned properly.</p>
*
* @param unscaledWidth Specifies the width of the component, in pixels,
* in the component's coordinates, regardless of the value of the
* <code>scaleX</code> property of the component.
*
* @param unscaledHeight Specifies the height of the component, in pixels,
* in the component's coordinates, regardless of the value of the
* <code>scaleY</code> property of the component.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
protected function layoutChrome(unscaledWidth:Number,
unscaledHeight:Number):void
{
// Border covers the whole thing.
if (border)
{
updateBackgroundImageRect();
border.move(0, 0);
border.setActualSize(unscaledWidth, unscaledHeight);
}
}
/**
* Creates the container's border skin
* if it is needed and does not already exist.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
protected function createBorder():void
{
if (!border && isBorderNeeded())
{
var borderClass:Class = getStyle("borderSkin");
if (borderClass != null)
{
border = new borderClass();
border.name = "border";
if (border is IUIComponent)
IUIComponent(border).enabled = enabled;
if (border is ISimpleStyleClient)
ISimpleStyleClient(border).styleName = this;
// Add the border behind all the children.
rawChildren.addChildAt(IUIComponent(border), 0);
invalidateDisplayList();
}
}
}
/**
* @private
* Store references to the default border classes here so we don't have to look them up
* every time.
*/
private static var haloBorder:Class;
private static var sparkBorder:Class;
private static var sparkContainerBorder:Class;
private static var didLookup:Boolean = false;
private static function getDefinition(name:String):Class
{
var result:Object = null;
try
{
result = getDefinitionByName(name);
}
catch(e:Error)
{
}
return result as Class;
}
/**
* @private
*/
private function isBorderNeeded():Boolean
{
//trace("isBorderNeeded",this,"ms",getStyle("mouseShield"),"borderStyle",getStyle("borderStyle"));
// If the borderSkin is a custom class, always assume the border is needed.
var c:Class = getStyle("borderSkin");
if (!didLookup)
{
// Lookup the default border classes by name to avoid a linkage dependency.
// Note: this code assumes either HaloBorder or spark BorderSkin is the default border skin.
// If this is changed in defaults.css, it must also be changed here.
haloBorder = getDefinition("mx.skins.halo::HaloBorder");
sparkBorder = getDefinition("mx.skins.spark::BorderSkin");
sparkContainerBorder = getDefinition("mx.skins.spark::ContainerBorderSkin");
didLookup = true;
}
if (!(c == haloBorder || c == sparkBorder || c == sparkContainerBorder))
return true;
var v:Object = getStyle("borderStyle");
if (v)
{
// If borderStyle is "none", then only create a border if the mouseShield style is true
// (meaning that there is a mouse event listener on this view). We don't create a border
// if our parent's mouseShieldChildren style is true.
if ((v != "none") || (v == "none" && getStyle("mouseShield")))
{
return true;
}
}
v = getStyle("contentBackgroundColor");
if (c == sparkBorder && v !== null)
return true;
v = getStyle("backgroundColor");
if (v !== null && v !== "")
return true;
v = getStyle("backgroundImage");
return v != null && v != "";
}
/**
* @private
*/
mx_internal function invalidateViewMetricsAndPadding():void
{
_viewMetricsAndPadding = null;
}
/**
* @private
*/
private function createOrDestroyBlocker():void
{
/*
// If this container is being enabled and a blocker exists,
// remove it. If this container is being disabled and a
// blocker doesn't exist, create it.
if (enabled)
{
if (blocker)
{
rawChildren.removeChild(blocker);
blocker = null;
}
}
else
{
if (!blocker)
{
blocker = new FlexSprite();
blocker.name = "blocker";
blocker.mouseEnabled = true;
rawChildren.addChild(blocker);
blocker.addEventListener(MouseEvent.CLICK,
blocker_clickHandler);
// If the focus is a child of ours, we clear it here.
var o:IUIComponent =
focusManager ?
IUIComponent(focusManager.getFocus()) :
null;
while (o)
{
if (o == this)
{
var sm:ISystemManager = systemManager;
if (sm && sm.stage)
sm.stage.focus = null;
break;
}
o = o.parent;
}
}
}
*/
}
/**
* @private
*/
private function updateBackgroundImageRect():void
{
/*
var rectBorder:IRectangularBorder = border as IRectangularBorder;
if (!rectBorder)
return;
// If viewableWidth and viewableHeight are 0, we don't have any
// scrollbars or clipped content.
if (viewableWidth == 0 && viewableHeight == 0)
{
rectBorder.backgroundImageBounds = null;
return;
}
var vm:EdgeMetrics = viewMetrics;
var bkWidth:Number = viewableWidth ? viewableWidth :
unscaledWidth - vm.left - vm.right;
var bkHeight:Number = viewableHeight ? viewableHeight :
unscaledHeight - vm.top - vm.bottom;
if (getStyle("backgroundAttachment") == "fixed")
{
rectBorder.backgroundImageBounds = new Rectangle(vm.left, vm.top,
bkWidth, bkHeight);
}
else
{
rectBorder.backgroundImageBounds = new Rectangle(vm.left, vm.top,
Math.max(scrollableWidth, bkWidth),
Math.max(scrollableHeight, bkHeight));
}
*/
}
//--------------------------------------------------------------------------
//
// Methods: Scrolling
//
//--------------------------------------------------------------------------
/**
* @private
*/
private function createContentPaneAndScrollbarsIfNeeded():Boolean
{
var bounds:Rectangle;
var changed:Boolean = false;
// No mask is needed if clipping isn't active
if (_clipContent)
{
// Get the new scrollable width, which is the equal to the right
// edge of the rightmost child. Also get the new scrollable height.
bounds = getScrollableRect();
if (border)
updateBackgroundImageRect();
return changed;
}
else
{
// Get scrollableWidth and scrollableHeight for scrollChildren()
bounds = getScrollableRect();
scrollableWidth = bounds.right;
scrollableHeight = bounds.bottom;
if (changed && border)
updateBackgroundImageRect();
return changed;
}
}
/**
* @private
*/
mx_internal function getScrollableRect():Rectangle
{
var left:Number = 0;
var top:Number = 0;
var right:Number = 0;
var bottom:Number = 0;
var n:int = numChildren;
for (var i:int = 0; i < n; i++)
{
var x:Number;
var y:Number;
var width:Number;
var height:Number;
var child:IUIComponent = getChildAt(i);
if (child is IUIComponent)
{
if (!IUIComponent(child).includeInLayout)
continue;
var uic:IUIComponent = /*PostScaleAdapter.getCompatibleIUIComponent(*/child/*)*/ as IUIComponent;
width = uic.width;
height = uic.height;
x = uic.x;
y = uic.y;
}
else
{
width = child.width;
height = child.height;
x = child.x;
y = child.y;
}
left = Math.min(left, x);
top = Math.min(top, y);
// width/height can be NaN if using percentages and
// hasn't been layed out yet.
if (!isNaN(width))
right = Math.max(right, x + width);
if (!isNaN(height))
bottom = Math.max(bottom, y + height);
}
// Add in the right/bottom margins and view metrics.
var vm:EdgeMetrics = viewMetrics;
var bounds:Rectangle = new Rectangle();
bounds.left = left;
bounds.top = top;
bounds.right = right;
bounds.bottom = bottom;
if (usePadding)
{
bounds.right += getStyle("paddingRight");
bounds.bottom += getStyle("paddingBottom");
}
return bounds;
}
/**
* @private
* Ensures that horizontalScrollPosition is in the range
* from 0 through maxHorizontalScrollPosition and that
* verticalScrollPosition is in the range from 0 through
* maxVerticalScrollPosition.
* Returns true if either horizontalScrollPosition or
* verticalScrollPosition was changed to ensure this.
*/
private function clampScrollPositions():Boolean
{
var changed:Boolean = false;
// Clamp horizontalScrollPosition to the range
// 0 through maxHorizontalScrollPosition.
// If horizontalScrollBar doesn't exist,
// maxHorizontalScrollPosition will be 0.
if (_horizontalScrollPosition < 0)
{
_horizontalScrollPosition = 0;
changed = true;
}
else if (_horizontalScrollPosition > maxHorizontalScrollPosition)
{
_horizontalScrollPosition = maxHorizontalScrollPosition;
changed = true;
}
// Clamp verticalScrollPosition to the range
// 0 through maxVerticalScrollPosition.
// If verticalScrollBar doesn't exist,
// maxVerticalScrollPosition will be 0.
if (_verticalScrollPosition < 0)
{
_verticalScrollPosition = 0;
changed = true;
}
else if (_verticalScrollPosition > maxVerticalScrollPosition)
{
_verticalScrollPosition = maxVerticalScrollPosition;
changed = true;
}
return changed;
}
/**
* @private
*/
mx_internal function createContentPane():void
{
if (contentPane)
return;
/*
creatingContentPane = true;
// Reparent the children. Get the number before we create contentPane
// because that changes logic of how many children we have
var n:int = numChildren;
var newPane:Sprite = new FlexSprite();
newPane.name = "contentPane";
// Place content pane above border and background image but below
// all other chrome.
var childIndex:int;
if (border)
{
childIndex = rawChildren.getChildIndex(IUIComponent(border)) + 1;
if (border is IRectangularBorder && IRectangularBorder(border).hasBackgroundImage)
childIndex++;
}
else
{
childIndex = 0;
}
rawChildren.addChildAt(newPane, childIndex);
for (var i:int = 0; i < n; i++)
{
// use super because contentPane now exists and messes up getChildAt();
var child:IUIComponent =
IUIComponent(super.getChildAt(_firstChildIndex));
newPane.addChild(IUIComponent(child));
child.parentChanged(newPane);
_numChildren--; // required
}
contentPane = newPane;
creatingContentPane = false
// UIComponent sets $visible to false. If we don't make it true here,
// nothing shows up. Making this true should be harmless, as the
// container itself should be false, and so should all its children.
contentPane.visible = true;
*/
}
/**
* Positions the container's content area relative to the viewable area
* based on the horizontalScrollPosition and verticalScrollPosition properties.
* Content that doesn't appear in the viewable area gets clipped.
* This method should be overridden by subclasses that have scrollable
* chrome in the content area.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
protected function scrollChildren():void
{
/*
if (!contentPane)
return;
var vm:EdgeMetrics = viewMetrics;
var x:Number = 0;
var y:Number = 0;
var w:Number = unscaledWidth - vm.left - vm.right;
var h:Number = unscaledHeight - vm.top - vm.bottom;
if (_clipContent)
{
x += _horizontalScrollPosition;
y += _verticalScrollPosition;
}
else
{
w = scrollableWidth;
h = scrollableHeight;
}
// If we have enough space to display everything, don't set
// scrollRect.
var sr:Rectangle = getScrollableRect();
if (x == 0 && y == 0 // Not scrolled
&& w >= sr.right && h >= sr.bottom && // Vertical content visible
sr.left >= 0 && sr.top >= 0 && _forceClippingCount <= 0) // No negative coordinates
{
contentPane.scrollRect = null;
contentPane.opaqueBackground = null;
contentPane.cacheAsBitmap = false;
}
else
{
contentPane.scrollRect = new Rectangle(x, y, w, h);
}
if (focusPane)
focusPane.scrollRect = contentPane.scrollRect;
if (border && border is IRectangularBorder &&
IRectangularBorder(border).hasBackgroundImage)
{
IRectangularBorder(border).layoutBackgroundImage();
}
*/
}
/**
* @private
* Used by a child component to force clipping during a Move effect
*/
private var _forceClippingCount:int;
mx_internal function set forceClipping(value:Boolean):void
{
if (_clipContent) // Can only force clipping if clipContent == true
{
if (value)
_forceClippingCount++
else
_forceClippingCount--;
createContentPane();
scrollChildren();
}
}
//--------------------------------------------------------------------------
//
// Methods: Binding
//
//--------------------------------------------------------------------------
/**
* Executes the bindings into this Container's child UIComponent objects.
* Flex calls this method automatically once a Container has been created.
*
* @param recurse If <code>false</code>, then only execute the bindings
* on the immediate children of this Container.
* If <code>true</code>, then also execute the bindings on this
* container's grandchildren,
* great-grandchildren, and so on.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function executeChildBindings(recurse:Boolean):void
{
/*
var n:int = numChildren;
for (var i:int = 0; i < n; i++)
{
var child:IUIComponent = IUIComponent(getChildAt(i));
if (child is IDeferredInstantiationUIComponent)
{
IDeferredInstantiationUIComponent(child).
executeBindings(recurse);
}
}
*/
}
//--------------------------------------------------------------------------
//
// Overridden event handlers
//
//--------------------------------------------------------------------------
/**
* @private
*/
override protected function keyDownHandler(event:KeyboardEvent):void
{
// If a text field currently has focus, it is handling all arrow keys.
// We shouldn't also scroll this Container.
var focusObj:Object = getFocus();
/*
if ((focusObj is TextField) ||
(richEditableTextClass && focusObj is richEditableTextClass))
{
return;
}
*/
// If the KeyBoardEvent can be canceled and a descendant has done so,
// don't process it at all.
if (event.isDefaultPrevented())
return;
}
//--------------------------------------------------------------------------
//
// Event handlers
//
//--------------------------------------------------------------------------
/**
* @private
* This method copied verbatim from mx.core.ScrollControlBase.
*/
private function mouseWheelHandler(event:MouseEvent):void
{
// If this Container has a vertical scrollbar, then handle the event
// and prevent further bubbling
}
/**
* @private
* This function is called when the LayoutManager finishes running.
* Clear the forceLayout flag that was set earlier.
*/
private function layoutCompleteHandler(event:FlexEvent):void
{
//UIComponentGlobals.layoutManager.removeEventListener(
// FlexEvent.UPDATE_COMPLETE, layoutCompleteHandler);
forceLayout = false;
var needToScrollChildren:Boolean = false;
if (!isNaN(horizontalScrollPositionPending))
{
if (horizontalScrollPositionPending < 0)
horizontalScrollPositionPending = 0;
else if (horizontalScrollPositionPending > maxHorizontalScrollPosition)
horizontalScrollPositionPending = maxHorizontalScrollPosition;
horizontalScrollPositionPending = NaN;
}
if (!isNaN(verticalScrollPositionPending))
{
// Clamp verticalScrollPosition to the range 0 through maxVerticalScrollPosition.
// If verticalScrollBar doesn't exist, maxVerticalScrollPosition will be 0.
if (verticalScrollPositionPending < 0)
verticalScrollPositionPending = 0;
else if (verticalScrollPositionPending > maxVerticalScrollPosition)
verticalScrollPositionPending = maxVerticalScrollPosition;
verticalScrollPositionPending = NaN;
}
if (needToScrollChildren)
scrollChildren();
}
/**
* @private
*/
private function creationCompleteHandler(event:FlexEvent):void
{
numChildrenCreated--;
if (numChildrenCreated <= 0)
dispatchEvent(new FlexEvent("childrenCreationComplete"));
}
/**
* @private
*/
private function blocker_clickHandler(event:Event):void
{
// Swallow click events from blocker.
event.stopPropagation();
}
/**
* @private
*/
override protected function measure():void
{
super.measure();
var preferredWidth:Number;
var preferredHeight:Number;
var minWidth:Number;
var minHeight:Number;
// Determine the size of each tile cell and cache the values
// in cellWidth and cellHeight for later use by updateDisplayList().
findCellSize();
// Min width and min height are large enough to display a single child.
minWidth = cellWidth;
minHeight = cellHeight;
// Determine the width and height necessary to display the tiles
// in an N-by-N grid (with number of rows equal to number of columns).
var n:int = this.numChildren;
// Don't count children that don't need their own layout space.
var temp:int = n;
for (var i:int = 0; i < n; i++)
{
if (!IUIComponent(getChildAt(i)).includeInLayout)
temp--;
}
n = temp;
if (n > 0)
{
var horizontalGap:Number = getStyle("horizontalGap");
var verticalGap:Number = getStyle("verticalGap");
var majorAxis:Number;
// If an explicit dimension or flex is set for the majorAxis,
// set as many children as possible along the axis.
if (direction == "horizontal")
{
var unscaledExplicitWidth:Number = explicitWidth / Math.abs(scaleX);
if (!isNaN(unscaledExplicitWidth))
{
// If we have an explicit height set,
// see how many children can fit in the given height:
// majorAxis * (cellWidth + horizontalGap) - horizontalGap == unscaledExplicitWidth
majorAxis = Math.floor((unscaledExplicitWidth + horizontalGap) /
(cellWidth + horizontalGap));
}
}
else
{
var unscaledExplicitHeight:Number = explicitHeight / Math.abs(scaleY);
if (!isNaN(unscaledExplicitHeight))
{
// If we have an explicit height set,
// see how many children can fit in the given height:
// majorAxis * (cellHeight + verticalGap) - verticalGap == unscaledExplicitHeight
majorAxis = Math.floor((unscaledExplicitHeight + verticalGap) /
(cellHeight + verticalGap));
}
}
// Finally, if majorAxis still isn't defined, use the
// square root of the number of children.
if (isNaN(majorAxis))
majorAxis = Math.ceil(Math.sqrt(n));
// Even if there's not room, force at least one cell
// on each row/column.
if (majorAxis < 1)
majorAxis = 1;
var minorAxis:Number = Math.ceil(n / majorAxis);
if (direction == "horizontal")
{
preferredWidth = majorAxis * cellWidth +
(majorAxis - 1) * horizontalGap;
preferredHeight = minorAxis * cellHeight +
(minorAxis - 1) * verticalGap;
}
else
{
preferredWidth = minorAxis * cellWidth +
(minorAxis - 1) * horizontalGap;
preferredHeight = majorAxis * cellHeight +
(majorAxis - 1) * verticalGap;
}
}
else
{
preferredWidth = minWidth;
preferredHeight = minHeight;
}
var vm:EdgeMetrics = viewMetricsAndPadding;
var hPadding:Number = vm.left + vm.right;
var vPadding:Number = vm.top + vm.bottom;
// Add padding for margins and borders.
minWidth += hPadding;
preferredWidth += hPadding;
minHeight += vPadding;
preferredHeight += vPadding;
measuredMinWidth = Math.ceil(minWidth);
measuredMinHeight = Math.ceil(minHeight);
measuredWidth = Math.ceil(preferredWidth);
measuredHeight = Math.ceil(preferredHeight);
var colCount:int;
// Determine the size of each tile cell
findCellSize();
// Min width and min height are large enough to display a single child
minWidth = cellWidth;
minHeight = cellHeight;
// Determine the width and height necessary to display the tiles in an
// N-by-N grid (with number of rows equal to number of columns).
var numChildren:int = this.numChildren;
if (numChildren > 0)
{
horizontalGap = getStyle("horizontalGap");
verticalGap = getStyle("verticalGap");
var columns:Array /* of Number */;
vm = viewMetricsAndPadding;
var rowCount:int;
// If an explicit dimension or flex is set for the majorAxis,
// set as many children as possible along the axis.
if (direction == "vertical")
{
var bCalcColumns:Boolean = false;
if (!isNaN(explicitHeight))
{
preferredHeight = explicitHeight - vm.top - vm.bottom;
bCalcColumns = true;
}
else if (!isNaN(_actualMajorAxisLength))
{
preferredHeight = _actualMajorAxisLength * cellHeight +
(_actualMajorAxisLength - 1) * verticalGap;
_actualMajorAxisLength = NaN;
bCalcColumns = true;
}
if (bCalcColumns)
{
columns = calcColumnWidthsForHeight(preferredHeight);
preferredWidth = 0;
colCount = columns.length;
n = colCount;
for (i = 0; i < n; i++)
{
preferredWidth += columns[i];
}
preferredWidth += (colCount - 1) * horizontalGap;
rowCount = Math.min(numChildren,
Math.max(1, Math.floor(
(preferredHeight + verticalGap) /
(cellHeight + verticalGap))));
preferredHeight = rowCount * cellHeight +
(rowCount - 1) * verticalGap;
_preferredMajorAxisLength = rowCount;
}
else
{
// If we have flex,
// our majorAxis can contain all our children
preferredHeight = numChildren * cellHeight +
(numChildren - 1) * verticalGap;
preferredWidth = cellWidth;
_preferredMajorAxisLength = numChildren;
}
}
else
{
if (!isNaN(explicitWidth))
{
// If we have an explicit height set,
// see how many children can fit in the given height.
preferredWidth = explicitWidth - vm.left - vm.right;
}
else if (!isNaN(_actualMajorAxisLength))
{
preferredWidth = _actualMajorAxisLength - vm.left - vm.right;
_actualMajorAxisLength = NaN;
}
else
{
preferredWidth = screen.width - vm.left - vm.right;
}
columns = calcColumnWidthsForWidth(preferredWidth);
preferredWidth = 0;
colCount = columns.length;
n = colCount;
for (i = 0; i < n; i++)
{
preferredWidth += columns[i];
}
preferredWidth += (colCount - 1) * horizontalGap;
rowCount = Math.ceil(numChildren / colCount);
preferredHeight = rowCount * cellHeight +
(rowCount - 1) * verticalGap;
_preferredMajorAxisLength = colCount;
}
}
else
{
preferredWidth = minWidth;
preferredHeight = minHeight;
}
// Add extra for borders and margins.
vm = viewMetricsAndPadding;
var hExtra:Number = vm.left + vm.right;
var vExtra:Number = vm.top + vm.bottom;
minWidth += hExtra;
preferredWidth += hExtra;
minHeight += vExtra;
preferredHeight += vExtra;
measuredMinWidth = minWidth;
measuredMinHeight = minHeight;
measuredWidth = preferredWidth;
measuredHeight = preferredHeight;
}
//--------------------------------------------------------------------------
//
// Methods
//
//--------------------------------------------------------------------------
/**
* @private
* Calculate and store the cellWidth and cellHeight.
*/
mx_internal function findCellSize():void
{
// If user explicitly supplied both a tileWidth and
// a tileHeight, then use those values.
var widthSpecified:Boolean = !isNaN(tileWidth);
var heightSpecified:Boolean = !isNaN(tileHeight);
if (widthSpecified && heightSpecified)
{
cellWidth = tileWidth;
cellHeight = tileHeight;
return;
}
// Reset the max child width and height
var maxChildWidth:Number = 0;
var maxChildHeight:Number = 0;
// Loop over the children to find the max child width and height.
var n:int = numChildren;
for (var i:int = 0; i < n; i++)
{
var child:IUIComponent = getLayoutChildAt(i);
if (!child.includeInLayout)
continue;
var width:Number = child.getExplicitOrMeasuredWidth();
if (width > maxChildWidth)
maxChildWidth = width;
var height:Number = child.getExplicitOrMeasuredHeight();
if (height > maxChildHeight)
maxChildHeight = height;
}
// If user explicitly specified either width or height, use the
// user-supplied value instead of the one we computed.
cellWidth = widthSpecified ? tileWidth : maxChildWidth;
cellHeight = heightSpecified ? tileHeight : maxChildHeight;
}
/**
* @private
* Assigns the actual size of the specified child,
* based on its measurement properties and the cell size.
*/
private function setChildSize(child:IUIComponent):void
{
var childWidth:Number;
var childHeight:Number;
var childPref:Number;
var childMin:Number;
if (child.percentWidth > 0)
{
// Set child width to be a percentage of the size of the cell.
childWidth = Math.min(cellWidth,
cellWidth * child.percentWidth / 100);
}
else
{
// The child is not flexible, so set it to its preferred width.
childWidth = child.getExplicitOrMeasuredWidth();
// If an explicit tileWidth has been set on this Tile,
// then the child may extend outside the bounds of the tile cell.
// In that case, we'll honor the child's width or minWidth,
// but only if those values were explicitly set by the developer,
// not if they were implicitly set based on measurements.
if (childWidth > cellWidth)
{
childPref = isNaN(child.explicitWidth) ?
0 :
child.explicitWidth;
childMin = isNaN(child.explicitMinWidth) ?
0 :
child.explicitMinWidth;
childWidth = (childPref > cellWidth ||
childMin > cellWidth) ?
Math.max(childMin, childPref) :
cellWidth;
}
}
if (child.percentHeight > 0)
{
childHeight = Math.min(cellHeight,
cellHeight * child.percentHeight / 100);
}
else
{
childHeight = child.getExplicitOrMeasuredHeight();
if (childHeight > cellHeight)
{
childPref = isNaN(child.explicitHeight) ?
0 :
child.explicitHeight;
childMin = isNaN(child.explicitMinHeight) ?
0 :
child.explicitMinHeight;
childHeight = (childPref > cellHeight ||
childMin > cellHeight) ?
Math.max(childMin, childPref) :
cellHeight;
}
}
child.setActualSize(childWidth, childHeight);
}
/**
* @private
* Compute how much adjustment must occur in the x direction
* in order to align a component of a given width into the cell.
*/
mx_internal function calcHorizontalOffset(width:Number,
horizontalAlign:String):Number
{
var xOffset:Number;
if (horizontalAlign == "left")
xOffset = 0;
else if (horizontalAlign == "center")
xOffset = (cellWidth - width) / 2;
else if (horizontalAlign == "right")
xOffset = (cellWidth - width);
return xOffset;
}
/**
* @private
* Compute how much adjustment must occur in the y direction
* in order to align a component of a given height into the cell.
*/
mx_internal function calcVerticalOffset(height:Number,
verticalAlign:String):Number
{
var yOffset:Number;
if (verticalAlign == "top")
yOffset = 0;
else if (verticalAlign == "middle")
yOffset = (cellHeight - height) / 2;
else if (verticalAlign == "bottom")
yOffset = (cellHeight - height);
return yOffset;
}
//--------------------------------------------------------------------------
//
// Methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
private function addLegendItem(legendData:Object):void
{
var c:Class = legendItemClass;
var newItem:LegendItem = new c();
if (legendData.label != "")
newItem.label = legendData.label;
if (legendData.element)
newItem.chartElement = legendData.element;
if ("fill" in legendData)
newItem.setStyle("fill",legendData["fill"]);
newItem.markerAspectRatio = legendData.aspectRatio;
newItem.legendData = legendData;
newItem.percentWidth = 100;
newItem.percentHeight = 100;
addChild(newItem);
newItem.marker = legendData.marker;
newItem.setStyle("backgroundColor", 0xEEEEFF);
}
/**
* @private
*/
private function populateFromArray(dp:Object):void
{
if (dp is ChartBase)
dp = dp.legendData;
removeAllChildren();
var curItem:Object;
var n:int = dp.length;
for (var i:int = 0; i < n; i++)
{
var curList:Array /* of LegendData */ = (dp[i] as Array);
if (!curList)
{
curItem = dp[i];
addLegendItem(curItem);
}
else
{
var m:int = curList.length;
for (var j:int = 0; j < m; j++)
{
curItem = curList[j];
addLegendItem(curItem);
}
}
}
_actualMajorAxisLength = NaN;
}
/**
* @private
* Returns a numeric value for the align setting.
* 0 = left/top, 0.5 = center, 1 = right/bottom
*/
private function findHorizontalAlignValue():Number
{
var horizontalAlign:String = getStyle("horizontalAlign");
if (horizontalAlign == "center")
return 0.5;
else if (horizontalAlign == "right")
return 1;
// default = left
return 0;
}
/**
* @private
* Returns a numeric value for the align setting.
* 0 = left/top, 0.5 = center, 1 = right/bottom
*/
private function findVerticalAlignValue():Number
{
var verticalAlign:String = getStyle("verticalAlign");
if (verticalAlign == "middle")
return 0.5;
else if (verticalAlign == "bottom")
return 1;
// default = top
return 0;
}
/**
* @private
*/
private function widthPadding(numChildren:Number):Number
{
var vm:EdgeMetrics = viewMetricsAndPadding;
var padding:Number = vm.left + vm.right;
if (numChildren > 1 && direction == "horizontal")
padding += getStyle("horizontalGap") * (numChildren - 1);
return padding;
}
/**
* @private
*/
private function heightPadding(numChildren:Number):Number
{
var vm:EdgeMetrics = viewMetricsAndPadding;
var padding:Number = vm.top + vm.bottom;
if (numChildren > 1 && direction == "vertical")
padding += getStyle("verticalGap") * (numChildren - 1);
return padding;
}
/**
* @private
*/
private function calcColumnWidthsForHeight(h:Number):Array /* of Number */
{
var n:Number = numChildren;
var verticalGap:Number = getStyle("verticalGap");
if (isNaN(verticalGap))
verticalGap = 0;
var rowCount:int = Math.min(n, Math.max(
1, Math.floor((h + verticalGap) / (cellHeight + verticalGap))));
var nColumns:int = rowCount == 0 ? 0: Math.ceil(n / rowCount);
var columnSizes:Array /* of Number */;
if (nColumns <= 1)
{
columnSizes = [cellWidth];
}
else
{
columnSizes = [];
for (var i:int = 0; i < nColumns; i++)
{
columnSizes[i] = 0;
}
for (i = 0; i < n; i++)
{
var child:IUIComponent = IUIComponent(getChildAt(i));
var col:int = Math.floor(i / rowCount);
columnSizes[col] = Math.max(columnSizes[col],
child.getExplicitOrMeasuredWidth());
}
}
return columnSizes;
}
/**
* @private
* Bound the layout in the vertical direction
* and let it grow horizontally.
*/
private function layoutVertical():void
{
var n:Number = numChildren;
var vm:EdgeMetrics = viewMetricsAndPadding;
var horizontalGap:Number = getStyle("horizontalGap");
var verticalGap:Number = getStyle("verticalGap");
var horizontalAlign:String = getStyle("horizontalAlign");
var verticalAlign:String = getStyle("verticalAlign");
var xPos:Number = vm.left;
var yPos:Number = vm.top;
var yEnd:Number = unscaledHeight - vm.bottom;
var rowCount:int = Math.min(n, Math.max(1, Math.floor(
(yEnd - yPos + verticalGap) / (cellHeight + verticalGap))));
var columnSizes:Array /* of Number */ = [];
columnSizes = calcColumnWidthsForHeight(yEnd - yPos);
var nColumns:int = columnSizes.length;
for (var i:Number = 0; i < n; i++)
{
var child:IUIComponent = IUIComponent(getChildAt(i));
var col:int = Math.floor(i / rowCount);
var colWidth:Number = columnSizes[col];
var childWidth:Number;
var childHeight:Number;
if (child.percentWidth > 0)
{
childWidth = Math.min(colWidth,
colWidth * child.percentWidth / 100);
}
else
{
childWidth = child.getExplicitOrMeasuredWidth();
}
if (child.percentHeight > 0)
{
childHeight = Math.min(cellHeight,
cellHeight * child.percentHeight / 100);
}
else
{
childHeight = child.getExplicitOrMeasuredHeight();
}
child.setActualSize(childWidth, childHeight);
// Align the child in the cell.
var xOffset:Number =
Math.floor(calcHorizontalOffset(child.width, horizontalAlign));
var yOffset:Number =
Math.floor(calcVerticalOffset(child.height, verticalAlign));
child.move(xPos + xOffset, yPos + yOffset);
if ((i % rowCount) == rowCount - 1)
{
yPos = vm.top;
xPos += (colWidth + horizontalGap);
}
else
{
yPos += (cellHeight + verticalGap);
}
}
if (rowCount != _preferredMajorAxisLength)
{
_actualMajorAxisLength = rowCount;
invalidateSize();
}
}
/**
* @private
*/
private function calcColumnWidthsForWidth(w:Number):Array /* of Number */
{
var n:Number = numChildren;
var horizontalGap:Number = getStyle("horizontalGap");
var xPos:Number = 0;
var xEnd:Number = w;
// first determine the max number of columns we can have;
var nColumns:int = 0;
var columnSizes:Array /* of Number */;
for (var i:Number = 0; i < n; i++)
{
var child:IUIComponent = IUIComponent(getChildAt(i));
var childPreferredWidth:Number = child.getExplicitOrMeasuredWidth();
// start a new row?
if (xPos + childPreferredWidth > xEnd)
{
break;
}
xPos += (childPreferredWidth + horizontalGap);
nColumns++;
}
var columnsTooWide:Boolean = true;
while (nColumns > 1 && columnsTooWide)
{
columnSizes = [];
for (i = 0; i < nColumns; i++)
{
columnSizes[i] = 0;
}
for (i = 0; i < n; i++)
{
var col:int = i % nColumns;
columnSizes[col] = Math.max(columnSizes[col],
IUIComponent(getChildAt(i)).getExplicitOrMeasuredWidth());
}
xPos = 0;
for (i = 0; i < nColumns; i++)
{
if (xPos + columnSizes[i] > xEnd)
break;
xPos += columnSizes[i] + horizontalGap;
}
if (i == nColumns)
columnsTooWide = false;
else
nColumns--;
}
if (nColumns <= 1)
{
nColumns = 1;
columnSizes = [cellWidth];
}
return columnSizes;
}
/**
* @private
*/
private function layoutHorizontal():void
{
var n:Number = numChildren;
var vm:EdgeMetrics = viewMetricsAndPadding;
var horizontalGap:Number = getStyle("horizontalGap");
var verticalGap:Number = getStyle("verticalGap")
var horizontalAlign:String = getStyle("horizontalAlign");
var verticalAlign:String = getStyle("verticalAlign");
var xPos:Number = vm.left;
var xEnd:Number = _unscaledWidth - vm.right;
var yPos:Number = vm.top;
// First determine the max number of columns we can have.
var nColumns:int = 0;
var columnSizes:Array /* of Number */;
columnSizes = calcColumnWidthsForWidth(xEnd - xPos);
nColumns = columnSizes.length;
for (var i:Number = 0; i < n; i++)
{
var child:IUIComponent = IUIComponent(getChildAt(i));
var col:int = i % nColumns;
var colWidth:Number = columnSizes[col];
var childWidth:Number;
var childHeight:Number;
if (child.percentWidth > 0)
{
childWidth = Math.min(colWidth,
colWidth * child.percentWidth / 100);
}
else
{
childWidth = child.getExplicitOrMeasuredWidth();
}
if (child.percentHeight > 0)
{
childHeight = Math.min(cellHeight,
cellHeight * child.percentHeight / 100);
}
else
{
childHeight = child.getExplicitOrMeasuredHeight();
}
child.setActualSize(childWidth, childHeight);
// Align the child in the cell.
var xOffset:Number =
Math.floor(calcHorizontalOffset(child.width, horizontalAlign));
var yOffset:Number =
Math.floor(calcVerticalOffset(child.height, verticalAlign));
child.move(xPos + xOffset, yPos + yOffset);
if (col == nColumns - 1)
{
xPos = vm.left;
yPos += (cellHeight + verticalGap);
}
else
{
xPos += (columnSizes[col] + horizontalGap);
}
}
if (nColumns != _preferredMajorAxisLength)
{
_actualMajorAxisLength = _unscaledWidth;
invalidateSize();
}
}
//--------------------------------------------------------------------------
//
// Event handlers
//
//--------------------------------------------------------------------------
/**
* @private
*/
private function legendDataChangedHandler(event:Event = null):void
{
invalidateProperties();
invalidateSize();
_childrenDirty = true;;
if (parent)
{
commitProperties();
measure();
updateDisplayList(getExplicitOrMeasuredWidth(), getExplicitOrMeasuredHeight());
}
}
/**
* @private
*/
private function childMouseEventHandler(event:MouseEvent):void
{
var p:IUIComponent = IUIComponent(event.target);
while (p != this && p.parent != this)
{
p = p.parent as IUIComponent;
}
if (p is LegendItem)
dispatchEvent(new LegendMouseEvent(event.type, event, LegendItem(p)));
}
}
}
import mx.core.IUIComponent;
import org.apache.royale.core.IUIBase;
import org.apache.royale.geom.Point;
import mx.charts.Legend;
import mx.core.IChildList;
import mx.core.mx_internal;
use namespace mx_internal;
/**
* @private
* Helper class for the rawChildren property of the Container class.
* For descriptions of the properties and methods,
* see the IChildList interface.
*
* @see mx.core.Container
*/
class LegendRawChildrenList implements IChildList
{
// include "../core/Version.as";
//--------------------------------------------------------------------------
//
// Notes
//
//--------------------------------------------------------------------------
/*
Although at the level of a Flash DisplayObjectContainer, all
children are equal, in a Flex Container some children are "more
equal than others". (George Orwell, "Animal Farm")
In particular, Flex distinguishes between content children and
non-content (or "chrome") children. Content children are the kind
that can be specified in MXML. If you put several controls
into a VBox, those are its content children. Non-content children
are the other ones that you get automatically, such as a
background/border, scrollbars, the titlebar of a Panel,
AccordionHeaders, etc.
Most application developers are uninterested in non-content children,
so Container overrides APIs such as numChildren and getChildAt()
to deal only with content children. For example, Container, keeps
its own _numChildren counter.
However, developers of custom containers need to be able to deal
with both content and non-content children, so they require similar
APIs that operate on all children.
For the public API, it would be ugly to have double APIs on Container
such as getChildAt() and all_getChildAt(). Instead, Container has
a public rawChildren property which lets you access APIs which
operate on all the children, in the same way that the
DisplayObjectContainer APIs do. For example, getChildAt(0) returns
the first content child, while rawChildren.getChildAt(0) returns
the first child (either content or non-content).
This ContainerRawChildrenList class implements the rawChildren
property. Note that it simply calls a second set of parallel
mx_internal APIs in Container. (They're named, for example,
_getChildAt() instead of all_getChildAt()).
Many of the all-children APIs in Container such as _getChildAt()
simply call super.getChildAt() in order to get the implementation
in DisplayObjectContainer. It would be nice if we could eliminate
_getChildAt() in Container and simply implement the all-children
version in this class by calling the DisplayObjectContainer method.
But once Container overrides getChildAt(), there is no way
to call the supermethod through an instance.
*/
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* @private
* Constructor.
*/
public function LegendRawChildrenList(owner:Legend)
{
super();
this.owner = owner;
}
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
/**
* @private
*/
private var owner:Legend;
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
//----------------------------------
// numChildren
//----------------------------------
/**
* @private
*/
public function get numChildren():int
{
return owner.$sprite_numChildren;
}
//--------------------------------------------------------------------------
//
// Methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
public function addChild(child:IUIComponent):IUIComponent
{
return owner.rawChildren_addChild(child);
}
/**
* @private
*/
public function addChildAt(child:IUIComponent, index:int):IUIComponent
{
return owner.rawChildren_addChildAt(child, index);
}
/**
* @private
*/
public function removeChild(child:IUIComponent):IUIComponent
{
return owner.rawChildren_removeChild(child);
}
/**
* @private
*/
public function removeChildAt(index:int):IUIComponent
{
return owner.rawChildren_removeChildAt(index);
}
/**
* @private
*/
public function getChildAt(index:int):IUIComponent
{
return owner.rawChildren_getChildAt(index);
}
/**
* @private
*/
public function getChildByName(name:String):IUIComponent
{
return owner.rawChildren_getChildByName(name);
}
/**
* @private
*/
public function getChildIndex(child:IUIComponent):int
{
return owner.rawChildren_getChildIndex(child);
}
/**
* @private
*/
public function setChildIndex(child:IUIComponent, newIndex:int):void
{
owner.rawChildren_setChildIndex(child, newIndex);
}
/**
* @private
*/
public function getObjectsUnderPoint(point:Point):Array
{
return owner.rawChildren_getObjectsUnderPoint(point);
}
/**
* @private
*/
public function contains(child:IUIBase):Boolean
{
return owner.rawChildren_contains(child);
}
}
|
import mx.utils.Delegate;
import com.GameInterface.Inventory;
import com.GameInterface.InventoryItem;
import com.GameInterface.SpellBase;
import com.GameInterface.UtilsBase;
import com.GameInterface.Game.BuffData;
import com.GameInterface.Game.Character;
import com.Utils.ID32;
import caurina.transitions.Tweener;
import descendent.hud.reticle.Color;
import descendent.hud.reticle.DefaultArcBarMeter;
import descendent.hud.reticle.Gauge;
import descendent.hud.reticle.IMeter;
class descendent.hud.reticle.special.DualPistolsGauge extends Gauge
{
private static var TAG_CHAMBER_1:Number = 9262328;
private static var TAG_CHAMBER_2:Number = 9262330;
private static var TAG_MATCH:Number = 9266708;
// private static var TAG_FULLHOUSE:Number = 9265024;
private static var TAG_FULLHOUSE_STACKEDDECK:Number = 9267064;
// private static var ABILITY_STACKEDDECK:Number = 9265315;
// private static var ABILITY_FULLHOUSE:Number = 9265025;
private static var THING_SIXSHOOTERS:Number = 6813528;
private static var MATCH_MAX:Number = 3000;
private var _r:Number;
private var _angle_a:Number;
private var _angle_b:Number;
private var _thickness:Number;
private var _equip:Number;
private var _character:Character;
private var _inventory:Inventory;
private var _meter_1_a:IMeter;
private var _meter_1_b:IMeter;
private var _meter_1_c:IMeter;
private var _meter_2_a:IMeter;
private var _meter_2_b:IMeter;
private var _meter_2_c:IMeter;
private var _meter_x_a:IMeter;
private var _meter_x_b:IMeter;
private var _meter_x_b_conditional:IMeter;
private var _meter_x_c:IMeter;
private var _timer:Number;
private var _refresh_meter:Function;
public function DualPistolsGauge(r:Number, angle_a:Number, angle_b:Number, thickness:Number,
equip:Number)
{
super();
this._r = r;
this._angle_a = angle_a;
this._angle_b = angle_b;
this._thickness = thickness;
this._equip = equip;
this._refresh_meter = Delegate.create(this, this.refresh_meter);
}
public function prepare(o:MovieClip):Void
{
super.prepare(o);
this._character = Character.GetClientCharacter();
this._inventory = new Inventory(new ID32(_global.Enums.InvType.e_Type_GC_WeaponContainer, this._character.GetID().GetInstance()));
this.prepare_meter();
this.refresh_meter();
this.refresh_color();
this.refresh_timer();
this.refresh_pulse();
this._character.SignalInvisibleBuffAdded.Connect(this.character_onTag, this);
this._character.SignalInvisibleBuffUpdated.Connect(this.character_onTag, this);
this._character.SignalBuffRemoved.Connect(this.character_onTag, this);
this._character.SignalBuffAdded.Connect(this.character_onTag, this);
this._inventory.SignalItemLoaded.Connect(this.inventory_onPlant, this);
this._inventory.SignalItemAdded.Connect(this.inventory_onPlant, this);
this._inventory.SignalItemChanged.Connect(this.inventory_onTransform, this);
this._inventory.SignalItemRemoved.Connect(this.inventory_onPluck, this);
}
private function prepare_meter():Void
{
this.prepare_meter_1();
this.prepare_meter_2();
this.prepare_meter_x();
}
private function prepare_meter_1():Void
{
this.prepare_meter_1_a();
this.prepare_meter_1_b();
this.prepare_meter_1_c();
}
private function prepare_meter_1_a():Void
{
var thickness:Number = this._thickness / 2.0;
var r:Number = (this._equip == _global.Enums.ItemEquipLocation.e_Wear_First_WeaponSlot)
? this._r + thickness
: this._r;
this._meter_1_a = new DefaultArcBarMeter(r, this._angle_a, this._angle_b, thickness,
// new Color(0xA3A3A3, 33), new Color(0xA3A3A3, 100), new Color(0xFFFFFF, 100), 1.0, false);
new Color(0xD7D7D7, 33), new Color(0xD7D7D7, 100), new Color(0xFFFFFF, 100), 1.0, false);
this._meter_1_a.prepare(this.content);
}
private function prepare_meter_1_b():Void
{
var thickness:Number = this._thickness / 2.0;
var r:Number = (this._equip == _global.Enums.ItemEquipLocation.e_Wear_First_WeaponSlot)
? this._r + thickness
: this._r;
this._meter_1_b = new DefaultArcBarMeter(r, this._angle_a, this._angle_b, thickness,
new Color(0x4895FF, 33), new Color(0x4895FF, 100), new Color(0xFFFFFF, 100), 1.0, false);
// new Color(0x1EA1FF, 33), new Color(0x1EA1FF, 100), new Color(0xFFFFFF, 100), 1.0, false);
this._meter_1_b.prepare(this.content);
}
private function prepare_meter_1_c():Void
{
var thickness:Number = this._thickness / 2.0;
var r:Number = (this._equip == _global.Enums.ItemEquipLocation.e_Wear_First_WeaponSlot)
? this._r + thickness
: this._r;
this._meter_1_c = new DefaultArcBarMeter(r, this._angle_a, this._angle_b, thickness,
new Color(0xFF2E2E, 33), new Color(0xFF2E2E, 100), new Color(0xFFFFFF, 100), 1.0, false);
// new Color(0xFF3C3C, 33), new Color(0xFF3C3C, 100), new Color(0xFFFFFF, 100), 1.0, false);
this._meter_1_c.prepare(this.content);
}
private function prepare_meter_2():Void
{
this.prepare_meter_2_a();
this.prepare_meter_2_b();
this.prepare_meter_2_c();
}
private function prepare_meter_2_a():Void
{
var thickness:Number = this._thickness / 2.0;
var r:Number = (this._equip == _global.Enums.ItemEquipLocation.e_Wear_Second_WeaponSlot)
? this._r + thickness
: this._r;
this._meter_2_a = new DefaultArcBarMeter(r, this._angle_a, this._angle_b, thickness,
// new Color(0xA3A3A3, 33), new Color(0xA3A3A3, 100), new Color(0xFFFFFF, 100), 1.0, false);
new Color(0xD7D7D7, 33), new Color(0xD7D7D7, 100), new Color(0xFFFFFF, 100), 1.0, false);
this._meter_2_a.prepare(this.content);
}
private function prepare_meter_2_b():Void
{
var thickness:Number = this._thickness / 2.0;
var r:Number = (this._equip == _global.Enums.ItemEquipLocation.e_Wear_Second_WeaponSlot)
? this._r + thickness
: this._r;
this._meter_2_b = new DefaultArcBarMeter(r, this._angle_a, this._angle_b, thickness,
new Color(0x4895FF, 33), new Color(0x4895FF, 100), new Color(0xFFFFFF, 100), 1.0, false);
// new Color(0x1EA1FF, 33), new Color(0x1EA1FF, 100), new Color(0xFFFFFF, 100), 1.0, false);
this._meter_2_b.prepare(this.content);
}
private function prepare_meter_2_c():Void
{
var thickness:Number = this._thickness / 2.0;
var r:Number = (this._equip == _global.Enums.ItemEquipLocation.e_Wear_Second_WeaponSlot)
? this._r + thickness
: this._r;
this._meter_2_c = new DefaultArcBarMeter(r, this._angle_a, this._angle_b, thickness,
new Color(0xFF2E2E, 33), new Color(0xFF2E2E, 100), new Color(0xFFFFFF, 100), 1.0, false);
// new Color(0xFF3C3C, 33), new Color(0xFF3C3C, 100), new Color(0xFFFFFF, 100), 1.0, false);
this._meter_2_c.prepare(this.content);
}
private function prepare_meter_x():Void
{
this.prepare_meter_x_a();
this.prepare_meter_x_b();
this.prepare_meter_x_b_conditional();
this.prepare_meter_x_c();
this.dismiss_meter_x();
this.refresh_maximum();
}
private function prepare_meter_x_a():Void
{
var notch:/*Number*/Array = [1000, 2500];
this._meter_x_a = new DefaultArcBarMeter(this._r, this._angle_a, this._angle_b, this._thickness,
// new Color(0xA3A3A3, 33), new Color(0xA3A3A3, 100), new Color(0xFFFFFF, 100), DualPistolsGauge.MATCH_MAX, false);
new Color(0xD7D7D7, 33), new Color(0xD7D7D7, 100), new Color(0xFFFFFF, 100), DualPistolsGauge.MATCH_MAX, false);
this._meter_x_a.setNotch(notch);
this._meter_x_a.prepare(this.content);
}
private function prepare_meter_x_b():Void
{
var notch:/*Number*/Array = [1000, 2500];
this._meter_x_b = new DefaultArcBarMeter(this._r, this._angle_a, this._angle_b, this._thickness,
new Color(0x4895FF, 33), new Color(0x4895FF, 100), new Color(0xFFFFFF, 100), DualPistolsGauge.MATCH_MAX, false);
// new Color(0x1EA1FF, 33), new Color(0x1EA1FF, 100), new Color(0xFFFFFF, 100), DualPistolsGauge.MATCH_MAX, false);
this._meter_x_b.setNotch(notch);
this._meter_x_b.prepare(this.content);
}
private function prepare_meter_x_b_conditional():Void
{
var notch:/*Number*/Array = [1000, 2500];
this._meter_x_b_conditional = new DefaultArcBarMeter(this._r, this._angle_a, this._angle_b, this._thickness,
new Color(0x4895FF, 33), new Color(0x4895FF, 100), new Color(0xFFFFFF, 100), DualPistolsGauge.MATCH_MAX + 2000, false);
// new Color(0x1EA1FF, 33), new Color(0x1EA1FF, 100), new Color(0xFFFFFF, 100), DualPistolsGauge.MATCH_MAX + 2000, false);
this._meter_x_b_conditional.setNotch(notch);
this._meter_x_b_conditional.prepare(this.content);
}
private function prepare_meter_x_c():Void
{
var notch:/*Number*/Array = [1000, 2500];
this._meter_x_c = new DefaultArcBarMeter(this._r, this._angle_a, this._angle_b, this._thickness,
new Color(0xFF2E2E, 33), new Color(0xFF2E2E, 100), new Color(0xFFFFFF, 100), DualPistolsGauge.MATCH_MAX, false);
// new Color(0xFF3C3C, 33), new Color(0xFF3C3C, 100), new Color(0xFFFFFF, 100), DualPistolsGauge.MATCH_MAX, false);
this._meter_x_c.setNotch(notch);
this._meter_x_c.prepare(this.content);
}
private function refresh_timer():Void
{
var tag:BuffData = this._character.m_InvisibleBuffList[DualPistolsGauge.TAG_MATCH];
if (tag != null)
this.timerBegin();
else
this.timerEnd();
}
private function timerBegin():Void
{
var tag:BuffData = this._character.m_InvisibleBuffList[DualPistolsGauge.TAG_MATCH];
var value:Number = (tag != null)
? tag.m_TotalTime - (UtilsBase.GetNormalTime() * 1000)
: 0;
this.dismiss_meter_1();
this.dismiss_meter_2();
this.dismiss_meter_x();
var meter:IMeter = this.meter_x();
meter.present();
meter.setMeter(0);
Tweener.addTween(meter, {
setMeter: value - 300,
time: 0.3,
transition: "linear",
onComplete: this.timerBegin_process,
onCompleteParams: null,
onCompleteScope: this
});
}
private function timerBegin_process():Void
{
clearInterval(this._timer);
this._timer = setInterval(this._refresh_meter, 200);
this.refresh_meter();
}
private function timerEnd():Void
{
clearInterval(this._timer);
this._timer = null;
this.refresh_meter();
this.refresh_color(true);
}
private function refresh_meter():Void
{
var tag:BuffData = this._character.m_InvisibleBuffList[DualPistolsGauge.TAG_MATCH];
var value:Number = (tag != null)
? tag.m_TotalTime - (UtilsBase.GetNormalTime() * 1000)
: 0;
var meter:IMeter = this.meter_x();
if (value == meter.getMeter())
return;
meter.setMeter(value);
Tweener.addTween(meter, {
setMeter: 0,
time: value / 1000,
transition: "linear"
});
}
private function meter_x():IMeter
{
var tag:BuffData = this._character.m_InvisibleBuffList[DualPistolsGauge.TAG_CHAMBER_1];
var value:Number = (tag != null)
? tag.m_Count
: 0;
var meter:IMeter;
if (value >= 6)
{
meter = this._meter_x_c;
}
else if (value >= 4)
{
meter = (this.tag_fullHouse_stackedDeck())
? this._meter_x_b_conditional
: this._meter_x_b;
}
else
{
meter = this._meter_x_a;
}
return meter;
}
private function tag_fullHouse_stackedDeck():Boolean
{
// if (!SpellBase.IsPassiveEquipped(DualPistolsGauge.ABILITY_STACKEDDECK))
// return false;
if (this._character.m_BuffList[DualPistolsGauge.TAG_FULLHOUSE_STACKEDDECK] == null)
return false;
return true;
}
private function refresh_color(still:Boolean):Void
{
this.refresh_color_1(still);
this.refresh_color_2(still);
}
private function refresh_color_1(still:Boolean):Void
{
if (this._character.m_InvisibleBuffList[DualPistolsGauge.TAG_MATCH] != null)
return;
var tag:BuffData = this._character.m_InvisibleBuffList[DualPistolsGauge.TAG_CHAMBER_1];
var value:Number = (tag != null)
? tag.m_Count
: 0;
this.dismiss_meter_x();
this.dismiss_meter_1();
var meter:IMeter;
if (value >= 6)
meter = this._meter_1_c;
else if (value >= 4)
meter = this._meter_1_b;
else
meter = this._meter_1_a;
meter.present();
if (still)
this.refresh_color_1_still(meter);
else
this.refresh_color_1_tween(meter);
}
private function refresh_color_1_still(meter:IMeter):Void
{
meter.setMeter(0.0);
}
private function refresh_color_1_tween(meter:IMeter):Void
{
meter.setMeter(0.0);
Tweener.addTween(meter, {
setMeter: 1.0,
time: 0.3,
transition: "linear"
});
}
private function refresh_color_2(still:Boolean):Void
{
if (this._character.m_InvisibleBuffList[DualPistolsGauge.TAG_MATCH] != null)
return;
var tag:BuffData = this._character.m_InvisibleBuffList[DualPistolsGauge.TAG_CHAMBER_2];
var value:Number = (tag != null)
? tag.m_Count
: 0;
this.dismiss_meter_x();
this.dismiss_meter_2();
var meter:IMeter;
if (value >= 6)
meter = this._meter_2_c;
else if (value >= 4)
meter = this._meter_2_b;
else
meter = this._meter_2_a;
meter.present();
if (still)
this.refresh_color_2_still(meter);
else
this.refresh_color_2_tween(meter);
}
private function refresh_color_2_still(meter:IMeter):Void
{
meter.setMeter(0.0);
}
private function refresh_color_2_tween(meter:IMeter):Void
{
meter.setMeter(0.0);
Tweener.addTween(meter, {
setMeter: 1.0,
time: 0.3,
transition: "linear"
});
// Support for Six Line used during match
Tweener.addTween([this._meter_1_a, this._meter_1_b, this._meter_1_c], {
setMeter: 1.0,
time: 0.3,
transition: "linear",
overwrite: false
});
}
private function refresh_maximum():Void
{
var maximum:Number = (this.equip_sixShooters())
? DualPistolsGauge.MATCH_MAX + 500
: DualPistolsGauge.MATCH_MAX;
this._meter_x_a.setMaximum(maximum);
this._meter_x_b.setMaximum(maximum);
this._meter_x_b_conditional.setMaximum(maximum + 2000);
this._meter_x_c.setMaximum(maximum);
}
private function equip_sixShooters():Boolean
{
var thing:InventoryItem = this._inventory.GetItemAt(this._equip);
if (thing == null)
return false;
if (thing.m_Icon.GetInstance() != DualPistolsGauge.THING_SIXSHOOTERS)
return false;
return true;
}
private function refresh_pulse():Void
{
if (this.pulse())
{
this._meter_x_a.pulseBegin();
this._meter_x_b.pulseBegin();
this._meter_x_b_conditional.pulseBegin();
this._meter_x_c.pulseBegin();
}
else
{
this._meter_x_a.pulseEnd();
this._meter_x_b.pulseEnd();
this._meter_x_b_conditional.pulseEnd();
this._meter_x_c.pulseEnd();
}
}
private function pulse():Boolean
{
if (this._character.m_InvisibleBuffList[DualPistolsGauge.TAG_MATCH] != null)
return true;
return false;
}
private function dismiss_meter_1():Void
{
this._meter_1_a.dismiss();
this._meter_1_b.dismiss();
this._meter_1_c.dismiss();
}
private function dismiss_meter_2():Void
{
this._meter_2_a.dismiss();
this._meter_2_b.dismiss();
this._meter_2_c.dismiss();
}
private function dismiss_meter_x():Void
{
this._meter_x_a.dismiss();
this._meter_x_b.dismiss();
this._meter_x_b_conditional.dismiss();
this._meter_x_c.dismiss();
}
public function discard():Void
{
this._character.SignalInvisibleBuffAdded.Disconnect(this.character_onTag, this);
this._character.SignalInvisibleBuffUpdated.Disconnect(this.character_onTag, this);
this._character.SignalBuffRemoved.Disconnect(this.character_onTag, this);
this._character.SignalBuffAdded.Disconnect(this.character_onTag, this);
this._inventory.SignalItemLoaded.Disconnect(this.inventory_onPlant, this);
this._inventory.SignalItemAdded.Disconnect(this.inventory_onPlant, this);
this._inventory.SignalItemChanged.Disconnect(this.inventory_onTransform, this);
this._inventory.SignalItemRemoved.Disconnect(this.inventory_onPluck, this);
clearInterval(this._timer);
this.discard_meter();
super.discard();
}
private function discard_meter():Void
{
this.discard_meter_1();
this.discard_meter_2();
}
private function discard_meter_1():Void
{
this.discard_meter_1_a();
this.discard_meter_1_b();
this.discard_meter_1_c();
}
private function discard_meter_1_a():Void
{
if (this._meter_1_a == null)
return;
Tweener.removeTweens(this._meter_1_a);
this._meter_1_a.discard();
this._meter_1_a = null;
}
private function discard_meter_1_b():Void
{
if (this._meter_1_b == null)
return;
Tweener.removeTweens(this._meter_1_b);
this._meter_1_b.discard();
this._meter_1_b = null;
}
private function discard_meter_1_c():Void
{
if (this._meter_1_c == null)
return;
Tweener.removeTweens(this._meter_1_c);
this._meter_1_c.discard();
this._meter_1_c = null;
}
private function discard_meter_2():Void
{
this.discard_meter_2_a();
this.discard_meter_2_b();
this.discard_meter_2_c();
}
private function discard_meter_2_a():Void
{
if (this._meter_2_a == null)
return;
Tweener.removeTweens(this._meter_2_a);
this._meter_2_a.discard();
this._meter_2_a = null;
}
private function discard_meter_2_b():Void
{
if (this._meter_2_b == null)
return;
Tweener.removeTweens(this._meter_2_b);
this._meter_2_b.discard();
this._meter_2_b = null;
}
private function discard_meter_2_c():Void
{
if (this._meter_2_c == null)
return;
Tweener.removeTweens(this._meter_2_c);
this._meter_2_c.discard();
this._meter_2_c = null;
}
private function discard_meter_x():Void
{
this.discard_meter_x_a();
this.discard_meter_x_b();
this.discard_meter_x_b_conditional();
this.discard_meter_x_c();
}
private function discard_meter_x_a():Void
{
if (this._meter_x_a == null)
return;
Tweener.removeTweens(this._meter_x_a);
this._meter_x_a.discard();
this._meter_x_a = null;
}
private function discard_meter_x_b():Void
{
if (this._meter_x_b == null)
return;
Tweener.removeTweens(this._meter_x_b);
this._meter_x_b.discard();
this._meter_x_b = null;
}
private function discard_meter_x_b_conditional():Void
{
if (this._meter_x_b_conditional == null)
return;
Tweener.removeTweens(this._meter_x_b_conditional);
this._meter_x_b_conditional.discard();
this._meter_x_b_conditional = null;
}
private function discard_meter_x_c():Void
{
if (this._meter_x_c == null)
return;
Tweener.removeTweens(this._meter_x_c);
this._meter_x_c.discard();
this._meter_x_c = null;
}
private function character_onTag(which:Number):Void
{
if (which == DualPistolsGauge.TAG_MATCH)
{
this.refresh_timer();
this.refresh_pulse();
}
else if (which == DualPistolsGauge.TAG_CHAMBER_1)
{
this.refresh_color_1();
}
else if (which == DualPistolsGauge.TAG_CHAMBER_2)
{
this.refresh_color_2();
}
}
private function inventory_onPlant(inventory:ID32, which:Number):Void
{
if (which != this._equip)
return;
this.refresh_maximum();
}
private function inventory_onTransform(inventory:ID32, which:Number):Void
{
if (which != this._equip)
return;
this.refresh_maximum();
}
private function inventory_onPluck(inventory:ID32, which:Number, replant:Boolean):Void
{
if (which != this._equip)
return;
this.refresh_maximum();
}
}
|
/**
* Apache License
* Version 2.0, January 2004
* http://www.apache.org/licenses/
*
* TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
*
* 1. Definitions.
*
* "License" shall mean the terms and conditions for use, reproduction,
* and distribution as defined by Sections 1 through 9 of this document.
*
* "Licensor" shall mean the copyright owner or entity authorized by
* the copyright owner that is granting the License.
*
* "Legal Entity" shall mean the union of the acting entity and all
* other entities that control, are controlled by, or are under common
* control with that entity. For the purposes of this definition,
* "control" means (i) the power, direct or indirect, to cause the
* direction or management of such entity, whether by contract or
* otherwise, or (ii) ownership of fifty percent (50%) or more of the
* outstanding shares, or (iii) beneficial ownership of such entity.
*
* "You" (or "Your") shall mean an individual or Legal Entity
* exercising permissions granted by this License.
*
* "Source" form shall mean the preferred form for making modifications,
* including but not limited to software source code, documentation
* source, and configuration files.
*
* "Object" form shall mean any form resulting from mechanical
* transformation or translation of a Source form, including but
* not limited to compiled object code, generated documentation,
* and conversions to other media types.
*
* "Work" shall mean the work of authorship, whether in Source or
* Object form, made available under the License, as indicated by a
* copyright notice that is included in or attached to the work
* (an example is provided in the Appendix below).
*
* "Derivative Works" shall mean any work, whether in Source or Object
* form, that is based on (or derived from) the Work and for which the
* editorial revisions, annotations, elaborations, or other modifications
* represent, as a whole, an original work of authorship. For the purposes
* of this License, Derivative Works shall not include works that remain
* separable from, or merely link (or bind by name) to the interfaces of,
* the Work and Derivative Works thereof.
*
* "Contribution" shall mean any work of authorship, including
* the original version of the Work and any modifications or additions
* to that Work or Derivative Works thereof, that is intentionally
* submitted to Licensor for inclusion in the Work by the copyright owner
* or by an individual or Legal Entity authorized to submit on behalf of
* the copyright owner. For the purposes of this definition, "submitted"
* means any form of electronic, verbal, or written communication sent
* to the Licensor or its representatives, including but not limited to
* communication on electronic mailing lists, source code control systems,
* and issue tracking systems that are managed by, or on behalf of, the
* Licensor for the purpose of discussing and improving the Work, but
* excluding communication that is conspicuously marked or otherwise
* designated in writing by the copyright owner as "Not a Contribution."
*
* "Contributor" shall mean Licensor and any individual or Legal Entity
* on behalf of whom a Contribution has been received by Licensor and
* subsequently incorporated within the Work.
*
* 2. Grant of Copyright License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* copyright license to reproduce, prepare Derivative Works of,
* publicly display, publicly perform, sublicense, and distribute the
* Work and such Derivative Works in Source or Object form.
*
* 3. Grant of Patent License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* (except as stated in this section) patent license to make, have made,
* use, offer to sell, sell, import, and otherwise transfer the Work,
* where such license applies only to those patent claims licensable
* by such Contributor that are necessarily infringed by their
* Contribution(s) alone or by combination of their Contribution(s)
* with the Work to which such Contribution(s) was submitted. If You
* institute patent litigation against any entity (including a
* cross-claim or counterclaim in a lawsuit) alleging that the Work
* or a Contribution incorporated within the Work constitutes direct
* or contributory patent infringement, then any patent licenses
* granted to You under this License for that Work shall terminate
* as of the date such litigation is filed.
*
* 4. Redistribution. You may reproduce and distribute copies of the
* Work or Derivative Works thereof in any medium, with or without
* modifications, and in Source or Object form, provided that You
* meet the following conditions:
*
* (a) You must give any other recipients of the Work or
* Derivative Works a copy of this License; and
*
* (b) You must cause any modified files to carry prominent notices
* stating that You changed the files; and
*
* (c) You must retain, in the Source form of any Derivative Works
* that You distribute, all copyright, patent, trademark, and
* attribution notices from the Source form of the Work,
* excluding those notices that do not pertain to any part of
* the Derivative Works; and
*
* (d) If the Work includes a "NOTICE" text file as part of its
* distribution, then any Derivative Works that You distribute must
* include a readable copy of the attribution notices contained
* within such NOTICE file, excluding those notices that do not
* pertain to any part of the Derivative Works, in at least one
* of the following places: within a NOTICE text file distributed
* as part of the Derivative Works; within the Source form or
* documentation, if provided along with the Derivative Works; or,
* within a display generated by the Derivative Works, if and
* wherever such third-party notices normally appear. The contents
* of the NOTICE file are for informational purposes only and
* do not modify the License. You may add Your own attribution
* notices within Derivative Works that You distribute, alongside
* or as an addendum to the NOTICE text from the Work, provided
* that such additional attribution notices cannot be construed
* as modifying the License.
*
* You may add Your own copyright statement to Your modifications and
* may provide additional or different license terms and conditions
* for use, reproduction, or distribution of Your modifications, or
* for any such Derivative Works as a whole, provided Your use,
* reproduction, and distribution of the Work otherwise complies with
* the conditions stated in this License.
*
* 5. Submission of Contributions. Unless You explicitly state otherwise,
* any Contribution intentionally submitted for inclusion in the Work
* by You to the Licensor shall be under the terms and conditions of
* this License, without any additional terms or conditions.
* Notwithstanding the above, nothing herein shall supersede or modify
* the terms of any separate license agreement you may have executed
* with Licensor regarding such Contributions.
*
* 6. Trademarks. This License does not grant permission to use the trade
* names, trademarks, service marks, or product names of the Licensor,
* except as required for reasonable and customary use in describing the
* origin of the Work and reproducing the content of the NOTICE file.
*
* 7. Disclaimer of Warranty. Unless required by applicable law or
* agreed to in writing, Licensor provides the Work (and each
* Contributor provides its Contributions) on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied, including, without limitation, any warranties or conditions
* of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
* PARTICULAR PURPOSE. You are solely responsible for determining the
* appropriateness of using or redistributing the Work and assume any
* risks associated with Your exercise of permissions under this License.
*
* 8. Limitation of Liability. In no event and under no legal theory,
* whether in tort (including negligence), contract, or otherwise,
* unless required by applicable law (such as deliberate and grossly
* negligent acts) or agreed to in writing, shall any Contributor be
* liable to You for damages, including any direct, indirect, special,
* incidental, or consequential damages of any character arising as a
* result of this License or out of the use or inability to use the
* Work (including but not limited to damages for loss of goodwill,
* work stoppage, computer failure or malfunction, or any and all
* other commercial damages or losses), even if such Contributor
* has been advised of the possibility of such damages.
*
* 9. Accepting Warranty or Additional Liability. While redistributing
* the Work or Derivative Works thereof, You may choose to offer,
* and charge a fee for, acceptance of support, warranty, indemnity,
* or other liability obligations and/or rights consistent with this
* License. However, in accepting such obligations, You may act only
* on Your own behalf and on Your sole responsibility, not on behalf
* of any other Contributor, and only if You agree to indemnify,
* defend, and hold each Contributor harmless for any liability
* incurred by, or claims asserted against, such Contributor by reason
* of your accepting any such warranty or additional liability.
*
* END OF TERMS AND CONDITIONS
*
* APPENDIX: How to apply the Apache License to your work.
*
* To apply the Apache License to your work, attach the following
* boilerplate notice, with the fields enclosed by brackets "{}"
* replaced with your own identifying information. (Don't include
* the brackets!) The text should be enclosed in the appropriate
* comment syntax for the file format. We also recommend that a
* file or class name and description of purpose be included on the
* same "printed page" as the copyright notice for easier
* identification within third-party archives.
*
* Copyright {yyyy} {name of copyright owner}
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.deleidos.rtws.tc.services.rest
{
import com.deleidos.rtws.tc.events.InstanceEvent;
import com.deleidos.rtws.tc.models.AuxiliaryModel;
import com.deleidos.rtws.tc.models.ParameterModel;
import com.deleidos.rtws.tc.services.IInstanceService;
import com.deleidos.rtws.tc.utils.HttpUtilities;
import mx.rpc.events.FaultEvent;
public class InstanceService extends TcSimpleTextBasedRestService implements IInstanceService
{
[Inject] public var parameterModel:ParameterModel;
[Inject] public var auxModel:AuxiliaryModel;
public function InstanceService():void
{
super("proxy/rtws/tenantapi/json/instance", 30);
}
public function retrieveGateway(tenantId:String):void
{
var context:Object = new Object();
context["event"] = new InstanceEvent(InstanceEvent.RETRIEVE_GATEWAY);
var url:String = "/anchor/" + encodeURIComponent(tenantId) +
"/" + encodeURIComponent(parameterModel.selectedRegion);
this.get(url, null, context);
}
protected override function processResponse(context:Object, data:String):void
{
var items:Array = HttpUtilities.getJsonArrayResponse(data);
if (context.event.type == InstanceEvent.RETRIEVE_GATEWAY) {
processRetrieveGatewayResponse(context, items);
}
}
protected override function processError(context:Object, event:FaultEvent):void
{
if (context.event.type == InstanceEvent.RETRIEVE_GATEWAY) {
dispatch(new InstanceEvent(InstanceEvent.RETRIEVE_GATEWAY_ERROR, {context:context, faultEvent:event}));
}
}
protected function processRetrieveGatewayResponse(context:Object, items:Array):void
{
auxModel.clear();
if (items.length > 0) {
var item:Object = items[0];
if (item.status != null) {
var status:Object = item.status;
if (status.state != null) auxModel.gatewayState = status.state;
if (status.message != null) auxModel.gatewayStatusMsg = status.message;
if (item["anchor-euca-public-ip"] != null) auxModel.gatewayPublicIpAddress = item["anchor-euca-public-ip"];
if (item.anchor != null) auxModel.gatewayPrivateIpAddress = item.anchor;
if (item.accounts != null) auxModel.accountsHostname = item.accounts;
if (item.database != null) auxModel.databaseIpAddress = item.database;
if (item.ldap != null) auxModel.ldapIpAddress = item.ldap;
}
}
dispatch(new InstanceEvent(InstanceEvent.RETRIEVE_GATEWAY_SUCCESS, {context:context}));
}
}
} |
package {
import flash.display.MovieClip
public class OverButtonShape extends MovieClip {
public function OverButtonShape() {
trace("//Constructed OverButtonShape (", this.name, ")!");
}
}
}
|
package
{
import org.flixel.FlxPoint;
import org.flixel.FlxSprite;
/**
* This class represents an object that can be abducted.
*
* While being abducted the object can be slowly dragged, and after released it will
* drop keepping the inertia.
*
* @author Alvaro Cavalcanti <alvarovictor@gmail.com>
*/
public class AbductableObject extends FlxSprite
{
private static const ACC_GRAVITY:int = 60;
private static const ACC_UPWARD:int = -40;
private static const ACC_HORIZONTAL:int = 20;
private static const MAX_VELOCITY_UP:int = 40;
private static const MAX_VELOCITY_DOWN:int = 80;
private static const MAX_VELOCITY_X:int = 25;
private static const VEL_DRAG:int = 10;
public var lifted:Boolean = false;
private var dragDirection:int = 0;
//public var stopping:Boolean = false;
public function AbductableObject(X:Number = 0, Y:Number = 0, SimpleGraphic:Class = null)
{
super(X, Y, SimpleGraphic);
this.maxVelocity.x = MAX_VELOCITY_X;
this.maxVelocity.y = MAX_VELOCITY_DOWN;
this.acceleration.y = ACC_GRAVITY;
this.drag.x = VEL_DRAG;
solid = true;
}
override public function update():void
{
super.update();
}
public function lift():void
{
if (!lifted) {
this.maxVelocity.y = MAX_VELOCITY_UP;
this.acceleration.y = ACC_UPWARD;
this.acceleration.x = 0;
this.lifted = true;
}
}
public function drop():void
{
if (lifted) {
this.maxVelocity.y = MAX_VELOCITY_DOWN;
this.acceleration.y = ACC_GRAVITY;
this.acceleration.x = 0;
this.lifted = false;
}
}
public function dragLeft():void
{
if (this.lifted) {
this.acceleration.x = -ACC_HORIZONTAL;
}
}
public function dragRight():void
{
if (this.lifted) {
this.acceleration.x = ACC_HORIZONTAL;
}
}
}
} |
////////////////////////////////////////////////////////////////////////////////
//
// ADOBE SYSTEMS INCORPORATED
// Copyright 2005-2006 Adobe Systems Incorporated
// All Rights Reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
package mx.effects.effectClasses
{
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import mx.core.mx_internal;
use namespace mx_internal;
/**
* The AddChildActionInstance class implements the instance class
* for the AddChildAction effect.
* Flex creates an instance of this class when it plays
* an AddChildAction effect; you do not create one yourself.
*
* @see mx.effects.AddChildAction
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public class AddChildActionInstance extends ActionEffectInstance
{
include "../../core/Version.as";
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @param target The Object to animate with this effect.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function AddChildActionInstance(target:Object)
{
super(target);
}
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
//----------------------------------
// index
//----------------------------------
/**
* The index of the child within the parent.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public var index:int = -1;
//----------------------------------
// relativeTo
//----------------------------------
/**
* The location where the child component is added.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public var relativeTo:DisplayObjectContainer;
//----------------------------------
// position
//----------------------------------
/**
* The position of the child component, relative to relativeTo, where it is added.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public var position:String;
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
override public function play():void
{
var targetDisplayObject:DisplayObject = DisplayObject(target);
// Dispatch an effectStart event from the target.
super.play();
if (!relativeTo && propertyChanges)
{
if (propertyChanges.start.parent == null &&
propertyChanges.end.parent != null)
{
relativeTo = propertyChanges.end.parent;
position = "index";
index = propertyChanges.end.index;
}
}
if (!playReversed)
{
// Set the style property
if (target && targetDisplayObject.parent == null && relativeTo)
{
switch (position)
{
case "index":
{
if (index == -1)
relativeTo.addChild(targetDisplayObject);
else
relativeTo.addChildAt(targetDisplayObject,
Math.min(index, relativeTo.numChildren));
break;
}
case "before":
{
relativeTo.parent.addChildAt(targetDisplayObject,
relativeTo.parent.getChildIndex(relativeTo));
break;
}
case "after":
{
relativeTo.parent.addChildAt(targetDisplayObject,
relativeTo.parent.getChildIndex(relativeTo) + 1);
break;
}
case "firstChild":
{
relativeTo.addChildAt(targetDisplayObject, 0);
}
case "lastChild":
{
relativeTo.addChild(targetDisplayObject);
}
}
}
}
else
{
if (target && relativeTo && targetDisplayObject.parent == relativeTo)
{
relativeTo.removeChild(targetDisplayObject);
}
}
// We're done...
finishRepeat();
}
}
}
|
package feathers.examples.layoutExplorer.data
{
import feathers.layout.HorizontalAlign;
import feathers.layout.VerticalAlign;
public class VerticalLayoutSettings
{
public function VerticalLayoutSettings()
{
}
public var itemCount:int = 75;
public var horizontalAlign:String = HorizontalAlign.LEFT;
public var verticalAlign:String = VerticalAlign.TOP;
public var gap:Number = 2;
public var paddingTop:Number = 0;
public var paddingRight:Number = 0;
public var paddingBottom:Number = 0;
public var paddingLeft:Number = 0;
}
}
|
package cmodule.lua_wrapper
{
public function __subc(param1:uint, param2:uint) : uint
{
var _loc3_:uint = 0;
_loc3_ = param1 - param2;
gstate.cf = uint(_loc3_ > param1);
return _loc3_;
}
}
|
package {
import flash.events.TimerEvent;
import flash.geom.Point;
import flash.utils.Timer;
import starling.display.Image;
import starling.display.Sprite;
import starling.display.Stage;
import starling.events.Event;
import starling.events.Touch;
import starling.events.TouchEvent;
import starling.events.TouchPhase;
import starling.text.TextField;
import starling.textures.TextureSmoothing;
import starling.utils.HAlign;
import starling.utils.VAlign;
public class Example1 {
static var tutorialText1:TextField;
static var tutorialText2:TextField;
static var dotList:Array = [];
static var turnRateList:Array = [0,0,0];
static var dropRate:Number = 0;
static var acceleration:Number = 1.3;
static var initFallSpeed:Number = (Board.dotWidth) * (3/111);
static var maxFallSpeed:Number = (Board.dotWidth) * (50/111);
static var alphaRate:Number = 0.18;
static var activeDot:int = 0;
static var touchList:Vector.<Touch>;
static var diffX:int;
static var origin:Point;
static var point:Point;
static var target:Image;
static var initX:int;
static var moveOK:Boolean = false;
static function setup(stage:Stage, dotWidth:int) {
// TEXT
tutorialText1 = new TextField(int(Environment.rectSprite.width*0.70), int(Environment.rectSprite.height*0.4412), String("LET'S GET\nSTARTED"), "Font", int(Environment.rectSprite.height*0.067), Hud.gameTextColor, false);
tutorialText1.hAlign = HAlign.CENTER;
tutorialText1.vAlign = VAlign.TOP;
tutorialText1.x = int((Environment.rectSprite.width/2 - tutorialText1.width/2) + Environment.rectSprite.x);
tutorialText1.y = int((Environment.rectSprite.height*0.0667) + Environment.rectSprite.y);
tutorialText1.touchable = false;
tutorialText1.alpha = 0;
stage.addChild(tutorialText1);
Screens.example1ScreenObjects.push(tutorialText1);
tutorialText2 = new TextField(int(Environment.rectSprite.width*0.80), int(Environment.rectSprite.height*0.13), String("SLIDE THE FAR\nBLOCK OVER"), "Font", int(Environment.rectSprite.height*0.0471), Hud.gameTextColor, false);
tutorialText2.hAlign = HAlign.CENTER;
tutorialText2.vAlign = VAlign.TOP;
tutorialText2.x = int((Environment.rectSprite.width/2 - tutorialText2.width/2) + Environment.rectSprite.x);
tutorialText2.y = int((Environment.rectSprite.height*0.72) + Environment.rectSprite.y);
tutorialText2.touchable = false;
tutorialText2.alpha = 0;
stage.addChild(tutorialText2);
Screens.example1ScreenObjects.push(tutorialText2);
// DOTS
var dot1:Image = Atlas.generate("game dot");
dot1.color = Board.dotColors0[0];
dot1.x = 0;
dot1.y = 0;
dot1.width = Board.dotWidth;
dot1.height = Board.dotWidth;
dot1.smoothing = TextureSmoothing.BILINEAR;
dot1.alpha = 0;
dotList.push(dot1);
Tutorial.tutSprite.addChild(dot1);
var dot2:Image = Atlas.generate("game dot");
dot2.color = Board.dotColors0[0];
dot2.x = dotWidth*2;
dot2.y = 0;
dot2.width = Board.dotWidth;
dot2.height = Board.dotWidth;
dot2.smoothing = TextureSmoothing.BILINEAR;
dot2.alpha = 0;
dotList.push(dot2);
Tutorial.tutSprite.addChild(dot2);
var dot3:Image = Atlas.generate("game dot");
dot3.color = Board.dotColors0[0];
dot3.x = dotWidth*3;
dot3.y = 0;
dot3.width = Board.dotWidth;
dot3.height = Board.dotWidth;
dot3.smoothing = TextureSmoothing.BILINEAR;
dot3.alpha = 0;
dotList.push(dot3);
Tutorial.tutSprite.addChild(dot3);
var timer5:Timer = new Timer(250);
timer5.start();
timer5.addEventListener(TimerEvent.TIMER, timer5Handler);
function timer5Handler(evt:TimerEvent):void {
timer5.addEventListener(TimerEvent.TIMER, timer5Handler);
timer5.stop();
timer5 = null
stage.addEventListener(Event.ENTER_FRAME, fadeInTitle);
function fadeInTitle(evt:Event):void {
if (tutorialText1.alpha < 1.0) {
tutorialText1.alpha += 0.08;
} else {
stage.removeEventListener(Event.ENTER_FRAME, fadeInTitle);
var timer4:Timer = new Timer(250);
timer4.start();
timer4.addEventListener(TimerEvent.TIMER, timerHandler4);
function timerHandler4(evt:TimerEvent):void {
timer4.stop();
timer4.removeEventListener(TimerEvent.TIMER, timerHandler4);
timer4 = null;
dot1.addEventListener(Event.ENTER_FRAME, drop);
stage.addEventListener(Event.ENTER_FRAME, fadeInSubTitle);
function fadeInSubTitle(evt:Event):void {
if (tutorialText2.alpha < 1.0) {
tutorialText2.alpha += 0.08;
} else {
stage.removeEventListener(Event.ENTER_FRAME, fadeInSubTitle);
}
}
}
}
}
}
function drop(evt:Event):void {
var h = evt.target;
if (turnRateList[activeDot] == 0) {
turnRateList[activeDot] = initFallSpeed;
}
if (dotList[activeDot].alpha < 1.0) {
dotList[activeDot].alpha += alphaRate;
}
turnRateList[activeDot] *= acceleration;
turnRateList[activeDot] = Math.ceil(turnRateList[activeDot]);
turnRateList[activeDot] = Math.min(turnRateList[activeDot], maxFallSpeed);
dotList[activeDot].y += turnRateList[activeDot];
if (dotList[activeDot].y > dotWidth*3) {
dotList[activeDot].y = dotWidth*3;
dotList[activeDot].removeEventListener(Event.ENTER_FRAME, drop);
activeDot++;
Audio.playClick();
if (activeDot <= 2) {
dotList[activeDot].addEventListener(Event.ENTER_FRAME, drop);
} else {
dot1.addEventListener(TouchEvent.TOUCH, moveDot1);
}
}
}
function moveDot1(evt:TouchEvent) {
touchList = evt.getTouches(Environment.stageRef);
if (touchList.length > 0) {
if (!moveOK && touchList[0].phase == TouchPhase.BEGAN) {
origin = touchList[0].getLocation(Tutorial.tutSprite);
point = touchList[0].getLocation(Tutorial.tutSprite);
target = evt.target as Image;
initX = target.x;
moveOK = true;
}
if (moveOK && touchList[0].phase == TouchPhase.MOVED) {
point = touchList[0].getLocation(Tutorial.tutSprite);
target.x -= origin.x - point.x;
diffX = point.x - origin.x;
// BOUNDS
if (target.x < 0) {
target.x = 0;
}
if (target.x >= dotWidth) {
target.x = dotWidth;
}
if (!target.bounds.containsPoint(point)) {
origin.x = target.x + target.width/2;
origin.y = target.y + target.height/2;
} else {
origin = touchList[0].getLocation(Tutorial.tutSprite);
}
}
if (moveOK && touchList[0].phase == TouchPhase.ENDED) {
moveOK = false;
// SNAP
if (target.x < Board.dotWidth/2) {
target.x = Board.dotWidth*0;
}
if (target.x >= dotWidth/2 && target.x < dotWidth*1.5) {
target.x =dotWidth*1;
}
// CHECK
if (target.x > 0) {
dot1.removeEventListener(TouchEvent.TOUCH, moveDot1);
dot1.pivotX = dot1.width/2 * 256/Board.dotWidth;
dot1.pivotY = dot1.height/2 * 256/Board.dotWidth;
dot1.x += (dot1.width/2);
dot1.y += (dot1.height/2);
dot2.pivotX = dot2.width/2 * 256/Board.dotWidth;
dot2.pivotY = dot2.height/2 * 256/Board.dotWidth;
dot2.x += (dot2.width/2);
dot2.y += (dot2.height/2);
dot3.pivotX = dot3.width/2 * 256/Board.dotWidth;
dot3.pivotY = dot3.height/2 * 256/Board.dotWidth;
dot3.x += (dot3.width/2);
dot3.y += (dot3.height/2);
Audio.playClear();
stage.addEventListener(Event.ENTER_FRAME, animate);
function animate(evt:Event) {
dot1.alpha -= 0.06;
dot1.scaleX *= 0.83;
dot1.scaleY *= 0.83;
dot2.alpha -= 0.06;
dot2.scaleX *= 0.83;
dot2.scaleY *= 0.83;
dot3.alpha -= 0.06;
dot3.scaleX *= 0.83;
dot3.scaleY *= 0.83;
if (dot1.alpha <=0) {
stage.removeEventListener(Event.ENTER_FRAME, animate);
Tutorial.tutSprite.removeChild(dot1);
Tutorial.tutSprite.removeChild(dot2);
Tutorial.tutSprite.removeChild(dot3);
var lastTransition:Timer = new Timer(550);
lastTransition.start();
lastTransition.addEventListener(TimerEvent.TIMER, lastTransitionHandler);
function lastTransitionHandler(evt:TimerEvent):void {
lastTransition.stop();
lastTransition.removeEventListener(TimerEvent.TIMER, lastTransitionHandler);
lastTransition = null;
stage.addEventListener(Event.ENTER_FRAME, loop2);
function loop2(evt:Event) {
tutorialText1.alpha -= 0.06;
tutorialText2.alpha -= 0.06;
if (tutorialText1.alpha <=0) {
stage.removeEventListener(Event.ENTER_FRAME, loop2);
var timer:Timer = new Timer(250);
timer.start();
timer.addEventListener(TimerEvent.TIMER, timerHandler);
function timerHandler(evt:TimerEvent):void {
timer.stop();
timer.removeEventListener(TimerEvent.TIMER, timerHandler);
timer = null;
tutorialText1.alpha = 0;
tutorialText1.y = dotWidth*3 + Tutorial.tutSprite.y + dotWidth - tutorialText1.height/2;
tutorialText1.text = String("WELL DONE");
tutorialText1.alpha = 1.0;
Audio.playExtra();
var timer2:Timer = new Timer(2000);
timer2.start();
timer2.addEventListener(TimerEvent.TIMER, timerHandler2);
function timerHandler2(evt:TimerEvent):void {
timer2.stop();
timer2.removeEventListener(TimerEvent.TIMER, timerHandler2);
timer2 = null;
stage.addEventListener(Event.ENTER_FRAME, fadeInEnd2);
function fadeInEnd2(evt:Event):void {
if (tutorialText1.alpha > 0) {
tutorialText1.alpha -= 0.08;
} else {
stage.removeEventListener(Event.ENTER_FRAME, fadeInEnd2);
Screens.clearExample1Screen();
Example2.setup(stage, dotWidth);
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
|
package com.company.assembleegameclient.ui.panels.itemgrids.itemtiles {
import com.company.assembleegameclient.objects.ObjectLibrary;
import com.company.util.PointUtil;
import flash.display.Bitmap;
import flash.display.Sprite;
import flash.filters.ColorMatrixFilter;
import flash.geom.Matrix;
import kabam.rotmg.text.view.BitmapTextFactory;
import kabam.rotmg.ui.view.components.PotionSlotView;
public class ItemTileSprite extends Sprite {
protected static const DIM_FILTER:Array = [new ColorMatrixFilter([0.4, 0, 0, 0, 0, 0, 0.4, 0, 0, 0, 0, 0, 0.4, 0, 0, 0, 0, 0, 1, 0])];
private static const IDENTITY_MATRIX:Matrix = new Matrix();
private static const DOSE_MATRIX:Matrix = function ():Matrix {
var _loc1_:* = new Matrix();
_loc1_.translate(8, 7);
return _loc1_;
}();
public function ItemTileSprite() {
super();
this.itemBitmap = new Bitmap();
addChild(this.itemBitmap);
this.itemId = -1;
}
public var itemId:int;
public var itemBitmap:Bitmap;
public function setDim(param1:Boolean):void {
filters = !!param1 ? DIM_FILTER : null;
}
public function setType(param1:int):void {
this.itemId = param1;
this.drawTile();
}
public function drawTile():void {
var _loc1_:* = null;
var _loc3_:* = null;
var _loc2_:* = null;
var _loc4_:int = this.itemId;
if (_loc4_ != -1) {
_loc1_ = ObjectLibrary.getRedrawnTextureFromType(_loc4_, 80, true);
_loc3_ = ObjectLibrary.xmlLibrary_[_loc4_];
if (_loc3_ && "Doses" in _loc3_) {
_loc1_ = _loc1_.clone();
_loc2_ = BitmapTextFactory.make(_loc3_.Doses, 12, 16777215, false, IDENTITY_MATRIX, false);
_loc2_.applyFilter(_loc2_, _loc2_.rect, PointUtil.ORIGIN, PotionSlotView.READABILITY_SHADOW_2);
_loc1_.draw(_loc2_, DOSE_MATRIX);
}
if (_loc3_ && "Quantity" in _loc3_) {
_loc1_ = _loc1_.clone();
_loc2_ = BitmapTextFactory.make(_loc3_.Quantity, 12, 16777215, false, IDENTITY_MATRIX, false);
_loc2_.applyFilter(_loc2_, _loc2_.rect, PointUtil.ORIGIN, PotionSlotView.READABILITY_SHADOW_2);
_loc1_.draw(_loc2_, DOSE_MATRIX);
}
this.itemBitmap.bitmapData = _loc1_;
this.itemBitmap.x = -_loc1_.width / 2;
this.itemBitmap.y = -_loc1_.height / 2;
visible = true;
} else {
visible = false;
}
}
}
}
|
package com.arxterra.utils
{
import com.arxterra.events.DebugByteArrayEvent;
import com.arxterra.events.DebugEventEx;
import com.arxterra.events.DialogEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.utils.ByteArray;
import flash.utils.setTimeout;
import mx.resources.IResourceManager;
import mx.resources.ResourceManager;
import mx.styles.IStyleManager2;
import mx.styles.StyleManager;
[Event(name="debugOut", type="com.arxterra.events.DebugEventEx")]
[Event(name="debug_byte_array", type="com.arxterra.events.DebugByteArrayEvent")]
/**
* Extends EventDispatcher with utility methods, such as <code>_callLater</code>,
* and access to <code>_resourceManager</code> and <code>_styleManager</code>,
* providing a light-weight alternative to UIComponent.
*/
public class NonUIComponentBase extends EventDispatcher
{
// STATIC CONSTANTS AND PROPERTIES
/**
* eventRelay IEventDispatcher reference to top level event dispatcher,
* such as the topLevelApplication, to dispatch events on behalf of
* objects not in the display list.
*/
public static var eventRelay:IEventDispatcher;
// CONSTRUCTOR / DESTRUCTOR
public function NonUIComponentBase ( )
{
super();
_styleMgr = StyleManager.getStyleManager ( null );
_rsrcMgr = ResourceManager.getInstance ( );
_rsrcMgr.addEventListener ( Event.CHANGE, _localeUpdate );
_CallQueueInit ( );
}
/**
* Overrides <b>must</b> call super.dismiss().
*/
public function dismiss ( ) : void
{
_CallQueueDismiss ( );
_rsrcMgr.removeEventListener ( Event.CHANGE, _localeUpdate );
_rsrcMgr = null;
_styleMgr = null;
}
// PROTECTED PROPERTIES AND ACCESSORS
protected function get _resourceManager ( ) : IResourceManager
{
return _rsrcMgr;
}
protected function get _styleManager ( ) : IStyleManager2
{
return _styleMgr;
}
// PROTECTED METHODS
protected function _alert (
message:String,
title:String = 'error',
messageParams:Array = null,
titleParams:Array = null
) : void
{
if ( eventRelay )
eventRelay.dispatchEvent (
new DialogEvent (
DialogEvent.ALERT,
message,
title,
messageParams,
titleParams
)
);
}
/**
* Works similarly to the UIComponent's callLater method, except its purpose
* is just to avoid blocking code and the timing of execution is not
* coordinated with display updates.
* @param func
* @param args
* @param scope
*/
protected function _callLater ( func:Function, args:Array = null, scope:Object = null ) : void
{
var oScope:Object = scope || this;
_vCallQueue [ _vCallQueue.length ] = new CallLaterData ( func, args, oScope, setTimeout ( _CallQueueService, _uCallDelay ) );
}
/**
* Sets timer delay for _callLater method
* @param msec milliseconds no less than 20,
* which is shortest interval considered safe in AS3 docs
*/
protected function _callLaterDelaySet ( msec:uint = 20 ) : void
{
if ( msec < 20 )
{
_uCallDelay = 20;
}
else
{
_uCallDelay = msec;
}
}
protected function _debugByteArrayOut ( messageResource:String, bytes:ByteArray ) : void
{
if ( eventRelay )
{
eventRelay.dispatchEvent ( new DebugByteArrayEvent ( DebugByteArrayEvent.DEBUG_BYTE_ARRAY, messageResource, bytes ) );
}
dispatchEvent ( new DebugByteArrayEvent ( DebugByteArrayEvent.DEBUG_BYTE_ARRAY, messageResource, bytes ) );
}
protected function _debugEventRelay ( event:DebugEventEx ) : void
{
if ( eventRelay )
{
eventRelay.dispatchEvent ( event );
}
dispatchEvent ( event );
}
protected function _debugOut (
message:String = '',
isResource:Boolean = false,
resourceParams:Array = null,
alertOk:Boolean = false,
end:String = '\n'
) : void
{
if ( eventRelay )
{
eventRelay.dispatchEvent (
new DebugEventEx (
DebugEventEx.DEBUG_OUT,
message,
isResource,
resourceParams,
alertOk,
end
)
);
}
dispatchEvent (
new DebugEventEx (
DebugEventEx.DEBUG_OUT,
message,
isResource,
resourceParams,
alertOk,
end
)
);
}
/**
* Initializes localization data loaded dynamically,
* such as from database queries and external configuration files.
* @param localeData Object with localization objects keyed to locale names, such as 'en_US'
* @param propNames Names of properties to be localized
* @param propDefaultValues Optional vector to provide default values
* if they are not simply the initial values of propNames properties
*/
protected function _dynamicLocalePropsInit (
localeData:Object,
propNames:Vector.<String>,
propDefaultValues:Vector.<String> = null
) : void
{
var i:int;
if ( localeData != null )
{
_oDynLocData = localeData;
_iDynLocPropsLim = propNames.length;
if ( _iDynLocPropsLim > 0 )
{
_vDynLocPropNames = propNames;
if ( propDefaultValues != null && propDefaultValues.length >= _iDynLocPropsLim )
{
// use supplied defaults
_vDynLocPropDefVals = propDefaultValues;
}
else
{
// use current values as defaults
_vDynLocPropDefVals = new <String> [];
for ( i=0; i<_iDynLocPropsLim; i++ )
{
_vDynLocPropDefVals [ i ] = this [ _vDynLocPropNames [ i ] ];
}
}
}
}
}
/**
* For any localizable properties initialized via the
* _dynamicLocalePropsInit method, looks up values
* based upon current locale chain
*/
protected function _dynamicLocalePropsUpdate ( ) : void
{
if ( _iDynLocPropsLim > 0 )
{
var vChain:Vector.<String> = Vector.<String> ( _resourceManager.localeChain );
var vLocObjs:Vector.<Object> = new <Object> [];
var i:int;
var iChainLim:int = vChain.length;
var iObjsLim:int;
var i_sLocName:String;
var i_sPropName:String;
var j:int;
var j_oLocData:Object;
// iterate locale chain to assemble array of available matching
// locale objects, if any, in current chain order
for ( i=0; i<iChainLim; i++ )
{
i_sLocName = vChain [ i ];
if ( i_sLocName in _oDynLocData )
{
vLocObjs [ iObjsLim++ ] = _oDynLocData [ i_sLocName ] as Object;
}
}
if ( iObjsLim < 1 )
{
// found nothing that matches current locale chain,
// so set all to defaults
for ( i=0; i<_iDynLocPropsLim; i++ )
{
this [ _vDynLocPropNames [ i ] ] = _vDynLocPropDefVals [ i ];
}
}
else
{
// iterate property names to be localized
propsLoop: for ( i=0; i<_iDynLocPropsLim; i++ )
{
i_sPropName = _vDynLocPropNames [ i ];
// iterate available locale objects until find localized value, if any
for ( j=0; j<iObjsLim; j++ )
{
j_oLocData = vLocObjs [ j ];
if ( i_sPropName in j_oLocData )
{
this [ i_sPropName ] = j_oLocData [ i_sPropName ] as String;
continue propsLoop;
}
}
// if get here, found nothing for this property in current locale chain, so use default
this [ i_sPropName ] = _vDynLocPropDefVals [ i ];
}
}
}
}
/**
* Handles locale change events.
* Subclass overrides should call super._localeUpdate()
*/
protected function _localeUpdate ( event:Event = null ) : void
{
_dynamicLocalePropsUpdate ( );
}
// PRIVATE PROPERTIES
private var _iDynLocPropsLim:int = 0;
private var _oDynLocData:Object;
private var _rsrcMgr:IResourceManager;
private var _styleMgr:IStyleManager2;
private var _uCallDelay:uint = 20;
private var _vCallQueue:Vector.<CallLaterData>;
private var _vDynLocPropDefVals:Vector.<String>;
private var _vDynLocPropNames:Vector.<String>;
// PRIVATE METHODS
private function _CallQueueDismiss ( ) : void
{
var i:int;
var iLim:int;
if ( _vCallQueue )
{
iLim = _vCallQueue.length;
for ( i=0; i<iLim; i++ )
{
_vCallQueue [ i ].cancel ( );
}
_vCallQueue.length = 0;
_vCallQueue = null;
}
}
private function _CallQueueInit ( ) : void
{
_vCallQueue = new <CallLaterData> [];
}
private function _CallQueueService ( ) : void
{
var cld:CallLaterData;
if ( _vCallQueue.length > 0 )
{
cld = _vCallQueue.shift ( );
cld.call ( );
cld = null;
}
}
}
} |
var size;
var DEBUG=true;
var datasizes = new Array(4);
datasizes[0] = 3000000;
datasizes[1] = 20000000;
datasizes[2] = 50000000;
datasizes[3] = 100000;
// Declare class data. Byte buffer plain1 holds the original
// data for encryption, crypt1 holds the encrypted data, and
// plain2 holds the decrypted data, which should match plain1
// byte for byte.
var array_rows;
var plain1; // byte Buffer for plaintext data.
var crypt1; // byte Buffer for encrypted data.
var plain2; // byte Buffer for decrypted data.
var userkey; // short Key for encryption/decryption.
var Z; // int Encryption subkey (userkey derived).
var RANDOM_SEED = 10101010;
var lastRandom=RANDOM_SEED;
var DK;
if (CONFIG::desktop) {
var start = new Date();
JGFrun(0);
var elapsed = new Date() - start;
}
else { // mobile
var start = getTimer();
JGFrun(3);
var elapsed = getTimer() - start;
}
if (JGFvalidate())
print("metric time "+elapsed);
else
print("validation failed");
function _randomInt()
{
lastRandom = (lastRandom * 214013 + 2531011) % 16777216;
return lastRandom;
}
function JGFsetsize(sizel) {
size = sizel;
}
function JGFinitialise() {
array_rows = datasizes[size];
buildTestData();
}
function JGFkernel() {
Do();
}
function JGFvalidate() {
var error;
error = false;
for (var i = 0; i < array_rows; i++) {
error = (plain1[i] != plain2[i]);
if (error) {
print("Validation failed");
print("Original Byte " + i + " = " + plain1[i]);
print("Encrypted Byte " + i + " = " + crypt1[i]);
print("Decrypted Byte " + i + " = " + plain2[i]);
break;
}
}
return !error;
}
function JGFrun(size) {
JGFsetsize(size);
JGFinitialise();
JGFkernel();
JGFvalidate();
}
function Do() {
cipher_idea(plain1, crypt1, Z); // Encrypt plain1.
//Alex: Since javascript doesn't handle specific byte type this converts whatever is
//Alx: returned in to a byte. So cuts of extra stuff that is not needed.
/*
for(var i=0;i<crypt1.length;i++)
{
crypt1[i] = crypt1[i]&0xFF;
}*/
//printarray("plain1",plain1);
//printarray("crypt1",crypt1);
cipher_idea(crypt1, plain2, DK); // Decrypt.
//Alex: Since javascript doesn't handle specific byte type this converts whatever is
//Alx: returned in to a byte. So cuts of extra stuff that is not needed.
/*
for(var i=0;i<crypt1.length;i++)
{
plain2[i] = plain2[i]&0xFF;
}*/
//printarray("plain2: ",plain2);
}
/*
* buildTestData
*
* Builds the data used for the test -- each time the test is run.
*/
function buildTestData() {
// Create three byte arrays that will be used (and reused) for
// encryption/decryption operations.
plain1 = new Array(array_rows);
crypt1 = new Array(array_rows);
plain2 = new Array(array_rows);
//Random rndnum = new Random(136506717L); // Create random number
// generator.
// Allocate three arrays to hold keys: userkey is the 128-bit key.
// Z is the set of 16-bit encryption subkeys derived from userkey,
// while DK is the set of 16-bit decryption subkeys also derived
// from userkey. NOTE: The 16-bit values are stored here in
// 32-bit int arrays so that the values may be used in calculations
// as if they are unsigned. Each 64-bit block of plaintext goes
// through eight processing rounds involving six of the subkeys
// then a final output transform with four of the keys; (8 * 6)
// + 4 = 52 subkeys.
userkey = new Array(8); // User key has 8 16-bit shorts.
Z = new Array(52); // Encryption subkey (user key derived).
DK = new Array(52); // Decryption subkey (user key derived).
// Generate user key randomly; eight 16-bit values in an array.
for (var i = 0; i < 8; i++) {
// Again, the random number function returns int. Converting
// to a short type preserves the bit pattern in the lower 16
// bits of the int and discards the rest.
userkey[i] = _randomInt()%65535;
//print("user Key: "+userkey[i]);
}
// Compute encryption and decryption subkeys.
calcEncryptKey();
calcDecryptKey();
// Fill plain1 with "text."
for (var i = 0; i < array_rows; i++) {
//Alex: Since JS doesn't cut of bytes if value is stored in byte array I need to do it manually.
plain1[i] = i&0xFF;
//Alex makes sure all the values are 1 byte long since this is suppose to be byte array
//plain1[i]= (plain1[i]<<24);
//plain1[i]=(plain1[i]>>>24);
// Converting to a byte
// type preserves the bit pattern in the lower 8 bits of the
// int and discards the rest.
}
//print("exiting buildTestData");
//printarray("plain1",plain1);
//printarray("userkey",userkey);
}
/*
* calcEncryptKey
*
* Builds the 52 16-bit encryption subkeys Z[] from the user key and stores
* in 32-bit int array. The routing corrects an error in the source code in
* the Schnier book. Basically, the sense of the 7- and 9-bit shifts are
* reversed. It still works reversed, but would encrypted code would not
* decrypt with someone else's IDEA code.
*/
function calcEncryptKey() {
var j; // Utility variable.
for (var i = 0; i < 52; i++)
// Zero out the 52-int Z array.
Z[i] = 0;
for (var i = 0; i < 8; i++) // First 8 subkeys are userkey itself.
{
Z[i] = userkey[i] & 0xffff; // Convert "unsigned"
// short to int.
}
//printarray("userkey",userkey);
//printarray("Z array",Z);
// Each set of 8 subkeys thereafter is derived from left rotating
// the whole 128-bit key 25 bits to left (once between each set of
// eight keys and then before the last four). Instead of actually
// rotating the whole key, this routine just grabs the 16 bits
// that are 25 bits to the right of the corresponding subkey
// eight positions below the current subkey. That 16-bit extent
// straddles two array members, so bits are shifted left in one
// member and right (with zero fill) in the other. For the last
// two subkeys in any group of eight, those 16 bits start to
// wrap around to the first two members of the previous eight.
for (var i = 8; i < 52; i++) {
j = i % 8;
if (j < 6) {
Z[i] = ((Z[i - 7] >>> 9) | (Z[i - 6] << 7)) & 0xFFFF; // Just 16 bits.
continue; // Next iteration.
}
if (j == 6) // Wrap to beginning for second chunk.
{
Z[i] = ((Z[i - 7] >>> 9) | (Z[i - 14] << 7)) & 0xFFFF;
continue;
}
// j == 7 so wrap to beginning for both chunks.
Z[i] = ((Z[i - 15] >>> 9) | (Z[i - 14] << 7)) & 0xFFFF;
}
//printarray("Encryption key: ",Z);
}
/*
* calcDecryptKey
*
* Builds the 52 16-bit encryption subkeys DK[] from the encryption- subkeys
* Z[]. DK[] is a 32-bit int array holding 16-bit values as unsigned.
*/
function calcDecryptKey() {
var j, k; // Index counters.
var t1, t2, t3; // Temps to hold decrypt subkeys.
t1 = inv(Z[0]); // Multiplicative inverse (mod x10001).
t2 = -Z[1] & 0xffff; // Additive inverse, 2nd encrypt subkey.
t3 = -Z[2] & 0xffff; // Additive inverse, 3rd encrypt subkey.
DK[51] = inv(Z[3]); // Multiplicative inverse (mod x10001).
DK[50] = t3;
DK[49] = t2;
DK[48] = t1;
j = 47; // Indices into temp and encrypt arrays.
k = 4;
for (var i = 0; i < 7; i++) {
t1 = Z[k++];
DK[j--] = Z[k++];
DK[j--] = t1;
t1 = inv(Z[k++]);
t2 = -Z[k++] & 0xffff;
t3 = -Z[k++] & 0xffff;
DK[j--] = inv(Z[k++]);
DK[j--] = t2;
DK[j--] = t3;
DK[j--] = t1;
}
t1 = Z[k++];
DK[j--] = Z[k++];
DK[j--] = t1;
t1 = inv(Z[k++]);
t2 = -Z[k++] & 0xffff;
t3 = -Z[k++] & 0xffff;
DK[j--] = inv(Z[k++]);
DK[j--] = t3;
DK[j--] = t2;
DK[j--] = t1;
//print("Decryption key");
//printarray("DK: ",DK);
}
/*
* cipher_idea
*
* IDEA encryption/decryption algorithm. It processes plaintext in 64-bit
* blocks, one at a time, breaking the block into four 16-bit unsigned
* subblocks. It goes through eight rounds of processing using 6 new subkeys
* each time, plus four for last step. The source text is in array text1,
* the destination text goes into array text2 The routine represents 16-bit
* subblocks and subkeys as type int so that they can be treated more easily
* as unsigned. Multiplication modulo 0x10001 interprets a zero sub-block as
* 0x10000; it must to fit in 16 bits.
*/
function cipher_idea(text1, text2, key)
{
var i1 = 0; // Index into first text array.
var i2 = 0; // Index varo second text array.
var ik; // Index varo key array.
var x1, x2, x3, x4, t1, t2; // Four "16-bit" blocks, two temps.
var r; // Eight rounds of processing.
for (var i = 0; i < text1.length; i += 8) {
ik = 0; // Restart key index.
r = 8; // Eight rounds of processing.
// Load eight plain1 bytes as four 16-bit "unsigned" varegers.
// Masking with 0xff prevents sign extension with cast to var.
x1 = text1[i1++] & 0xff; // Build 16-bit x1 from 2 bytes,
x1 |= (text1[i1++] & 0xff) << 8; // assuming low-order byte
// first.
x2 = text1[i1++] & 0xff;
x2 |= (text1[i1++] & 0xff) << 8;
x3 = text1[i1++] & 0xff;
x3 |= (text1[i1++] & 0xff) << 8;
x4 = text1[i1++] & 0xff;
x4 |= (text1[i1++] & 0xff) << 8;
do {
// 1) Multiply (modulo 0x10001), 1st text sub-block
// with 1st key sub-block.
x1 = x1 * key[ik++] % 0x10001 & 0xffff;
// 2) Add (modulo 0x10000), 2nd text sub-block
// with 2nd key sub-block.
x2 = x2 + key[ik++] & 0xffff;
// 3) Add (modulo 0x10000), 3rd text sub-block
// with 3rd key sub-block.
x3 = x3 + key[ik++] & 0xffff;
// 4) Multiply (modulo 0x10001), 4th text sub-block
// with 4th key sub-block.
x4 = x4 * key[ik++] % 0x10001 & 0xffff;
// 5) XOR results from steps 1 and 3.
t2 = x1 ^ x3;
// 6) XOR results from steps 2 and 4.
// Included in step 8.
// 7) Multiply (modulo 0x10001), result of step 5
// with 5th key sub-block.
t2 = t2 * key[ik++] % 0x10001 & 0xffff;
// 8) Add (modulo 0x10000), results of steps 6 and 7.
t1 = t2 + (x2 ^ x4) & 0xffff;
// 9) Multiply (modulo 0x10001), result of step 8
// with 6th key sub-block.
t1 = t1 * key[ik++] % 0x10001 & 0xffff;
// 10) Add (modulo 0x10000), results of steps 7 and 9.
t2 = t1 + t2 & 0xffff;
// 11) XOR results from steps 1 and 9.
x1 ^= t1;
// 14) XOR results from steps 4 and 10. (Out of order).
x4 ^= t2;
// 13) XOR results from steps 2 and 10. (Out of order).
t2 ^= x2;
// 12) XOR results from steps 3 and 9. (Out of order).
x2 = x3 ^ t1;
x3 = t2; // Results of x2 and x3 now swapped.
} while (--r != 0); // Repeats seven more rounds.
// Final output transform (4 steps).
// 1) Multiply (modulo 0x10001), 1st text-block
// with 1st key sub-block.
x1 = x1 * key[ik++] % 0x10001 & 0xffff;
// 2) Add (modulo 0x10000), 2nd text sub-block
// with 2nd key sub-block. It says x3, but that is to undo swap
// of subblocks 2 and 3 in 8th processing round.
x3 = x3 + key[ik++] & 0xffff;
// 3) Add (modulo 0x10000), 3rd text sub-block
// with 3rd key sub-block. It says x2, but that is to undo swap
// of subblocks 2 and 3 in 8th processing round.
x2 = x2 + key[ik++] & 0xffff;
// 4) Multiply (modulo 0x10001), 4th text-block
// with 4th key sub-block.
x4 = x4 * key[ik++] % 0x10001 & 0xffff;
// Repackage from 16-bit sub-blocks to 8-bit byte array text2.
//Alex: & by FF so ony lower two bytes are stored.
//Alex: in Java this happens automatically when casted to byte
text2[i2++] = x1&0xFF;
text2[i2++] = (x1 >>> 8);
text2[i2++] = x3&0xFF; // x3 and x2 are switched
text2[i2++] = (x3 >>> 8); // only in name.
text2[i2++] = x2&0xFF;
text2[i2++] = (x2 >>> 8);
text2[i2++] = x4&0xFF;
text2[i2++] = (x4 >>> 8);
} // End for loop.
} // End routine.
/*
* mul
*
* Performs multiplication, modulo (2**16)+1. This code is structured on the
* assumption that untaken branches are cheaper than taken branches, and
* that the compiler doesn't schedule branches. Java: Must work with 32-bit
* var and one 64-bit long to keep 16-bit values and their products
* "unsigned." The routine assumes that both a and b could fit in 16 bits
* even though they come in as 32-bit vars. Lots of "& 0xFFFF" masks here to
* keep things 16-bit. Also, because the routine stores mod (2**16)+1
* results in a 2**16 space, the result is truncated to zero whenever the
* result would zero, be 2**16. And if one of the multiplicands is 0, the
* result is not zero, but (2**16) + 1 minus the other multiplicand (sort of
* an additive inverse mod 0x10001).
*
* NOTE: The java conversion of this routine works correctly, but is half
* the speed of using Java's modulus division function (%) on the
* multiplication with a 16-bit masking of the result--running in the
* Symantec Caje IDE. So it's not called for now; the test uses Java %
* instead.
*/
function mul(a, b){
var p; // Large enough to catch 16-bit multiply
// without hitting sign bit.
if (a != 0) {
if (b != 0) {
p = a * b;
b = p & 0xFFFF; // Lower 16 bits.
a = p >>> 16; // Upper 16 bits.
return (b - a + (b < a ? 1 : 0) & 0xFFFF);
} else
return ((1 - a) & 0xFFFF); // If b = 0, then same as
// 0x10001 - a.
} else
// If a = 0, then return
return ((1 - b) & 0xFFFF); // same as 0x10001 - b.
}
/*
* inv
*
* Compute multiplicative inverse of x, modulo (2**16)+1 using extended
* Euclid's GCD (greatest common divisor) algorithm. It is unrolled twice to
* avoid swapping the meaning of the registers. And some subtracts are
* changed to adds. Java: Though it uses signed 32-bit vars, the
* varerpretation of the bits within is strictly unsigned 16-bit.
*/
function inv(x) {
var t0, t1;
var q, y;
if (x <= 1) // Assumes positive x.
return (x); // 0 and 1 are self-inverse.
/* (2**16+1)/x; x is >= 2, so fits 16 bits.*/
t1 = Math.floor(0x10001 / x);
y = 0x10001 % x;
if (y == 1)
return ((1 - t1) & 0xFFFF);
t0 = 1;
do {
q = Math.floor(x / y);
x = x % y;
t0 += q * t1;
if (x == 1)
return (t0);
q = Math.floor(y / x);
y = y % x;
t1 += q * t0;
} while (y != 1);
return ((1 - t1) & 0xFFFF);
}
function printarray(_name,_data)
{
var _length =_data.length;
print(_name);
for(var i=0;i<_length;i++)
{
print(i+" element:"+_data[i]);
}
}
|
package lib.engine.iface.game
{
/**
* 游戏状态
* @author caihua
*
*/
public interface IGameState
{
/**
* 获取状态名称
*/
function getStateName():String;
/**
* 进入状态
*
*/
function onEnterState(params:Object = null):void;
/**
* 退出状态
*
*/
function onExitState(params:Object = null):void;
}
} |
/* ***** 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 ***** */
import GetSetStaticExtended.*;
var SECTION = "FunctionAccessors";
var VERSION = "AS3";
var TITLE = "Function Accessors";
var BUGNUMBER = "";
startTest();
var res;
/*
*
* statics are not inherited
* New instances of vars will be created since the statics don't exist
*
*/
try {
AddTestCase("Static getter var:int", undefined, GetSetStatic.y);
res = "no exception";
} catch(e1) {
res = "exception";
}
AddTestCase("Static getter var:int", "no exception", res);
try {
AddTestCase("Static setter var:int", 23334, (GetSetStatic.y = 23334, GetSetStatic.y));
res = "no exception";
} catch(e2) {
res = "exception";
}
AddTestCase("Static setter var:int", "no exception", res);
try {
// exception calling toString() on undefined GetSetStatic.x
GetSetStatic.x.toString();
res = "no exception";
} catch(e3) {
res = "exception";
}
AddTestCase("Static getter var:Array", "exception", res);
try {
AddTestCase("Static setter var:Array", "4,5,6", (GetSetStatic.x = new Array(4,5,6), GetSetStatic.x.toString()));
res = "no exception";
} catch(e4) {
res = "exception";
}
AddTestCase("Static setter var:Array", "no exception", res);
try {
AddTestCase("Static getter var:Boolean", undefined, GetSetStatic.boolean);
res = "no exception";
} catch(e5) {
res = "exception";
}
AddTestCase("Static getter var:Boolean", "no exception", res);
try {
AddTestCase("Static setter var:Boolean", false, (GetSetStatic.boolean = false, GetSetStatic.boolean));
res = "no exception";
} catch(e6) {
res = "exception";
}
AddTestCase("Static setter var:Boolean", "no exception", res);
try {
AddTestCase("Static getter var:uint", undefined, GetSetStatic.u);
res = "no exception";
} catch(e7) {
res = "exception";
}
AddTestCase("Static getter var:uint", "no exception", res);
try {
AddTestCase("Static setter var:uint", 42, (GetSetStatic.u = 42, GetSetStatic.u));
res = "no exception";
} catch(e8) {
res = "exception";
}
AddTestCase("Static setter var:uint", "no exception", res);
try {
AddTestCase("Static getter var:String", undefined, GetSetStatic.string);
res = "no exception";
} catch(e9) {
res = "exception";
}
AddTestCase("Static getter var:String", "no exception", res);
try {
AddTestCase("Static setter var:String", "new string", (GetSetStatic.string = "new string", GetSetStatic.string));
res = "no exception";
} catch(e10) {
res = "exception";
}
AddTestCase("Static setter var:String", "no exception", res);
test();
|
////////////////////////////////////////////////////////////////////////////////
//
// 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
{
internal class MobileThemeClassesAIR2
{
/**
* @private
* This class is used to link additional classes into mobile.swc
* beyond those that are found by dependecy analysis starting
* from the classes specified in manifest.xml.
*/
import spark.skins.mobile.ActionBarSkin; ActionBarSkin;
import spark.skins.mobile.BeveledActionButtonSkin; BeveledActionButtonSkin;
import spark.skins.mobile.BeveledBackButtonSkin; BeveledBackButtonSkin;
import spark.skins.mobile.ButtonBarSkin; spark.skins.mobile.ButtonBarSkin;
import spark.skins.mobile.ButtonSkin; spark.skins.mobile.ButtonSkin;
import spark.skins.mobile.CalloutSkin; spark.skins.mobile.CalloutSkin;
import spark.skins.mobile.CalloutActionBarSkin; spark.skins.mobile.CalloutActionBarSkin;
import spark.skins.mobile.CalloutViewNavigatorSkin; spark.skins.mobile.CalloutViewNavigatorSkin;
import spark.skins.mobile.CheckBoxSkin; spark.skins.mobile.CheckBoxSkin;
import spark.skins.mobile.DefaultBeveledActionButtonSkin; spark.skins.mobile.DefaultBeveledActionButtonSkin;
import spark.skins.mobile.DefaultBeveledBackButtonSkin; spark.skins.mobile.DefaultBeveledBackButtonSkin;
import spark.skins.mobile.DefaultButtonSkin; spark.skins.mobile.DefaultButtonSkin;
import spark.skins.mobile.DefaultTransparentActionButtonSkin; spark.skins.mobile.DefaultTransparentActionButtonSkin;
import spark.skins.mobile.DefaultTransparentNavigationButtonSkin; spark.skins.mobile.DefaultTransparentNavigationButtonSkin;
import spark.skins.mobile.DateSpinnerSkin; spark.skins.mobile.DateSpinnerSkin;
import spark.skins.mobile.HScrollBarSkin; spark.skins.mobile.HScrollBarSkin;
import spark.skins.mobile.HSliderSkin; spark.skins.mobile.HSliderSkin;
import spark.skins.mobile.ImageSkin; spark.skins.mobile.ImageSkin;
import spark.skins.mobile.ListSkin; spark.skins.mobile.ListSkin;
import spark.skins.mobile.RadioButtonSkin; spark.skins.mobile.RadioButtonSkin;
import spark.skins.mobile.SpinnerListContainerSkin; SpinnerListContainerSkin;
import spark.skins.mobile.SpinnerListScrollerSkin; SpinnerListScrollerSkin;
import spark.skins.mobile.SpinnerListSkin; SpinnerListSkin;
import spark.skins.mobile.SkinnableContainerSkin; SkinnableContainerSkin;
import spark.skins.mobile.SplitViewNavigatorSkin; SplitViewNavigatorSkin;
import spark.skins.mobile.TabbedViewNavigatorApplicationSkin; TabbedViewNavigatorApplicationSkin;
import spark.skins.mobile.TabbedViewNavigatorSkin; TabbedViewNavigatorSkin;
import spark.skins.mobile.TabbedViewNavigatorTabBarSkin; TabbedViewNavigatorTabBarSkin;
import spark.skins.mobile.TextAreaSkin; TextAreaSkin;
import spark.skins.mobile.TextAreaHScrollBarSkin; TextAreaHScrollBarSkin;
import spark.skins.mobile.TextAreaVScrollBarSkin; TextAreaVScrollBarSkin;
import spark.skins.mobile.TextInputSkin; TextInputSkin;
import spark.skins.mobile.ToggleSwitchSkin; ToggleSwitchSkin;
import spark.skins.mobile.TransparentActionButtonSkin; TransparentActionButtonSkin;
import spark.skins.mobile.TransparentNavigationButtonSkin; TransparentNavigationButtonSkin;
import spark.skins.mobile.ViewMenuItemSkin; ViewMenuItemSkin;
import spark.skins.mobile.ViewMenuSkin; ViewMenuSkin;
import spark.skins.mobile.ViewNavigatorApplicationSkin; ViewNavigatorApplicationSkin;
import spark.skins.mobile.ViewNavigatorSkin; ViewNavigatorSkin;
import spark.skins.mobile.VScrollBarSkin; spark.skins.mobile.VScrollBarSkin;
}
}
|
package starling.utils
{
import flash.geom.Matrix;
import flash.geom.Matrix3D;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.geom.Vector3D;
import starling.errors.AbstractClassError;
public class Pool
{
private static var sPoints:Vector.<Point> = new Vector.<Point>(0);
private static var sPoints3D:Vector.<Vector3D> = new Vector.<Vector3D>(0);
private static var sMatrices:Vector.<Matrix> = new Vector.<Matrix>(0);
private static var sMatrices3D:Vector.<Matrix3D> = new Vector.<Matrix3D>(0);
private static var sRectangles:Vector.<Rectangle> = new Vector.<Rectangle>(0);
public function Pool()
{
super();
throw new AbstractClassError();
}
public static function getPoint(param1:Number = 0, param2:Number = 0) : Point
{
var _loc3_:* = null;
if(sPoints.length == 0)
{
return new Point(param1,param2);
}
_loc3_ = sPoints.pop();
_loc3_.x = param1;
_loc3_.y = param2;
return _loc3_;
}
public static function putPoint(param1:Point) : void
{
if(param1)
{
sPoints[sPoints.length] = param1;
}
}
public static function getPoint3D(param1:Number = 0, param2:Number = 0, param3:Number = 0) : Vector3D
{
var _loc4_:* = null;
if(sPoints3D.length == 0)
{
return new Vector3D(param1,param2,param3);
}
_loc4_ = sPoints3D.pop();
_loc4_.x = param1;
_loc4_.y = param2;
_loc4_.z = param3;
return _loc4_;
}
public static function putPoint3D(param1:Vector3D) : void
{
if(param1)
{
sPoints3D[sPoints3D.length] = param1;
}
}
public static function getMatrix(param1:Number = 1, param2:Number = 0, param3:Number = 0, param4:Number = 1, param5:Number = 0, param6:Number = 0) : Matrix
{
var _loc7_:* = null;
if(sMatrices.length == 0)
{
return new Matrix(param1,param2,param3,param4,param5,param6);
}
_loc7_ = sMatrices.pop();
_loc7_.setTo(param1,param2,param3,param4,param5,param6);
return _loc7_;
}
public static function putMatrix(param1:Matrix) : void
{
if(param1)
{
sMatrices[sMatrices.length] = param1;
}
}
public static function getMatrix3D(param1:Boolean = true) : Matrix3D
{
var _loc2_:* = null;
if(sMatrices3D.length == 0)
{
return new Matrix3D();
}
_loc2_ = sMatrices3D.pop();
if(param1)
{
_loc2_.identity();
}
return _loc2_;
}
public static function putMatrix3D(param1:Matrix3D) : void
{
if(param1)
{
sMatrices3D[sMatrices3D.length] = param1;
}
}
public static function getRectangle(param1:Number = 0, param2:Number = 0, param3:Number = 0, param4:Number = 0) : Rectangle
{
var _loc5_:* = null;
if(sRectangles.length == 0)
{
return new Rectangle(param1,param2,param3,param4);
}
_loc5_ = sRectangles.pop();
_loc5_.setTo(param1,param2,param3,param4);
return _loc5_;
}
public static function putRectangle(param1:Rectangle) : void
{
if(param1)
{
sRectangles[sRectangles.length] = param1;
}
}
}
}
|
package com.destroytoday.util {
import flash.display.DisplayObject;
/**
* The DisplayObjectUtil class is a collection of methods for managing DisplayObjects.
* @author Jonnie Hallman
*/
public class DisplayObjectUtil {
/**
* @private
*/
public function DisplayObjectUtil() {
throw new Error("The DisplayObjectUtil class cannot be instantiated.");
}
/**
* Brings the DisplayObject to the front of the display list. The <code>back</code> parameter can be used to pull the DisplayObject back a few levels from the front.
* @param object the DisplayObject to reorder
* @param back the number of levels from the front of the display list
* @return the new index of the DisplayObject
*/
public static function bringToFront(object:DisplayObject, back:uint = 0):int {
if (!object.parent) return -1;
var index:int = object.parent.numChildren - (back + 1);
index = NumberUtil.confine(index, 0, object.parent.numChildren - 1);
object.parent.setChildIndex(object, index);
return index;
}
/**
* Brings the DisplayObject forward in the display list. The <code>steps</code> parameter can be used to jump more than one level.
* @param object the DisplayObject to reorder
* @param steps the number of levels bring the DisplayObject forward
* @return the new index of the DisplayObject
*/
public static function bringForward(object:DisplayObject, steps:uint = 1):int {
if (!object.parent) return -1;
var index:int = object.parent.getChildIndex(object) + steps;
index = NumberUtil.confine(index, 0, object.parent.numChildren - 1);
object.parent.setChildIndex(object, index);
return index;
}
/**
* Sends the DisplayObject to the back of the display list. The <code>forward</code> parameter can be used to bring the DisplayObject forward a few levels from the back.
* @param object the DisplayObject to reorder
* @param forward the number of levels from the back of the display list
* @return the new index of the DisplayObject
*/
public static function sendToBack(object:DisplayObject, forward:uint = 0):int {
if (!object.parent) return -1;
var index:int = NumberUtil.confine(forward, 0, object.parent.numChildren - 1);
object.parent.setChildIndex(object, index);
return index;
}
/**
* Sends the DisplayObject back in the display list. The <code>steps</code> parameter can be used to jump more than one level.
* @param object the DisplayObject to reorder
* @param steps the number of levels send the DisplayObject backward
* @return the new index of the DisplayObject
*/
public static function sendBackward(object:DisplayObject, steps:uint = 1):int {
if (!object.parent) return -1;
var index:int = object.parent.getChildIndex(object) - steps;
index = NumberUtil.confine(index, 0, object.parent.numChildren - 1);
object.parent.setChildIndex(object, index);
return index;
}
}
} |
package com.gen6.toro.controller
{
import com.gen6.toro.model.EncryptedLocalStoreProxy;
import org.puremvc.as3.interfaces.INotification;
import org.puremvc.as3.patterns.command.SimpleCommand;
public class LoadEncryptedCredentialsCommand extends SimpleCommand
{
public override function execute(notification:INotification):void
{
var proxy : EncryptedLocalStoreProxy = facade.retrieveProxy( EncryptedLocalStoreProxy.NAME ) as EncryptedLocalStoreProxy;
proxy.loadCredentials();
}
}
} |
package devoron.aswing3d.ext{
import org.aswing.Component;
import org.aswing.Container;
import org.aswing.Insets;
import org.aswing.LayoutManager;
import org.aswing.geom.IntDimension;
/**
* @author iiley (Burstyx Studio)
*/
public class DateGridLayout implements LayoutManager{
protected var indent:int;
protected var days:int;
protected var hgap:int;
protected var vgap:int;
protected var rows:int;
protected var cols:int;
/**
* DateGrid's rows and cols are fixed after construction.
*/
public function DateGridLayout(rows:int, cols:int, hgap:int=0, vgap:int=0){
this.rows = rows;
this.cols = cols;
this.hgap = hgap;
this.vgap = vgap;
indent = 0;
days = 31;
}
public function setMonth(indent:int, days:int):void{
this.indent = indent;
this.days = days;
}
public function addLayoutComponent(comp:Component, constraints:Object):void{
}
public function removeLayoutComponent(comp:Component):void{
}
protected function countLayoutSize(target:Container, sizeFuncName:String):IntDimension{
var n:int = target.getComponentCount();
var w:int = 0;
var h:int = 0;
for(var i:int=0; i<n; i++){
var c:Component = target.getComponent(i);
var size:IntDimension = c[sizeFuncName]();
if(size.width > w){
w = size.width;
}
if(size.height > h){
h = size.height;
}
}
var insets:Insets = target.getInsets();
return new IntDimension((((insets.left + insets.right) + (cols * w)) + ((cols - 1) * hgap)), (((insets.top + insets.bottom) + (rows * h)) + ((rows - 1) * vgap)));
}
public function preferredLayoutSize(target:Container):IntDimension{
return countLayoutSize(target, "getPreferredSize");
}
public function minimumLayoutSize(target:Container):IntDimension{
return countLayoutSize(target, "getMinimumSize");
}
public function maximumLayoutSize(target:Container):IntDimension{
return new IntDimension(1000000, 1000000);
}
public function layoutContainer(target:Container):void{
var insets:Insets = target.getInsets();
var n:int = target.getComponentCount();
if (n == 0){
return ;
}
var w:int = (target.getWidth() - (insets.left + insets.right));
var h:int = (target.getHeight() - (insets.top + insets.bottom));
w = Math.floor((w - ((cols - 1) * hgap)) / cols);
h = Math.floor((h - ((rows - 1) * vgap)) / rows);
var x:int = insets.left;
var y:int = insets.top;
var i:int=0;
for(var r:int=0; r<rows; r++){
x = insets.left;
for(var c:int=0; c<cols; c++){
i = ((r * cols) + c - indent);
if(i>=0 && i<days && i<n){
var comp:Component = target.getComponent(i);
target.getComponent(i).setComBoundsXYWH(x, y, w, h);
}
x += (w + hgap);
}
y += (h + vgap);
}
//TODO remainder children's
//for()
}
public function getLayoutAlignmentX(target:Container):Number{
return 0.5;
}
public function getLayoutAlignmentY(target:Container):Number{
return 0.5;
}
public function invalidateLayout(target:Container):void{
}
}
} |
////////////////////////////////////////////////////////////////////////////////
//
// 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.flash
{
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.InteractiveObject;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.Stage;
import flash.events.Event;
import flash.events.FocusEvent;
import flash.geom.ColorTransform;
import flash.geom.Matrix;
import flash.geom.Matrix3D;
import flash.geom.PerspectiveProjection;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.geom.Vector3D;
import flash.system.ApplicationDomain;
import flash.ui.Keyboard;
import mx.automation.IAutomationObject;
import mx.core.AdvancedLayoutFeatures;
import mx.core.DesignLayer;
import mx.core.IConstraintClient;
import mx.core.IDeferredInstantiationUIComponent;
import mx.core.IFlexDisplayObject;
import mx.core.IFlexModule;
import mx.core.IFlexModuleFactory;
import mx.core.IInvalidating;
import mx.core.ILayoutElement;
import mx.core.IStateClient;
import mx.core.IUIComponent;
import mx.core.IVisualElement;
import mx.core.LayoutElementUIComponentUtils;
import mx.core.LayoutDirection;
import mx.core.UIComponentDescriptor;
import mx.core.mx_internal;
import mx.events.FlexEvent;
import mx.events.MoveEvent;
import mx.events.PropertyChangeEvent;
import mx.events.ResizeEvent;
import mx.events.StateChangeEvent;
import mx.geom.TransformOffsets;
import mx.managers.IFocusManagerComponent;
import mx.managers.ISystemManager;
import mx.managers.IToolTipManagerClient;
import mx.utils.MatrixUtil;
import mx.utils.TransformUtil;
use namespace mx_internal;
//--------------------------------------
// Lifecycle events
//--------------------------------------
/**
* Dispatched when the component is added to a container as a content child
* by using the <code>addChild()</code> or <code>addChildAt()</code> method.
* If the component is added to the container as a noncontent child by
* using the <code>rawChildren.addChild()</code> or
* <code>rawChildren.addChildAt()</code> method, the event is not dispatched.
*
* @eventType mx.events.FlexEvent.ADD
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="add", type="mx.events.FlexEvent")]
/**
* Dispatched when the component has finished its construction.
* For Flash-based components, this is the same time as the
* <code>initialize</code> event.
*
* @eventType mx.events.FlexEvent.CREATION_COMPLETE
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="creationComplete", type="mx.events.FlexEvent")]
/**
* Dispatched when an object's state changes from visible to invisible.
*
* @eventType mx.events.FlexEvent.HIDE
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="hide", type="mx.events.FlexEvent")]
/**
* Dispatched when the component has finished its construction
* and has all initialization properties set.
*
* @eventType mx.events.FlexEvent.INITIALIZE
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="initialize", type="mx.events.FlexEvent")]
/**
* Dispatched when the object has moved.
*
* <p>You can move the component by setting the <code>x</code>
* or <code>y</code> properties, by calling the <code>move()</code>
* method, by setting one
* of the following properties either on the component or on other
* components such that the LayoutManager needs to change the
* <code>x</code> or <code>y</code> properties of the component:</p>
*
* <ul>
* <li><code>minWidth</code></li>
* <li><code>minHeight</code></li>
* <li><code>maxWidth</code></li>
* <li><code>maxHeight</code></li>
* <li><code>explicitWidth</code></li>
* <li><code>explicitHeight</code></li>
* </ul>
*
* <p>When you call the <code>move()</code> method, the <code>move</code>
* event is dispatched before the method returns.
* In all other situations, the <code>move</code> event is not dispatched
* until after the property changes.</p>
*
* @eventType mx.events.MoveEvent.MOVE
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="move", type="mx.events.MoveEvent")]
/**
* Dispatched at the beginning of the component initialization sequence.
* The component is in a very raw state when this event is dispatched.
* Many components, such as the Button control, create internal child
* components to implement functionality; for example, the Button control
* creates an internal UITextField component to represent its label text.
* When Flex dispatches the <code>preinitialize</code> event,
* the children, including the internal children, of a component
* have not yet been created.
*
* @eventType mx.events.FlexEvent.PREINITIALIZE
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="preinitialize", type="mx.events.FlexEvent")]
/**
* Dispatched when the component is removed from a container as a content child
* by using the <code>removeChild()</code> or <code>removeChildAt()</code> method.
* If the component is removed from the container as a noncontent child by
* using the <code>rawChildren.removeChild()</code> or
* <code>rawChildren.removeChildAt()</code> method, the event is not dispatched.
*
* @eventType mx.events.FlexEvent.REMOVE
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="remove", type="mx.events.FlexEvent")]
/**
* Dispatched when the component is resized.
*
* <p>You can resize the component by setting the <code>width</code> or
* <code>height</code> property, by calling the <code>setActualSize()</code>
* method, or by setting one of
* the following properties either on the component or on other components
* such that the LayoutManager needs to change the <code>width</code> or
* <code>height</code> properties of the component:</p>
*
* <ul>
* <li><code>minWidth</code></li>
* <li><code>minHeight</code></li>
* <li><code>maxWidth</code></li>
* <li><code>maxHeight</code></li>
* <li><code>explicitWidth</code></li>
* <li><code>explicitHeight</code></li>
* </ul>
*
* <p>The <code>resize</code> event is not
* dispatched until after the property changes.</p>
*
* @eventType mx.events.ResizeEvent.RESIZE
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="resize", type="mx.events.ResizeEvent")]
/**
* Dispatched when an object's state changes from invisible to visible.
*
* @eventType mx.events.FlexEvent.SHOW
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="show", type="mx.events.FlexEvent")]
//--------------------------------------
// Mouse events
//--------------------------------------
/**
* Dispatched from a component opened using the PopUpManager
* when the user clicks outside it.
*
* @eventType mx.events.FlexMouseEvent.MOUSE_DOWN_OUTSIDE
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="mouseDownOutside", type="mx.events.FlexMouseEvent")]
/**
* Dispatched from a component opened using the PopUpManager
* when the user scrolls the mouse wheel outside it.
*
* @eventType mx.events.FlexMouseEvent.MOUSE_WHEEL_OUTSIDE
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="mouseWheelOutside", type="mx.events.FlexMouseEvent")]
//--------------------------------------
// Drag-and-drop events
//--------------------------------------
/**
* Dispatched by a component when the user moves the mouse over the component
* during a drag operation.
*
* <p>In order to be a valid drop target, you must define a handler
* for this event.
* In the handler, you can change the appearance of the drop target
* to provide visual feedback to the user that the component can accept
* the drag.
* For example, you could draw a border around the drop target,
* or give focus to the drop target.</p>
*
* <p>If you want to accept the drag, you must call the
* <code>DragManager.acceptDragDrop()</code> method. If you don't
* call <code>acceptDragDrop()</code>, you will not get any of the
* other drag events.</p>
*
* <p>The value of the <code>action</code> property is always
* <code>DragManager.MOVE</code>, even if you are doing a copy.
* This is because the <code>dragEnter</code> event occurs before
* the control recognizes that the Control key is pressed to signal a copy.
* The <code>action</code> property of the event object for the
* <code>dragOver</code> event does contain a value that signifies the type of
* drag operation.</p>
*
* <p>You may change the type of drag action by calling the
* <code>DragManager.showFeedback()</code> method.</p>
*
* @see mx.managers.DragManager
*
* @eventType mx.events.DragEvent.DRAG_ENTER
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="dragEnter", type="mx.events.DragEvent")]
/**
* Dispatched by a component when the user moves the mouse while over the component
* during a drag operation.
*
* <p>In the handler, you can change the appearance of the drop target
* to provide visual feedback to the user that the component can accept
* the drag.
* For example, you could draw a border around the drop target,
* or give focus to the drop target.</p>
*
* <p>You should handle this event to perform additional logic
* before allowing the drop, such as dropping data to various locations
* in the drop target, reading keyboard input to determine if the
* drag-and-drop action is a move or copy of the drag data, or providing
* different types of visual feedback based on the type of drag-and-drop
* action.</p>
*
* <p>You may also change the type of drag action by changing the
* <code>DragManager.showFeedback()</code> method.
* The default value of the <code>action</code> property is
* <code>DragManager.MOVE</code>.</p>
*
* @see mx.managers.DragManager
*
* @eventType mx.events.DragEvent.DRAG_OVER
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="dragOver", type="mx.events.DragEvent")]
/**
* Dispatched by the component when the user drags outside the component,
* but does not drop the data onto the target.
*
* <p>You use this event to restore the drop target to its normal appearance
* if you modified its appearance as part of handling the
* <code>dragEnter</code> or <code>dragOver</code> event.</p>
*
* @eventType mx.events.DragEvent.DRAG_EXIT
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="dragExit", type="mx.events.DragEvent")]
/**
* Dispatched by the drop target when the user releases the mouse over it.
*
* <p>You use this event handler to add the drag data to the drop target.</p>
*
* <p>If you call <code>Event.preventDefault()</code> in the event handler
* for the <code>dragDrop</code> event for
* a Tree control when dragging data from one Tree control to another,
* it prevents the drop.</p>
*
* @eventType mx.events.DragEvent.DRAG_DROP
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="dragDrop", type="mx.events.DragEvent")]
/**
* Dispatched by the drag initiator (the component that is the source
* of the data being dragged) when the drag operation completes,
* either when you drop the dragged data onto a drop target or when you end
* the drag-and-drop operation without performing a drop.
*
* <p>You can use this event to perform any final cleanup
* of the drag-and-drop operation.
* For example, if you drag a List control item from one list to another,
* you can delete the List control item from the source if you no longer
* need it.</p>
*
* <p>If you call <code>Event.preventDefault()</code> in the event handler
* for the <code>dragComplete</code> event for
* a Tree control when dragging data from one Tree control to another,
* it prevents the drop.</p>
*
* @eventType mx.events.DragEvent.DRAG_COMPLETE
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="dragComplete", type="mx.events.DragEvent")]
//--------------------------------------
// State events
//--------------------------------------
/**
* Dispatched after the <code>currentState</code> property changes,
* but before the view state changes.
*
* @eventType mx.events.StateChangeEvent.CURRENT_STATE_CHANGING
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="currentStateChanging", type="mx.events.StateChangeEvent")]
/**
* Dispatched after the view state has changed.
*
* @eventType mx.events.StateChangeEvent.CURRENT_STATE_CHANGE
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="currentStateChange", type="mx.events.StateChangeEvent")]
//--------------------------------------
// Tooltip events
//--------------------------------------
/**
* Dispatched by the component when it is time to create a ToolTip.
*
* <p>If you create your own IToolTip object and place a reference
* to it in the <code>toolTip</code> property of the event object
* that is passed to your <code>toolTipCreate</code> handler,
* the ToolTipManager displays your custom ToolTip.
* Otherwise, the ToolTipManager creates an instance of
* <code>ToolTipManager.toolTipClass</code> to display.</p>
*
* <p>The sequence of ToolTip events is <code>toolTipStart</code>,
* <code>toolTipCreate</code>, <code>toolTipShow</code>,
* <code>toolTipShown</code>, <code>toolTipHide</code>,
* and <code>toolTipEnd</code>.</p>
*
* @eventType mx.events.ToolTipEvent.TOOL_TIP_CREATE
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="toolTipCreate", type="mx.events.ToolTipEvent")]
/**
* Dispatched by the component when its ToolTip has been hidden
* and will be discarded soon.
*
* <p>If you specify an effect using the
* <code>ToolTipManager.hideEffect</code> property,
* this event is dispatched after the effect stops playing.</p>
*
* <p>The sequence of ToolTip events is <code>toolTipStart</code>,
* <code>toolTipCreate</code>, <code>toolTipShow</code>,
* <code>toolTipShown</code>, <code>toolTipHide</code>,
* and <code>toolTipEnd</code>.</p>
*
* @eventType mx.events.ToolTipEvent.TOOL_TIP_END
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="toolTipEnd", type="mx.events.ToolTipEvent")]
/**
* Dispatched by the component when its ToolTip is about to be hidden.
*
* <p>If you specify an effect using the
* <code>ToolTipManager.hideEffect</code> property,
* this event is dispatched before the effect starts playing.</p>
*
* <p>The sequence of ToolTip events is <code>toolTipStart</code>,
* <code>toolTipCreate</code>, <code>toolTipShow</code>,
* <code>toolTipShown</code>, <code>toolTipHide</code>,
* and <code>toolTipEnd</code>.</p>
*
* @eventType mx.events.ToolTipEvent.TOOL_TIP_HIDE
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="toolTipHide", type="mx.events.ToolTipEvent")]
/**
* Dispatched by the component when its ToolTip is about to be shown.
*
* <p>If you specify an effect using the
* <code>ToolTipManager.showEffect</code> property,
* this event is dispatched before the effect starts playing.
* You can use this event to modify the ToolTip before it appears.</p>
*
* <p>The sequence of ToolTip events is <code>toolTipStart</code>,
* <code>toolTipCreate</code>, <code>toolTipShow</code>,
* <code>toolTipShown</code>, <code>toolTipHide</code>,
* and <code>toolTipEnd</code>.</p>
*
* @eventType mx.events.ToolTipEvent.TOOL_TIP_SHOW
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="toolTipShow", type="mx.events.ToolTipEvent")]
/**
* Dispatched by the component when its ToolTip has been shown.
*
* <p>If you specify an effect using the
* <code>ToolTipManager.showEffect</code> property,
* this event is dispatched after the effect stops playing.</p>
*
* <p>The sequence of ToolTip events is <code>toolTipStart</code>,
* <code>toolTipCreate</code>, <code>toolTipShow</code>,
* <code>toolTipShown</code>, <code>toolTipHide</code>,
* and <code>toolTipEnd</code>.</p>
*
* @eventType mx.events.ToolTipEvent.TOOL_TIP_SHOWN
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="toolTipShown", type="mx.events.ToolTipEvent")]
/**
* Dispatched by a component whose <code>toolTip</code> property is set,
* as soon as the user moves the mouse over it.
*
* <p>The sequence of ToolTip events is <code>toolTipStart</code>,
* <code>toolTipCreate</code>, <code>toolTipShow</code>,
* <code>toolTipShown</code>, <code>toolTipHide</code>,
* and <code>toolTipEnd</code>.</p>
*
* @eventType mx.events.ToolTipEvent.TOOL_TIP_START
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="toolTipStart", type="mx.events.ToolTipEvent")]
/**
* Components created in Adobe Flash Professional for use in Flex
* are subclasses of the mx.flash.UIMovieClip class.
* The UIMovieClip class implements the interfaces necessary for a Flash component
* to be used like a normal Flex component. Therefore, a subclass of UIMovieClip
* can be used as a child of a Flex container or as a skin,
* and it can respond to events, define view states and transitions,
* and work with effects in the same way as can any Flex component.
*
* <p>The following procedure describes the basic process for creating
* a Flex component in Flash Professional:</p>
*
* <ol>
* <li>Install the Adobe Flash Component Kit for Flex.</li>
* <li>Create symbols for your dynamic assets in the FLA file.</li>
* <li>Run Commands > Make Flex Component to convert your symbol
* to a subclass of the UIMovieClip class, and to configure
* the Flash Professional publishing settings for use with Flex.</li>
* <li>Publish your FLA file as a SWC file.</li>
* <li>Reference the class name of your symbols in your Flex application
* as you would any class.</li>
* <li>Include the SWC file in your <code>library-path</code> when you compile
* your Flex application.</li>
* </ol>
*
* <p>For more information, see the documentation that ships with the
* Flex/Flash Integration Kit at
* <a href="http://www.adobe.com/go/flex3_cs3_swfkit">http://www.adobe.com/go/flex3_cs3_swfkit</a>.</p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public dynamic class UIMovieClip extends MovieClip
implements IDeferredInstantiationUIComponent, IToolTipManagerClient,
IStateClient, IFocusManagerComponent, IConstraintClient, IAutomationObject,
IVisualElement, ILayoutElement, IFlexModule
{
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function UIMovieClip()
{
super();
// Add a focus in event handler so we can catch mouse focus within our
// content.
addEventListener(FocusEvent.FOCUS_IN, focusInHandler, false, 0, true);
// Add a creationComplete handler so we can attach an event handler
// to the stage
addEventListener(FlexEvent.CREATION_COMPLETE, creationCompleteHandler);
// we want to set currentState initially by checking the currentLabel, but we
// defer this so that if curentState is set explicitely,
// we do a goToAndStop() instead of short-circuiting the currentState
// setter at "if (value == _currentState)"
addEventListener(Event.ENTER_FRAME, setUpFirstCurrentState);
}
//--------------------------------------------------------------------------
//
// Internal variables
//
//--------------------------------------------------------------------------
/**
* @copy mx.core.UIComponent#initialized
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
protected var initialized:Boolean = false;
private var validateMeasuredSizeFlag:Boolean = true;
private var _parent:DisplayObjectContainer;
private var stateMap:Object;
// Focus vars
private var focusableObjects:Array = [];
private var reverseDirectionFocus:Boolean = false;
private var focusListenersAdded:Boolean = false;
// Transition playhead vars
private var transitionStartFrame:Number;
private var transitionEndFrame:Number;
private var transitionDirection:Number = 0;
private var transitionEndState:String;
// Location change detection vars
private var oldX:Number;
private var oldY:Number;
private var oldWidth:Number;
private var oldHeight:Number;
private var explicitSizeChanged:Boolean = false;
private var explicitTabEnabledChanged:Boolean = false;
//--------------------------------------------------------------------------
//
// Public variables
//
//--------------------------------------------------------------------------
//----------------------------------
// alpha
//----------------------------------
/**
* @private
* Storage for the alpha property.
*/
private var _alpha:Number = 1.0;
/**
* @private
*/
override public function get alpha():Number
{
// Here we roundtrip alpha in the same manner as the
// player (purposely introducing a rounding error).
return int(_alpha * 256.0) / 256.0;
}
/**
* @private
*/
override public function set alpha(value:Number):void
{
if (_alpha != value)
{
_alpha = value;
if (designLayer)
value = value * designLayer.effectiveAlpha;
super.alpha = value;
}
}
//----------------------------------
// autoUpdateMeasuredSize
//----------------------------------
/**
* @private
*/
private var _autoUpdateMeasuredSize:Boolean = false;
[Inspectable(category="General")]
/**
* Whether we should actively watch changes to the size of the flash object.
* If this is set to <code>true</code>, then every frame, the size of the flash
* object will be determined. If the size has changed, then the flash object
* will scale appropriately to fit its explicit bounds (or it will resize and
* notify its parent if there is no explicit sizing).
*
* <p>Note: Setting this property to <code>true</code> may be expensive because
* we now are asking the flash object its current size every single frame.</p>
*
* @default false
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 4
*/
public function get autoUpdateMeasuredSize():Boolean
{
return _autoUpdateMeasuredSize;
}
/**
* @private
*/
public function set autoUpdateMeasuredSize(value:Boolean):void
{
if (_autoUpdateMeasuredSize == value)
return;
_autoUpdateMeasuredSize = value;
if (_autoUpdateMeasuredSize)
{
addEventListener(Event.ENTER_FRAME, autoUpdateMeasuredSizeEnterFrameHandler, false, 0, true);
}
else
{
removeEventListener(Event.ENTER_FRAME, autoUpdateMeasuredSizeEnterFrameHandler);
}
}
//----------------------------------
// autoUpdateCurrentState
//----------------------------------
/**
* @private
*/
private var _autoUpdateCurrentState:Boolean = false;
[Inspectable(category="General")]
/**
* Whether we should actively watch changes to the label of the flash object.
* The Flex <code>currentState</code> property depends on this flash label.
* If this is set to <code>true</code>, then every frame, the label of the flash
* obejct will be quieried. If the label has changed, that will become the new
* <code>currentState</code> for the Flex object.
*
* <p>Note: Setting this property to <code>true</code> may be expensive because
* we now are asking the flash object for is current label every single frame.</p>
*
* @default false
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 4
*/
public function get autoUpdateCurrentState():Boolean
{
return _autoUpdateCurrentState;
}
/**
* @private
*/
public function set autoUpdateCurrentState(value:Boolean):void
{
if (_autoUpdateCurrentState == value)
return;
_autoUpdateCurrentState = value;
if (_autoUpdateCurrentState)
{
addEventListener(Event.ENTER_FRAME, autoUpdateCurrentStateEnterFrameHandler, false, 0, true);
}
else
{
removeEventListener(Event.ENTER_FRAME, autoUpdateCurrentStateEnterFrameHandler);
}
}
//----------------------------------
// x
//----------------------------------
[Inspectable(category="General")]
/**
* Number that specifies the component's horizontal position,
* in pixels, within its parent container.
*
* <p>Setting this property directly or calling <code>move()</code>
* will have no effect -- or only a temporary effect -- if the
* component is parented by a layout container such as HBox, Grid,
* or Form, because the layout calculations of those containers
* set the <code>x</code> position to the results of the calculation.
* However, the <code>x</code> property must almost always be set
* when the parent is a Canvas or other absolute-positioning
* container because the default value is 0.</p>
*
* @default 0
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
override public function get x():Number
{
return (_layoutFeatures == null) ? super.x : _layoutFeatures.layoutX;
}
/**
* @private
*/
override public function set x(value:Number):void
{
if (x == value)
return;
if (_layoutFeatures == null)
{
super.x = value;
}
else
{
_layoutFeatures.layoutX = value;
invalidateTransform();
}
//invalidateProperties();
addEventListener(Event.ENTER_FRAME, enterFrameHandler, false, 0, true);
invalidateParentSizeAndDisplayList();
}
//----------------------------------
// y
//----------------------------------
[Inspectable(category="General")]
/**
* Number that specifies the component's vertical position,
* in pixels, within its parent container.
*
* <p>Setting this property directly or calling <code>move()</code>
* will have no effect -- or only a temporary effect -- if the
* component is parented by a layout container such as HBox, Grid,
* or Form, because the layout calculations of those containers
* set the <code>x</code> position to the results of the calculation.
* However, the <code>x</code> property must almost always be set
* when the parent is a Canvas or other absolute-positioning
* container because the default value is 0.</p>
*
* @default 0
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
override public function get y():Number
{
return (_layoutFeatures == null) ? super.y : _layoutFeatures.layoutY;
}
/**
* @private
*/
override public function set y(value:Number):void
{
if (y == value)
return;
if (_layoutFeatures == null)
{
super.y = value;
}
else
{
_layoutFeatures.layoutY = value;
invalidateTransform();
}
//invalidateProperties();
addEventListener(Event.ENTER_FRAME, enterFrameHandler, false, 0, true);
invalidateParentSizeAndDisplayList();
}
//----------------------------------
// z
//----------------------------------
[Bindable("zChanged")]
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 3
*/
override public function get z():Number
{
return (_layoutFeatures == null) ? super.z : _layoutFeatures.layoutZ;
}
/**
* @private
*/
override public function set z(value:Number):void
{
if (z == value)
return;
if (_layoutFeatures == null)
initAdvancedLayoutFeatures();
hasDeltaIdentityTransform = false;
_layoutFeatures.layoutZ = value;
invalidateTransform();
//invalidateProperties();
invalidateParentSizeAndDisplayList();
}
//----------------------------------
// boundingBoxName
//----------------------------------
[Inspectable]
/**
* Name of the object to use as the bounding box.
*
* <p>The bounding box is an object that is used by Flex to determine
* the size of the component. The actual content can be larger or
* smaller than the bounding box, but Flex uses the size of the
* bounding box when laying out the component. This object is optional.
* If omitted, the actual content size of the component is used instead.</p>
*
* @default "boundingBox"
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public var boundingBoxName:String = "boundingBox";
//----------------------------------
// Layout Constraints
//----------------------------------
private var _baseline:*;
[Inspectable]
[Bindable]
/**
* The vertical distance in pixels from the top edge of the content area
* to the component's baseline position.
* If this property is set, the baseline of the component is anchored
* to the top edge of its content area;
* when its container is resized, the two edges maintain their separation.
*
* <p>This property only has an effect when used on a component in a Canvas container,
* or when used on a component in a Panel or Application container
* that has the layout property set to <code>absolute</code>.</p>
*
* <p>The default value is <code>undefined</code>, which means it is not set.</p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get baseline():Object
{
return _baseline;
}
/**
* @private
*/
public function set baseline(value:Object):void
{
if (value != _baseline)
{
_baseline = value;
invalidateParentSizeAndDisplayList();
}
}
private var _bottom:*;
[Inspectable]
[Bindable]
/**
* The vertical distance, in pixels, from the lower edge of the component
* to the lower edge of its content area.
* If this property is set, the lower edge of the component is anchored
* to the bottom edge of its content area;
* when its container is resized, the two edges maintain their separation.
*
* <p>This property only has an effect when used on a component in a Canvas container,
* or when used on a component in a Panel or Application container
* that has the layout property set to <code>absolute</code>.</p>
*
* <p>The default value is <code>undefined</code>, which means it is not set.</p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get bottom():Object
{
return _bottom;
}
/**
* @private
*/
public function set bottom(value:Object):void
{
if (value != _bottom)
{
_bottom = value;
invalidateParentSizeAndDisplayList();
}
}
private var _horizontalCenter:*;
[Inspectable]
[Bindable]
/**
* The horizontal distance in pixels from the center of the
* component's content area to the center of the component.
* If this property is set, the center of the component
* will be anchored to the center of its content area;
* when its container is resized, the two centers maintain their horizontal separation.
*
* <p>This property only has an effect when used on a component in a Canvas container,
* or when used on a component in a Panel or Application container
* that has the layout property set to <code>absolute</code>.</p>
*
* <p>The default value is <code>undefined</code>, which means it is not set.</p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get horizontalCenter():Object
{
return _horizontalCenter;
}
/**
* @private
*/
public function set horizontalCenter(value:Object):void
{
if (value != _horizontalCenter)
{
_horizontalCenter = value;
invalidateParentSizeAndDisplayList();
}
}
private var _left:*;
[Inspectable]
[Bindable]
/**
* The horizontal distance, in pixels, from the left edge of the component's
* content area to the left edge of the component.
* If this property is set, the left edge of the component is anchored
* to the left edge of its content area;
* when its container is resized, the two edges maintain their separation.
*
* <p>This property only has an effect when used on a component in a Canvas container,
* or when used on a component in a Panel or Application container
* that has the layout property set to <code>absolute</code>.</p>
*
* <p>The default value is <code>undefined</code>, which means it is not set.</p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get left():Object
{
return _left;
}
/**
* @private
*/
public function set left(value:Object):void
{
if (value != _left)
{
_left = value;
invalidateParentSizeAndDisplayList();
}
}
private var _right:*;
[Inspectable]
[Bindable]
/**
* The horizontal distance, in pixels, from the right edge of the component
* to the right edge of its content area.
* If this property is set, the right edge of the component is anchored
* to the right edge of its content area;
* when its container is resized, the two edges maintain their separation.
*
* <p>This property only has an effect when used on a component in a Canvas container,
* or when used on a component in a Panel or Application container
* that has the layout property set to <code>absolute</code>.</p>
*
* <p>The default value is <code>undefined</code>, which means it is not set.</p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get right():Object
{
return _right;
}
/**
* @private
*/
public function set right(value:Object):void
{
if (value != _right)
{
_right = value;
invalidateParentSizeAndDisplayList();
}
}
private var _top:*;
[Inspectable]
[Bindable]
/**
* The vertical distance, in pixels, from the top edge of the control's content area
* to the top edge of the component.
* If this property is set, the top edge of the component is anchored
* to the top edge of its content area;
* when its container is resized, the two edges maintain their separation.
*
* <p>This property only has an effect when used on a component in a Canvas container,
* or when used on a component in a Panel or Application container
* that has the layout property set to <code>absolute</code>.</p>
*
* <p>The default value is <code>undefined</code>, which means it is not set.</p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get top():Object
{
return _top;
}
/**
* @private
*/
public function set top(value:Object):void
{
if (value != _top)
{
_top = value;
invalidateParentSizeAndDisplayList();
}
}
private var _verticalCenter:*;
[Inspectable]
[Bindable]
/**
* The vertical distance in pixels from the center of the component's content area
* to the center of the component.
* If this property is set, the center of the component is anchored
* to the center of its content area;
* when its container is resized, the two centers maintain their vertical separation.
*
* <p>This property only has an effect when used on a component in a Canvas container,
* or when used on a component in a Panel or Application container
* that has the layout property set to <code>absolute</code>.</p>
*
* <p>The default value is <code>undefined</code>, which means it is not set.</p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get verticalCenter():Object
{
return _verticalCenter;
}
/**
* @private
*/
public function set verticalCenter(value:Object):void
{
if (value != _verticalCenter)
{
_verticalCenter = value;
invalidateParentSizeAndDisplayList();
}
}
//--------------------------------------------------------------------------
//
// IDeferredInstantiationUIComponent properties
//
//--------------------------------------------------------------------------
//----------------------------------
// cacheHeuristic
//----------------------------------
/**
* Used by Flex to suggest bitmap caching for the object.
* If <code>cachePolicy</code> is <code>UIComponentCachePolicy.AUTO</code>,
* then <code>cacheHeuristic</code>
* is used to control the object's <code>cacheAsBitmap</code> property.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function set cacheHeuristic(value:Boolean):void
{
// ignored
}
//----------------------------------
// cachePolicy
//----------------------------------
/**
* Specifies the bitmap caching policy for this object.
* Possible values in MXML are <code>"on"</code>,
* <code>"off"</code> and
* <code>"auto"</code> (default).
*
* <p>Possible values in ActionScript are <code>UIComponentCachePolicy.ON</code>,
* <code>UIComponentCachePolicy.OFF</code> and
* <code>UIComponentCachePolicy.AUTO</code> (default).</p>
*
* <p><ul>
* <li>A value of <code>UIComponentCachePolicy.ON</code> means that
* the object is always cached as a bitmap.</li>
* <li>A value of <code>UIComponentCachePolicy.OFF</code> means that
* the object is never cached as a bitmap.</li>
* <li>A value of <code>UIComponentCachePolicy.AUTO</code> means that
* the framework uses heuristics to decide whether the object should
* be cached as a bitmap.</li>
* </ul></p>
*
* @default UIComponentCachePolicy.AUTO
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get cachePolicy():String
{
return "";
}
//----------------------------------
// descriptor
//----------------------------------
private var _descriptor:UIComponentDescriptor;
/**
* Reference to the UIComponentDescriptor, if any, that was used
* by the <code>createComponentFromDescriptor()</code> method to create this
* UIComponent instance. If this UIComponent instance
* was not created from a descriptor, this property is null.
*
* @see mx.core.UIComponentDescriptor
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get descriptor():UIComponentDescriptor
{
return _descriptor;
}
/**
* @private
*/
public function set descriptor(value:UIComponentDescriptor):void
{
_descriptor = value;
}
//----------------------------------
// id
//----------------------------------
private var _id:String;
/**
* ID of the component. This value becomes the instance name of the object
* and should not contain any white space or special characters. Each component
* throughout an application should have a unique id.
*
* <p>If your application is going to be tested by third party tools, give each component
* a meaningful id. Testing tools use ids to represent the control in their scripts and
* having a meaningful name can make scripts more readable. For example, set the
* value of a button to submit_button rather than b1 or button1.</p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get id():String
{
return _id;
}
/**
* @private
*/
public function set id(value:String):void
{
_id = value;
}
//--------------------------------------------------------------------------
//
// IDeferredInstantiationUIComponent methods
//
//--------------------------------------------------------------------------
/**
* Creates an <code>id</code> reference to this IUIComponent object
* on its parent document object.
* This function can create multidimensional references
* such as b[2][4] for objects inside one or more repeaters.
* If the indices are null, it creates a simple non-Array reference.
*
* @param parentDocument The parent of this IUIComponent object.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function createReferenceOnParentDocument(
parentDocument:IFlexDisplayObject):void
{
if (id && id != "")
{
parentDocument[id] = this;
}
}
/**
* Deletes the <code>id</code> reference to this IUIComponent object
* on its parent document object.
* This function can delete from multidimensional references
* such as b[2][4] for objects inside one or more Repeaters.
* If the indices are null, it deletes the simple non-Array reference.
*
* @param parentDocument The parent of this IUIComponent object.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function deleteReferenceOnParentDocument(
parentDocument:IFlexDisplayObject):void
{
if (id && id != "")
{
parentDocument[id] = null;
}
}
/**
* Executes the data bindings into this UIComponent object.
*
* @param recurse Recursively execute bindings for children of this component.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function executeBindings(recurse:Boolean = false):void
{
var bindingsHost:Object = descriptor && descriptor.document ? descriptor.document : parentDocument;
var mgr:* = ApplicationDomain.currentDomain.getDefinition("mx.binding.BindingManager");
if (mgr != null)
mgr.executeBindings(bindingsHost, id, this);
}
/**
* For each effect event, register the EffectManager
* as one of the event listeners.
*
* @param effects An Array of strings of effect names.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function registerEffects(effects:Array /* of String*/):void
{
// ignored
}
//--------------------------------------------------------------------------
//
// IUIComponent properties
//
//--------------------------------------------------------------------------
//----------------------------------
// baselinePosition
//----------------------------------
/**
* The y-coordinate of the baseline
* of the first line of text of the component.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get baselinePosition():Number
{
return 0;
}
//----------------------------------
// document
//----------------------------------
mx_internal var _document:Object;
/**
* @copy mx.core.IUIComponent#document
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get document():Object
{
return _document;
}
/**
* @private
*/
public function set document(value:Object):void
{
_document = value;
}
//----------------------------------
// explicitHeight
//----------------------------------
private var _explicitHeight:Number;
/**
* The explicitly specified height for the component,
* in pixels, as the component's coordinates.
* If no height is explicitly specified, the value is <code>NaN</code>.
*
* @see mx.core.UIComponent#explicitHeight
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get explicitHeight():Number
{
return _explicitHeight;
}
/**
* @private
*/
public function set explicitHeight(value:Number):void
{
_explicitHeight = value;
explicitSizeChanged = true;
invalidateParentSizeAndDisplayList();
addEventListener(Event.ENTER_FRAME, enterFrameHandler, false, 0, true);
}
//----------------------------------
// explicitMaxHeight
//----------------------------------
private var _explicitMaxHeight:Number;
/**
* Number that specifies the maximum height of the component,
* in pixels, as the component's coordinates.
*
* @see mx.core.UIComponent#explicitMaxHeight
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get explicitMaxHeight():Number
{
return _explicitMaxHeight;
}
public function set explicitMaxHeight(value:Number):void
{
_explicitMaxHeight = value;
invalidateParentSizeAndDisplayList();
}
//----------------------------------
// explicitMaxWidth
//----------------------------------
private var _explicitMaxWidth:Number;
/**
* Number that specifies the maximum width of the component,
* in pixels, as the component's coordinates.
*
* @see mx.core.UIComponent#explicitMaxWidth
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get explicitMaxWidth():Number
{
return _explicitMaxWidth;
}
public function set explicitMaxWidth(value:Number):void
{
_explicitMaxWidth = value;
invalidateParentSizeAndDisplayList();
}
//----------------------------------
// explicitMinHeight
//----------------------------------
private var _explicitMinHeight:Number;
/**
* Number that specifies the minimum height of the component,
* in pixels, as the component's coordinates.
*
* @see mx.core.UIComponent#explicitMinHeight
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get explicitMinHeight():Number
{
return _explicitMinHeight;
}
public function set explicitMinHeight(value:Number):void
{
_explicitMinHeight = value;
invalidateParentSizeAndDisplayList();
}
//----------------------------------
// explicitMinWidth
//----------------------------------
private var _explicitMinWidth:Number;
/**
* Number that specifies the minimum width of the component,
* in pixels, as the component's coordinates.
*
* @see mx.core.UIComponent#explicitMinWidth
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get explicitMinWidth():Number
{
return _explicitMinWidth;
}
public function set explicitMinWidth(value:Number):void
{
_explicitMinWidth = value;
invalidateParentSizeAndDisplayList();
}
//----------------------------------
// explicitWidth
//----------------------------------
private var _explicitWidth:Number;
/**
* The explicitly specified width for the component,
* in pixels, as the component's coordinates.
* If no width is explicitly specified, the value is <code>NaN</code>.
*
* @see mx.core.UIComponent#explicitWidth
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get explicitWidth():Number
{
return _explicitWidth;
}
public function set explicitWidth(value:Number):void
{
_explicitWidth = value;
explicitSizeChanged = true;
invalidateParentSizeAndDisplayList();
addEventListener(Event.ENTER_FRAME, enterFrameHandler, false, 0, true);
}
//----------------------------------
// focusPane
//----------------------------------
private var _focusPane:Sprite;
/**
* A single Sprite object that is shared among components
* and used as an overlay for drawing focus.
* Components share this object if their parent is a focused component,
* not if the component implements the IFocusManagerComponent interface.
*
* @see mx.core.UIComponent#focusPane
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get focusPane():Sprite
{
return _focusPane;
}
/**
* @private
*/
public function set focusPane(value:Sprite):void
{
_focusPane = value;
}
//----------------------------------
// includeInLayout
//----------------------------------
private var _includeInLayout:Boolean = true;
/**
* Specifies whether this component is included in the layout of the
* parent container.
* If <code>true</code>, the object is included in its parent container's
* layout. If <code>false</code>, the object is positioned by its parent
* container as per its layout rules, but it is ignored for the purpose of
* computing the position of the next child.
*
* @default true
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get includeInLayout():Boolean
{
return _includeInLayout;
}
/**
* @private
*/
public function set includeInLayout(value:Boolean):void
{
_includeInLayout = value;
invalidateParentSizeAndDisplayList();
}
//----------------------------------
// isPopUp
//----------------------------------
private var _isPopUp:Boolean = false;
/**
* Set to <code>true</code> by the PopUpManager to indicate
* that component has been popped up.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get isPopUp():Boolean
{
return _isPopUp;
}
/**
* @private
*/
public function set isPopUp(value:Boolean):void
{
_isPopUp = value;
}
//----------------------------------
// layer
//----------------------------------
/**
* @private
* Storage for the layer property.
*/
private var _designLayer:DesignLayer;
[Inspectable (environment='none')]
/**
* @copy mx.core.IVisualElement#designLayer
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function get designLayer():DesignLayer
{
return _designLayer;
}
/**
* @private
*/
public function set designLayer(value:DesignLayer):void
{
if (_designLayer)
_designLayer.removeEventListener("layerPropertyChange", layer_PropertyChange, false);
_designLayer = value;
if (_designLayer)
_designLayer.addEventListener("layerPropertyChange", layer_PropertyChange, false, 0, true);
super.alpha = _designLayer ? _alpha * _designLayer.effectiveAlpha : _alpha;
super.visible = _designLayer ? _visible && _designLayer.effectiveVisibility : _visible;
}
//----------------------------------
// maxHeight
//----------------------------------
/**
* Number that specifies the maximum height of the component,
* in pixels, as the component's coordinates.
*
* @see mx.core.UIComponent#maxHeight
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get maxHeight():Number
{
return isNaN(explicitMaxHeight) ? 10000 : explicitMaxHeight;
}
public function set maxHeight(value:Number):void
{
explicitMaxHeight = value;
}
//----------------------------------
// maxWidth
//----------------------------------
/**
* Number that specifies the maximum width of the component,
* in pixels, as the component's coordinates.
*
* @see mx.core.UIComponent#maxWidth
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get maxWidth():Number
{
return isNaN(explicitMaxWidth) ? 10000 : explicitMaxWidth;
}
public function set maxWidth(value:Number):void
{
explicitMaxWidth = value;
}
//----------------------------------
// measuredMinHeight
//----------------------------------
private var _measuredMinHeight:Number = 0;
/**
* The default minimum height of the component, in pixels.
* This value is set by the <code>measure()</code> method.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get measuredMinHeight():Number
{
return _measuredMinHeight;
}
/**
* @private
*/
public function set measuredMinHeight(value:Number):void
{
_measuredMinHeight = value;
}
//----------------------------------
// measuredMinWidth
//----------------------------------
private var _measuredMinWidth:Number = 0;
/**
* The default minimum width of the component, in pixels.
* This value is set by the <code>measure()</code> method.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get measuredMinWidth():Number
{
return _measuredMinWidth;
}
/**
* @private
*/
public function set measuredMinWidth(value:Number):void
{
_measuredMinWidth = value;
}
//----------------------------------
// minHeight
//----------------------------------
/**
* Number that specifies the minimum height of the component,
* in pixels, as the component's coordinates.
*
* @see mx.core.UIComponent#minHeight
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get minHeight():Number
{
if (!isNaN(explicitMinHeight))
return explicitMinHeight;
return measuredMinHeight;
}
public function set minHeight(value:Number):void
{
explicitMinHeight = value;
}
//----------------------------------
// minWidth
//----------------------------------
/**
* Number that specifies the minimum width of the component,
* in pixels, as the component's coordinates.
*
* @see mx.core.UIComponent#minWidth
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get minWidth():Number
{
if (!isNaN(explicitMinWidth))
return explicitMinWidth;
return measuredMinWidth;
}
public function set minWidth(value:Number):void
{
explicitMinWidth = value;
}
//----------------------------------
// moduleFactory
//----------------------------------
/**
* @private
* Storage for the moduleFactory property.
*/
private var _moduleFactory:IFlexModuleFactory;
[Inspectable(environment="none")]
/**
* A module factory is used as context for using embeded fonts and for
* finding the style manager that controls the styles for this
* component.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 4
*/
public function get moduleFactory():IFlexModuleFactory
{
return _moduleFactory;
}
/**
* @private
*/
public function set moduleFactory(factory:IFlexModuleFactory):void
{
var n:int = numChildren;
for (var i:int = 0; i < n; i++)
{
var child:IFlexModule = getChildAt(i) as IFlexModule;
if (!child)
continue;
if (child.moduleFactory == null || child.moduleFactory == _moduleFactory)
{
child.moduleFactory = factory;
}
}
_moduleFactory = factory;
}
//----------------------------------
// owner
//----------------------------------
private var _owner:DisplayObjectContainer;
/**
* Typically the parent container of this component.
* However, if this is a popup component, the owner is
* the component that popped it up.
* For example, the owner of a dropdown list of a ComboBox control
* is the ComboBox control itself.
* This property is not managed by Flex, but
* by each component.
* Therefore, if you popup a component,
* you should set this property accordingly.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get owner():DisplayObjectContainer
{
return _owner ? _owner : parent;
}
/**
* @private
*/
public function set owner(value:DisplayObjectContainer):void
{
_owner = value;
}
//----------------------------------
// percentHeight
//----------------------------------
private var _percentHeight:Number;
/**
* Number that specifies the height of a component as a
* percentage of its parent's size.
* Allowed values are 0 to 100.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get percentHeight():Number
{
return _percentHeight;
}
public function set percentHeight(value:Number):void
{
_percentHeight = value;
invalidateParentSizeAndDisplayList();
}
//----------------------------------
// percentWidth
//----------------------------------
private var _percentWidth:Number;
/**
* Number that specifies the width of a component as a
* percentage of its parent's size.
* Allowed values are 0 to 100.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get percentWidth():Number
{
return _percentWidth;
}
public function set percentWidth(value:Number):void
{
_percentWidth = value;
invalidateParentSizeAndDisplayList();
}
//----------------------------------
// systemManager
//----------------------------------
private var _systemManager:ISystemManager;
/**
* A reference to the SystemManager object for this component.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get systemManager():ISystemManager
{
if (!_systemManager)
{
var r:DisplayObject = root;
if (r && !(r is Stage))
{
// If this object is attached to the display list, then
// the root property holds its SystemManager.
_systemManager = (r as ISystemManager);
}
else if (r)
{
// if the root is the Stage, then we are in a second AIR window
_systemManager = Stage(r).getChildAt(0) as ISystemManager;
}
else
{
// If this object isn't attached to the display list, then
// we need to walk up the parent chain ourselves.
var o:DisplayObjectContainer = parent;
while (o)
{
var ui:IUIComponent = o as IUIComponent;
if (ui)
{
_systemManager = ui.systemManager;
break;
}
else if (o is ISystemManager)
{
_systemManager = o as ISystemManager;
break;
}
o = o.parent;
}
}
}
return _systemManager;
}
/**
* @private
*/
public function set systemManager(value:ISystemManager):void
{
_systemManager = value;
}
//----------------------------------
// tweeningProperties
//----------------------------------
private var _tweeningProperties:Array;
/**
* Used by EffectManager.
* Returns non-null if a component
* is not using the EffectManager to execute a Tween.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get tweeningProperties():Array
{
return _tweeningProperties;
}
/**
* @private
*/
public function set tweeningProperties(value:Array):void
{
_tweeningProperties = value;
}
//----------------------------------
// visible
//----------------------------------
/**
* @private
* Storage for the visible property.
*/
private var _visible:Boolean = true;
/**
* Whether or not the display object is visible.
* Display objects that are not visible are disabled.
* For example, if <code>visible=false</code> for an InteractiveObject instance,
* it cannot be clicked.
*
* <p>When setting to <code>true</code>, the object dispatches
* a <code>show</code> event.
* When setting to <code>false</code>, the object dispatches
* a <code>hide</code> event.
* In either case the children of the object does not emit a
* <code>show</code> or <code>hide</code> event unless the object
* has specifically written an implementation to do so.</p>
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
override public function get visible():Boolean
{
return _visible;
}
/**
* @private
*/
override public function set visible(value:Boolean):void
{
setVisible(value);
}
//--------------------------------------------------------------------------
//
// IFlexDisplayObject properties
//
//--------------------------------------------------------------------------
//----------------------------------
// height
//----------------------------------
/**
* @private
*/
protected var _height:Number;
/**
* The height of this object, in pixels.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[PercentProxy("percentHeight")]
override public function get height():Number
{
if (!isNaN(_height))
return _height;
return super.height;
}
/**
* @private
*/
override public function set height(value:Number):void
{
explicitHeight = value;
}
//----------------------------------
// measuredHeight
//----------------------------------
private var _measuredHeight:Number;
/**
* The measured height of this object.
*
* <p>This is typically hard-coded for graphical skins
* because this number is simply the number of pixels in the graphic.
* For code skins, it can also be hard-coded
* if you expect to be drawn at a certain size.
* If your size can change based on properties, you may want
* to also be an ILayoutManagerClient so a <code>measure()</code>
* method will be called at an appropriate time,
* giving you an opportunity to compute a <code>measuredHeight</code>.</p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get measuredHeight():Number
{
validateMeasuredSize();
return _measuredHeight;
}
//----------------------------------
// measuredWidth
//----------------------------------
private var _measuredWidth:Number;
/**
* The measured width of this object.
*
* <p>This is typically hard-coded for graphical skins
* because this number is simply the number of pixels in the graphic.
* For code skins, it can also be hard-coded
* if you expect to be drawn at a certain size.
* If your size can change based on properties, you may want
* to also be an ILayoutManagerClient so a <code>measure()</code>
* method will be called at an appropriate time,
* giving you an opportunity to compute a <code>measuredHeight</code>.</p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get measuredWidth():Number
{
validateMeasuredSize();
return _measuredWidth;
}
//----------------------------------
// width
//----------------------------------
/**
* @private
*/
protected var _width:Number;
/**
* The width of this object, in pixels.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[PercentProxy("percentWidth")]
override public function get width():Number
{
if (!isNaN(_width))
return _width;
return super.width;
}
/**
* @private
*/
override public function set width(value:Number):void
{
explicitWidth = value;
}
//----------------------------------
// scaleX
//----------------------------------
[Inspectable(category="Size", defaultValue="1.0")]
/**
* Number that specifies the horizontal scaling factor.
*
* <p>The default value is 1.0, which means that the object
* is not scaled.
* A <code>scaleX</code> of 2.0 means the object has been
* magnified by a factor of 2, and a <code>scaleX</code> of 0.5
* means the object has been reduced by a factor of 2.</p>
*
* <p>A value of 0.0 is an invalid value.
* Rather than setting it to 0.0, set it to a small value, or set
* the <code>visible</code> property to <code>false</code> to hide the component.</p>
*
* @default 1.0
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
override public function get scaleX():Number
{
// if it's been set, layoutFeatures won't be null. Otherwise, return 1 as
// super.scaleX might be some other value since we change the width/height
// through scaling
return (_layoutFeatures == null) ? 1 : _layoutFeatures.layoutScaleX;
}
override public function set scaleX(value:Number):void
{
if (value == scaleX)
return;
if (_layoutFeatures == null)
initAdvancedLayoutFeatures();
hasDeltaIdentityTransform = false;
_layoutFeatures.layoutScaleX = value;
invalidateTransform();
//invalidateProperties();
// If we're not compatible with Flex3 (measuredWidth is pre-scale always)
// and scaleX is changing we need to invalidate parent size and display list
// since we are not going to detect a change in measured sizes during measure.
invalidateParentSizeAndDisplayList();
}
/**
* The actual scaleX of the component. Because scaling is used
* to resize the component, this is considerred an internal
* implementation detail, whereas scaleX is the user-set scale
* of the component.
*
* @private
*/
mx_internal function get $scaleX():Number
{
return super.scaleX;
}
/**
* @private
*/
mx_internal function set $scaleX(value:Number):void
{
super.scaleX = value;
}
//----------------------------------
// scaleY
//----------------------------------
[Inspectable(category="Size", defaultValue="1.0")]
/**
* Number that specifies the vertical scaling factor.
*
* <p>The default value is 1.0, which means that the object
* is not scaled.
* A <code>scaleY</code> of 2.0 means the object has been
* magnified by a factor of 2, and a <code>scaleY</code> of 0.5
* means the object has been reduced by a factor of 2.</p>
*
* <p>A value of 0.0 is an invalid value.
* Rather than setting it to 0.0, set it to a small value, or set
* the <code>visible</code> property to <code>false</code> to hide the component.</p>
*
* @default 1.0
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
override public function get scaleY():Number
{
// if it's been set, layoutFeatures won't be null. Otherwise, return 1 as
// super.scaleX might be some other value since we change the width/height
// through scaling
return (_layoutFeatures == null) ? 1 : _layoutFeatures.layoutScaleY;
}
override public function set scaleY(value:Number):void
{
if (value == scaleY)
return;
if (_layoutFeatures == null)
initAdvancedLayoutFeatures();
hasDeltaIdentityTransform = false;
_layoutFeatures.layoutScaleY = value;
invalidateTransform();
//invalidateProperties();
// If we're not compatible with Flex3 (measuredWidth is pre-scale always)
// and scaleY is changing we need to invalidate parent size and display list
// since we are not going to detect a change in measured sizes during measure.
invalidateParentSizeAndDisplayList();
}
/**
* The actual scaleY of the component. Because scaling is used
* to resize the component, this is considerred an internal
* implementation detail, whereas scaleY is the user-set scale
* of the component.
*
* @private
*/
mx_internal function get $scaleY():Number
{
return super.scaleY;
}
/**
* @private
*/
mx_internal function set $scaleY(value:Number):void
{
super.scaleY = value;
}
//----------------------------------
// scaleZ
//----------------------------------
[Inspectable(category="Size", defaultValue="1.0")]
/**
* Number that specifies the scaling factor along the z axis.
*
* <p>A scaling along the z axis will not affect a typical component, which lies flat
* in the z=0 plane. components with children that have 3D transforms applied, or
* components with a non-zero transformZ, will be affected.</p>
*
* <p>The default value is 1.0, which means that the object
* is not scaled.</p>
*
* <p>This property is ignored during calculation by any of Flex's 2D layouts. </p>
*
* @default 1.0
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.1
* @productversion Flex 3
*/
override public function get scaleZ():Number
{
return (_layoutFeatures == null) ? super.scaleZ : _layoutFeatures.layoutScaleZ;
}
/**
* @private
*/
override public function set scaleZ(value:Number):void
{
if (scaleZ == value)
return;
if (_layoutFeatures == null)
initAdvancedLayoutFeatures();
hasDeltaIdentityTransform = false;
_layoutFeatures.layoutScaleZ = value;
invalidateTransform();
//invalidateProperties();
invalidateParentSizeAndDisplayList();
}
//--------------------------------------------------------------------------
//
// IToolTipManagerClient properties
//
//--------------------------------------------------------------------------
//----------------------------------
// toolTip
//----------------------------------
private var _toolTip:String;
/**
* Text to display in the ToolTip.
*
* @default null
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get toolTip():String
{
return _toolTip;
}
/**
* @private
*/
public function set toolTip(value:String):void
{
var toolTipManager:* = ApplicationDomain.currentDomain.getDefinition(
"mx.managers.ToolTipManager");
var oldValue:String = _toolTip;
_toolTip = value;
if (toolTipManager)
toolTipManager.registerToolTip(this, oldValue, value);
}
//--------------------------------------------------------------------------
//
// IFocusManagerComponent properties
//
//--------------------------------------------------------------------------
//----------------------------------
// focusEnabled
//----------------------------------
private var _focusEnabled:Boolean = true;
/**
* A flag that indicates whether the component can receive focus when selected.
*
* <p>As an optimization, if a child component in your component
* implements the IFocusManagerComponent interface, and you
* never want it to receive focus,
* you can set <code>focusEnabled</code>
* to <code>false</code> before calling <code>addChild()</code>
* on the child component.</p>
*
* <p>This will cause the FocusManager to ignore this component
* and not monitor it for changes to the <code>tabFocusEnabled</code>,
* <code>tabChildren</code>, and <code>mouseFocusEnabled</code> properties.
* This also means you cannot change this value after
* <code>addChild()</code> and expect the FocusManager to notice.</p>
*
* <p>Note: It does not mean that you cannot give this object focus
* programmatically in your <code>setFocus()</code> method;
* it just tells the FocusManager to ignore this IFocusManagerComponent
* component in the Tab and mouse searches.</p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get focusEnabled():Boolean
{
return _focusEnabled && focusableObjects.length > 0;
}
/**
* @private
*/
public function set focusEnabled(value:Boolean):void
{
_focusEnabled = value;
}
//----------------------------------
// hasFocusableChildren
//----------------------------------
/**
* @private
* Storage for the hasFocusableChildren property.
*/
private var _hasFocusableChildren:Boolean = true;
[Bindable("hasFocusableChildrenChange")]
[Inspectable(defaultValue="true")]
/**
* @copy mx.core.UIComponent#hasFocusableChildren
*
* @default true
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function get hasFocusableChildren():Boolean
{
return _hasFocusableChildren;
}
/**
* @private
*/
public function set hasFocusableChildren(value:Boolean):void
{
if (value != _hasFocusableChildren)
{
_hasFocusableChildren = value;
dispatchEvent(new Event("hasFocusableChildrenChange"));
}
}
//----------------------------------
// mouseFocusEnabled
//----------------------------------
/**
* A flag that indicates whether the component can receive focus
* when selected with the mouse.
* If <code>false</code>, focus will be transferred to
* the first parent that is <code>mouseFocusEnabled</code>.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get mouseFocusEnabled():Boolean
{
return false;
}
//----------------------------------
// tabFocusEnabled
//----------------------------------
/**
* @private
* Storage for the tabFocusEnabled property.
*/
private var _tabFocusEnabled:Boolean = true;
[Bindable("tabFocusEnabledChange")]
[Inspectable(defaultValue="true")]
/**
* A flag that indicates whether child objects can receive focus
*
* <p>This is similar to the <code>tabEnabled</code> property
* used by the Flash Player.</p>
*
* <p>This is usually <code>true</code> for components that
* handle keyboard input, but some components in controlbars
* have them set to <code>false</code> because they should not steal
* focus from another component like an editor.
* </p>
*
* @default true
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function get tabFocusEnabled():Boolean
{
return _tabFocusEnabled;
}
/**
* @private
*/
public function set tabFocusEnabled(value:Boolean):void
{
if (value != _tabFocusEnabled)
{
_tabFocusEnabled = value;
dispatchEvent(new Event("tabFocusEnabledChange"));
}
}
//--------------------------------------------------------------------------
//
// IConstraintClient methods
//
//--------------------------------------------------------------------------
/**
* @copy mx.core.IConstraintClient#getConstraintValue()
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function getConstraintValue(constraintName:String):*
{
return this["_"+constraintName];
}
/**
* @copy mx.core.IConstraintClient#setConstraintValue()
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function setConstraintValue(constraintName:String, value:*):void
{
// set it using the setter first
this[constraintName] = value;
// this is so we can have the value typed as *
this["_"+constraintName] = value;
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function get depth():Number
{
return (_layoutFeatures == null) ? 0 : _layoutFeatures.depth;
}
/**
* @private
*/
public function set depth(value:Number):void
{
if (value == depth)
return;
if (_layoutFeatures == null)
initAdvancedLayoutFeatures();
_layoutFeatures.depth = value;
if (parent != null && "invalidateLayering" in parent && parent["invalidateLayering"] is Function)
parent["invalidateLayering"]();
// TODO (rfrishbe): should be in some interface...
}
/**
* @copy mx.core.UIComponent#transformX
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function get transformX():Number
{
return (_layoutFeatures == null) ? 0 : _layoutFeatures.transformX;
}
/**
* @private
*/
public function set transformX(value:Number):void
{
if (transformX == value)
return;
if (_layoutFeatures == null)
initAdvancedLayoutFeatures();
_layoutFeatures.transformX = value;
invalidateTransform();
//invalidateProperties();
invalidateParentSizeAndDisplayList();
}
/**
* @copy mx.core.UIComponent#transformY
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function get transformY():Number
{
return (_layoutFeatures == null) ? 0 : _layoutFeatures.transformY;
}
/**
* @private
*/
public function set transformY(value:Number):void
{
if (transformY == value)
return;
if (_layoutFeatures == null)
initAdvancedLayoutFeatures();
_layoutFeatures.transformY = value;
invalidateTransform();
//invalidateProperties();
invalidateParentSizeAndDisplayList();
}
/**
* @copy mx.core.UIComponent#transformZ
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function get transformZ():Number
{
return (_layoutFeatures == null) ? 0 : _layoutFeatures.transformZ;
}
/**
* @private
*/
public function set transformZ(value:Number):void
{
if (transformZ == value)
return;
if (_layoutFeatures == null)
initAdvancedLayoutFeatures();
_layoutFeatures.transformZ = value;
invalidateTransform();
//invalidateProperties();
invalidateParentSizeAndDisplayList();
}
/**
* @copy mx.core.IFlexDisplayObject#rotation
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
override public function get rotation():Number
{
return (_layoutFeatures == null) ? super.rotation : _layoutFeatures.layoutRotationZ;
}
/**
* @private
*/
override public function set rotation(value:Number):void
{
if (rotation == value)
return;
hasDeltaIdentityTransform = false;
if (_layoutFeatures == null)
super.rotation = MatrixUtil.clampRotation(value);
else
_layoutFeatures.layoutRotationZ = value;
invalidateTransform();
//invalidateProperties();
invalidateParentSizeAndDisplayList();
}
/**
* Indicates the x-axis rotation of the DisplayObject instance, in degrees,
* from its original orientation relative to the 3D parent container.
* Values from 0 to 180 represent clockwise rotation; values from 0 to -180
* represent counterclockwise rotation. Values outside this range are added
* to or subtracted from 360 to obtain a value within the range.
*
* This property is ignored during calculation by any of Flex's 2D layouts.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 3
*/
override public function get rotationX():Number
{
return (_layoutFeatures == null) ? super.rotationX : _layoutFeatures.layoutRotationX;
}
/**
* @private
*/
override public function set rotationX(value:Number):void
{
if (rotationX == value)
return;
if (_layoutFeatures == null)
initAdvancedLayoutFeatures();
_layoutFeatures.layoutRotationX = value;
invalidateTransform();
//invalidateProperties();
invalidateParentSizeAndDisplayList();
}
/**
* Indicates the y-axis rotation of the DisplayObject instance, in degrees,
* from its original orientation relative to the 3D parent container.
* Values from 0 to 180 represent clockwise rotation; values from 0 to -180
* represent counterclockwise rotation. Values outside this range are added
* to or subtracted from 360 to obtain a value within the range.
*
* This property is ignored during calculation by any of Flex's 2D layouts.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 3
*/
override public function get rotationY():Number
{
return (_layoutFeatures == null) ? super.rotationY : _layoutFeatures.layoutRotationY;
}
/**
* @private
*/
override public function set rotationY(value:Number):void
{
if (rotationY == value)
return;
if (_layoutFeatures == null)
initAdvancedLayoutFeatures();
_layoutFeatures.layoutRotationY = value;
invalidateTransform();
//invalidateProperties();
invalidateParentSizeAndDisplayList();
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 3
*/
override public function get rotationZ():Number
{
return rotation;
}
/**
* @private
*/
override public function set rotationZ(value:Number):void
{
rotation = value;
}
//----------------------------------
// layoutDirection
//----------------------------------
private var _layoutDirection:String = null;
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function get layoutDirection():String
{
if (_layoutDirection != null)
return _layoutDirection;
const parentElt:IVisualElement = parent as IVisualElement;
return (parentElt) ? parentElt.layoutDirection : LayoutDirection.LTR;
}
/**
* @private
*/
public function set layoutDirection(value:String):void
{
if (_layoutDirection == value)
return;
_layoutDirection = value;
invalidateLayoutDirection();
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function invalidateLayoutDirection():void
{
const parentElt:IVisualElement = parent as IVisualElement;
if (!parentElt)
return;
// If this element's layoutDirection doesn't match its parent's, then
// set the _layoutFeatures.mirror flag. Similarly, if mirroring isn't
// required, then clear the _layoutFeatures.mirror flag.
const mirror:Boolean = (_layoutDirection != null) && (_layoutDirection != parentElt.layoutDirection);
if ((_layoutFeatures) ? (mirror != _layoutFeatures.mirror) : mirror)
{
if (_layoutFeatures == null)
initAdvancedLayoutFeatures();
_layoutFeatures.mirror = mirror;
invalidateTransform();
invalidateParentSizeAndDisplayList();
}
}
/**
* Defines a set of adjustments that can be applied to the component's transform in a way that is
* invisible to the component's parent's layout. For example, if you want a layout to adjust
* for a component that will be rotated 90 degrees, you set the component's <code>rotation</code> property.
* If you want the layout to <i>not</i> adjust for the component being rotated, you set its <code>postLayoutTransformOffsets.rotationZ</code>
* property.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function set postLayoutTransformOffsets(value:TransformOffsets):void
{
if (_layoutFeatures == null)
initAdvancedLayoutFeatures();
if (_layoutFeatures.postLayoutTransformOffsets != null)
_layoutFeatures.postLayoutTransformOffsets.removeEventListener(Event.CHANGE,transformOffsetsChangedHandler);
_layoutFeatures.postLayoutTransformOffsets = value;
if (_layoutFeatures.postLayoutTransformOffsets != null)
_layoutFeatures.postLayoutTransformOffsets.addEventListener(Event.CHANGE,transformOffsetsChangedHandler);
invalidateTransform();
}
/**
* @private
*/
public function get postLayoutTransformOffsets():TransformOffsets
{
return (_layoutFeatures != null)? _layoutFeatures.postLayoutTransformOffsets:null;
}
private function transformOffsetsChangedHandler(e:Event):void
{
invalidateTransform();
}
/**
* @private
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
override public function get transform():flash.geom.Transform
{
if (_transform == null)
{
setTransform(new mx.geom.Transform(this));
}
return _transform;
}
/**
* @private
*/
override public function set transform(value:flash.geom.Transform):void
{
var m:Matrix = value.matrix;
var m3:Matrix3D = value.matrix3D;
var ct:ColorTransform = value.colorTransform;
var pp:PerspectiveProjection = value.perspectiveProjection;
var mxTransform:mx.geom.Transform = value as mx.geom.Transform;
if (mxTransform)
{
if (!mxTransform.applyMatrix)
m = null;
if (!mxTransform.applyMatrix3D)
m3 = null;
}
setTransform(value);
if (m != null)
setLayoutMatrix(m.clone(), true /*triggerLayoutPass*/);
else if (m3 != null)
setLayoutMatrix3D(m3.clone(), true /*triggerLayoutPass*/);
super.transform.colorTransform = ct;
super.transform.perspectiveProjection = pp;
if (maintainProjectionCenter)
applyPerspectiveProjection();
}
/**
* Documentation is not currently available
*/
mx_internal function get $transform():flash.geom.Transform
{
return super.transform;
}
/**
* @private
*/
private var _maintainProjectionCenter:Boolean = false;
/**
* When true, the component will keep its projection matrix centered on the
* middle of its bounding box. If no projection matrix is defined on the
* component, one will be added automatically.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function set maintainProjectionCenter(value:Boolean):void
{
_maintainProjectionCenter = value;
if (value && super.transform.perspectiveProjection == null)
{
super.transform.perspectiveProjection = new PerspectiveProjection();
}
applyPerspectiveProjection();
}
/**
* @private
*/
public function get maintainProjectionCenter():Boolean
{
return _maintainProjectionCenter;
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function getLayoutMatrix():Matrix
{
if (_layoutFeatures != null || super.transform.matrix == null)
{
// TODO: this is a workaround for a situation in which the
// object is in 2D, but used to be in 3D and the player has not
// yet cleaned up the matrices. So the matrix property is null, but
// the matrix3D property is non-null. layoutFeatures can deal with
// that situation, so we allocate it here and let it handle it for
// us. The downside is that we have now allocated layoutFeatures
// forever and will continue to use it for future situations that
// might not have required it. Eventually, we should recognize
// situations when we can de-allocate layoutFeatures and back off
// to letting the player handle transforms for us.
if (_layoutFeatures == null)
initAdvancedLayoutFeatures();
// esg: _layoutFeatures keeps a single internal copy of the layoutMatrix.
// since this is an internal class, we don't need to worry about developers
// accidentally messing with this matrix, _unless_ we hand it out. Instead,
// we hand out a clone.
return _layoutFeatures.layoutMatrix.clone();
}
else
{
// flash also returns copies.
return super.transform.matrix;
}
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function setLayoutMatrix(value:Matrix, invalidateLayout:Boolean):void
{
hasDeltaIdentityTransform = false;
if (_layoutFeatures == null)
{
// flash will make a copy of this on assignment.
super.transform.matrix = value;
}
else
{
// layout features will internally make a copy of this matrix rather than
// holding onto a reference to it.
_layoutFeatures.layoutMatrix = value;
invalidateTransform();
}
//invalidateProperties();
if (invalidateLayout)
invalidateParentSizeAndDisplayList();
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function getLayoutMatrix3D():Matrix3D
{
if (_layoutFeatures == null)
initAdvancedLayoutFeatures();
// esg: _layoutFeatures keeps a single internal copy of the layoutMatrix.
// since this is an internal class, we don't need to worry about developers
// accidentally messing with this matrix, _unless_ we hand it out. Instead,
// we hand out a clone.
return _layoutFeatures.layoutMatrix3D.clone();
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function get hasLayoutMatrix3D():Boolean
{
return _layoutFeatures ? _layoutFeatures.layoutIs3D : false;
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function get is3D():Boolean
{
return _layoutFeatures ? _layoutFeatures.is3D : false;
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function setLayoutMatrix3D(value:Matrix3D, invalidateLayout:Boolean):void
{
if (_layoutFeatures == null)
initAdvancedLayoutFeatures();
// layout features will internally make a copy of this matrix rather than
// holding onto a reference to it.
_layoutFeatures.layoutMatrix3D = value;
invalidateTransform();
//invalidateProperties();
if (invalidateLayout)
invalidateParentSizeAndDisplayList();
}
private function setTransform(value:flash.geom.Transform):void
{
// Clean up the old transform
var oldTransform:mx.geom.Transform = _transform as mx.geom.Transform;
if (oldTransform)
oldTransform.target = null;
var newTransform:mx.geom.Transform = value as mx.geom.Transform;
if (newTransform)
newTransform.target = this;
_transform = value;
}
/**
* A utility method to update the rotation, scale, and translation of the
* transform while keeping a particular point, specified in the component's
* own coordinate space, fixed in the parent's coordinate space.
* This function will assign the rotation, scale, and translation values
* provided, then update the x/y/z properties as necessary to keep
* the transform center fixed.
*
* @param transformCenter The point, in the component's own coordinates, to keep fixed relative to its parent.
*
* @param scale The new values for the scale of the transform
*
* @param rotation The new values for the rotation of the transform
*
* @param translation The new values for the translation of the transform
*
* @param postLayoutScale
*
* @param postLayoutRotation
*
* @param postLayoutTranslation
*
* @param invalidateLayout
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function transformAround(transformCenter:Vector3D,
scale:Vector3D = null,
rotation:Vector3D = null,
translation:Vector3D = null,
postLayoutScale:Vector3D = null,
postLayoutRotation:Vector3D = null,
postLayoutTranslation:Vector3D = null,
invalidateLayout:Boolean = true):void
{
// Make sure that no transform setters will trigger parent invalidation.
// Reset the flag at the end of the method.
var oldIncludeInLayout:Boolean;
if (!invalidateLayout)
{
oldIncludeInLayout = _includeInLayout;
_includeInLayout = false;
}
TransformUtil.transformAround(this,
transformCenter,
scale,
rotation,
translation,
postLayoutScale,
postLayoutRotation,
postLayoutTranslation,
_layoutFeatures,
initAdvancedLayoutFeatures);
if (_layoutFeatures != null)
{
invalidateTransform();
// Will not invalidate parent if we have set _includeInLayout to false
// in the beginning of the method
invalidateParentSizeAndDisplayList();
}
if (!invalidateLayout)
_includeInLayout = oldIncludeInLayout;
}
/**
* A utility method to transform a point specified in the local
* coordinates of this object to its location in the object's parent's
* coordinates. The pre-layout and post-layout result will be set on
* the <code>position</code> and <code>postLayoutPosition</code>
* parameters, if they are non-null.
*
* @param localPosition The point to be transformed, specified in the
* local coordinates of the object.
* @position A Vector3D point that will hold the pre-layout
* result. If null, the parameter is ignored.
* @postLayoutPosition A Vector3D point that will hold the post-layout
* result. If null, the parameter is ignored.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function transformPointToParent(localPosition:Vector3D,
position:Vector3D,
postLayoutPosition:Vector3D):void
{
TransformUtil.transformPointToParent(this,
localPosition,
position,
postLayoutPosition,
_layoutFeatures);
}
/**
* Helper method to invalidate parent size and display list if
* this object affects its layout (includeInLayout is true).
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
protected function invalidateParentSizeAndDisplayList():void
{
if (!includeInLayout)
return;
var p:IInvalidating = parent as IInvalidating;
if (!p)
return;
p.invalidateSize();
p.invalidateDisplayList();
}
/**
* @private
*
* storage for advanced layout and transform properties.
*/
mx_internal var _layoutFeatures:AdvancedLayoutFeatures;
/**
* @private
* When true, the transform on this component consists only of translation.
* Otherwise, it may be arbitrarily complex.
*/
protected var hasDeltaIdentityTransform:Boolean = true;
/**
* @private
* Storage for the modified Transform object that can dispatch
* change events correctly.
*/
private var _transform:flash.geom.Transform;
/**
* @private
* Initializes the implementation and storage of some of the less
* frequently used advanced layout features of a component.
* Call this function before attempting to use any of the
* features implemented by the AdvancedLayoutFeatures object.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
private function initAdvancedLayoutFeatures():AdvancedLayoutFeatures
{
var features:AdvancedLayoutFeatures = new AdvancedLayoutFeatures();
hasDeltaIdentityTransform = false;
features.layoutScaleX = scaleX;
features.layoutScaleY = scaleY;
features.layoutScaleZ = scaleZ;
features.layoutRotationX = rotationX;
features.layoutRotationY = rotationY;
features.layoutRotationZ = rotation;
features.layoutX = x;
features.layoutY = y;
features.layoutZ = z;
features.layoutWidth = _width; // for the mirror transform
// Initialize the internal variable last,
// since the transform getters depend on it.
_layoutFeatures = features;
invalidateTransform();
return features;
}
private function invalidateTransform():void
{
if (_layoutFeatures && _layoutFeatures.updatePending == false)
{
_layoutFeatures.updatePending = true;
applyComputedMatrix();
}
}
/**
* Commits the computed matrix built from the combination of the layout matrix and the transform offsets to the flash displayObject's transform.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
private function applyComputedMatrix():void
{
_layoutFeatures.updatePending = false;
if (_layoutFeatures.is3D)
{
super.transform.matrix3D = _layoutFeatures.computedMatrix3D;
}
else
{
super.transform.matrix = _layoutFeatures.computedMatrix;
}
}
private function applyPerspectiveProjection():void
{
var pmatrix:PerspectiveProjection = super.transform.perspectiveProjection;
if (pmatrix != null)
{
// width, height instead of unscaledWidth, unscaledHeight
pmatrix.projectionCenter = new Point(width/2,height/2);
}
}
//--------------------------------------------------------------------------
//
// Methods
//
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//
// ILayoutElement
//
//--------------------------------------------------------------------------
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function getPreferredBoundsWidth(postLayoutTransform:Boolean = true):Number
{
return LayoutElementUIComponentUtils.getPreferredBoundsWidth(this,postLayoutTransform? nonDeltaLayoutMatrix():null);
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function getPreferredBoundsHeight(postLayoutTransform:Boolean = true):Number
{
return LayoutElementUIComponentUtils.getPreferredBoundsHeight(this,postLayoutTransform? nonDeltaLayoutMatrix():null);
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function getMinBoundsWidth(postLayoutTransform:Boolean = true):Number
{
return LayoutElementUIComponentUtils.getMinBoundsWidth(this,postLayoutTransform? nonDeltaLayoutMatrix():null);
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function getMinBoundsHeight(postLayoutTransform:Boolean = true):Number
{
return LayoutElementUIComponentUtils.getMinBoundsHeight(this,postLayoutTransform? nonDeltaLayoutMatrix():null);
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function getMaxBoundsWidth(postLayoutTransform:Boolean = true):Number
{
return LayoutElementUIComponentUtils.getMaxBoundsWidth(this,postLayoutTransform? nonDeltaLayoutMatrix():null);
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function getMaxBoundsHeight(postLayoutTransform:Boolean = true):Number
{
return LayoutElementUIComponentUtils.getMaxBoundsHeight(this,postLayoutTransform? nonDeltaLayoutMatrix():null);
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function getBoundsXAtSize(width:Number, height:Number, postLayoutTransform:Boolean = true):Number
{
return LayoutElementUIComponentUtils.getBoundsXAtSize(this, width, height,
postLayoutTransform ? nonDeltaLayoutMatrix() : null);
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function getBoundsYAtSize(width:Number, height:Number, postLayoutTransform:Boolean = true):Number
{
return LayoutElementUIComponentUtils.getBoundsYAtSize(this, width, height,
postLayoutTransform ? nonDeltaLayoutMatrix() : null);
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function getLayoutBoundsWidth(postLayoutTransform:Boolean = true):Number
{
return LayoutElementUIComponentUtils.getLayoutBoundsWidth(this,postLayoutTransform? nonDeltaLayoutMatrix():null);
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function getLayoutBoundsHeight(postLayoutTransform:Boolean = true):Number
{
return LayoutElementUIComponentUtils.getLayoutBoundsHeight(this,postLayoutTransform? nonDeltaLayoutMatrix():null);
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function getLayoutBoundsX(postLayoutTransform:Boolean = true):Number
{
return LayoutElementUIComponentUtils.getLayoutBoundsX(this,postLayoutTransform? nonDeltaLayoutMatrix():null);
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function getLayoutBoundsY(postLayoutTransform:Boolean = true):Number
{
return LayoutElementUIComponentUtils.getLayoutBoundsY(this,postLayoutTransform? nonDeltaLayoutMatrix():null);
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function setLayoutBoundsPosition(x:Number, y:Number, postLayoutTransform:Boolean = true):void
{
LayoutElementUIComponentUtils.setLayoutBoundsPosition(this,x,y,postLayoutTransform? nonDeltaLayoutMatrix():null);
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function setLayoutBoundsSize(width:Number,
height:Number,
postLayoutTransform:Boolean = true):void
{
LayoutElementUIComponentUtils.setLayoutBoundsSize(this,width,height,postLayoutTransform? nonDeltaLayoutMatrix():null);
}
/**
* @private
* Returns the layout matrix, or null if it only consists of translations.
*/
private function nonDeltaLayoutMatrix():Matrix
{
if (hasDeltaIdentityTransform)
return null;
if (_layoutFeatures != null)
{
return _layoutFeatures.layoutMatrix;
}
else
{
// Lose scale
// if scale is actually set (and it's not just our "secret scale"), then
// layoutFeatures wont' be null and we won't be down here
return MatrixUtil.composeMatrix(x, y, 1, 1, rotation,
transformX, transformY);
}
}
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
//----------------------------------
// bounds
//----------------------------------
/**
* The unscaled bounds of the content.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
protected function get bounds():Rectangle
{
if (boundingBoxName && boundingBoxName != ""
&& boundingBoxName in this && this[boundingBoxName])
{
return this[boundingBoxName].getBounds(this);
}
return getBounds(this);
}
//----------------------------------
// parent
//----------------------------------
/**
* @private
* Override the parent getter to skip non-UIComponent parents.
*/
override public function get parent():DisplayObjectContainer
{
return _parent ? _parent : super.parent;
}
//----------------------------------
// parentDocument
//----------------------------------
/**
* The document containing this component.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get parentDocument():Object
{
if (document == this)
{
var p:IUIComponent = parent as IUIComponent;
if (p)
return p.document;
var sm:ISystemManager = parent as ISystemManager;
if (sm)
return sm.document;
return null;
}
else
{
return document;
}
}
//----------------------------------
// currentState
//----------------------------------
private var _currentState:String;
/**
* The current state of this component. For UIMovieClip, the value of the
* <code>currentState</code> property is the current frame label.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get currentState():String
{
return _currentState;
}
public function set currentState(value:String):void
{
if (value == _currentState)
return;
if (!stateMap)
buildStateMap();
if (stateMap[value])
{
// See if we have a transition. The first place to looks is for a specific
// transition between the old and new states.
var frameName:String = _currentState + "-" + value + ":start";
var startFrame:Number;
var endFrame:Number;
if (stateMap[frameName])
{
startFrame = stateMap[frameName].frame;
endFrame = stateMap[_currentState + "-" + value + ":end"].frame;
}
if (isNaN(startFrame))
{
// Next, look for new-old to play backwards
frameName = value + "-" + _currentState + ":end";
if (stateMap[frameName])
{
startFrame = stateMap[frameName].frame;
endFrame = stateMap[value + "-" + _currentState + ":start"].frame;
}
}
if (isNaN(startFrame))
{
// Next, look for *-new
frameName = "*-" + value + ":start";
if (stateMap[frameName])
{
startFrame = stateMap[frameName].frame;
endFrame = stateMap["*-" + value + ":end"].frame;
}
}
if (isNaN(startFrame))
{
// Next, look for new-* to play backwards
frameName = value + "-*:end";
if (stateMap[frameName])
{
startFrame = stateMap[frameName].frame;
endFrame = stateMap[value + "-*:start"].frame;
}
}
if (isNaN(startFrame))
{
// Next, look for old-*
frameName = _currentState + "-*:start";
if (stateMap[frameName])
{
startFrame = stateMap[frameName].frame;
endFrame = stateMap[_currentState + "-*:end"].frame;
}
}
if (isNaN(startFrame))
{
// Next, look for *-old to play backwards
frameName = "*-" + _currentState + ":end";
if (stateMap[frameName])
{
startFrame = stateMap[frameName].frame;
endFrame = stateMap["*-" + _currentState + ":start"].frame;
}
}
if (isNaN(startFrame))
{
// Next, look for *-*
frameName = "*-*:start";
if (stateMap[frameName])
{
startFrame = stateMap[frameName].frame;
endFrame = stateMap["*-*:end"].frame;
}
}
// Finally, just look for the frame of the new state.
if (isNaN(startFrame) && (value in stateMap))
{
startFrame = stateMap[value].frame;
}
// If, after all that searching, we still haven't found a frame to go to, let's
// get outta here.
if (isNaN(startFrame))
return;
var event:StateChangeEvent = new StateChangeEvent(StateChangeEvent.CURRENT_STATE_CHANGING);
event.oldState = _currentState;
event.newState = value;
dispatchEvent(event);
if (isNaN(endFrame))
{
// No transtion - go immediately to the state
gotoAndStop(startFrame);
transitionDirection = 0;
}
else
{
addEventListener(Event.ENTER_FRAME, transitionEnterFrameHandler, false, 0, true);
// If the new transition is starting inside the current transition, start from
// the current frame location.
if (currentFrame < Math.min(startFrame, endFrame) || currentFrame > Math.max(startFrame, endFrame))
gotoAndStop(startFrame);
else
startFrame = currentFrame;
transitionStartFrame = startFrame;
transitionEndFrame = endFrame;
transitionDirection = (endFrame > startFrame) ? 1 : -1;
transitionEndState = value;
}
event = new StateChangeEvent(StateChangeEvent.CURRENT_STATE_CHANGE);
event.oldState = _currentState;
event.newState = value;
dispatchEvent(event);
_currentState = value;
}
}
/**
* @private
*/
override public function get tabEnabled():Boolean
{
return super.tabEnabled;
}
/**
* @private
*/
override public function set tabEnabled(value:Boolean):void
{
super.tabEnabled = value;
explicitTabEnabledChanged = true;
}
//--------------------------------------------------------------------------
//
// IUIComponent methods
//
//--------------------------------------------------------------------------
/**
* Initialize the object.
*
* @see mx.core.UIComponent#initialize()
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function initialize():void
{
initialized = true;
dispatchEvent(new FlexEvent(FlexEvent.PREINITIALIZE));
// Hide the bounding box, if present
if (boundingBoxName && boundingBoxName != ""
&& boundingBoxName in this && this[boundingBoxName])
{
this[boundingBoxName].visible = false;
}
// get the size before we add children or anything else
validateMeasuredSize();
// Location check.
if (isNaN(oldX))
oldX = x;
if (isNaN(oldY))
oldY = y;
if (isNaN(oldWidth))
oldWidth = _width = measuredWidth;
if (isNaN(oldHeight))
oldHeight = _height = measuredHeight;
// Set initial explicit size, if needed
if (explicitSizeChanged)
{
explicitSizeChanged = false;
setActualSize(getExplicitOrMeasuredWidth(), getExplicitOrMeasuredHeight());
}
// Look for focus candidates
findFocusCandidates(this);
// Call initialize() on any IUIComponent children
for (var i:int = 0; i < numChildren; i++)
{
var child:IUIComponent = getChildAt(i) as IUIComponent;
if (child)
child.initialize();
}
dispatchEvent(new FlexEvent(FlexEvent.INITIALIZE));
dispatchEvent(new FlexEvent(FlexEvent.CREATION_COMPLETE));
}
/**
* Called by Flex when a UIComponent object is added to or removed from a parent.
* Developers typically never need to call this method.
*
* @param p The parent of this UIComponent object.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function parentChanged(p:DisplayObjectContainer):void
{
if (!p)
{
_parent = null;
}
else if (p is IUIComponent || p is ISystemManager)
{
_parent = p;
}
else
{
_parent = p.parent;
}
}
/**
* A convenience method for determining whether to use the
* explicit or measured width
*
* @return A Number which is explicitWidth if defined
* or measuredWidth if not.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function getExplicitOrMeasuredWidth():Number
{
if (isNaN(explicitWidth))
{
var mWidth:Number = measuredWidth;
if (!isNaN(explicitMinWidth) && mWidth < explicitMinWidth)
mWidth = explicitMinWidth;
if (!isNaN(explicitMaxWidth) && mWidth > explicitMaxWidth)
mWidth = explicitMaxWidth;
return mWidth;
}
return explicitWidth;
}
/**
* A convenience method for determining whether to use the
* explicit or measured height
*
* @return A Number which is explicitHeight if defined
* or measuredHeight if not.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function getExplicitOrMeasuredHeight():Number
{
if (isNaN(explicitHeight))
{
var mHeight:Number = measuredHeight;
if (!isNaN(explicitMinHeight) && mHeight < explicitMinHeight)
mHeight = explicitMinHeight;
if (!isNaN(explicitMaxHeight) && mHeight > explicitMaxHeight)
mHeight = explicitMaxHeight;
return mHeight;
}
return explicitHeight;
}
/**
* Called when the <code>visible</code> property changes.
* You should set the <code>visible</code> property to show or hide
* a component instead of calling this method directly.
*
* @param value The new value of the <code>visible</code> property.
* Specify <code>true</code> to show the component, and <code>false</code> to hide it.
*
* @param noEvent If <code>true</code>, do not dispatch an event.
* If <code>false</code>, dispatch a <code>show</code> event when
* the component becomes visible, and a <code>hide</code> event when
* the component becomes invisible.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function setVisible(value:Boolean, noEvent:Boolean = false):void
{
_visible = value;
if (designLayer && !designLayer.effectiveVisibility)
value = false;
if (super.visible == value)
return;
super.visible = value;
if (!noEvent)
dispatchEvent(new FlexEvent(value ? FlexEvent.SHOW : FlexEvent.HIDE));
}
/**
* Returns <code>true</code> if the chain of <code>owner</code> properties
* points from <code>child</code> to this UIComponent.
*
* @param child A UIComponent.
*
* @return <code>true</code> if the child is parented or owned by this UIComponent.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function owns(displayObject:DisplayObject):Boolean
{
while (displayObject && displayObject != this)
{
// do a parent walk
if (displayObject is IUIComponent)
displayObject = IUIComponent(displayObject).owner;
else
displayObject = displayObject.parent;
}
return displayObject == this;
}
//--------------------------------------------------------------------------
//
// IFlexDisplayObject methods
//
//--------------------------------------------------------------------------
/**
* Moves this object to the specified x and y coordinates.
*
* @param x The new x-position for this object.
*
* @param y The new y-position for this object.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function move(x:Number, y:Number):void
{
var changed:Boolean = false;
if (x != this.x)
{
if (_layoutFeatures == null)
super.x = x;
else
_layoutFeatures.layoutX = x;
dispatchEvent(new Event("xChanged"));
changed = true;
}
if (y != this.y)
{
if (_layoutFeatures == null)
super.y = y;
else
_layoutFeatures.layoutY = y;
dispatchEvent(new Event("yChanged"));
changed = true;
}
if (changed)
{
invalidateTransform();
dispatchMoveEvent();
}
}
/**
* Sets the actual size of this object.
*
* <p>This method is mainly for use in implementing the
* <code>updateDisplayList()</code> method, which is where
* you compute this object's actual size based on
* its explicit size, parent-relative (percent) size,
* and measured size.
* You then apply this actual size to the object
* by calling <code>setActualSize()</code>.</p>
*
* <p>In other situations, you should be setting properties
* such as <code>width</code>, <code>height</code>,
* <code>percentWidth</code>, or <code>percentHeight</code>
* rather than calling this method.</p>
*
* @param newWidth The new width for this object.
*
* @param newHeight The new height for this object.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function setActualSize(newWidth:Number, newHeight:Number):void
{
// Remember our new actual size so we can report it later in the
// width/height getters.
_width = newWidth;
_height = newHeight;
// Use scaleX/scaleY to change our size since the new size is based
// on our measured size, which can be different than our actual size.
var widthScale:Number = (newWidth / measuredWidth);
var heightScale:Number = (newHeight / measuredHeight);
// if we need to scale due to sizing differences or if we might've scaled before,
// then we need to set _layoutFeatures.stretchX/stretchY
if (widthScale != 1 || heightScale != 1 || _layoutFeatures != null)
{
if (_layoutFeatures == null)
initAdvancedLayoutFeatures();
_layoutFeatures.stretchX = widthScale;
_layoutFeatures.stretchY = heightScale;
// need to apply this scale if using layout offsets
invalidateTransform();
}
if (sizeChanged(width, oldWidth) || sizeChanged(height, oldHeight))
dispatchResizeEvent();
}
//--------------------------------------------------------------------------
//
// IFocusManagerComponent methods
//
//--------------------------------------------------------------------------
/**
* Called by the FocusManager when the component receives focus.
* The component may in turn set focus to an internal component.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function setFocus():void
{
stage.focus = focusableObjects[reverseDirectionFocus ? focusableObjects.length - 1 : 0];
addFocusEventListeners();
}
/**
* Called by the FocusManager when the component receives focus.
* The component should draw or hide a graphic
* that indicates that the component has focus.
*
* @param isFocused If <code>true</code>, draw the focus indicator,
* otherwise hide it.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function drawFocus(isFocused:Boolean):void
{
}
//--------------------------------------------------------------------------
//
// Layout methods
//
//--------------------------------------------------------------------------
/**
* Validate the measuredWidth and measuredHeight properties to match the
* current size of the content.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
private function validateMeasuredSize():void
{
if (validateMeasuredSizeFlag)
{
validateMeasuredSizeFlag = false;
_measuredWidth = bounds.width;
_measuredHeight = bounds.height;
}
}
/**
* Notify our parent that our size has changed.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
protected function notifySizeChanged():void
{
invalidateParentSizeAndDisplayList();
}
/**
* @private
*/
private function dispatchMoveEvent():void
{
var moveEvent:MoveEvent = new MoveEvent(MoveEvent.MOVE);
moveEvent.oldX = oldX;
moveEvent.oldY = oldY;
dispatchEvent(moveEvent);
oldX = x;
oldY = y;
}
/**
* @private
*/
protected function dispatchResizeEvent():void
{
var resizeEvent:ResizeEvent = new ResizeEvent(ResizeEvent.RESIZE);
resizeEvent.oldWidth = oldWidth;
resizeEvent.oldHeight = oldHeight;
dispatchEvent(resizeEvent);
oldWidth = width;
oldHeight = height;
}
/**
* @private
*/
protected function sizeChanged(oldValue:Number, newValue:Number):Boolean
{
// Only detect size changes that are greater than 1 pixel. Flex rounds sizes to the nearest
// pixel, which causes infinite resizing if we have a fractional pixel width and are
// detecting changes that are smaller than 1 pixel.
return Math.abs(oldValue - newValue) > 1;
}
//--------------------------------------------------------------------------
//
// Focus methods
//
//--------------------------------------------------------------------------
/**
* Recursively finds all children that have tabEnabled=true and adds them
* to the focusableObjects array.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
protected function findFocusCandidates(obj:DisplayObjectContainer):void
{
for (var i:int = 0; i < obj.numChildren; i++)
{
var child:InteractiveObject = obj.getChildAt(i) as InteractiveObject;
if (child && child.tabEnabled)
{
focusableObjects.push(child);
if (!explicitTabEnabledChanged)
{
tabEnabled = true;
tabFocusEnabled = true;
}
}
if (child is DisplayObjectContainer)
findFocusCandidates(DisplayObjectContainer(child));
}
}
//--------------------------------------------------------------------------
//
// State/Transition methods
//
//--------------------------------------------------------------------------
/**
* Build a map of state name to labels.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
private function buildStateMap():void
{
var labels:Array = currentLabels;
stateMap = {};
for (var i:int = 0; i < labels.length; i++)
{
stateMap[labels[i].name] = labels[i];
}
}
//--------------------------------------------------------------------------
//
// Event Handlers
//
//--------------------------------------------------------------------------
/**
* This enter frame handler is used when our width, height, x, or y
* value changes. This is so the change can be delayed so that setting
* x and y at the same time only results in one change event.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
protected function enterFrameHandler(event:Event):void
{
// explicit size change check.
if (explicitSizeChanged)
{
explicitSizeChanged = false;
setActualSize(getExplicitOrMeasuredWidth(), getExplicitOrMeasuredHeight());
}
if (x != oldX || y != oldY)
dispatchMoveEvent();
removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
}
/**
* @private
* This enter frame handler watches the flash object's size to see if
* it has changed. If it's chagned, we will notify our flex parent of
* the change. This size change may also cause the flash component
* to rescale if it's been explicitly sized so it fits within the
* correct bounds.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 4
*/
protected function autoUpdateMeasuredSizeEnterFrameHandler(event:Event):void
{
// Size check.
var currentBounds:Rectangle = bounds;
// take secret scale into account as it's our real width/height
if (_layoutFeatures != null)
{
currentBounds.width *= _layoutFeatures.stretchX;
currentBounds.height *= _layoutFeatures.stretchY;
}
if (sizeChanged(currentBounds.width, oldWidth) || sizeChanged(currentBounds.height, oldHeight))
{
_width = currentBounds.width;
_height = currentBounds.height;
validateMeasuredSizeFlag = true;
notifySizeChanged();
dispatchResizeEvent();
}
else if (sizeChanged(width, oldWidth) || sizeChanged(height, oldHeight))
{
dispatchResizeEvent();
}
}
/**
* @private
* This enter frame handler watches our currentLabel for changes so that it
* can be reflected in the currentState.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 4
*/
protected function autoUpdateCurrentStateEnterFrameHandler(event:Event):void
{
// Check for the current state. This is really only checked for if
// autoUpdateCurrentState == true. This is so that if we magically land
// on a "foo" labelled frame, we return "foo" as the currentState.
if (currentLabel && currentLabel.indexOf(":") < 0 && currentLabel != _currentState)
_currentState = currentLabel;
}
/**
* @private
* Sets up the current state the very first time. This will only run once.
*/
private function setUpFirstCurrentState(event:Event):void
{
// only run this code the very first time.
removeEventListener(Event.ENTER_FRAME, setUpFirstCurrentState);
if (currentLabel && currentLabel.indexOf(":") < 0 && currentLabel != _currentState)
_currentState = currentLabel;
}
/**
* This enter frame handler progresses through transitions.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 4
*/
protected function transitionEnterFrameHandler(event:Event):void
{
// Play the next frame of the transition, if needed.
var newFrame:Number = currentFrame + transitionDirection;
if ((transitionDirection > 0 && newFrame >= transitionEndFrame) ||
(transitionDirection < 0 && newFrame <= transitionEndFrame))
{
gotoAndStop(stateMap[transitionEndState].frame);
transitionDirection = 0;
removeEventListener(Event.ENTER_FRAME, transitionEnterFrameHandler);
}
else
{
gotoAndStop(newFrame);
}
}
/**
* Add the focus event listeners.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
private function addFocusEventListeners():void
{
// If we get a security error because we're not allowed to add event listeners to the stage,
// then just add them to the systemManager instead because we could be an untrusted app.
try
{
stage.addEventListener(FocusEvent.KEY_FOCUS_CHANGE, keyFocusChangeHandler, false, 1, true);
stage.addEventListener(FocusEvent.FOCUS_OUT, focusOutHandler, false, 0, true);
}
catch (err:SecurityError)
{
systemManager.addEventListener(FocusEvent.KEY_FOCUS_CHANGE, keyFocusChangeHandler, false, 1, true);
systemManager.addEventListener(FocusEvent.FOCUS_OUT, focusOutHandler, false, 0, true);
}
focusListenersAdded = true;
}
/**
* Remove our focus event listeners.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
private function removeFocusEventListeners():void
{
// Same security issue as addFocusEventListeners()
try
{
if (stage)
{
stage.removeEventListener(FocusEvent.KEY_FOCUS_CHANGE, keyFocusChangeHandler);
stage.removeEventListener(FocusEvent.FOCUS_OUT, focusOutHandler);
}
}
catch (err:SecurityError)
{
systemManager.removeEventListener(FocusEvent.KEY_FOCUS_CHANGE, keyFocusChangeHandler);
systemManager.removeEventListener(FocusEvent.FOCUS_OUT, focusOutHandler);
}
focusListenersAdded = false;
}
/**
* Called when the focus is changed by keyboard navigation (TAB or Shift+TAB).
* If we are currently managing the focus, stop the event propagation to
* "steal" the event from the Flex focus manager.
* If we are at the end of our focusable items (first item for Shift+TAB, or
* last item for TAB), remove our event handlers to give control back
* to the Flex focus manager.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
private function keyFocusChangeHandler(event:FocusEvent):void
{
if (event.keyCode == Keyboard.TAB)
{
if (stage.focus == focusableObjects[event.shiftKey ? 0 : focusableObjects.length - 1])
removeFocusEventListeners();
else
event.stopImmediatePropagation();
}
}
/**
* Called when focus is entering any of our children. Make sure our
* focus event handlers are called so we can take control from the
* Flex focus manager.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
protected function focusInHandler(event:FocusEvent):void
{
if (!focusListenersAdded)
addFocusEventListeners();
}
/**
* Called when focus is leaving an object. We check to see if the new
* focus item is in our focusableObjects list, and if not we remove
* our event listeners to give control back to the Flex focus manager.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
private function focusOutHandler(event:FocusEvent):void
{
if (focusableObjects.indexOf(event.relatedObject) == -1)
removeFocusEventListeners();
}
/**
* Called during event capture phase when keyboard navigation is changing
* focus. All we do here is set a flag so we know which direction the
* focus is changing - TAB = forward; Shift+TAB = reverse.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
private function keyFocusChangeCaptureHandler(event:FocusEvent):void
{
reverseDirectionFocus = event.shiftKey;
}
private function creationCompleteHandler(event:Event):void
{
removeEventListener(FlexEvent.CREATION_COMPLETE, creationCompleteHandler);
// Add a key focus change handler at the capture phase. We use this to
// determine focus direction in the setFocus() call.
if (systemManager)
{
// If we get a security error because we're not allowed to add event listeners to the stage,
// then just add them to the systemManager instead because we could be an untrusted app.
try
{
systemManager.stage.addEventListener(FocusEvent.KEY_FOCUS_CHANGE, keyFocusChangeCaptureHandler,
true, 0, true);
}
catch (err:SecurityError)
{
systemManager.addEventListener(FocusEvent.KEY_FOCUS_CHANGE, keyFocusChangeCaptureHandler,
true, 0, true);
}
}
else if (parentDocument && parentDocument.systemManager)
{
// Same security issue as above
try
{
parentDocument.systemManager.stage.addEventListener(FocusEvent.KEY_FOCUS_CHANGE, keyFocusChangeCaptureHandler,
true, 0, true);
}
catch (err:SecurityError)
{
parentDocument.systemManager.addEventListener(FocusEvent.KEY_FOCUS_CHANGE, keyFocusChangeCaptureHandler,
true, 0, true);
}
}
}
/**
* @private
*/
protected function layer_PropertyChange(event:PropertyChangeEvent):void
{
switch (event.property)
{
case "effectiveVisibility":
{
var newValue:Boolean = (event.newValue && _visible);
if (newValue != super.visible)
super.visible = newValue;
break;
}
case "effectiveAlpha":
{
var newAlpha:Number = Number(event.newValue) * _alpha;
if (newAlpha != super.alpha)
super.alpha = newAlpha;
break;
}
}
}
// IAutomationObject Interface defenitions
private var _automationDelegate:IAutomationObject;
/**
* The delegate object that handles the automation-related functionality.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get automationDelegate():Object
{
return _automationDelegate;
}
/**
* @private
*/
public function set automationDelegate(value:Object):void
{
_automationDelegate = value as IAutomationObject;
}
//----------------------------------
// automationName
//----------------------------------
/**
* @private
* Storage for the <code>automationName</code> property.
*/
private var _automationName:String = null;
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get automationName():String
{
if (_automationName)
return _automationName;
if (automationDelegate)
return automationDelegate.automationName;
return "";
}
/**
* @private
*/
public function set automationName(value:String):void
{
_automationName = value;
}
/**
* @copy mx.automation.IAutomationObject#automationValue
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get automationValue():Array
{
if (automationDelegate)
return automationDelegate.automationValue;
return [];
}
//----------------------------------
// automationOwner
//----------------------------------
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 4
*/
public function get automationOwner():DisplayObjectContainer
{
return owner;
}
//----------------------------------
// automationParent
//----------------------------------
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 4
*/
public function get automationParent():DisplayObjectContainer
{
return parent;
}
//----------------------------------
// automationEnabled
//----------------------------------
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 4
*/
public function get automationEnabled():Boolean
{
return enabled;
}
//----------------------------------
// automationVisible
//----------------------------------
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 4
*/
public function get automationVisible():Boolean
{
return visible;
}
//----------------------------------
// showInAutomationHierarchy
//----------------------------------
/**
* @private
* Storage for the <code>showInAutomationHierarchy</code> property.
*/
private var _showInAutomationHierarchy:Boolean = true;
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get showInAutomationHierarchy():Boolean
{
return _showInAutomationHierarchy;
}
/**
* @private
*/
public function set showInAutomationHierarchy(value:Boolean):void
{
_showInAutomationHierarchy = value;
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function createAutomationIDPart(child:IAutomationObject):Object
{
if (automationDelegate)
return automationDelegate.createAutomationIDPart(child);
return null;
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function createAutomationIDPartWithRequiredProperties(child:IAutomationObject,
properties:Array):Object
{
if (automationDelegate)
return automationDelegate.createAutomationIDPartWithRequiredProperties(child, properties);
return null;
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function resolveAutomationIDPart(criteria:Object):Array
{
if (automationDelegate)
return automationDelegate.resolveAutomationIDPart(criteria);
return [];
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function getAutomationChildAt(index:int):IAutomationObject
{
if (automationDelegate)
return automationDelegate.getAutomationChildAt(index);
return null;
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function getAutomationChildren():Array
{
if (automationDelegate)
return automationDelegate.getAutomationChildren();
return null;
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get numAutomationChildren():int
{
if (automationDelegate)
return automationDelegate.numAutomationChildren;
return 0;
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get automationTabularData():Object
{
if (automationDelegate)
return automationDelegate.automationTabularData;
return null;
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function replayAutomatableEvent(event:Event):Boolean
{
if (automationDelegate)
return automationDelegate.replayAutomatableEvent(event);
return false;
}
}
}
|
package cadet2D.util
{
import cadet2D.components.skins.IRenderable;
public class RenderablesUtil
{
public static function sortSkinsById( renderableA:IRenderable, renderableB:IRenderable):int
{
var skinA_Ids:Array = renderableA.indexStr.split("_");
var skinB_Ids:Array = renderableB.indexStr.split("_");
var longest:uint = Math.max(skinA_Ids.length, skinB_Ids.length);
var index:uint = 0;
while ( index < longest ) {
var idA:Number = index < skinA_Ids.length ? skinA_Ids[index] : -1;
var idB:Number = index < skinB_Ids.length ? skinB_Ids[index] : -1;
if ( idA < idB ) {
return -1;
} else if ( idA > idB ) {
return 1;
}
index ++;
}
return 0;
}
}
} |
package org.apache.thrift
{
import org.apache.thrift.protocol.TField;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.protocol.TProtocolUtil;
import org.apache.thrift.protocol.TStruct;
import org.apache.thrift.protocol.TType;
public class TApplicationError extends TError
{
private static const TAPPLICATION_EXCEPTION_STRUCT:TStruct = new TStruct("TApplicationException");
private static const MESSAGE_FIELD:TField = new TField("message",TType.STRING,1);
private static const TYPE_FIELD:TField = new TField("type",TType.I32,2);
public static const UNKNOWN:int = 0;
public static const UNKNOWN_METHOD:int = 1;
public static const INVALID_MESSAGE_TYPE:int = 2;
public static const WRONG_METHOD_NAME:int = 3;
public static const BAD_SEQUENCE_ID:int = 4;
public static const MISSING_RESULT:int = 5;
public static const INTERNAL_ERROR:int = 6;
public static const PROTOCOL_ERROR:int = 7;
public static const INVALID_TRANSFORM:int = 8;
public static const INVALID_PROTOCOL:int = 9;
public static const UNSUPPORTED_CLIENT_TYPE:int = 10;
public function TApplicationError(param1:int = 0, param2:String = "")
{
super(param2,param1);
}
public static function read(param1:TProtocol) : TApplicationError
{
var _loc2_:TField = null;
param1.readStructBegin();
var _loc3_:String = null;
var _loc4_:int = UNKNOWN;
while(true)
{
_loc2_ = param1.readFieldBegin();
if(_loc2_.type == TType.STOP)
{
break;
}
switch(_loc2_.id)
{
case 1:
if(_loc2_.type == TType.STRING)
{
_loc3_ = param1.readString();
}
else
{
TProtocolUtil.skip(param1,_loc2_.type);
}
break;
case 2:
if(_loc2_.type == TType.I32)
{
_loc4_ = param1.readI32();
}
else
{
TProtocolUtil.skip(param1,_loc2_.type);
}
break;
default:
TProtocolUtil.skip(param1,_loc2_.type);
break;
}
param1.readFieldEnd();
}
param1.readStructEnd();
return new TApplicationError(_loc4_,_loc3_);
}
public function write(param1:TProtocol) : void
{
param1.writeStructBegin(TAPPLICATION_EXCEPTION_STRUCT);
if(message != null)
{
param1.writeFieldBegin(MESSAGE_FIELD);
param1.writeString(message);
param1.writeFieldEnd();
}
param1.writeFieldBegin(TYPE_FIELD);
param1.writeI32(errorID);
param1.writeFieldEnd();
param1.writeFieldStop();
param1.writeStructEnd();
}
}
}
|
package kabam.rotmg.pets.view.components {
import com.company.assembleegameclient.ui.DeprecatedTextButton;
import flash.display.Sprite;
import flash.events.MouseEvent;
import kabam.rotmg.pets.util.PetsConstants;
import kabam.rotmg.ui.view.SignalWaiter;
import org.osflash.signals.natives.NativeSignal;
public class PetsButtonBar extends Sprite {
public var buttonOne:DeprecatedTextButton;
public var buttonTwo:DeprecatedTextButton;
public var buttonOneSignal:NativeSignal;
public var buttonTwoSignal:NativeSignal;
public function PetsButtonBar() {
this.buttonOne = new DeprecatedTextButton(14, "buttonOne", 70);
this.buttonTwo = new DeprecatedTextButton(14, "buttonTwo", 70);
this.buttonOneSignal = new NativeSignal(this.buttonOne, MouseEvent.CLICK);
this.buttonTwoSignal = new NativeSignal(this.buttonTwo, MouseEvent.CLICK);
super();
this.addTextChangedWaiter();
this.addButtons();
}
private function addButtons():void {
addChild(this.buttonOne);
addChild(this.buttonTwo);
}
private function addTextChangedWaiter():void {
var _local3:DeprecatedTextButton;
var _local1:Array = [this.buttonOne, this.buttonTwo];
var _local2:SignalWaiter = new SignalWaiter();
for each (_local3 in _local1) {
_local2.push(_local3.textChanged);
}
_local2.complete.addOnce(this.positionButtons);
}
private function positionButtons():void {
this.buttonOne.x = PetsConstants.BUTTON_BAR_SPACING;
this.buttonTwo.x = ((PetsConstants.WINDOW_BACKGROUND_WIDTH - this.buttonTwo.width) - PetsConstants.BUTTON_BAR_SPACING);
}
}
}
|
/**
* Load tester main script
*
* @author Paul Gregoire (mondain@gmail.com)
*/
import flash.events.*;
import flash.media.*;
import flash.net.*;
import flash.utils.ByteArray;
import flash.utils.Timer;
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.core.*;
import mx.events.*;
//player
private var ncPlayer:NetConnection;
private var nsPlayer:NetStream;
private var playerVideo:Video;
[Bindable]
private var streamName:String;
[Bindable]
private var hostString:String = 'localhost';
[Bindable]
public var clientId:String = '';
[Bindable]
public var viewerList:ArrayCollection = new ArrayCollection();
[Bindable]
public var soUserList:ArrayCollection = new ArrayCollection();
private static var timer:Timer = null;
public function init():void {
Security.allowDomain("*");
var pattern:RegExp = new RegExp("http://([^/]*)/");
if (pattern.test(Application.application.url) == true) {
var results:Array = pattern.exec(Application.application.url);
hostString = results[1];
//need to strip the port to avoid confusion
if (hostString.indexOf(":") > 0) {
hostString = hostString.split(":")[0];
}
}
log('Host: ' + hostString);
}
public function onBWDone():void {
// have to have this for an RTMP connection
log('onBWDone');
}
public function onBWCheck(... rest):uint {
log('onBWCheck');
//have to return something, so returning anything :)
return 0;
}
private function playerNetStatusHandler(event:NetStatusEvent):void {
log('Net status (player): '+event.info.code);
switch (event.info.code) {
case "NetConnection.Connect.Success":
connectPlayerStream();
connector.label = "Disconnect";
indicatorOn.visible=true;
indicatorOff.visible=false;
break;
case "NetStream.Play.StreamNotFound":
log("Unable to locate video: " + givenPath.text + '/' + playerStream.text);
break;
case "NetConnection.Connect.Failed":
break;
case "NetConnection.Connect.Rejected":
break;
case "NetConnection.Connect.Closed":
connector.label = 'Connect';
indicatorOn.visible=false;
indicatorOff.visible=true;
break;
}
}
//called by the server
public function setClientId(param:Object):void {
log('Set client id called: '+param);
clientId = param as String;
log('Setting client id: '+clientId);
}
//called by the server in the event of a server side error
public function setAlert(alert:Object):void {
log('Got an alert: '+alert);
Alert.show(String(alert), 'Server Error');
}
public function doPlayerView():void {
log('Trying to start player');
if (connector.label === 'Connect') {
// create the netConnection
ncPlayer = new NetConnection();
ncPlayer.objectEncoding = ObjectEncoding.AMF3;
// set it's client/focus to this
ncPlayer.client = this;
// add listeners for netstatus and security issues
ncPlayer.addEventListener(NetStatusEvent.NET_STATUS, playerNetStatusHandler);
ncPlayer.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
ncPlayer.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
ncPlayer.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
ncPlayer.connect(givenPath.text, null);
} else if (connector.label === 'Disconnect') {
if (ncPlayer.connected) {
ncPlayer.close();
}
}
}
public function connectPlayerStream():void {
log('Connect player netstream');
nsPlayer = new NetStream(ncPlayer);
nsPlayer.client = this;
nsPlayer.addEventListener(NetStatusEvent.NET_STATUS, playerNetStatusHandler);
nsPlayer.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
playerVideo = new Video();
playerVideo.attachNetStream(nsPlayer);
nsPlayer.play(playerStream.text);
playerDisplay.addChild(playerVideo);
playerVideo.width = 160;
playerVideo.height = 120;
}
public function onMetaData(info:Object):void {
log('Got meta data');
var key:String;
for (key in info) {
log('Meta: '+ key + ': ' + info[key]);
}
}
public function onCuePoint(info:Object):void {
log("Cuepoint: time=" + info.time + " name=" + info.name + " type=" + info.type);
}
public function onPlayStatus(info:Object):void {
log('Got play status');
}
public function startTest():void {
log('Start test');
if (ncPlayer.connected) {
ncPlayer.close();
}
log('Load delay: '+requestDelay.text);
var delay:int = Number(requestDelay.text);
if (delay < 1) {
log('Invalid delay entered, setting to .1');
delay = .1;
}
//convert to seconds
delay = (delay * 1000);
log('Load delay: '+delay+(delay >= 1000?'s':'ms'));
//create the timer only once
if (!timer) {
timer = new Timer(delay);
timer.addEventListener("timer", timerHandler);
}
timer.start();
}
public function stopTest():void {
if (timer) {
timer.stop();
timer = null;
}
log('Trying to stop view');
if (ncPlayer && ncPlayer.connected) {
nsPlayer.close();
ncPlayer.close();
}
var i:int = 0;
//go thru viewer list
var viewer:Viewer;
for (; i < viewerList.length; i += 1) {
viewer = viewerList.getItemAt(i) as Viewer;
viewer.stop();
}
viewerList.removeAll();
//go thru so user list
var souser:SOUser;
for (i = 0; i < soUserList.length; i += 1) {
souser = soUserList.getItemAt(i) as SOUser;
souser.stop();
}
soUserList.removeAll();
}
public function timerHandler(event:TimerEvent):void {
var maxViewers:int = Number(numRequest.text);
if (viewerList.length < maxViewers) {
//start a new view
log('Creating a new viewer');
var viewer:Viewer = new Viewer();
viewer.sid = String(viewerList.length);
viewer.setEncoding(useAMF3.selected === true ? 3 : 0);
viewer.path = givenPath.text;
viewer.stream = playerStream.text;
viewer.start();
viewerList.addItem(viewer);
} else {
log('Max viewer requests reached');
}
var maxSOUsers:int = Number(soUserCount.text);
if (soUserList.length < maxSOUsers) {
//start a new view
log('Creating a new SO user');
var souser:SOUser = new SOUser();
souser.sid = String(soUserList.length);
souser.setEncoding(useAMF3.selected === true ? 3 : 0);
souser.setUpdateInterval(int(updateInterval.text));
souser.setUseDirtyFlag(useDirty.selected);
souser.start();
soUserList.addItem(souser);
} else {
log('Max SO users reached');
}
if (viewerList.length === maxViewers && soUserList.length === maxSOUsers) {
timer.stop();
}
}
private function forceSOUpdate():void {
log('Forcing update');
for each (var souser:SOUser in soUserList) {
souser.updateSO();
}
}
private function securityErrorHandler(e:SecurityErrorEvent):void {
log('Security Error: '+e);
}
private function ioErrorHandler(e:IOErrorEvent):void {
log('IO Error: '+e);
}
private function asyncErrorHandler(e:AsyncErrorEvent):void {
log('Async Error: '+e);
}
public function log(text:String):void {
var tmp:String = String(messages.data);
tmp += text + '\n';
messages.data = tmp;
}
public function traceObject(obj:Object, indent:uint = 0):void {
var indentString:String = "";
var i:uint;
var prop:String;
var val:*;
for (i = 0; i < indent; i++) {
indentString += "\t";
}
for (prop in obj) {
val = obj[prop];
if (typeof(val) == "object") {
log(indentString + " " + i + ": [Object]");
traceObject(val, indent + 1);
} else {
log(indentString + " " + prop + ": " + val);
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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.plugin.haxe.hxproject
{
import flash.display.DisplayObject;
import flash.events.Event;
import flash.filesystem.File;
import flash.net.SharedObject;
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.utils.ObjectUtil;
import actionScripts.events.AddTabEvent;
import actionScripts.events.GlobalEventDispatcher;
import actionScripts.events.NewProjectEvent;
import actionScripts.events.ProjectEvent;
import actionScripts.events.RefreshTreeEvent;
import actionScripts.factory.FileLocation;
import actionScripts.locator.IDEModel;
import actionScripts.plugin.console.ConsoleOutputter;
import actionScripts.plugin.haxe.hxproject.exporter.HaxeExporter;
import actionScripts.plugin.haxe.hxproject.importer.HaxeImporter;
import actionScripts.plugin.haxe.hxproject.vo.HaxeProjectVO;
import actionScripts.plugin.settings.SettingsView;
import actionScripts.plugin.settings.vo.AbstractSetting;
import actionScripts.plugin.settings.vo.ISetting;
import actionScripts.plugin.settings.vo.PathSetting;
import actionScripts.plugin.settings.vo.SettingsWrapper;
import actionScripts.plugin.settings.vo.StaticLabelSetting;
import actionScripts.plugin.settings.vo.StringSetting;
import actionScripts.plugin.templating.TemplatingHelper;
import actionScripts.ui.tabview.CloseTabEvent;
import actionScripts.utils.SharedObjectConst;
import actionScripts.plugin.settings.vo.DropDownListSetting;
import actionScripts.plugin.haxe.hxproject.utils.getHaxeProjectOutputPath;
public class CreateHaxeProject extends ConsoleOutputter
{
public function CreateHaxeProject(event:NewProjectEvent)
{
createHaxeProject(event);
}
private var project:HaxeProjectVO;
private var newProjectNameSetting:StringSetting;
private var newProjectPathSetting:PathSetting;
private var newProjectPlatformSetting:DropDownListSetting;
private var isInvalidToSave:Boolean;
private var cookie:SharedObject;
private var templateLookup:Object = {};
private var model:IDEModel = IDEModel.getInstance();
private var dispatcher:GlobalEventDispatcher = GlobalEventDispatcher.getInstance();
private var _currentCauseToBeInvalid:String;
private function createHaxeProject(event:NewProjectEvent):void
{
var lastSelectedProjectPath:String;
CONFIG::OSX
{
if (model.osxBookmarkerCore.availableBookmarkedPaths == "") model.osxBookmarkerCore.removeFlashCookies();
}
cookie = SharedObject.getLocal(SharedObjectConst.MOONSHINE_IDE_LOCAL);
if (cookie.data.hasOwnProperty('recentProjectPath'))
{
model.recentSaveProjectPath.source = cookie.data.recentProjectPath;
if (cookie.data.hasOwnProperty('lastSelectedProjectPath')) lastSelectedProjectPath = cookie.data.lastSelectedProjectPath;
}
else
{
lastSelectedProjectPath = model.fileCore.documentsDirectory.nativePath;
if (!model.recentSaveProjectPath.contains(lastSelectedProjectPath))
{
model.recentSaveProjectPath.addItem(lastSelectedProjectPath);
}
}
var tmpProjectSourcePath:String = (lastSelectedProjectPath && model.recentSaveProjectPath.getItemIndex(lastSelectedProjectPath) != -1) ? lastSelectedProjectPath : model.recentSaveProjectPath.source[model.recentSaveProjectPath.length - 1];
var folderLocation:FileLocation = new FileLocation(tmpProjectSourcePath);
// Remove spaces from project name
var templateName:String = event.templateDir.fileBridge.name;
var projectName:String = (templateName.indexOf("(") != -1) ? templateName.substr(0, templateName.indexOf("(")) : templateName;
projectName = "New" + projectName.replace(/ /g, "");
project = new HaxeProjectVO(folderLocation, projectName);
//this seems kind of hacky, but other indicators haven't been populated yet
project.isLime = templateName.indexOf("OpenFL") != -1 || templateName.indexOf("Lime") != -1 || templateName.indexOf("Feathers UI") != -1;
var settingsView:SettingsView = new SettingsView();
settingsView.exportProject = event.exportProject;
settingsView.Width = 150;
settingsView.defaultSaveLabel = event.isExport ? "Export" : "Create";
settingsView.isNewProjectSettings = true;
settingsView.addCategory("");
var settings:SettingsWrapper = getProjectSettings(project, event);
settingsView.addEventListener(SettingsView.EVENT_SAVE, createSave);
settingsView.addEventListener(SettingsView.EVENT_CLOSE, createClose);
settingsView.addSetting(settings, "");
settingsView.label = "New Project";
settingsView.associatedData = project;
dispatcher.dispatchEvent(new AddTabEvent(settingsView));
templateLookup[project] = event.templateDir;
}
private function getProjectSettings(project:HaxeProjectVO, eventObject:NewProjectEvent):SettingsWrapper
{
var historyPaths:ArrayCollection = ObjectUtil.copy(model.recentSaveProjectPath) as ArrayCollection;
if (historyPaths.length == 0)
{
historyPaths.addItem(project.folderPath);
}
newProjectNameSetting = new StringSetting(project, 'projectName', 'Project name', '^ ~`!@#$%\\^&*()\\-+=[{]}\\\\|:;\'",<.>/?');
newProjectPathSetting = new PathSetting(project, 'folderPath', 'Parent directory', true, null, false, true);
newProjectPathSetting.dropdownListItems = historyPaths;
newProjectPathSetting.addEventListener(AbstractSetting.PATH_SELECTED, onProjectPathChanged);
newProjectNameSetting.addEventListener(StringSetting.VALUE_UPDATED, onProjectNameChanged);
if(!project.isLime)
{
newProjectPlatformSetting = new DropDownListSetting(project, "haxePlatform", "Platform", project.haxePlatformTypes);
}
if (eventObject.isExport)
{
//newProjectNameSetting.isEditable = false;
var settings:SettingsWrapper = new SettingsWrapper("Name & Location", Vector.<ISetting>([
new StaticLabelSetting('New ' + eventObject.templateDir.fileBridge.name),
newProjectNameSetting, // No space input either plx
newProjectPathSetting
]));
if(newProjectPlatformSetting)
{
settings.getSettingsList().push(newProjectPlatformSetting);
}
return settings;
}
settings = new SettingsWrapper("Name & Location", Vector.<ISetting>([
new StaticLabelSetting('New '+ eventObject.templateDir.fileBridge.name),
newProjectNameSetting, // No space input either plx
newProjectPathSetting
]));
if(newProjectPlatformSetting)
{
settings.getSettingsList().push(newProjectPlatformSetting);
}
return settings;
}
private function checkIfProjectDirectory(value:FileLocation):void
{
var tmpFile:FileLocation = HaxeImporter.test(value.fileBridge.getFile);
if (!tmpFile && value.fileBridge.exists)
{
tmpFile = value;
}
if (tmpFile)
{
newProjectPathSetting.setMessage((_currentCauseToBeInvalid = "Project can not be created to an existing project directory:\n"+ value.fileBridge.nativePath), AbstractSetting.MESSAGE_CRITICAL);
}
else
{
newProjectPathSetting.setMessage(value.fileBridge.nativePath);
}
if (newProjectPathSetting.stringValue == "")
{
isInvalidToSave = true;
_currentCauseToBeInvalid = 'Unable to access Project Directory:\n'+ value.fileBridge.nativePath +'\nPlease try to create the project again and use the "Change" link to open the target directory again.';
}
else
{
isInvalidToSave = tmpFile ? true : false;
}
}
private function onProjectPathChanged(event:Event, makeNull:Boolean=true):void
{
if (makeNull) project.projectFolder = null;
project.folderLocation = new FileLocation(newProjectPathSetting.stringValue);
newProjectPathSetting.label = "Parent Directory";
checkIfProjectDirectory(project.folderLocation.resolvePath(newProjectNameSetting.stringValue));
}
private function onProjectNameChanged(event:Event):void
{
checkIfProjectDirectory(project.folderLocation.resolvePath(newProjectNameSetting.stringValue));
}
private function createClose(event:Event):void
{
var view:SettingsView = event.target as SettingsView;
view.removeEventListener(SettingsView.EVENT_CLOSE, createClose);
view.removeEventListener(SettingsView.EVENT_SAVE, createSave);
if (newProjectPathSetting)
{
newProjectPathSetting.removeEventListener(AbstractSetting.PATH_SELECTED, onProjectPathChanged);
newProjectNameSetting.removeEventListener(StringSetting.VALUE_UPDATED, onProjectNameChanged);
}
delete templateLookup[view.associatedData];
dispatcher.dispatchEvent(
new CloseTabEvent(CloseTabEvent.EVENT_CLOSE_TAB, view as DisplayObject)
);
}
private function createSave(event:Event):void
{
if (isInvalidToSave)
{
throwError();
return;
}
var view:SettingsView = event.target as SettingsView;
var project:HaxeProjectVO = view.associatedData as HaxeProjectVO;
//save project path in shared object
cookie = SharedObject.getLocal(SharedObjectConst.MOONSHINE_IDE_LOCAL);
var tmpParent:FileLocation = project.folderLocation;
if (!model.recentSaveProjectPath.contains(tmpParent.fileBridge.nativePath))
{
model.recentSaveProjectPath.addItem(tmpParent.fileBridge.nativePath);
}
cookie.data["lastSelectedProjectPath"] = project.folderLocation.fileBridge.nativePath;
cookie.data["recentProjectPath"] = model.recentSaveProjectPath.source;
cookie.flush();
project = createFileSystemBeforeSave(project, view.exportProject as HaxeProjectVO);
if (!project)
{
return;
}
this.project = project;
// Open main file for editing
dispatcher.dispatchEvent(
new ProjectEvent(ProjectEvent.ADD_PROJECT, project)
);
dispatcher.dispatchEvent(new RefreshTreeEvent(project.folderLocation));
}
private function throwError():void
{
Alert.show(_currentCauseToBeInvalid +" Project creation terminated.", "Error!");
}
private function createFileSystemBeforeSave(pvo:HaxeProjectVO, exportProject:HaxeProjectVO = null):HaxeProjectVO
{
var templateDir:FileLocation = templateLookup[pvo];
var projectName:String = pvo.projectName;
var sourceFileWithExtension:String = pvo.projectName + ".hx";
var sourcePath:String = "src";
var targetFolder:FileLocation = pvo.folderLocation;
// Create project root directory
CONFIG::OSX
{
if (!model.osxBookmarkerCore.isPathBookmarked(targetFolder.fileBridge.nativePath))
{
_currentCauseToBeInvalid = 'Unable to access Parent Directory:\n'+ targetFolder.fileBridge.nativePath +'\nPlease try to create the project again and use the "Change" link to open the target directory again.';
throwError();
return null;
}
}
targetFolder = targetFolder.resolvePath(projectName);
targetFolder.fileBridge.createDirectory();
//setting these values ensures that getHaxeProjectOutputPath()
//returns the correct value
pvo.folderLocation = targetFolder;
pvo.haxeOutput.path = targetFolder.resolvePath("bin");
// Time to do the templating thing!
var th:TemplatingHelper = new TemplatingHelper();
th.isProjectFromExistingSource = false;
th.templatingData["$ProjectName"] = projectName;
var pattern:RegExp = new RegExp(/(_)/g);
th.templatingData["$ProjectID"] = projectName.replace(pattern, "");
th.templatingData["$Settings"] = projectName;
th.templatingData["$SourcePath"] = sourcePath;
th.templatingData["$SourceFile"] = sourceFileWithExtension ? (sourcePath + File.separator + sourceFileWithExtension) : "";
th.templatingData["$ProjectPlatform"] = project.haxeOutput.platform;
th.templatingData["$ProjectOutput"] = getHaxeProjectOutputPath(project);
th.projectTemplate(templateDir, targetFolder);
var projectSettingsFileName:String = projectName + ".hxproj";
var settingsFile:FileLocation = targetFolder.resolvePath(projectSettingsFileName);
pvo = HaxeImporter.parse(targetFolder, projectName, settingsFile);
HaxeExporter.export(pvo);
return pvo;
}
}
} |
package game.animations
{
import flash.display.DisplayObject;
import flash.geom.Point;
public class StrLinearTween extends BaseStageTween
{
private var _speed:int = 1;
private var _duration:int = 0;
public function StrLinearTween(param1:TweenObject = null)
{
super(param1);
}
override public function get type() : String
{
return "StrLinearTween";
}
override public function update(param1:DisplayObject) : Point
{
if(!_prepared)
{
return null;
}
var _loc2_:Point = new Point(param1.x,param1.y);
var _loc3_:Point = new Point(target.x - param1.x,target.y - param1.y);
if(_loc3_.length >= this.speed)
{
_loc3_.normalize(this.speed);
_loc2_.x = _loc2_.x + _loc3_.x;
_loc2_.y = _loc2_.y + _loc3_.y;
}
else
{
_loc2_ = target;
}
return _loc2_;
}
public function set speed(param1:int) : void
{
this._speed = param1;
}
public function get speed() : int
{
return this._speed;
}
public function set duration(param1:int) : void
{
this._duration = param1;
}
public function get duration() : int
{
return this._duration;
}
override protected function get propertysNeed() : Array
{
return ["target","speed","duration"];
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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.skins.mobile
{
import mx.core.DPIClassification;
import mx.core.mx_internal;
import spark.components.Button;
import spark.components.HScrollBar;
import spark.skins.mobile.supportClasses.MobileSkin;
use namespace mx_internal;
/**
* ActionScript-based skin for HScrollBar components in mobile applications.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public class HScrollBarSkin extends MobileSkin
{
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public function HScrollBarSkin()
{
super();
minWidth = 20;
thumbSkinClass = HScrollBarThumbSkin;
var paddingBottom:int;
var paddingHorizontal:int;
// Depending on density set our measured height
switch (applicationDPI)
{
case DPIClassification.DPI_640:
{
minHeight = 24;
paddingBottom = HScrollBarThumbSkin.PADDING_BOTTOM_640DPI;
paddingHorizontal = HScrollBarThumbSkin.PADDING_HORIZONTAL_640DPI;
break;
}
case DPIClassification.DPI_480:
{
minHeight = 18;
paddingBottom = HScrollBarThumbSkin.PADDING_BOTTOM_480DPI;
paddingHorizontal = HScrollBarThumbSkin.PADDING_HORIZONTAL_480DPI;
break;
}
case DPIClassification.DPI_320:
{
minHeight = 12;
paddingBottom = HScrollBarThumbSkin.PADDING_BOTTOM_320DPI;
paddingHorizontal = HScrollBarThumbSkin.PADDING_HORIZONTAL_320DPI;
break;
}
case DPIClassification.DPI_240:
{
minHeight = 9;
paddingBottom = HScrollBarThumbSkin.PADDING_BOTTOM_240DPI;
paddingHorizontal = HScrollBarThumbSkin.PADDING_HORIZONTAL_240DPI;
break;
}
case DPIClassification.DPI_120:
{
minHeight = 5;
paddingBottom = HScrollBarThumbSkin.PADDING_BOTTOM_120DPI;
paddingHorizontal = HScrollBarThumbSkin.PADDING_HORIZONTAL_120DPI;
break;
}
default:
{
// default DPI_160
minHeight = 6;
paddingBottom = HScrollBarThumbSkin.PADDING_BOTTOM_DEFAULTDPI;
paddingHorizontal = HScrollBarThumbSkin.PADDING_HORIZONTAL_DEFAULTDPI;
break;
}
}
// The minimum width is set such that, at it's smallest size, the thumb appears
// as wide as it is high.
minThumbWidth = (minHeight - paddingBottom) + (paddingHorizontal * 2);
}
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
/**
* @copy spark.skins.spark.ApplicationSkin#hostComponent
*/
public var hostComponent:HScrollBar;
/**
* Minimum width for the thumb
*/
protected var minThumbWidth:Number;
/**
* Skin to use for the thumb Button skin part
*/
protected var thumbSkinClass:Class;
//--------------------------------------------------------------------------
//
// Skin parts
//
//--------------------------------------------------------------------------
/**
* HScrollbar track skin part.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public var track:Button;
/**
* HScrollbar thumb skin part.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public var thumb:Button;
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
override protected function createChildren():void
{
// Create our skin parts if necessary: track and thumb.
if (!track)
{
// We don't want a visible track so we set the skin to MobileSkin
track = new Button();
track.setStyle("skinClass", spark.skins.mobile.supportClasses.MobileSkin);
track.width = minWidth;
track.height = minHeight;
addChild(track);
}
if (!thumb)
{
thumb = new Button();
thumb.minWidth = minThumbWidth;
thumb.setStyle("skinClass", thumbSkinClass);
thumb.width = minHeight;
thumb.height = minHeight;
addChild(thumb);
}
}
/**
* @private
*/
override protected function layoutContents(unscaledWidth:Number, unscaledHeight:Number):void
{
super.layoutContents(unscaledWidth, unscaledHeight);
setElementSize(track, unscaledWidth, unscaledHeight);
}
}
} |
////////////////////////////////////////////////////////////////////////////////
//
// ADOBE SYSTEMS INCORPORATED
// Copyright 2006-2007 Adobe Systems Incorporated
// All Rights Reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
package mx.managers
{
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.utils.Timer;
import mx.controls.ToolTip;
import mx.core.FlexGlobals;
import mx.core.IFlexModule;
import mx.core.IInvalidating;
import mx.core.IToolTip;
import mx.core.IUIComponent;
import mx.core.mx_internal;
import mx.effects.EffectManager;
import mx.effects.IAbstractEffect;
import mx.events.DynamicEvent;
import mx.events.EffectEvent;
import mx.events.InterManagerRequest;
import mx.events.ToolTipEvent;
import mx.styles.CSSStyleDeclaration;
import mx.styles.IStyleClient;
import mx.styles.IStyleManager2;
import mx.validators.IValidatorListener;
use namespace mx_internal;
[ExcludeClass]
/**
* @private
* The ToolTipManager lets you set basic ToolTip and error tip functionality,
* such as display delay and the disabling of ToolTips.
*
* @see mx.controls.ToolTip
* @see mx.validators.Validator
*/
public class ToolTipManagerImpl extends EventDispatcher
implements IToolTipManager2
{
include "../core/Version.as";
//--------------------------------------------------------------------------
//
// Class variables
//
//--------------------------------------------------------------------------
/**
* @private
*/
private static var instance:IToolTipManager2;
//--------------------------------------------------------------------------
//
// Class methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
public static function getInstance():IToolTipManager2
{
if (!instance)
instance = new ToolTipManagerImpl();
return instance;
}
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* @private
*/
public function ToolTipManagerImpl()
{
super();
if (instance)
throw new Error("Instance already exists.");
this.systemManager = SystemManagerGlobals.topLevelSystemManagers[0] as ISystemManager;
sandboxRoot = this.systemManager.getSandboxRoot();
sandboxRoot.addEventListener(InterManagerRequest.TOOLTIP_MANAGER_REQUEST, marshalToolTipManagerHandler, false, 0, true);
var me:InterManagerRequest = new InterManagerRequest(InterManagerRequest.TOOLTIP_MANAGER_REQUEST);
me.name = "update";
// trace("--->update request for ToolTipManagerImpl", systemManager);
sandboxRoot.dispatchEvent(me);
// trace("<---update request for ToolTipManagerImpl", systemManager);
}
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
/**
* @private
*/
private var systemManager:ISystemManager = null;
/**
* @private
*/
private var sandboxRoot:IEventDispatcher = null;
/**
* @private
* A flag that keeps track of whether this class's initialize()
* method has been executed.
*/
mx_internal var initialized:Boolean = false;
/**
* @private
* This timer is used to delay the appearance of a normal ToolTip
* after the mouse moves over a target; an error tip has no such delay.
*
* <p>This timer, which is lazily created, is started when the mouse
* moves over an object with a ToolTip, with a duration specified
* by showDelay.
* If the mouse moves out of this object before the timer fires,
* the ToolTip is never created.
* If the mouse stays over the object until the timer fires,
* the ToolTip is created and its showEffect is started.
*/
mx_internal var showTimer:Timer;
/**
* @private
* This timer is used to make the tooltip "time out" and hide itself
* if the mouse stays over a target.
*
* <p>This timer, which is lazily created, is started
* when the showEffect ends.
* When it fires, the hideEffect is started.</p>
*/
mx_internal var hideTimer:Timer;
/**
* @private
* This timer is used to implement mousing quickly over multiple targets
* with ToolTip...
*
* <p>This timer, which is lazily created, is started
* when ...</p>
*/
mx_internal var scrubTimer:Timer;
/**
* @private
*/
mx_internal var currentText:String;
/**
* @private
*/
mx_internal var isError:Boolean;
/**
* The UIComponent with the ToolTip assigned to it
* that was most recently under the mouse.
* During much of the tool tip life cycle this property
* has the same value as the <code>currentTarget</code> property.
*/
mx_internal var previousTarget:DisplayObject;
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
//----------------------------------
// currentTarget
//----------------------------------
/**
* @private
*/
private var _currentTarget:DisplayObject;
/**
* The UIComponent that is currently displaying a ToolTip,
* or <code>null</code> if none is.
*/
public function get currentTarget():DisplayObject
{
return _currentTarget;
}
/**
* @private
*/
public function set currentTarget(value:DisplayObject):void
{
_currentTarget = value;
}
//----------------------------------
// currentToolTip
//----------------------------------
/**
* @private
*/
private var _currentToolTip:DisplayObject;
/**
* The ToolTip object that is currently visible,
* or <code>null</code> if none is shown.
*/
public function get currentToolTip():IToolTip
{
return _currentToolTip as IToolTip;
}
/**
* @private
*/
public function set currentToolTip(value:IToolTip):void
{
_currentToolTip = value as DisplayObject;
var me:InterManagerRequest = new InterManagerRequest(InterManagerRequest.TOOLTIP_MANAGER_REQUEST);
me.name = "currentToolTip";
me.value = value;
// trace("-->dispatched currentToolTip for ToolTipManagerImpl", systemManager, value);
sandboxRoot.dispatchEvent(me);
}
//----------------------------------
// enabled
//----------------------------------
/**
* @private
*/
private var _enabled:Boolean = true;
/**
* If <code>true</code>, the ToolTipManager will automatically show
* ToolTips when the user moves the mouse pointer over components.
* If <code>false</code>, no ToolTips will be shown.
*
* @default true
*/
public function get enabled():Boolean
{
return _enabled;
}
/**
* @private
*/
public function set enabled(value:Boolean):void
{
_enabled = value;
}
//----------------------------------
// hideDelay
//----------------------------------
/**
* @private
*/
private var _hideDelay:Number = 10000; // milliseconds
/**
* The amount of time, in milliseconds, that Flex waits
* to hide the ToolTip after it appears.
* Once Flex hides a ToolTip, the user must move the mouse
* off the component and then back onto it to see the ToolTip again.
* If you set <code>hideDelay</code> to <code>Infinity</code>,
* Flex does not hide the ToolTip until the user triggers an event,
* such as moving the mouse off of the component.
*
* @default 10000
*/
public function get hideDelay():Number
{
return _hideDelay;
}
/**
* @private
*/
public function set hideDelay(value:Number):void
{
_hideDelay = value;
}
//----------------------------------
// hideEffect
//----------------------------------
/**
* @private
*/
private var _hideEffect:IAbstractEffect;
/**
* The effect that plays when a ToolTip is hidden,
* or <code>null</code> if the ToolTip should disappear with no effect.
*
* <p>Effects are not marshaled across applicationDomains in a sandbox
* as they may not be supportable in different versions</p>
*
* @default null
*/
public function get hideEffect():IAbstractEffect
{
return _hideEffect;
}
/**
* @private
*/
public function set hideEffect(value:IAbstractEffect):void
{
_hideEffect = value as IAbstractEffect;
}
//----------------------------------
// scrubDelay
//----------------------------------
/**
* @private
*/
private var _scrubDelay:Number = 100; // milliseconds
/**
* The amount of time, in milliseconds, that a user can take
* when moving the mouse between controls before Flex again waits
* for the duration of <code>showDelay</code> to display a ToolTip.
*
* <p>This setting is useful if the user moves quickly from one control
* to another; after displaying the first ToolTip, Flex will display
* the others immediately rather than waiting.
* The shorter the setting for <code>scrubDelay</code>, the more
* likely that the user must wait for an amount of time specified
* by <code>showDelay</code> in order to see the next ToolTip.
* A good use of this property is if you have several buttons on a
* toolbar, and the user will quickly scan across them to see brief
* descriptions of their functionality.</p>
*
* @default 100
*/
public function get scrubDelay():Number
{
return _scrubDelay;
}
/**
* @private
*/
public function set scrubDelay(value:Number):void
{
_scrubDelay = value;
}
//----------------------------------
// showDelay
//----------------------------------
/**
* @private
*/
private var _showDelay:Number = 500; // milliseconds
/**
* The amount of time, in milliseconds, that Flex waits
* before displaying the ToolTip box once a user
* moves the mouse over a component that has a ToolTip.
* To make the ToolTip appear instantly, set <code>showDelay</code> to 0.
*
* @default 500
*/
public function get showDelay():Number
{
return _showDelay;
}
/**
* @private
*/
public function set showDelay(value:Number):void
{
_showDelay = value;
}
//----------------------------------
// showEffect
//----------------------------------
/**
* @private
*/
private var _showEffect:IAbstractEffect;
/**
* The effect that plays when a ToolTip is shown,
* or <code>null</code> if the ToolTip should appear with no effect.
*
* <p>Effects are not marshaled across applicationDomains in a sandbox
* as they may not be supportable in different versions</p>
*
* @default null
*/
public function get showEffect():IAbstractEffect
{
return _showEffect;
}
/**
* @private
*/
public function set showEffect(value:IAbstractEffect):void
{
_showEffect = value as IAbstractEffect;
}
//----------------------------------
// toolTipClass
//----------------------------------
/**
* @private
*/
private var _toolTipClass:Class = ToolTip;
/**
* The class to use for creating ToolTips.
*
* <p>The ToolTipClass is not marshaled across applicationDomains in a sandbox
* as they may not be supportable in different versions. Child
* applications should only be interested in setting the tooltip
* for objects within themselves</p>
*
* @default mx.controls.ToolTip
*/
public function get toolTipClass():Class
{
return _toolTipClass;
}
/**
* @private
*/
public function set toolTipClass(value:Class):void
{
_toolTipClass = value;
}
//--------------------------------------------------------------------------
//
// Methods
//
//--------------------------------------------------------------------------
/**
* @private
* Initializes the class.
*
* <p>This method sets up three Timer objects that ToolTipManager
* starts and stops while tracking the mouse.
* The repeatCount is set to 1 so that they fire only once.
* Their duration is set later, just before they are started.
* The timers are never destroyed once they are created here.</p>
*
* <p>This method is called by targetChanged(); Flex waits to initialize
* the class until mouse-tracking happens in order to optimize
* startup time.</p>
*/
mx_internal function initialize():void
{
if (!showTimer)
{
showTimer = new Timer(0, 1);
showTimer.addEventListener(TimerEvent.TIMER,
showTimer_timerHandler);
}
if (!hideTimer)
{
hideTimer = new Timer(0, 1);
hideTimer.addEventListener(TimerEvent.TIMER,
hideTimer_timerHandler);
}
if (!scrubTimer)
scrubTimer = new Timer(0, 1);
initialized = true;
}
/**
* Registers a target UIComponent or IUITextField, and the text
* for its ToolTip, with the ToolTipManager.
* This causes the ToolTipManager to display a ToolTip
* when the mouse hovers over the target.
*
* <p>This method is called by the setter
* for the toolTip property in UIComponent and IUITextField.</p>
*
* @param target The UIComponent or IUITextField that owns the ToolTip.
*
* @param oldToolTip The old text that was displayed
* in the ToolTip.
*
* @param newToolTip The new text to display in the ToolTip.
* If null, no ToolTip will be displayed when the mouse hovers
* over the target.
*/
public function registerToolTip(target:DisplayObject,
oldToolTip:String,
newToolTip:String):void
{
if (!oldToolTip && newToolTip)
{
target.addEventListener(MouseEvent.MOUSE_OVER,
toolTipMouseOverHandler);
target.addEventListener(MouseEvent.MOUSE_OUT,
toolTipMouseOutHandler);
// If the mouse is already over the object
// that's getting a toolTip, show the tip.
if (mouseIsOver(target))
showImmediately(target);
}
else if (oldToolTip && !newToolTip)
{
target.removeEventListener(MouseEvent.MOUSE_OVER,
toolTipMouseOverHandler);
target.removeEventListener(MouseEvent.MOUSE_OUT,
toolTipMouseOutHandler);
// If the mouse is over the object whose toolTip
// is being removed, hide the tip.
if (mouseIsOver(target))
hideImmediately(target);
}
}
/**
* Registers a target UIComponent, and the text
* for its error tip, with the ToolTipManager.
* This causes the ToolTipManager to display an error tip
* when the mouse hovers over the target.
*
* <p>This method is called by the setter
* for the errorString property in UIComponent.</p>
*
* @param target The UIComponent or IUITextField that owns the ToolTip.
*
* @param oldErrorString The old text that was displayed
* in the error tip.
*
* @param newErrorString The new text to display in the error tip.
* If null, no error tip will be displayed when the mouse hovers
* over the target.
*/
public function registerErrorString(target:DisplayObject,
oldErrorString:String,
newErrorString:String):void
{
if (!oldErrorString && newErrorString)
{
target.addEventListener(MouseEvent.MOUSE_OVER,
errorTipMouseOverHandler);
target.addEventListener(MouseEvent.MOUSE_OUT,
errorTipMouseOutHandler);
// If the mouse is already over the object
// that's getting an errorTip, show the tip.
if (mouseIsOver(target))
showImmediately(target);
}
else if (oldErrorString && !newErrorString)
{
target.removeEventListener(MouseEvent.MOUSE_OVER,
errorTipMouseOverHandler);
target.removeEventListener(MouseEvent.MOUSE_OUT,
errorTipMouseOutHandler);
// If the mouse is over the object whose toolTip
// is being removed, hide the tip.
if (mouseIsOver(target))
hideImmediately(target);
}
}
/**
* @private
* Returns true if the mouse is over the specified target.
*/
private function mouseIsOver(target:DisplayObject):Boolean
{
if (!target || !target.stage)
return false;
//SDK:13465 - If we pass through the above if block, then
//we have a target component and its been added to the
//display list. If the mouse coordinates are (0,0), there
//is a chance the component has not been positioned yet
//and we'll end up mistakenly showing tooltips since the
//target hitTest will return true.
if ((target.stage.mouseX == 0) && (target.stage.mouseY == 0))
return false;
return target.hitTestPoint(target.stage.mouseX,
target.stage.mouseY, true);
}
/**
* @private
* Shows the tip immediately when the toolTip or errorTip property
* becomes non-null and the mouse is over the target.
*/
/*modified*/
public function showImmediately(target:DisplayObject):void
{
var oldShowDelay:Number = ToolTipManager.showDelay;
ToolTipManager.showDelay = 0;
checkIfTargetChanged(target);
ToolTipManager.showDelay = oldShowDelay;
}
/**
* @private
* Hides the tip immediately when the toolTip or errorTip property
* becomes null and the mouse is over the target.
*/
/*modified*/
public function hideImmediately(target:DisplayObject = null):void
{
checkIfTargetChanged(null);
}
/*mofified*/
public function updatePos() : void
{
if ( currentToolTip )
{
positionTip();
}
}
/**
* Replaces the ToolTip, if necessary.
*
* <p>Determines whether the UIComponent or IUITextField object
* with the ToolTip assigned to it that is currently under the mouse
* pointer is the most recent such object.
* If not, it removes the old ToolTip and displays the new one.</p>
*
* @param displayObject The UIComponent or IUITextField that is currently under the mouse.
*/
mx_internal function checkIfTargetChanged(displayObject:DisplayObject):void
{
if (!enabled)
return;
findTarget(displayObject);
if (currentTarget != previousTarget)
{
targetChanged();
previousTarget = currentTarget;
}
}
/**
* Searches from the <code>displayObject</code> object up the chain
* of parent objects until it finds a UIComponent or IUITextField object
* with a <code>toolTip</code> or <code>errorString</code> property.
* Treats an empty string as a valid <code>toolTip</code> property.
* Sets the <code>currentTarget</code> property.
*/
mx_internal function findTarget(displayObject:DisplayObject):void
{
// Walk up the DisplayObject parent chain looking for a UIComponent
// with a toolTip or errorString property. Note that we stop
// even if we find a tooltip which is an empty string. Although
// we don't display empty tooltips, we have to track when we
// are over a movieclip with an empty tooltip so that we can
// hide any previous tooltip. This allows a child to set
// toolTip="" to "cancel" its parent's toolTip.
while (displayObject)
{
if (displayObject is IValidatorListener)
{
currentText = IValidatorListener(displayObject).errorString;
if (currentText != null && currentText != "")
{
currentTarget = displayObject;
isError = true;
return;
}
}
if (displayObject is IToolTipManagerClient)
{
currentText = IToolTipManagerClient(displayObject).toolTip;
if (currentText != null)
{
currentTarget = displayObject;
isError = false;
return;
}
}
displayObject = displayObject.parent;
}
currentText = null;
currentTarget = null;
}
/**
* Removes any ToolTip that is currently displayed and displays
* the ToolTip for the UIComponent that is currently under the mouse
* pointer, as determined by the <code>currentTarget</code> property.
*/
mx_internal function targetChanged():void
{
// Do lazy creation of the Timer objects this class uses.
if (!initialized)
initialize()
var event:ToolTipEvent;
if (previousTarget && currentToolTip)
{
if (currentToolTip is IToolTip)
{
event = new ToolTipEvent(ToolTipEvent.TOOL_TIP_HIDE);
event.toolTip = currentToolTip;
previousTarget.dispatchEvent(event);
}
else
{
var me:InterManagerRequest = new InterManagerRequest(InterManagerRequest.TOOLTIP_MANAGER_REQUEST);
me.name = ToolTipEvent.TOOL_TIP_HIDE;
// trace("-->dispatched hide for ToolTipManagerImpl", systemManager);
sandboxRoot.dispatchEvent(me);
}
}
reset();
if (currentTarget)
{
// Don't display empty tooltips.
if (currentText == "")
return;
// Dispatch a "startToolTip" event
// from the object displaying the tooltip.
event = new ToolTipEvent(ToolTipEvent.TOOL_TIP_START);
currentTarget.dispatchEvent(event);
if (showDelay == 0 || scrubTimer.running)
{
// Create the tooltip and start its showEffect.
createTip();
initializeTip();
positionTip();
showTip();
}
else
{
showTimer.delay = showDelay;
showTimer.start();
// After the delay, showTimer_timerHandler()
// will create the tooltip and start its showEffect.
}
}
}
/**
* Creates an invisible new ToolTip.
*
* <p>If the ToolTipManager's <code>enabled</code> property is
* <code>true</code> this method is automatically called
* when the user moves the mouse over an object that has
* the <code>toolTip</code> property set,
* The ToolTipManager makes subsequent calls to
* <code>initializeTip()</code>, <code>positionTip()</code>,
* and <code>showTip()</code> to complete the display
* of the ToolTip.</p>
*
* <p>The type of ToolTip that is created is determined by the
* <code>toolTipClass</code> property.
* By default, this is the ToolTip class.
* This class can be styled to appear as either a normal ToolTip
* (which has a yellow background by default) or as an error tip
* for validation errors (which is red by default).</p>
*
* <p>After creating the ToolTip with the <code>new</code>
* operator, this method stores a reference to it in the
* <code>currentToolTip</code> property.
* It then uses addChild() to add this ToolTip to the
* SystemManager's toolTips layer.</p>
*/
mx_internal function createTip():void
{
// Dispatch a "createToolTip" event
// from the object displaying the tooltip.
var event:ToolTipEvent =
new ToolTipEvent(ToolTipEvent.TOOL_TIP_CREATE);
currentTarget.dispatchEvent(event);
if (event.toolTip)
currentToolTip = event.toolTip;
else
currentToolTip = new toolTipClass();
currentToolTip.visible = false;
// Set the tooltip to be in the same module factory as the target to the
// correct style manager is used. Don't overwrite an existing module factory.
if (currentToolTip is IFlexModule && IFlexModule(currentToolTip).moduleFactory == null &&
currentTarget is IFlexModule)
IFlexModule(currentToolTip).moduleFactory = IFlexModule(currentTarget).moduleFactory;
if (hasEventListener("createTip"))
if (!dispatchEvent(new Event("createTip", false, true)))
return;
var sm:ISystemManager = getSystemManager(currentTarget) as ISystemManager;
sm.topLevelSystemManager.toolTipChildren.addChild(currentToolTip as DisplayObject);
isSystemToolTip = ( currentToolTip is IStyleClient ) && ( IStyleClient( currentToolTip ).getStyle( 'borderSkin' ) != undefined );
}
/*modified*/
mx_internal var isSystemToolTip : Boolean;
/*modified*/
/**
* Initializes a newly created ToolTip with the appropriate text,
* based on the object under the mouse.
*
* <p>If the ToolTipManager's <code>enabled</code> property is
* <code>true</code> this method is automatically called
* when the user moves the mouse over an object that has
* the <code>toolTip</code> property set.
* The ToolTipManager calls <code>createTip()</code> before
* this method, and <code>positionTip()</code> and
* <code>showTip()</code> after.</p>
*
* <p>If a normal ToolTip is being displayed, this method
* sets its text as specified by the <code>toolTip</code>
* property of the object under the mouse.
* If an error tip is being displayed, the text is as
* specified by the <code>errorString</code> property
* of the object under the mouse.</p>
*
* <p>This method also makes the ToolTip the appropriate
* size for the text that it needs to display.</p>
*/
mx_internal function initializeTip():void
{
// Set the text of the tooltip.
if (currentToolTip is IToolTip)
IToolTip(currentToolTip).text = currentText;
if (isError && currentToolTip is IStyleClient)
IStyleClient(currentToolTip).setStyle("styleName", "errorTip");
sizeTip(currentToolTip);
if (currentToolTip is IStyleClient)
{
// Set up its "show" and "hide" effects.
if (showEffect)
IStyleClient(currentToolTip).setStyle("showEffect", showEffect);
if (hideEffect)
IStyleClient(currentToolTip).setStyle("hideEffect", hideEffect);
}
if (showEffect || hideEffect)
{
currentToolTip.addEventListener(EffectEvent.EFFECT_END,
effectEndHandler);
}
}
/**
* @private
* Objects added to the SystemManager's ToolTip layer don't get
* automatically measured or sized, so ToolTipManager has to
* measure it and set its size.
*/
public function sizeTip(toolTip:IToolTip):void
{
// Force measure() to be called on the tooltip.
// Otherwise, its measured size will be 0.
if (toolTip is IInvalidating)
IInvalidating(toolTip).validateNow();
toolTip.setActualSize(
toolTip.getExplicitOrMeasuredWidth(),
toolTip.getExplicitOrMeasuredHeight());
toolTipWidth = toolTip.width;
toolTipHeight = toolTip.height;
}
private var toolTipWidth : Number;
private var toolTipHeight : Number;
/**
* Positions a newly created and initialized ToolTip on the stage.
*
* <p>If the ToolTipManager's <code>enabled</code> property is
* <code>true</code> this method is automatically called
* when the user moves the mouse over an object that has
* the <code>toolTip</code> property set.
* The ToolTipManager calls <code>createTip()</code> and
* <code>initializeTip()</code> before this method,
* and <code>showTip()</code> after.</p>
*
* <p>If a normal ToolTip is being displayed, this method positions
* its upper-left corner near the lower-right of the arrow cursor.
* This method ensures that the ToolTip is completely in view.
*/
mx_internal function positionTip():void
{
var x:Number;
var y:Number;
var screenWidth:Number = currentToolTip.screen.width;
var screenHeight:Number = currentToolTip.screen.height;
if (/*isError*/isSystemToolTip ) //modified
{
var target : DisplayObject = IStyleClient( currentTarget ).getStyle( 'toolTipTarget' );
if ( ! target )
{
target = currentTarget;
}
var targetGlobalBounds:Rectangle = getGlobalBounds(target, currentToolTip.root);
var placementX : int = -1;
var placementY : int = -1;
var borderStyle : String;
if (currentTarget is IStyleClient)
borderStyle = IStyleClient(currentTarget).getStyle( 'toolTipPlacement' );
if ( borderStyle )
{
if ( borderStyle == "errorTipRight" )
{
placementX = 3;
}
else if ( borderStyle == 'errorTipAbove' )
{
placementX = 1;
placementY = 1;
}
else if ( borderStyle == 'errorTipBelow' )
{
placementX = 0;
placementY = 0;
}
else if ( borderStyle == 'errorTipAboveRight' )
{
placementX = 2;
placementY = 2;
}
else if ( borderStyle == 'errorTipBelowRight' )
{
placementX = 4;
}
}
//Если компонентом не определен вариант размещения, то определяем его
if ( placementX == -1 )
{
//Определяем вариант размещения по оси Х
if ( ( targetGlobalBounds.right - toolTipWidth ) < 0 )
{
placementX = 0;
}
else
if ( ( targetGlobalBounds.x + toolTipWidth ) > screenWidth )
{
placementX = 2;
}
else
{
placementX = 1;
}
//Определяем вариант размещения по оси Y
if ( ( targetGlobalBounds.y - toolTipHeight ) < 0 )
{
placementY = 0;
}
else
if ( ( targetGlobalBounds.bottom + toolTipHeight ) > screenHeight )
{
placementY = 2;
}
else
{
placementY = 1;
}
}
//Основной вариант размещения
if (
( ( placementX == 1 ) && ( placementY == 1 ) ) ||
( ( placementX == 1 ) && ( placementY == 2 ) ) ||
( ( placementX == 0 ) && ( placementY == 1 ) ) ||
( ( placementX == 0 ) && ( placementY == 2 ) )
)
{
x = targetGlobalBounds.x;
y = targetGlobalBounds.y - toolTipHeight - 11;
borderStyle = "errorTipAbove";
}
else
if (
( ( placementX == 0 ) && ( placementY == 0 ) ) ||
( ( placementX == 1 ) && ( placementY == 0 ) )
)
{
x = targetGlobalBounds.x;
y = targetGlobalBounds.bottom;
borderStyle = "errorTipBelow";
}
else
if (
( ( placementX == 2 ) && ( placementY == 2 ) ) ||
( ( placementX == 2 ) && ( placementY == 1 ) )
)
{
x = targetGlobalBounds.right - toolTipWidth;
y = targetGlobalBounds.y - toolTipHeight - 11;
borderStyle = "errorTipAboveRight";
}
else if ( placementX == 3 )
{
x = targetGlobalBounds.right;
y = targetGlobalBounds.y - 5;
}
else
{
x = targetGlobalBounds.right - toolTipWidth;
y = targetGlobalBounds.bottom;
borderStyle = "errorTipBelowRight";
}
if ( currentToolTip is IStyleClient )
IStyleClient(currentToolTip).setStyle("borderStyle", borderStyle);
// If there's no room to the right of the control, put it above
// or below, with the left edge of the error tip aligned with
// the left edge of the target.
/*
if (x + currentToolTip.width > screenWidth)
{
var newWidth:Number = NaN;
var oldWidth:Number = NaN;
x = targetGlobalBounds.left - 2;
// If the error tip would be too wide for the stage,
// reduce the maximum width to fit onstage. Note that
// we have to reassign the text in order to get the tip
// to relayout after changing the border style and maxWidth.
if (x + currentToolTip.width + 4 > screenWidth)
{
newWidth = screenWidth - x - 4;
oldWidth = Object(toolTipClass).maxWidth;
Object(toolTipClass).maxWidth = newWidth;
if (currentToolTip is IStyleClient)
IStyleClient(currentToolTip).setStyle("borderStyle", "errorTipAbove");
currentToolTip["text"] = currentToolTip["text"];
}
// Even if the error tip will fit onstage, we still need to
// change the border style and get the error tip to relayout.
else
{
if (currentToolTip is IStyleClient)
IStyleClient(currentToolTip).setStyle("borderStyle", "errorTipAbove");
currentToolTip["text"] = currentToolTip["text"];
}
if (currentToolTip.height + 2 < targetGlobalBounds.top)
{
// There's room to put it above the control.
y = targetGlobalBounds.top - (currentToolTip.height + 2);
}
else
{
// No room above, put it below the control.
y = targetGlobalBounds.bottom + 2;
if (!isNaN(newWidth))
Object(toolTipClass).maxWidth = newWidth;
if (currentToolTip is IStyleClient)
IStyleClient(currentToolTip).setStyle("borderStyle", "errorTipBelow");
currentToolTip["text"] = currentToolTip["text"];
}
}
// Since the border style of the error tip may have changed,
// we have to force a remeasurement and change its size.
// This is because objects in the toolTips layer
// don't undergo normal measurement and layout.
sizeTip(currentToolTip)
// If we changed the tooltip max size, we change it back
if (!isNaN(oldWidth))
Object(toolTipClass).maxWidth = oldWidth;
*/
}
else
{
var sm:ISystemManager = getSystemManager(currentTarget);
/*modified*/
// Position the upper-left of the tooltip
// at the lower-right of the arrow cursor.
//x = DisplayObject(sm).mouseX + 11;
//y = DisplayObject(sm).mouseY + 22;
// If the tooltip is too wide to fit onstage, move it left.
//var toolTipWidth:Number = currentToolTip.width;
//if (x + toolTipWidth > screenWidth)
// x = screenWidth - toolTipWidth;
// If the tooltip is too tall to fit onstage, move it up.
//var toolTipHeight:Number = currentToolTip.height;
//if (y + toolTipHeight > screenHeight)
// y = screenHeight - toolTipHeight;
var toolTipPoint : Point = getToolTipPos( DisplayObject(sm).mouseX, DisplayObject(sm).mouseY,
screenWidth, screenHeight, toolTipWidth, toolTipHeight );
var pos:Point = new Point(toolTipPoint.x, toolTipPoint.y);
/*modified*/
pos = DisplayObject(sm).localToGlobal(pos);
pos = DisplayObject(sandboxRoot).globalToLocal(pos);
x = pos.x;
y = pos.y;
}
currentToolTip.move(x, y);
}
/*modified*/
private static const leftOffset : Number = 11;
private static const topOffset : Number = 11;
//Возвращет координаты тултипа для болле корректного всплывания
/*
Варианты всплывания
3|2
4|1
*/
private function getToolTipPos( pointX : Number, pointY : Number, screenWidth : Number, screenHeight : Number,
toolTipWidth : Number, toolTipHeight : Number ) : Point
{
pointX += leftOffset;
pointY += topOffset;
if ( pointX < 0 )
{
pointX = leftOffset;
}
else
if ( ( pointX + toolTipWidth ) > screenWidth )
{
pointX = screenWidth - toolTipWidth - leftOffset;
}
if ( pointY < 0 )
{
pointY = topOffset;
}
else
if ( ( pointY + toolTipHeight ) > screenHeight )
{
pointY = screenHeight - toolTipHeight - topOffset;
}
return new Point( pointX, pointY );
}
/*modified*/
/**
* Shows a newly created, initialized, and positioned ToolTip.
*
* <p>If the ToolTipManager's <code>enabled</code> property is
* <code>true</code> this method is automatically called
* when the user moves the mouse over an object that has
* the <code>toolTip</code> property set.
* The ToolTipManager calls <code>createTip()</code>,
* <code>initializeTip()</code>, and <code>positionTip()</code>
* before this method.</p>
*
* <p>This method first dispatches a <code>"showToolTip"</code>
* event from the object under the mouse.
* This gives you a chance to do special processing on a
* particular object's ToolTip just before it becomes visible.
* It then makes the ToolTip visible, which triggers
* the ToolTipManager's <code>showEffect</code> if one is specified.
*/
mx_internal function showTip():void
{
// Dispatch a "showToolTip" event
// from the object displaying the tooltip.
var event:ToolTipEvent =
new ToolTipEvent(ToolTipEvent.TOOL_TIP_SHOW);
event.toolTip = currentToolTip;
currentTarget.dispatchEvent(event);
if (isError)
{
// Listen for a change event so we know when to hide the tip
currentTarget.addEventListener("change", changeHandler);
}
else
{
var sm:ISystemManager = getSystemManager(currentTarget);
sm.addEventListener(MouseEvent.MOUSE_DOWN,
systemManager_mouseDownHandler);
}
// Make the tooltip visible.
// If showEffect exists, this effect will play.
// When the effect ends, effectEndHandler()
// will start the hideTimer.
currentToolTip.visible = true;
if (!showEffect)
showEffectEnded();
}
/**
* Hides the current ToolTip.
*/
mx_internal function hideTip():void
{
// Dispatch a "hideToolTip" event
// from the object that was displaying the tooltip.
if (previousTarget)
{
var event:ToolTipEvent =
new ToolTipEvent(ToolTipEvent.TOOL_TIP_HIDE);
event.toolTip = currentToolTip;
previousTarget.dispatchEvent(event);
}
// Make the tooltip invisible.
// If hideEffect exists, this effect will play.
// When the effect ends, effectEndHandler()
// will reset the ToolTipManager to a no-tip state.
if (currentToolTip)
currentToolTip.visible = false;
// When to do this?
if (isError)
{
if (currentTarget)
currentTarget.removeEventListener("change", changeHandler);
}
else
{
if (previousTarget)
{
var sm:ISystemManager = getSystemManager(previousTarget);
sm.removeEventListener(MouseEvent.MOUSE_DOWN,
systemManager_mouseDownHandler);
}
}
if (!hideEffect)
hideEffectEnded();
}
/**
* Removes any currently visible ToolTip.
* If the ToolTip is starting to show or hide, this method
* removes the ToolTip immediately without completing the effect.
*/
mx_internal function reset():void
{
// Reset the three timers, in case any are running.
showTimer.reset();
hideTimer.reset();
// If there is a current tooltip...
if (currentToolTip)
{
// Remove the event handlers for the effectEnd of the showEffect
// and hideEffect, so that calling endEffectsForTarget() doesn't
// trigger effectEndHandler().
if (showEffect || hideEffect)
{
currentToolTip.removeEventListener(EffectEvent.EFFECT_END,
effectEndHandler);
}
// End any show or hide effects that might be playing on it.
EffectManager.endEffectsForTarget(currentToolTip);
var e:DynamicEvent;
if (hasEventListener("removeChild"))
{
e = new DynamicEvent("removeChild", false, true);
e.sm = currentToolTip.systemManager;
e.toolTip = currentToolTip;
}
if (!e || dispatchEvent(e))
{
// Remove it.
var sm:ISystemManager = currentToolTip.systemManager as ISystemManager;
sm.topLevelSystemManager.toolTipChildren.removeChild(currentToolTip as DisplayObject);
}
currentToolTip = null;
scrubTimer.delay = scrubDelay;
scrubTimer.reset();
if (scrubDelay > 0)
{
scrubTimer.delay = scrubDelay;
scrubTimer.start();
}
}
}
/**
* Creates an instance of the ToolTip class with the specified text
* and displays it at the specified location in stage coordinates.
*
* <p>ToolTips appear in their own layer, on top of everything
* except cursors.</p>
*
* <p>The standard way of using ToolTips is to let the ToolTipManager
* automatically show and hide them as the user moves the mouse over
* the objects that have the <code>toolTip</code> property set.
* You can turn off this automatic ToolTip management by setting
* the ToolTipManager's <code>enabled</code> property to
* <code>false</code>.</p>
*
* <p>By contrast, this method—along with <code>hideToolTip()</code>—gives
* you programmatic control over ToolTips.
* You can show them when and where you choose,
* and you can even show more than one at once if you need to.
* (The ToolTipManager never does this, because it is generally
* confusing to the user).</p>
*
* <p>This method first creates a new instance of ToolTip and calls the
* <code>addChild()</code> method to put it into the SystemManager's
* toolTips layer.
* If you are showing an error tip, it sets the appropriate styles.
* Then it sets the text for the ToolTip, sizes the ToolTip based on
* its text, and positions it where you specified.</p>
*
* <p>You must save the reference to the ToolTip that this method
* returns so that you can pass it to the <code>hideToolTip()</code> method.</p>
*
* @param text The text to display in the ToolTip instance.
*
* @param x The horizontal coordinate of the ToolTip in stage coordinates.
* In case of multiple stages, the relevant stage is determined
* from the <code>context</code> argument.
*
* @param y The vertical coordinate of the ToolTip in stage coordinates.
* In case of multiple stages, the relevant stage is determined
* from the <code>context</code> argument.
*
* @param errorTipBorderStyle The border style of an error tip. This method
* argument can be null, "errorTipRight", "errorTipAbove", or "errorTipBelow".
* If it is null, then the <code>createToolTip()</code> method creates a normal ToolTip. If it is
* "errorTipRight", "errorTipAbove", or "errorTipBelow", then the <code>createToolTip()</code>
* method creates an error tip, and this parameter determines where the arrow
* of the error tip points to (the error's target). For example, if you pass "errorTipRight", Flex
* positions the error tip (via the x and y arguments) to the
* right of the error target; the arrow is on the left edge of the error tip.
*
* @param context This property is not currently used.
*
* @return The newly created ToolTip.
*
*/
public function createToolTip(text:String, x:Number, y:Number,
errorTipBorderStyle:String = null,
context:IUIComponent = null):IToolTip
{
var toolTip:ToolTip = new ToolTip();
var sm:ISystemManager = context ?
context.systemManager as ISystemManager:
FlexGlobals.topLevelApplication.systemManager as ISystemManager;
if (context is IFlexModule)
toolTip.moduleFactory = IFlexModule(context).moduleFactory;
else
toolTip.moduleFactory = sm;
var e:DynamicEvent;
if (hasEventListener("addChild"))
{
e = new DynamicEvent("addChild", false, true);
e.sm = sm;
e.toolTip = toolTip;
}
if (!e || dispatchEvent(e))
{
sm.topLevelSystemManager.toolTipChildren.addChild(toolTip as DisplayObject);
}
if (errorTipBorderStyle)
{
toolTip.setStyle("styleName", "errorTip");
toolTip.setStyle("borderStyle", errorTipBorderStyle);
}
toolTip.text = text;
sizeTip(toolTip);
toolTip.move(x, y);
// Ensure that tip is on screen?
// Should x and y for error tip be tip of pointy border?
// show effect?
return toolTip as IToolTip;
}
/**
* Destroys a specified ToolTip that was created by the <code>createToolTip()</code> method.
*
* <p>This method calls the <code>removeChild()</code> method to remove the specified
* ToolTip from the SystemManager's ToolTips layer.
* It will then be garbage-collected unless you keep a
* reference to it.</p>
*
* <p>You should not call this method on the ToolTipManager's
* <code>currentToolTip</code>.</p>
*
* @param toolTip The ToolTip instance to destroy.
*/
public function destroyToolTip(toolTip:IToolTip):void
{
var e:DynamicEvent;
if (hasEventListener("removeChild"))
{
e = new DynamicEvent("removeChild", false, true);
e.sm = toolTip.systemManager;
e.toolTip = toolTip;
}
if (!e || dispatchEvent(e))
{
// Remove it.
var sm:ISystemManager = toolTip.systemManager as ISystemManager;
sm.topLevelSystemManager.toolTipChildren.removeChild(toolTip as DisplayObject);
}
// hide effect?
}
/**
* @private
*/
mx_internal function showEffectEnded():void
{
if (hideDelay == 0)
{
hideTip();
}
else if (hideDelay < Infinity)
{
hideTimer.delay = hideDelay;
hideTimer.start();
}
if (currentTarget)
{
// Dispatch a "toolTipShown" event
// from the object displaying the tooltip.
var event:ToolTipEvent =
new ToolTipEvent(ToolTipEvent.TOOL_TIP_SHOWN);
event.toolTip = currentToolTip;
currentTarget.dispatchEvent(event);
}
}
/**
* @private
*/
mx_internal function hideEffectEnded():void
{
reset();
// Dispatch a "toolTipEnd" event
// from the object that was displaying the tooltip.
if (previousTarget)
{
var event:ToolTipEvent =
new ToolTipEvent(ToolTipEvent.TOOL_TIP_END);
event.toolTip = currentToolTip;
previousTarget.dispatchEvent(event);
}
}
/**
* @private
*/
private function getSystemManager(
target:DisplayObject):ISystemManager
{
return target is IUIComponent ?
IUIComponent(target).systemManager :
null;
}
/**
* @private
*/
private function getGlobalBounds(obj:DisplayObject, parent:DisplayObject):Rectangle
{
/*var upperLeft:Point = new Point(0, 0);
upperLeft = obj.localToGlobal(upperLeft);
upperLeft = parent.globalToLocal(upperLeft);*/
return obj.getBounds( parent );
//return new Rectangle(upperLeft.x, upperLeft.y, obj.width, obj.height);
}
//--------------------------------------------------------------------------
//
// Event handlers
//
//--------------------------------------------------------------------------
/**
* @private
* This handler is called when the mouse moves over an object
* with a toolTip.
*/
mx_internal function toolTipMouseOverHandler(event:MouseEvent):void
{
checkIfTargetChanged(DisplayObject(event.target));
}
/**
* @private
* This handler is called when the mouse moves out of an object
* with a toolTip.
*/
mx_internal function toolTipMouseOutHandler(event:MouseEvent):void
{
checkIfTargetChanged(event.relatedObject);
}
/**
* @private
* This handler is called when the mouse moves over an object
* with an errorString.
*/
mx_internal function errorTipMouseOverHandler(event:MouseEvent):void
{
checkIfTargetChanged(DisplayObject(event.target));
}
/**
* @private
* This handler is called when the mouse moves out of an object
* with an errorString.
*/
mx_internal function errorTipMouseOutHandler(event:MouseEvent):void
{
checkIfTargetChanged(event.relatedObject);
}
/**
* @private
* This handler is called when the showTimer fires.
* It creates the tooltip and starts its showEffect.
*/
mx_internal function showTimer_timerHandler(event:TimerEvent):void
{
// Make sure we still have a currentTarget when the timer fires.
if (currentTarget)
{
createTip();
initializeTip();
positionTip();
showTip();
}
}
/**
* @private
* This handler is called when the hideTimer fires.
* It starts the hideEffect.
*/
mx_internal function hideTimer_timerHandler(event:TimerEvent):void
{
hideTip();
}
/**
* @private
* This handler is called when the showEffect or hideEffect ends.
* When the showEffect ends, it starts the hideTimer,
* which will automatically start hiding the tooltip when it fires,
* even if the mouse is still over the target.
* When the hideEffect ends, the tooltip is removed.
*/
mx_internal function effectEndHandler(event:EffectEvent):void
{
if (event.effectInstance.effect == showEffect)
showEffectEnded();
else if (event.effectInstance.effect == hideEffect)
hideEffectEnded();
}
/**
* @private
* This handler is called when the user clicks the mouse
* while a normal tooltip is displayed.
* It immediately hides the tooltip.
*/
mx_internal function systemManager_mouseDownHandler(event:MouseEvent):void
{
reset();
}
/**
* @private
*/
mx_internal function changeHandler(event:Event):void
{
reset();
}
/**
* Marshal dragManager
*/
private function marshalToolTipManagerHandler(event:Event):void
{
if (event is InterManagerRequest)
return;
var me:InterManagerRequest;
var marshalEvent:Object = event;
switch (marshalEvent.name)
{
case "currentToolTip":
// trace("--marshaled currentToolTip for ToolTipManagerImpl", systemManager, marshalEvent.value);
_currentToolTip = marshalEvent.value;
break;
case ToolTipEvent.TOOL_TIP_HIDE:
// trace("--handled hide for ToolTipManagerImpl", systemManager);
if (_currentToolTip is IToolTip)
hideTip()
break;
case "update":
// anyone can answer so prevent others from responding as well
event.stopImmediatePropagation();
// update the others
// trace("-->marshaled update for ToolTipManagerImpl", systemManager);
me = new InterManagerRequest(InterManagerRequest.TOOLTIP_MANAGER_REQUEST);
me.name = "currentToolTip";
me.value = _currentToolTip;
// trace("-->dispatched currentToolTip for ToolTipManagerImpl", systemManager, true);
sandboxRoot.dispatchEvent(me);
// trace("<--dispatched currentToolTip for ToolTipManagerImpl", systemManager, true);
// trace("<--marshaled update for ToolTipManagerImpl", systemManager);
}
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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.controls.advancedDataGridClasses
{
import flash.display.DisplayObject;
import flash.geom.Point;
import mx.collections.IGroupingCollection;
import mx.collections.IGroupingCollection2;
import mx.controls.AdvancedDataGrid;
import mx.controls.listClasses.IDropInListItemRenderer;
import mx.controls.listClasses.IListItemRenderer;
import mx.core.UIComponent;
import mx.core.mx_internal;
use namespace mx_internal;
/**
* The AdvancedDataGridDragProxy class defines the default drag proxy
* used when dragging data from an AdvancedDataGrid control.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public class AdvancedDataGridDragProxy extends UIComponent
{
include "../../core/Version.as";
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function AdvancedDataGridDragProxy()
{
super();
}
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
override protected function createChildren():void
{
super.createChildren();
var advancedDataGrid:AdvancedDataGrid = AdvancedDataGrid(owner);
var items:Array /* of unit */ = advancedDataGrid.selectedItems;
var n:int = items.length;
for (var i:int = 0; i < n; i++)
{
var src:IListItemRenderer = advancedDataGrid.itemToItemRenderer(items[i]);
if (!src)
continue;
var o:UIComponent;
var data:Object = items[i];
o = new UIComponent();
addChild(DisplayObject(o));
// The drag proxy should have the same layoutDirection as the
// AdvancedDataGrid.
o.layoutDirection = advancedDataGrid.layoutDirection;
var ww:Number = 0;
var m:int = advancedDataGrid.visibleColumns.length;
for (var j:int = 0; j < m; j++)
{
var col:AdvancedDataGridColumn = advancedDataGrid.visibleColumns[j];
var c:IListItemRenderer = advancedDataGrid.getRenderer(col, data, true);
var label:String = col.itemToLabel(data);
if (advancedDataGrid._rootModel &&
col.colNum == 0 && advancedDataGrid._rootModel.canHaveChildren(data))
{
// if the data is grouped, get the groupLabelField.
var groupLabelField:String;
if (advancedDataGrid._rootModel is IGroupingCollection
&& IGroupingCollection(advancedDataGrid._rootModel).grouping)
groupLabelField = IGroupingCollection(advancedDataGrid._rootModel).grouping.label;
// check for GroupingCollection2 also
if (advancedDataGrid._rootModel is IGroupingCollection2
&& IGroupingCollection2(advancedDataGrid._rootModel).grouping)
groupLabelField = IGroupingCollection2(advancedDataGrid._rootModel).grouping.label;
// Checking for a groupLabelFunction or a groupLabelField property to be present
if (advancedDataGrid.groupLabelFunction != null)
label = advancedDataGrid.groupLabelFunction(data, col);
else if (groupLabelField != null && data.hasOwnProperty(groupLabelField))
label = data[groupLabelField];
}
var rowData:AdvancedDataGridListData = new AdvancedDataGridListData(
label, col.dataField,
col.colNum, "", advancedDataGrid);
if (c is IDropInListItemRenderer)
{
IDropInListItemRenderer(c).listData =
data ? rowData : null;
}
c.data = data;
c.styleName = advancedDataGrid;
c.visible = true;
o.addChild(DisplayObject(c));
var itemWidth:Number = advancedDataGrid.getWidthOfItem(c, col, j);
c.setActualSize(itemWidth, src.height);
c.move(ww, 0);
ww += itemWidth;
if (advancedDataGrid.rendererProviders.length != 0)
{
var adgDescription:AdvancedDataGridRendererDescription =
advancedDataGrid.getRendererDescription(data, col, true);
if (adgDescription && adgDescription.renderer)
{
if (adgDescription.columnSpan == 0)
break;
else
j += adgDescription.columnSpan - 1;
}
}
}
o.setActualSize(ww, src.height);
var pt:Point = new Point(0, 0);
pt = DisplayObject(src).localToGlobal(pt);
pt = AdvancedDataGrid(owner).globalToLocal(pt);
o.y = pt.y;
measuredHeight = o.y + o.height;
measuredWidth = ww;
}
invalidateDisplayList();
}
/**
* @private
*/
override protected function measure():void
{
super.measure();
var w:Number = 0;
var h:Number = 0;
var child:UIComponent;
for (var i:int = 0; i < numChildren; i++)
{
child = getChildAt(i) as UIComponent;
if (child)
{
w = Math.max(w, child.x + child.width);
h = Math.max(h, child.y + child.height);
}
}
measuredWidth = measuredMinWidth = w;
measuredHeight = measuredMinHeight = h;
}
}
}
|
/*
* _________ __ __
* _/ / / /____ / /________ ____ ____ ___
* _/ / / __/ -_) __/ __/ _ `/ _ `/ _ \/ _ \
* _/________/ \__/\__/\__/_/ \_,_/\_, /\___/_//_/
* /___/
*
* Tetragon : Game Engine for multi-platform ActionScript projects.
* http://www.tetragonengine.com/ - Copyright (C) 2012 Sascha Balkau
*
* 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 tetragon.core.types
{
/**
* A simple color value object for use with the Palette class.
*/
public final class PaletteColor
{
//-----------------------------------------------------------------------------------------
// Properties
//-----------------------------------------------------------------------------------------
public var value:uint;
public var name:String;
//-----------------------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------------------
/**
* Creates a new instance of the class.
*
* @param value uint value of the color.
* @param name Optional name of the color.
*/
public function PaletteColor(value:uint, name:String = null)
{
this.value = value;
this.name = name;
}
}
}
|
/**
* Created by max.rozdobudko@gmail.com on 7/22/17.
*/
package feathersx.mvvc {
import feathers.controls.AutoSizeMode;
import feathers.controls.LayoutGroup;
import feathers.controls.StackScreenNavigator;
import feathers.controls.StackScreenNavigatorItem;
import feathers.layout.AnchorLayout;
import feathers.layout.AnchorLayoutData;
import feathers.motion.Fade;
import feathersx.motion.Slide;
import feathersx.mvvc.support.NavigationControllerStackScreenNavigator;
import feathersx.mvvc.support.StackScreenNavigatorHolderHelper;
import feathersx.mvvc.support.ViewControllerStackScreenNavigatorItem;
import flash.debugger.enterDebugger;
import skein.core.WeakReference;
import skein.logger.Log;
import skein.utils.StringUtil;
import skein.utils.VectorUtil;
import starling.animation.Transitions;
import starling.core.Starling;
import starling.display.DisplayObject;
public class NavigationController extends ViewController {
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
public function NavigationController(rootViewController: ViewController) {
super();
setViewControllers(new <ViewController>[rootViewController], false);
}
//--------------------------------------------------------------------------
//
// Dispose
//
//--------------------------------------------------------------------------
override public function dispose(): void {
viewControllers.forEach(function (vc: ViewController, ...rest): void {
vc.dispose();
});
setViewControllersInternal(new <ViewController>[]);
super.dispose();
}
//--------------------------------------------------------------------------
//
// Delegate
//
//--------------------------------------------------------------------------
private var _delegate: WeakReference;
public function get delegate(): NavigationControllerDelegate {
return _delegate ? _delegate.value : null;
}
public function set delegate(value: NavigationControllerDelegate): void {
_delegate = new WeakReference(value);
}
//--------------------------------------------------------------------------
//
// View
//
//--------------------------------------------------------------------------
// override public function get isViewLoaded(): Boolean {
// trace(_navigator, _view);
// return _navigator != null; // TODO(dev) if (isViewLoaded) { after loadView signature is changed
// }
//--------------------------------------------------------------------------
//
// Transition
//
//--------------------------------------------------------------------------
protected function getPushTransition(animated: Boolean): Function {
if (animated) {
var onProgress:Function = function (progress:Number): void {};
var onComplete:Function = function (): void {};
return Slide.createSlideLeftTransition(0.5, Transitions.EASE_OUT, null, onProgress, onComplete);
} else {
return null;
}
}
protected function getPopTransition(animated: Boolean): Function {
if (animated) {
var onProgress:Function = function(progress:Number): void {};
var onComplete:Function = function(): void {};
return Slide.createSlideRightTransition(0.5, Transitions.EASE_OUT, null, onProgress, onComplete);
} else {
return null;
}
}
private function getReplaceTransition(animated: Boolean): Function {
if (animated) {
return Fade.createFadeInTransition();
} else {
return function (oldScreen: DisplayObject, newScreen: DisplayObject, onComplete: Function): void {
if (onComplete != null) {
onComplete();
}
}
}
}
//--------------------------------------------------------------------------
//
// Push & Pop stack items
//
//--------------------------------------------------------------------------
override public function show(vc: ViewController, sender: Object = null): void {
pushViewController(vc, true);
}
// Push
public function pushViewController(vc: ViewController, animated: Boolean):void {
resetNavigationBar();
if (delegate) {
delegate.navigationControllerWillShow(this, vc, animated);
}
setupNavigationControllerForViewControllers(new <ViewController>[vc]);
doPushScreenOfViewController(vc, animated, null);
_navigationBar.pushItem(vc.navigationItem, animated);
_toolbar.setItems(topViewController.toolbarItems, true);
}
// Pop
public function popViewController(animated: Boolean): ViewController {
if (viewControllers.length == 0) {
return null;
}
if (viewControllers.length == 1) {
return null;
}
var popped: ViewController = viewControllers[viewControllers.length - 1];
doPopScreenOfViewController(popped, animated, function(): void {
clearNavigationControllerForViewControllers(new <ViewController>[popped]);
});
_navigationBar.popItem(animated);
_toolbar.setItems(topViewController.toolbarItems, true);
return popped;
}
public function popToRootViewController(animated: Boolean): Vector.<ViewController> {
if (viewControllers.length == 0) {
return null;
}
if (viewControllers.length == 1) {
return null;
}
var popped: Vector.<ViewController> = viewControllers.splice(1, viewControllers.length - 1);
doPopToRootScreenOfViewControllers(popped, animated, function (): void {
clearNavigationControllerForViewControllers(popped);
popped.forEach(function(vc: ViewController, ...rest): void {
vc.dispose();
});
});
_navigationBar.popToRootItem(animated);
_toolbar.setItems(topViewController.toolbarItems, animated);
return popped;
}
public function popToViewController(viewController:ViewController, animated:Boolean): ViewController {
return null;
}
//--------------------------------------------------------------------------
//
// Navigation Stack
//
//--------------------------------------------------------------------------
protected var _proposedViewControllers: Vector.<ViewController>;
// viewControllers
public function get viewControllers(): Vector.<ViewController> {
return _navigator ? NavigationControllerStackScreenNavigator(_navigator).viewControllers : new <ViewController>[];
}
// topViewController
public function get topViewController(): ViewController {
if (viewControllers.length > 0) {
return viewControllers[viewControllers.length - 1];
}
return null;
}
// setViewControllers
public function setViewControllers(viewControllers: Vector.<ViewController>, animated: Boolean, completion: Function = null): void {
if (!isViewLoaded) {
_proposedViewControllers = viewControllers;
return;
}
doSetViewControllers(viewControllers, animated, completion);
}
protected function doSetViewControllers(viewControllers: Vector.<ViewController>, animated: Boolean, completion: Function = null): void {
resetNavigationBar();
// TODO: handle empty viewControllers list
if (viewControllers.length > 0) {
if (navigator.activeScreenID == null) {
var newRootViewController: ViewController = viewControllers[0];
setupNavigationControllerForViewControllers(new <ViewController>[newRootViewController]);
setRootViewController(newRootViewController, function(): void {
setViewControllersInternal(viewControllers);
if (completion != null) {
completion();
}
});
_toolbar.setItems(newRootViewController.toolbarItems, animated);
} else {
var newTopViewController: ViewController = viewControllers[viewControllers.length - 1];
setupNavigationControllerForViewControllers(new <ViewController>[newTopViewController]);
replaceTopViewController(newTopViewController, animated, function(): void {
setViewControllersInternal(viewControllers);
if (completion != null) {
completion();
}
});
_toolbar.setItems(newTopViewController.toolbarItems, animated);
}
}
_navigationBar.setItems(navigationItemsFromViewControllers(viewControllers), animated);
}
protected function setViewControllersInternal(viewControllers: Vector.<ViewController>): void {
if (viewControllers == this.viewControllers) {
enterDebugger();
return;
}
var helper: StackScreenNavigatorHolderHelper = new StackScreenNavigatorHolderHelper(navigator);
// oldViewControllers
var oldViewControllers: Vector.<ViewController> = this.viewControllers.filter(function(oldViewController: ViewController, ...rest): Boolean {
return viewControllers.indexOf(oldViewController) == -1;
});
oldViewControllers.forEach(function (oldViewController: ViewController, ...rest): void {
var oldScreen: ViewControllerStackScreenNavigatorItem = helper.getScreenWithId(oldViewController.identifier) as ViewControllerStackScreenNavigatorItem;
if (oldScreen == null) {
Log.w("feathers-uikit", StringUtil.substitute("Warning: attempt to release view controller's navigator item for view controller {0} failed due to {1} is an invalid navigator item.", oldViewController, helper.getScreenWithId(oldViewController.identifier)));
return;
}
oldScreen.release();
});
var idsToRemove: Vector.<String> = idsForViewControllers(oldViewControllers).filter(function(id: String, ...rest): Boolean {
return viewControllers.every(function(controller: ViewController, ...rest): Boolean {
return controller.identifier != id;
})
});
helper.removeScreenWithIds(idsToRemove, function(): void {
clearNavigationControllerForViewControllers(oldViewControllers);
});
if (!VectorUtil.same(idsToRemove, idsForViewControllers(oldViewControllers))) {
enterDebugger();
}
// newViewControllers
var newViewControllers: Vector.<ViewController> = viewControllers.filter(function(newViewController: ViewController, ...rest): Boolean {
return !helper.hasScreenWithId(newViewController.identifier);
});
helper.addScreensWithIds(idsForViewControllers(newViewControllers), screensForViewControllers(newViewControllers), function(): void {
setupNavigationControllerForViewControllers(newViewControllers);
newViewControllers.forEach(function (newViewController: ViewController, ...rest): void {
var newScreen: ViewControllerStackScreenNavigatorItem = helper.getScreenWithId(newViewController.identifier) as ViewControllerStackScreenNavigatorItem;
if (newScreen == null) {
Log.w("feathers-uikit", StringUtil.substitute("Warning: attempt to retain view controllers navigator item for view controller {0} failed due to {1} is an invalid navigator item.", newViewController, helper.getScreenWithId(newViewController.identifier)));
return;
}
newScreen.retain();
});
});
}
// MARK: StackScreenNavigator utils
protected function doPushScreenOfViewController(vc: ViewController, animated: Boolean, completion: Function): void {
var item: ViewControllerStackScreenNavigatorItem = new ViewControllerStackScreenNavigatorItem(vc);
item.retain();
var transition: Function = getPushTransition(animated);
new StackScreenNavigatorHolderHelper(navigator).pushScreenWithId(vc.identifier, item, transition, completion);
}
protected function doPopScreenOfViewController(vc: ViewController, animated: Boolean, completion: Function): void {
var item: ViewControllerStackScreenNavigatorItem = navigator.getScreen(vc.identifier) as ViewControllerStackScreenNavigatorItem;
item.release();
var transition: Function = getPopTransition(animated);
new StackScreenNavigatorHolderHelper(navigator).popScreenWithId(vc.identifier, transition, completion);
}
protected function doPopToRootScreenOfViewControllers(viewControllers: Vector.<ViewController>, animated: Boolean, completion: Function): void {
var ids: Vector.<String> = idsForViewControllers(viewControllers);
ids.forEach(function(id: String, ...rest): void {
var item: ViewControllerStackScreenNavigatorItem = navigator.getScreen(id) as ViewControllerStackScreenNavigatorItem;
item.release();
});
var transition: Function = getPopTransition(animated);
new StackScreenNavigatorHolderHelper(navigator).popToRootScreenWithIds(ids, transition, completion);
}
protected function setRootViewController(vc: ViewController, completion: Function = null):void {
var item: ViewControllerStackScreenNavigatorItem = new ViewControllerStackScreenNavigatorItem(vc);
item.retain();
new StackScreenNavigatorHolderHelper(navigator).setRootScreenWithId(vc.identifier, item, completion);
}
protected function replaceTopViewController(vc: ViewController, animated: Boolean, completion: Function): void {
var oldItem: ViewControllerStackScreenNavigatorItem = navigator.getScreen(navigator.activeScreenID) as ViewControllerStackScreenNavigatorItem;
oldItem.release();
var newItem: ViewControllerStackScreenNavigatorItem = new ViewControllerStackScreenNavigatorItem(vc);
newItem.retain();
var transition: Function = getReplaceTransition(animated);
new StackScreenNavigatorHolderHelper(navigator).replaceScreenWithId(vc.identifier, newItem, transition, completion);
}
private function setupNavigationControllerForViewControllers(viewControllers: Vector.<ViewController>): void {
var self: NavigationController = this;
viewControllers.forEach(function (vc: ViewController, ...rest): void {
vc.setNavigationController(self);
});
}
private function clearNavigationControllerForViewControllers(viewControllers: Vector.<ViewController>): void {
viewControllers.forEach(function (vc: ViewController, ...rest): void {
vc.setNavigationController(null);
});
}
//--------------------------------------------------------------------------
//
// Stack Navigator
//
//--------------------------------------------------------------------------
override protected function loadView(): DisplayObject {
var view:LayoutGroup = new LayoutGroup();
view.autoSizeMode = AutoSizeMode.STAGE;
view.layout = new AnchorLayout();
_navigator = new NavigationControllerStackScreenNavigator();
_navigator.layoutData = new AnchorLayoutData(0, 0, 0, 0);
view.addChild(_navigator);
_navigationBar = new NavigationBar();
_navigationBar.layoutData = new AnchorLayoutData(safeArea.top, 0, NaN, 0);
_navigationBar.onBack = navigationBarOnBack;
view.addChild(_navigationBar);
_toolbar = new Toolbar();
_toolbar.layoutData = new AnchorLayoutData(NaN, 0, 0, 0);
_toolbar.height += safeArea.bottom;
_toolbar.visible = _toolbar.includeInLayout = !_isToolbarHidden;
view.addChild(_toolbar);
if (_proposedViewControllers) {
doSetViewControllers(_proposedViewControllers, false);
_proposedViewControllers = null;
}
return view;
}
private var _navigator:StackScreenNavigator;
public function get navigator(): StackScreenNavigator {
return _navigator;
}
//--------------------------------------------------------------------------
//
// NavigatorBar
//
//--------------------------------------------------------------------------
private var _navigationBar: NavigationBar;
public function get navigationBar(): NavigationBar {
loadViewIfRequired();
return _navigationBar;
}
private function navigationBarOnBack(): void {
popViewController(true);
}
private function navigationItemsFromViewControllers(viewControllers: Vector.<ViewController>): Vector.<NavigationItem> {
var items: Vector.<NavigationItem> = new <NavigationItem>[];
viewControllers.forEach(function (vc: ViewController, index: int, vector:*):void {
items[items.length] = vc.navigationItem;
});
return items;
}
public function getTopGuide():Number {
if (navigationBar != null) {
return navigationBar.height;
} else {
return 0;
}
}
private function resetNavigationBar(): void {
_navigationBar.resetAppearanceToDefault();
}
private var _isNavigationBarHidden: Boolean = false;
public function get isNavigationBarHidden(): Boolean {
return _isNavigationBarHidden;
}
public function set isNavigationBarHidden(value: Boolean): void {
setNavigationBarHidden(value, false);
}
public function setNavigationBarHidden(hidden: Boolean, animated: Boolean): void {
if (hidden == _isNavigationBarHidden) {
return;
}
_isNavigationBarHidden = hidden;
if (animated) {
Starling.current.juggler.tween(_navigationBar, 0.3, {alpha: hidden ? 0.0 : 1.0});
} else {
_navigationBar.alpha = hidden ? 0.0 : 1.0;
}
}
//--------------------------------------------------------------------------
//
// Toolbar
//
//--------------------------------------------------------------------------
private var _toolbar:Toolbar;
public function get toolbar(): Toolbar {
return _toolbar;
}
private var _isToolbarHidden: Boolean = true;
public function get isToolbarHidden(): Boolean {
return _isToolbarHidden;
}
public function set isToolbarHidden(value: Boolean): void {
setToolbarHidden(value, false);
}
public function setToolbarHidden(hidden: Boolean, animated: Boolean): void {
_isToolbarHidden = hidden;
if (_toolbar != null) {
_toolbar.visible = _toolbar.includeInLayout = !_isToolbarHidden;
}
}
public function getBottomGuide():Number {
if (toolbar != null && !isToolbarHidden) {
return toolbar.height;
} else {
return 0;
}
}
//--------------------------------------------------------------------------
//
// Root
//
//--------------------------------------------------------------------------
override protected function cleanRootView(): void {
if (_root != null) {
_root.removeChild(this.view);
}
}
override protected function setupRootView(): void {
if (_root == null) {
throw new Error("[mvvc] root must be set.");
}
_root.addChild(this.view);
}
//--------------------------------------------------------------------------
//
// Utils
//
//--------------------------------------------------------------------------
protected function idsForViewControllers(viewControllers: Vector.<ViewController>): Vector.<String> {
var ids: Vector.<String> = new <String>[];
viewControllers.forEach(function (vc: ViewController, ...rest): void {
ids.push(vc.identifier);
});
return ids;
}
protected function screensForViewControllers(viewControllers: Vector.<ViewController>): Vector.<StackScreenNavigatorItem> {
var screens: Vector.<StackScreenNavigatorItem> = new <StackScreenNavigatorItem>[];
viewControllers.forEach(function (vc: ViewController, ...rest): void {
screens.push(new ViewControllerStackScreenNavigatorItem(vc));
});
return screens;
}
//--------------------------------------------------------------------------
//
// Description
//
//--------------------------------------------------------------------------
override public function toString(): String {
return "[NavigationController("+identifier+")]";
}
}
}
|
/*
* 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{
import Box2D.Collision.*;
import Box2D.Collision.Shapes.*;
import Box2D.Dynamics.Contacts.*;
import Box2D.Dynamics.Joints.*;
import Box2D.Common.Math.*;
import Box2D.Common.*;
/// Joints and shapes are destroyed when their associated
/// body is destroyed. Implement this listener so that you
/// may nullify references to these joints and shapes.
public class b2DestructionListener
{
/// Called when any joint is about to be destroyed due
/// to the destruction of one of its attached bodies.
public virtual function SayGoodbyeJoint(joint:b2Joint) : void{};
/// Called when any shape is about to be destroyed due
/// to the destruction of its parent body.
public virtual function SayGoodbyeShape(shape:b2Shape) : void{};
};
}
|
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.net
{
public class MimeTypeMap
{
private var types:Array =
[["application/andrew-inset","ez"],
["application/atom+xml","atom"],
["application/mac-binhex40","hqx"],
["application/mac-compactpro","cpt"],
["application/mathml+xml","mathml"],
["application/msword","doc"],
["application/octet-stream","bin","dms","lha","lzh","exe","class","so","dll","dmg"],
["application/oda","oda"],
["application/ogg","ogg"],
["application/pdf","pdf"],
["application/postscript","ai","eps","ps"],
["application/rdf+xml","rdf"],
["application/smil","smi","smil"],
["application/srgs","gram"],
["application/srgs+xml","grxml"],
["application/vnd.adobe.apollo-application-installer-package+zip","air"],
["application/vnd.mif","mif"],
["application/vnd.mozilla.xul+xml","xul"],
["application/vnd.ms-excel","xls"],
["application/vnd.ms-powerpoint","ppt"],
["application/vnd.rn-realmedia","rm"],
["application/vnd.wap.wbxml","wbxml"],
["application/vnd.wap.wmlc","wmlc"],
["application/vnd.wap.wmlscriptc","wmlsc"],
["application/voicexml+xml","vxml"],
["application/x-bcpio","bcpio"],
["application/x-cdlink","vcd"],
["application/x-chess-pgn","pgn"],
["application/x-cpio","cpio"],
["application/x-csh","csh"],
["application/x-director","dcr","dir","dxr"],
["application/x-dvi","dvi"],
["application/x-futuresplash","spl"],
["application/x-gtar","gtar"],
["application/x-hdf","hdf"],
["application/x-javascript","js"],
["application/x-koan","skp","skd","skt","skm"],
["application/x-latex","latex"],
["application/x-netcdf","nc","cdf"],
["application/x-sh","sh"],
["application/x-shar","shar"],
["application/x-shockwave-flash","swf"],
["application/x-stuffit","sit"],
["application/x-sv4cpio","sv4cpio"],
["application/x-sv4crc","sv4crc"],
["application/x-tar","tar"],
["application/x-tcl","tcl"],
["application/x-tex","tex"],
["application/x-texinfo","texinfo","texi"],
["application/x-troff","t","tr","roff"],
["application/x-troff-man","man"],
["application/x-troff-me","me"],
["application/x-troff-ms","ms"],
["application/x-ustar","ustar"],
["application/x-wais-source","src"],
["application/xhtml+xml","xhtml","xht"],
["application/xml","xml","xsl"],
["application/xml-dtd","dtd"],
["application/xslt+xml","xslt"],
["application/zip","zip"],
["audio/basic","au","snd"],
["audio/midi","mid","midi","kar"],
["audio/mpeg","mp3","mpga","mp2"],
["audio/x-aiff","aif","aiff","aifc"],
["audio/x-mpegurl","m3u"],
["audio/x-pn-realaudio","ram","ra"],
["audio/x-wav","wav"],
["chemical/x-pdb","pdb"],
["chemical/x-xyz","xyz"],
["image/bmp","bmp"],
["image/cgm","cgm"],
["image/gif","gif"],
["image/ief","ief"],
["image/jpeg","jpg","jpeg","jpe"],
["image/png","png"],
["image/svg+xml","svg"],
["image/tiff","tiff","tif"],
["image/vnd.djvu","djvu","djv"],
["image/vnd.wap.wbmp","wbmp"],
["image/x-cmu-raster","ras"],
["image/x-icon","ico"],
["image/x-portable-anymap","pnm"],
["image/x-portable-bitmap","pbm"],
["image/x-portable-graymap","pgm"],
["image/x-portable-pixmap","ppm"],
["image/x-rgb","rgb"],
["image/x-xbitmap","xbm"],
["image/x-xpixmap","xpm"],
["image/x-xwindowdump","xwd"],
["model/iges","igs","iges"],
["model/mesh","msh","mesh","silo"],
["model/vrml","wrl","vrml"],
["text/calendar","ics","ifb"],
["text/css","css"],
["text/html","html","htm"],
["text/plain","txt","asc"],
["text/richtext","rtx"],
["text/rtf","rtf"],
["text/sgml","sgml","sgm"],
["text/tab-separated-values","tsv"],
["text/vnd.wap.wml","wml"],
["text/vnd.wap.wmlscript","wmls"],
["text/x-setext","etx"],
["video/3gpp","3gpp","3gp"],
["video/3gpp2","3gpp2","3g2"],
["video/animaflex","afl"],
["video/avs-video","avs"],
["video/dl","dl"],
["video/fli","fli"],
["video/gl","gl"],
["video/mp4","mp4","m4p","m4v"],
["video/mpeg","m1v","m2v","mpe","mpeg","mpg"],
["video/ogg","ogv","ogx","ogg","spx"],
["video/quicktime","moov","mov","qt"],
["video/vdo","vdo"],
["video/vivo","viv","vivo"],
["video/vnd.mpegurl","m4u","mxu"],
["video/vnd.rn-realvideo","rv"],
["video/vosaic","vos"],
["video/webm","webm","vp8"],
["video/x-amt-demorun","xdr"],
["video/x-amt-showrun","xsr"],
["video/x-atomic3d-feature","fmf"],
["video/x-dv","dif","dv"],
["video/x-flv","flv","f4v","f4p"],
["video/x-isvideo","isu"],
["video/x-motion-jpeg","mjpg"],
["video/x-ms-wmv","wmv"],
["video/x-ms-asf","asf","asx"],
["video/x-msvideo","avi"],
["video/x-mxf","mxf"],
["video/x-qtc","qtc"],
["video/x-scm","scm"],
["video/x-sgi-movie","movie","mv"],
["video/x-vp6","vp6"],
["x-conference/x-cooltalk","ice"]
];
/**
* Returns the mimetype for the given extension.
*/
public function getMimeType(extension:String):String
{
extension = extension.toLocaleLowerCase();
for each (var a:Array in types)
{
for each (var b:String in a)
{
if (b == extension)
{
return a[0];
}
}
}
return null;
}
/**
* Returns the prefered extension for the given mimetype.
*/
public function getExtension(mimetype:String):String
{
mimetype = mimetype.toLocaleLowerCase();
for each (var a:Array in types)
{
if (a[0] == mimetype)
{
return a[1];
}
}
return null;
}
/**
* Adds a mimetype to the map. The order of the extensions matters. The most preferred should come first.
*/
public function addMimeType(mimetype:String, extensions:Array):void
{
var newType:Array = [mimetype];
for each (var a:String in extensions)
{
newType.push(a);
}
types.push(newType);
}
}
} |
// =================================================================================================
//
// Starling Framework
// Copyright Gamua GmbH. 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
{
import starling.animation.Juggler;
import starling.display.Sprite;
import starling.utils.AssetManager;
public class Recipe extends Sprite
{
private var _description:String;
private var _juggler:Juggler;
public function Recipe(description:String)
{
_description = description;
_juggler = new Juggler();
}
public function advanceTime(passedTime:Number):void
{
_juggler.advanceTime(passedTime);
}
public function get description():String { return _description; }
protected function get juggler():Juggler { return _juggler; }
protected function get assets():AssetManager { return Root.assets; }
}
}
|
/**
* Copyright (c) Michael Baczynski 2007
* http://lab.polygonal.de/ds/
*
* This software is distributed under licence. Use of this software
* implies agreement with all terms and conditions of the accompanying
* software licence.
*/
package de.polygonal.ds
{
/**
* All objects you want to insert into a PriorityQueue have to extend this class.
*
* <p>I could have defined this as an interface, but this would
* force me to write functions to just get or set the priority value.</p>
*/
public class Prioritizable
{
public var priority:int;
public function Prioritizable()
{
priority = -1;
}
public function toString():String
{
return "[Prioritizable, priority=" + priority + "]";
}
}
} |
////////////////////////////////////////////////////////////////////////////////
//
// 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.core
{
import flash.text.engine.FontLookup;
import flash.text.engine.Kerning;
import flashx.textLayout.formats.TextLayoutFormat;
import flashx.textLayout.property.Property;
import flashx.textLayout.tlf_internal;
import mx.core.mx_internal;
import mx.styles.IStyleClient;
[ExcludeClass]
/**
* @private
* This class is used by components such as RichText
* and RichEditableText which use TLF to display their text.
* The default formatting for their text is determined
* by the component's CSS styles.
*
* TLF recognizes the copy that is done in this constructor and does not
* do another one. If TLF adds formats to TextLayoutFormats this should
* continue to work as long as Flex doesn't want some alterate behavior.
*
* The only extra functionality supported here, beyond what TLF has,
* is the ability for the fontLookup style to have the value "auto";
* in this case, the client object's embeddedFontContext is used
* to determine whether the the fontLookup format in TLF should be
* "embeddedCFF" or "device".
*/
public class CSSTextLayoutFormat extends TextLayoutFormat
{
include "../core/Version.as";
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* @private
* Constructor
*/
public function CSSTextLayoutFormat(client:IStyleClient)
{
super();
for each (var prop:Property in TextLayoutFormat.tlf_internal::description)
{
const propName:String = prop.name;
if (propName == "fontLookup")
{
this[propName] = convertedFontLookup(client);
}
else if (propName == "kerning")
{
this[propName] = convertedKerning(client);
}
else
{
const value:* = client.getStyle(propName);
if (value !== undefined)
this[propName] = value;
}
}
}
/**
* @private
*/
private static function convertedFontLookup(client:IStyleClient):*
{
var value:String = client.getStyle("fontLookup");
// Special processing of the "auto" value is required,
// because this value has meaning only in Flex, not in TLF.
// It tells Flex to use its EmbeddedFontRegistry to determine
// whether the font is embedded or not.
if (value == "auto")
{
if (client.mx_internal::embeddedFontContext)
value = FontLookup.EMBEDDED_CFF;
else
value = FontLookup.DEVICE;
}
return value;
}
/**
* @private
*/
private static function convertedKerning(client:IStyleClient):*
{
var kerning:Object = client.getStyle("kerning");
// In Halo components based on TextField,
// kerning is supposed to be true or false.
// The default in TextField and Flex 3 is false
// because kerning doesn't work for device fonts
// and is slow for embedded fonts.
// In Spark components based on TLF and FTE,
// kerning is "auto", "on", or, "off".
// The default in TLF and FTE is "auto"
// (which means kern non-Asian characters)
// because kerning works even on device fonts
// and has miminal performance impact.
// Since a CSS selector or parent container
// can affect both Halo and Spark components,
// we need to map true to "on" and false to "off"
// here and in Label.
// For Halo components, UITextField and UIFTETextField
// do the opposite mapping
// of "auto" and "on" to true and "off" to false.
// We also support a value of "default"
// (which we set in the global selector)
// to mean "auto" for Spark and false for Halo
// to get the recommended behavior in both sets of components.
if (kerning === "default")
kerning = Kerning.AUTO;
else if (kerning === true)
kerning = Kerning.ON;
else if (kerning === false)
kerning = Kerning.OFF;
return kerning;
}
}
}
|
package test.net.sfmultimedia.argonaut
{
import flash.text.TextField;
/**
* @author mtanenbaum
*/
public class TestSuperClass
{
public var aNumber:Number;
public var anInt:int;
public var aUint:uint;
public var aBoolean:Boolean;
public var aString:String;
public var anArray:Array;
public var aStar:*;
public var anObject:Object;
public var aComplexObject:TextField;
public const aConstant:String = "Phineas";
public var anEmptyObject:Object = {};
public var anEmptyArray:Array = [];
//Everything below this line shouldn't be serialized
[DontSerialize]
public var aNonserialized:String;
[DontSerialize]
public const aConstantSuppressed:String = "Creusa";
public static var aStaticVar:String;
public function aFunction():void{};
}
}
|
package com.company.assembleegameclient.map.partyoverlay {
import com.company.assembleegameclient.map.Camera;
import com.company.assembleegameclient.map.Map;
import com.company.assembleegameclient.map.Quest;
import com.company.assembleegameclient.objects.GameObject;
import com.company.assembleegameclient.parameters.Parameters;
import com.company.assembleegameclient.ui.tooltip.PortraitToolTip;
import com.company.assembleegameclient.ui.tooltip.QuestToolTip;
import com.company.assembleegameclient.ui.tooltip.ToolTip;
import flash.events.MouseEvent;
import flash.utils.getTimer;
public class QuestArrow extends GameObjectArrow {
public var map_:Map;
public function QuestArrow(_arg1:Map) {
super(16352321, 12919330, true);
this.map_ = _arg1;
}
public function refreshToolTip():void {
setToolTip(this.getToolTip(go_, getTimer()));
}
override protected function onMouseOver(_arg1:MouseEvent):void {
super.onMouseOver(_arg1);
this.refreshToolTip();
}
override protected function onMouseOut(_arg1:MouseEvent):void {
super.onMouseOut(_arg1);
this.refreshToolTip();
}
private function getToolTip(_arg1:GameObject, _arg2:int):ToolTip {
if ((((_arg1 == null)) || ((_arg1.texture_ == null)))) {
return (null);
}
if (this.shouldShowFullQuest(_arg2)) {
return (new QuestToolTip(go_));
}
if (Parameters.data_.showQuestPortraits) {
return (new PortraitToolTip(_arg1));
}
return (null);
}
private function shouldShowFullQuest(_arg1:int):Boolean {
var _local2:Quest = this.map_.quest_;
return (((mouseOver_) || (_local2.isNew(_arg1))));
}
override public function draw(_arg1:int, _arg2:Camera):void {
var _local4:Boolean;
var _local5:Boolean;
var _local3:GameObject = this.map_.quest_.getObject(_arg1);
if (_local3 != go_) {
setGameObject(_local3);
setToolTip(this.getToolTip(_local3, _arg1));
}
else {
if (go_ != null) {
_local4 = (tooltip_ is QuestToolTip);
_local5 = this.shouldShowFullQuest(_arg1);
if (_local4 != _local5) {
setToolTip(this.getToolTip(_local3, _arg1));
}
}
}
super.draw(_arg1, _arg2);
}
}
}
|
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.display.Sprite;
import flash.utils.getTimer;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.net.SharedObject;
import flash.net.URLRequest;
import flash.net.navigateToURL;
import com.greensock.TweenMax;
public class Main extends MovieClip {
private const YOUR_SITE:String = "http://activeden.net/user/duquekarl?ref=duquekarl";
private const TIME_WALK:Number = 0.1;
private const TIME_PUSH:Number = 0.5;
private var TIME_MOV:Number = 0.5;
private const g:int = 1; // grass
private const T:int = 16; // Tree (block)
private const P:int = 32; // Player
private const L:int = 64; // Light (goal position)
private const I:int = 128; // Idol (box)
private const LI:int = L+I;
private const LP:int = L+P;
private const ROWS:int = 10;
private const COLS:int = 10;
private const TILE_W:int = 50;
private const TILE_H:int = 41;
private const LEVELS:Array = [
// Level 1
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, T, T, T, T, 0, 0, 0,
0, 0, T, g, g, g, g, T, 0, 0,
0, 0, T, g, g, L, g, T, 0, 0,
0, 0, T, g, I, P, g, T, 0, 0,
0, 0, T, g, T, g, g, T, 0, 0,
0, 0, 0, T, T, T, T, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
// Level 2
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, T, T, T, T, T, T, T, 0,
0, 0, T, g, g, g, g, g, T, 0,
0, 0, T, g, L, I, T, g, T, 0,
0, 0, T, g,LI,LI, P, g, T, 0,
0, 0, T, g, g, g, g, g, T, 0,
0, 0, T, T, T, T, T, T, T, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
// Level 3
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, T, T, T, T, T, T, T, T, 0,
0, T, g, g, g, g, g, g, T, 0,
0, T, g, L,LI,LI, I, P, T, 0,
0, T, g, g, g, g, g, g, T, 0,
0, T, T, T, T, T, g, g, T, 0,
0, 0, 0, 0, 0, T, T, T, T, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
// Level 4
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, T, T, T, T, T, T, T, 0,
0, 0, T, g, g, g, g, g, T, 0,
0, 0, T, g, L, I, L, g, T, 0,
0, T, T, g, I, P, I, g, T, 0,
0, T, g, g, L, I, L, g, T, 0,
0, T, g, g, g, g, g, g, T, 0,
0, T, T, T, T, T, T, T, T, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
// Level 5
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, T, T, T, T, 0, 0, 0, 0,
0, 0, T, g, L, T, 0, 0, 0, 0,
0, 0, T, g, g, T, T, T, 0, 0,
0, 0, T,LI, P, g, g, T, 0, 0,
0, 0, T, g, g, I, g, T, 0, 0,
0, 0, T, g, g, T, T, T, 0, 0,
0, 0, T, T, T, T, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
// Level 6
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, T, T, T, T, 0, 0, 0, 0,
T, T, T, g, g, T, T, T, T, 0,
T, g, g, g, g, g, I, g, T, 0,
T, g, T, g, g, T, I, g, T, 0,
T, g, L, g, L, T, P, g, T, 0,
T, T, T, T, T, T, T, T, T, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
// Level 7
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, T, T, T, T, T, T, T, 0,
0, 0, T, g, g, g, g, g, T, 0,
0, 0, T, g, L, I, L, g, T, 0,
0, 0, T, g, I, L, I, g, T, 0,
0, 0, T, g, L, I, L, g, T, 0,
0, 0, T, g, I, L, I, g, T, 0,
0, 0, T, g, g, P, g, g, T, 0,
0, 0, T, T, T, T, T, T, T, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
// Level 8
[0, 0, 0, T, T, T, T, T, T, 0,
0, 0, 0, T, g, L, L, P, T, 0,
0, 0, 0, T, g, I, I, g, T, 0,
0, 0, 0, T, T, g, T, T, T, 0,
0, T, T, T, T, g, T, 0, 0, 0,
0, T, g, g, g, g, T, T, T, 0,
0, T, g, T, g, g, g, g, T, 0,
0, T, g, g, g, g, T, g, T, 0,
0, T, T, T, g, g, g, g, T, 0,
0, 0, 0, T, T, T, T, T, T, 0],
// Level 9
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, T, T, T, T, T, 0, 0, 0,
0, 0, T, L, g, g, T, T, 0, 0,
0, 0, T, P, I, I, g, T, 0, 0,
0, 0, T, T, g, g, g, T, 0, 0,
0, 0, 0, T, T, g, g, T, 0, 0,
0, 0, 0, 0, T, T, L, T, 0, 0,
0, 0, 0, 0, 0, T, T, T, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
// Level 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, T, T, T, T, T, T, 0,
0, 0, 0, T, g, g, g, g, T, 0,
0, 0, 0, T, g, T, T, P, T, 0,
0, T, T, T, g, T, g, I, T, T,
0, T, g, L, L, T, g, I, g, T,
0, T, g, g, g, g, g, g, g, T,
0, T, g, g, T, T, T, T, T, 0,
0, T, T, T, T, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
// Level 11
[0, 0, T, T, T, T, 0, 0, 0, 0,
0, 0, T, L, g, T, T, 0, 0, 0,
0, 0, T, L, P, g, T, 0, 0, 0,
0, 0, T, L, g, I, T, 0, 0, 0,
0, 0, T, T, I, g, T, T, T, 0,
0, 0, 0, T, g, I, g, g, T, 0,
0, 0, 0, T, g, g, g, g, T, 0,
0, 0, 0, T, g, g, T, T, T, 0,
0, 0, 0, T, g, g, T, 0, 0, 0,
0, 0, 0, T, T, T, T, 0, 0, 0],
// Level 12
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, T, T, T, T, T, 0, 0, 0, 0,
0, T, g, g, g, T, T, 0, 0, 0,
0, T, g, I, g, g, T, 0, 0, 0,
0, T, T, g, I, g, T, T, T, T,
0, 0, T, T, T, P, L, g, g, T,
0, 0, T, g, g, g, L, T, g, T,
0, 0, T, g, g, g, g, g, g, T,
0, 0, T, T, T, T, T, T, T, T,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
// Level 13
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, T, T, T, T, T, T, T, 0,
0, 0, T, g, g, g, g, g, T, 0,
0, 0, T, g, T, g, T, g, T, 0,
0, 0, T, L, g, I,LI, P, T, 0,
0, 0, T, g, g, g, T, T, T, 0,
0, 0, T, T, T, T, T, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
// Level 14
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, T, T, T, T, T, 0, 0, 0, 0,
0, T, g, g, g, T, T, T, T, 0,
0, T, g, g, g, g, g, g, T, 0,
T, T, g, T, T, g, g, g, T, 0,
T, L, g, L, T, g, P, I, T, T,
T, g, g, g, T, g, I, I, g, T,
T, g, g, L, T, g, g, g, g, T,
T, T, T, T, T, T, T, T, T, T,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
// Level 15
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, T, T, T, T, T, 0, 0, 0,
0, 0, T, g, P, g, T, 0, 0, 0,
0, 0, T, L, L, L, T, 0, 0, 0,
0, 0, T, I, I, I, T, T, 0, 0,
0, 0, T, g, g, g, g, T, 0, 0,
0, 0, T, g, g, g, g, T, 0, 0,
0, 0, T, T, T, T, T, T, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
// Level 16
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, T, T, T, T, T, T, T, 0,
0, 0, T, g, g, g, g, g, T, 0,
0, 0, T, L, g, L, g, g, T, 0,
0, 0, T, g, T, T, g, T, T, 0,
0, 0, T, g, g, I, g, T, 0, 0,
0, 0, T, T, T, I, g, T, 0, 0,
0, 0, 0, 0, T, P, g, T, 0, 0,
0, 0, 0, 0, T, g, g, T, 0, 0,
0, 0, 0, 0, T, T, T, T, 0, 0],
// Level 17
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, T, T, T, T, T, T, T, T, 0,
0, T, g, g, g, L, L, g, T, 0,
0, T, g, g, P, I, I, g, T, 0,
0, T, T, T, T, T, g, T, T, 0,
0, 0, 0, 0, T, g, g, T, 0, 0,
0, 0, 0, 0, T, g, g, T, 0, 0,
0, 0, 0, 0, T, g, g, T, 0, 0,
0, 0, 0, 0, T, g, g, T, 0, 0,
0, 0, 0, 0, T, T, T, T, 0, 0],
// Level 18
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, T, T, T, T, 0, 0, 0, 0,
0, 0, T, g, g, T, T, T, T, 0,
0, 0, T, g, L, g, L, g, T, 0,
0, 0, T, g, I, I, T, P, T, 0,
0, 0, T, T, g, g, g, g, T, 0,
0, 0, 0, T, T, T, T, T, T, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
// Level 19
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, T, T, T, T, T, 0, 0, 0,
0, 0, T, g, g, g, T, T, T, 0,
0, 0, T, L, g, L, g, g, T, 0,
0, 0, T, g, g, g, T, g, T, 0,
0, 0, T, T, g, T, g, g, T, 0,
0, 0, 0, T, P, I, I, g, T, 0,
0, 0, 0, T, g, g, g, g, T, 0,
0, 0, 0, T, g, g, T, T, T, 0,
0, 0, 0, T, T, T, T, 0, 0, 0],
// Level 20
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, T, T, T, T, T, T, 0, 0,
0, 0, T, g, g, g, L, T, 0, 0,
0, 0, T, g, T, T, g, T, T, 0,
0, 0, T, g, g, I, I, P, T, 0,
0, 0, T, g, T, g, g, g, T, 0,
0, 0, T, L, g, g, T, T, T, 0,
0, 0, T, T, T, T, T, T, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
// Level 21
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, T, T, T, T, T, 0, 0, 0,
0, 0, T, g, g, g, T, 0, 0, 0,
0, 0, T, g, P, g, T, 0, 0, 0,
0, 0, T, g, I, I, T, T, T, 0,
0, 0, T, T, L, g, L, g, T, 0,
0, 0, 0, T, g, g, g, g, T, 0,
0, 0, 0, T, T, T, T, T, T, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
];
private const TOTAL_LEVELS:int = LEVELS.length;
private var instructions:instructions_mc = new instructions_mc();
private var winScreen:win_screen_mc = new win_screen_mc();
private var tilesContainer:Sprite;
private var player:player_mc = new player_mc();
private var currentLevel:Array = [];
private var level:int = 1; //TOTAL_LEVELS; //1;
private var lightsLevel:int = 0;
private var lightsCompleted:int = 0;
private var startTime:int;
private var oldTime:int;
private var keyPressed:Object = {};
private var moves:int;
private var movingPlayer:Boolean = false;
private var savedGame:SharedObject;
private var fileSaved:String = "magic_idols";
//[F001] Main
public function Main() {
// constructor code
loadGames();
showInstructions();
prepareGameButtons();
}
//[F002] Load saved games
private function loadGames():void {
savedGame = SharedObject.getLocal(fileSaved);
if (savedGame.data.level) {
// Load Data
level = savedGame.data.level;
}
savedGame.close();
}
//[F003] Save game progress
private function saveGame():void {
savedGame = SharedObject.getLocal(fileSaved);
// Save Data
savedGame.data.level = level;
savedGame.close();
}
//[F004] Show Instructions
private function showInstructions():void {
addChild(instructions);
instructions.buttonMode = true;
instructions.mouseChildren = false;
instructions.addEventListener(MouseEvent.CLICK, removeInstructions);
}
//[F005] Remove Instructions
private function removeInstructions(e:MouseEvent):void {
removeChild(instructions);
prepareGame();
}
//[F006] Prepare Game Buttons
private function prepareGameButtons():void {
game.restart.buttonMode = true;
game.restart.mouseChildren = false;
game.your_logo.buttonMode = true;
game.restart.addEventListener(MouseEvent.CLICK, restartLevel);
game.your_logo.addEventListener(MouseEvent.CLICK, onClickLogo);
}
//[F007] Click on Logo -> opens an HTML link on a new tab
private function onClickLogo(e:MouseEvent) {
var url:URLRequest = new URLRequest( YOUR_SITE );
navigateToURL(url, "_blank");
}
//[F008] Prepare Game
private function prepareGame():void {
game.txt_level.text = "LEVEL: ".concat(level);
game.txt_lights.text = "0/0";
game.txt_moves.text = "MOVES: 0";
game.txt_time.text = "TIME: 0";
lightsLevel = 0;
lightsCompleted = 0;
oldTime = 0;
moves = 0;
loadLevel();
startGame();
}
//[F009] Load Level Tiles
private function loadLevel():void {
tilesContainer = new Sprite();
addChildAt(tilesContainer, numChildren-1);
var isLight:Boolean;
// Create all the tiles
for (var i:int = 0; i < ROWS; i++) {
for (var j:int = 0; j < COLS; j++) {
currentLevel[i*COLS + j] = 0;
switch (LEVELS[level - 1][i*COLS + j]) {
case 0:
break;
case L: // Goal position (light)
currentLevel[i*COLS + j] = g;
isLight = true;
addTile(new tile_mc(), i, j, isLight);
break;
case T: // BLOCKING tile (trees, water)
currentLevel[i*COLS + j] = T;
addTile(new tile_mc(), i, j);
addTile(new tree_mc(), i, j);
break;
case I: // IDOL
currentLevel[i*COLS + j] = g;
addTile(new tile_mc(), i, j);
addTile(new idol_mc(), i, j);
break;
case LI: // Light+Idol
currentLevel[i*COLS + j] = g;
isLight = true;
addTile(new tile_mc(), i, j, isLight);
addTile(new idol_mc(), i, j, isLight);
break;
//case 0: tile.gotoAndStop(3);
case g: // Walkable (grass)
currentLevel[i*COLS + j] = g;
addTile(new tile_mc(), i, j);
break;
case P: // Player start position (is walkable)
currentLevel[i*COLS + j] = g;
addTile(new tile_mc(), i, j);
addPlayer(i, j);
break;
default: break;
}
}
}
// Align to center of the screen
tilesContainer.x = (stage.stageWidth - TILE_W*COLS)*0.5 + TILE_W*0.5;
tilesContainer.y = (stage.stageHeight - TILE_H*ROWS)*0.5 + TILE_H*0.5;
// Init Lights text
game.txt_lights.text = "".concat(lightsCompleted).concat("/").concat(lightsLevel);
}
//[F010] Add a level tile
private function addTile(tile:MovieClip, i:int, j:int, isLight:Boolean = false):void {
// Choose the different themes: forest - brown - sea
tile.gotoAndStop(1);
if (level >= 14) {
tile.gotoAndStop(3);
} else if (level >= 7) {
tile.gotoAndStop(2);
}
tile.width = TILE_W;
if (tile is tree_mc && tile.currentFrame != 3) {
tile.width *= 0.75;
// Chest
} else if (tile is idol_mc) {
tile.width *= 0.8;
tile.i = i;
tile.j = j;
tile.name = "idol_" + i + "_" + j;
tile.onLight = isLight;
tile.eyes.visible = isLight;
if (isLight) {
lightsCompleted++;
}
// Floor tile (may be Light)
} else if (tile is tile_mc) {
tile.isLight.visible = isLight;
tile.name = i + "_" + j;
if (isLight) {
lightsLevel++;
}
}
tile.scaleY = tile.scaleX;
tile.x = 0 + j*TILE_W;
tile.y = 0 + i*TILE_H;
tilesContainer.addChild(tile);
}
//[F011] Create Player
private function addPlayer(i:int, j:int):void {
player.gotoAndStop(1);
player.width = TILE_W;
//player.width *= 0.8;
player.scaleY = player.scaleX;
player.x = 0 + j*TILE_W;
player.y = 0 + i*TILE_H;
player.j = j;
player.i = i;
tilesContainer.addChild(player);
}
//[F012] Starts the game
private function startGame():void {
startTime = getTimer();
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
addEventListener(Event.ENTER_FRAME, enterFrame);
}
//[F013] Reads keyboard presses
private function keyDown(e:KeyboardEvent) {
switch(e.keyCode) {
case Keyboard.LEFT:
walk(-1, 0);
keyPressed.left = true;
break;
case Keyboard.RIGHT:
walk(1, 0);
keyPressed.right = true;
break;
case Keyboard.UP:
walk(0, -1);
keyPressed.up = true;
break;
case Keyboard.DOWN:
walk(0, 1);
keyPressed.down = true;
break;
case Keyboard.R:
restartLevel();
break;
case Keyboard.N:
// Can't move more!
//stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDown);
//stage.removeEventListener(KeyboardEvent.KEY_UP, keyUp);
//winLevel();
break;
}
}
//[F014] Reads keys released
private function keyUp(e:KeyboardEvent) {
switch(e.keyCode) {
case Keyboard.LEFT:
keyPressed.left = ! true;
break;
case Keyboard.RIGHT:
keyPressed.right = ! true;
break;
case Keyboard.UP:
keyPressed.up = ! true;
break;
case Keyboard.DOWN:
keyPressed.down = ! true;
break;
}
}
//[F015] Enter Frame!
private function enterFrame(e:Event) {
stage.focus = stage;
var timeEllapsed:int = (getTimer() - startTime) * 0.001;
if (timeEllapsed > oldTime) {
oldTime = timeEllapsed;
game.txt_time.text = "TIME: ".concat( timeString(timeEllapsed) );
}
}
//[F016] Convert a time (in seconds) to a String (m:ss)
private function timeString(t:int):String {
// Seconds
const SEC_PER_MIN:int = 60;
if (t < SEC_PER_MIN) return t.toString();
// Min
var s:int = t % SEC_PER_MIN;
var m:int = t / SEC_PER_MIN;
var secString:String;
var minString:String;
if (s < 10) {
secString = "0".concat(s);
} else {
secString = s.toString();
}
minString = m.toString();
return minString.concat(":", secString);
}
//[F017] Make the player walk (if he is not moving already!)
private function walk(incX:int, incY:int):void {
if (movingPlayer) return;
var idol:idol_mc;
var row:int = player.i + incY;
var col:int = player.j + incX;
var newTile:int = getTile(row, col);
switch(newTile) {
case g:
idol = tilesContainer.getChildByName("idol_" + row + "_" + col) as idol_mc;
if (idol) {
pushIdol(incX, incY);
} else {
TIME_MOV = TIME_WALK;
movePlayerTo(incX, incY);
}
break;
}
// Look up/down
if (incY > 0) {
player.gotoAndStop(3); // walk up
player.scaleX *= (player.scaleX < 0 ? -1 : 1);
} else if (incY < 0) {
player.gotoAndStop(5);
player.scaleX *= (player.scaleX < 0 ? -1 : 1);
}
// Look left/right
if (incX > 0) {
player.gotoAndStop(1);
player.scaleX *= (player.scaleX < 0 ? 1 : -1);
} else if (incX < 0) {
player.gotoAndStop(1);
player.scaleX *= (player.scaleX < 0 ? -1 : 1);
}
}
//[F018] Gets the value of a tile
private function getTile(r:int, c:int):int {
return (currentLevel[r*COLS + c]);
}
//[F019] Moves Player To ...X,Y...
private function movePlayerTo(incX:int, incY:int):void {
movingPlayer = true;
var oldIndex:int = tilesContainer.getChildIndex( tilesContainer.getChildByName(player.i + "_" + player.j) as tile_mc );
player.i += incY;
player.j += incX;
var index:int = tilesContainer.getChildIndex( tilesContainer.getChildByName(player.i + "_" + player.j) as tile_mc );
var newPlayerX:int = 0 + player.j*TILE_W;
var newPlayerY:int = 0 + player.i*TILE_H;
tilesContainer.removeChild(player);
tilesContainer.addChildAt(player, Math.max(index+1, oldIndex+1) );
// Move smooth
TweenMax.to(player, TIME_MOV, {x:newPlayerX, y:newPlayerY, onComplete:finishMoving});
TweenMax.delayedCall(TIME_MOV, setIndex, [player, index+1]);
animWalk();
// Update moves
moves++;
game.txt_moves.text = "MOVES: ".concat(moves);
}
//[F020] Finished moving
private function finishMoving():void {
movingPlayer = false;
}
//[F021] Walk Animation
private function animWalk():void {
const TOTAL_WALK_FRAMES:int = 2;
const ANIMATION:int = (player.currentFrame - 1) / TOTAL_WALK_FRAMES; // Frames 1-2 are ANIMATION 0 (side), 3-4 are ANIMATION 1 (front), 5-6 are ANIMATION 2 (back)
const IDLE_FRAME:int = ANIMATION * TOTAL_WALK_FRAMES + 1; // Idle (ANIM0) = 1, Idle (anim1) = 3, Idle(anim2) = 5
var animFrame:int = player.currentFrame - IDLE_FRAME;
// If the current frame is 2, 4, 6 (walking animation),
// then set the player frame to the "Idle" frames 1, 3, 5
if (animFrame > 0) { // Player is animating
if (!movingPlayer) {
player.gotoAndStop( IDLE_FRAME );
return;
}
}
// The player is walking, animate him
animFrame = (animFrame + 1) % TOTAL_WALK_FRAMES;
player.gotoAndStop( IDLE_FRAME + animFrame );
TweenMax.to(this, 0.1, {onComplete:animWalk});
}
//[F022] Push an Idol
private function pushIdol(incX:int, incY:int):void {
var row:int = player.i + incY*2;
var col:int = player.j + incX*2;
var newTile:int = getTile(row, col);
if (newTile == g &&
! tilesContainer.getChildByName("idol_" + row + "_" + col) ) {
TIME_MOV = TIME_PUSH;
movePlayerTo(incX, incY);
moveChestTo(incX, incY);
}
}
//[F023] Move Chest To ..X,Y..
private function moveChestTo(incX:int, incY:int):void {
var idol:idol_mc = tilesContainer.getChildByName("idol_" + player.i + "_" + player.j) as idol_mc;
var oldTile:tile_mc = tilesContainer.getChildByName(idol.i + "_" + idol.j) as tile_mc;
var oldIndex:int = tilesContainer.getChildIndex( oldTile );
idol.i = player.i + incY;
idol.j = player.j + incX;
var newTile:tile_mc = tilesContainer.getChildByName(idol.i + "_" + idol.j) as tile_mc;
var index:int = tilesContainer.getChildIndex( newTile );
var newChestX:int = 0 + idol.j*TILE_W;
var newChestY:int = 0 + idol.i*TILE_H;
idol.name = "idol_" + idol.i + "_" + idol.j;
tilesContainer.removeChild(idol);
tilesContainer.addChildAt(idol, Math.max(index+1, oldIndex+1) );
// Move smooth
TweenMax.to(idol, TIME_MOV, {x:newChestX, y:newChestY, onComplete:checkWin, onCompleteParams:[idol]});
TweenMax.delayedCall(TIME_MOV, setIndex, [idol, index+1]);
}
//[F024] Changes the index of Tile
private function setIndex(obj:MovieClip, index:int):void {
tilesContainer.removeChild(obj);
tilesContainer.addChildAt(obj, index);
}
//[F025] Check if the last move of idol is: Win Level
private function checkWin(idol:idol_mc):void {
// New tile where the idol will land
var newTile:tile_mc = tilesContainer.getChildByName(idol.i + "_" + idol.j) as tile_mc;
if (idol.onLight) {
idol.onLight = false;
lightsCompleted--;
idol.eyes.visible = false;
}
if (newTile.isLight.visible) {
lightsCompleted++;
idol.onLight = true;
idol.eyes.visible = true;
}
// Show the number of lights
game.txt_lights.text = "".concat(lightsCompleted).concat("/").concat(lightsLevel);
// Win Level!!!
if (lightsCompleted == lightsLevel) {
// Can't move anymore!
stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDown);
stage.removeEventListener(KeyboardEvent.KEY_UP, keyUp);
player.gotoAndStop(7);
TweenMax.delayedCall(0.5, winLevel);
}
}
//[F026] You win!
private function winLevel():void {
// Remove old
removeEventListener(Event.ENTER_FRAME, enterFrame);
while (tilesContainer.numChildren > 0) {
tilesContainer.removeChildAt(0);
}
// Increment your level!
level++;
// Add the winning screen
var timeEllapsed:int = (getTimer() - startTime) * 0.001;
winScreen.win_text.txtMoves.text = moves;
winScreen.win_text.txtTime.text = "".concat( timeString(timeEllapsed) );
TweenMax.fromTo(winScreen, 1, {alpha:0}, {alpha:1, onComplete:addWinListeners});
winScreen.alpha = 0;
addChild(winScreen);
}
//[F027] If you click the WIN SCREEN, go to the Next Level
private function addWinListeners():void {
winScreen.addEventListener(MouseEvent.CLICK, nextLevel);
}
//[F028] Next Level: Save progress and prepare the game for the next level
private function nextLevel(e:MouseEvent):void {
winScreen.removeEventListener(MouseEvent.CLICK, nextLevel);
removeChild(winScreen);
if (level <= TOTAL_LEVELS) {
prepareGame();
// Save Progress
saveGame();
} else {
level = 1;
showInstructions();
}
}
//[F029] Restart Level
private function restartLevel(e:MouseEvent = null):void {
TweenMax.killAll();
movingPlayer = false;
// Remove old
stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDown);
stage.removeEventListener(KeyboardEvent.KEY_UP, keyUp);
removeEventListener(Event.ENTER_FRAME, enterFrame);
while (tilesContainer.numChildren > 0) {
tilesContainer.removeChildAt(0);
}
// Start the level (again)
prepareGame();
}
}
}
|
package kabam.rotmg.assets.EmbeddedAssets {
import mx.core.*;
[Embed(source="spritesheets/EmbeddedAssets_d3LofiObjBigEmbed_.png")]
public class EmbeddedAssets_d3LofiObjBigEmbed_ extends BitmapAsset {
public function EmbeddedAssets_d3LofiObjBigEmbed_() {
super();
return;
}
}
}
|
package cmodule.decry
{
import avm2.intrinsics.memory.li32;
import avm2.intrinsics.memory.si32;
public final class FSM___one_cmpldi2 extends Machine
{
public function FSM___one_cmpldi2()
{
super();
}
public static function start() : void
{
var _loc1_:int = 0;
var _loc2_:int = 0;
FSM___one_cmpldi2.esp = FSM___one_cmpldi2.esp - 4;
si32(FSM___one_cmpldi2.ebp,FSM___one_cmpldi2.esp);
FSM___one_cmpldi2.ebp = FSM___one_cmpldi2.esp;
FSM___one_cmpldi2.esp = FSM___one_cmpldi2.esp - 0;
_loc1_ = li32(FSM___one_cmpldi2.ebp + 8);
_loc2_ = li32(FSM___one_cmpldi2.ebp + 12);
_loc2_ = _loc2_ ^ -1;
_loc1_ = _loc1_ ^ -1;
FSM___one_cmpldi2.edx = _loc2_;
FSM___one_cmpldi2.eax = _loc1_;
FSM___one_cmpldi2.esp = FSM___one_cmpldi2.ebp;
FSM___one_cmpldi2.ebp = li32(FSM___one_cmpldi2.esp);
FSM___one_cmpldi2.esp = FSM___one_cmpldi2.esp + 4;
FSM___one_cmpldi2.esp = FSM___one_cmpldi2.esp + 4;
}
}
}
|
/*
* 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.Collision{
import Box2D.Common.Math.*;
import Box2D.Common.*;
import Box2D.Collision.Shapes.*;
import Box2D.Collision.*;
public class b2Distance
{
// GJK using Voronoi regions (Christer Ericson) and region selection
// optimizations (Casey Muratori).
// The origin is either in the region of points[1] or in the edge region. The origin is
// not in region of points[0] because that is the old point.
static public function ProcessTwo(x1:b2Vec2, x2:b2Vec2, p1s:Array, p2s:Array, points:Array):int
{
var points_0:b2Vec2 = points[0];
var points_1:b2Vec2 = points[1];
var p1s_0:b2Vec2 = p1s[0];
var p1s_1:b2Vec2 = p1s[1];
var p2s_0:b2Vec2 = p2s[0];
var p2s_1:b2Vec2 = p2s[1];
// If in point[1] region
//b2Vec2 r = -points[1];
var rX:Number = -points_1.x;
var rY:Number = -points_1.y;
//b2Vec2 d = points[1] - points[0];
var dX:Number = points_0.x - points_1.x;
var dY:Number = points_0.y - points_1.y;
//float32 length = d.Normalize();
var length:Number = Math.sqrt(dX*dX + dY*dY);
dX /= length;
dY /= length;
//float32 lambda = b2Dot(r, d);
var lambda:Number = rX * dX + rY * dY;
if (lambda <= 0.0 || length < Number.MIN_VALUE)
{
// The simplex is reduced to a point.
//*p1Out = p1s[1];
x1.SetV(p1s_1);
//*p2Out = p2s[1];
x2.SetV(p2s_1);
//p1s[0] = p1s[1];
p1s_0.SetV(p1s_1);
//p2s[0] = p2s[1];
p2s_0.SetV(p2s_1);
points_0.SetV(points_1);
return 1;
}
// Else in edge region
lambda /= length;
//*x1 = p1s[1] + lambda * (p1s[0] - p1s[1]);
x1.x = p1s_1.x + lambda * (p1s_0.x - p1s_1.x);
x1.y = p1s_1.y + lambda * (p1s_0.y - p1s_1.y);
//*x2 = p2s[1] + lambda * (p2s[0] - p2s[1]);
x2.x = p2s_1.x + lambda * (p2s_0.x - p2s_1.x);
x2.y = p2s_1.y + lambda * (p2s_0.y - p2s_1.y);
return 2;
}
// Possible regions:
// - points[2]
// - edge points[0]-points[2]
// - edge points[1]-points[2]
// - inside the triangle
static public function ProcessThree(x1:b2Vec2, x2:b2Vec2, p1s:Array, p2s:Array, points:Array):int
{
var points_0:b2Vec2 = points[0];
var points_1:b2Vec2 = points[1];
var points_2:b2Vec2 = points[2];
var p1s_0:b2Vec2 = p1s[0];
var p1s_1:b2Vec2 = p1s[1];
var p1s_2:b2Vec2 = p1s[2];
var p2s_0:b2Vec2 = p2s[0];
var p2s_1:b2Vec2 = p2s[1];
var p2s_2:b2Vec2 = p2s[2];
//b2Vec2 a = points[0];
var aX:Number = points_0.x;
var aY:Number = points_0.y;
//b2Vec2 b = points[1];
var bX:Number = points_1.x;
var bY:Number = points_1.y;
//b2Vec2 c = points[2];
var cX:Number = points_2.x;
var cY:Number = points_2.y;
//b2Vec2 ab = b - a;
var abX:Number = bX - aX;
var abY:Number = bY - aY;
//b2Vec2 ac = c - a;
var acX:Number = cX - aX;
var acY:Number = cY - aY;
//b2Vec2 bc = c - b;
var bcX:Number = cX - bX;
var bcY:Number = cY - bY;
//float32 sn = -b2Dot(a, ab), sd = b2Dot(b, ab);
var sn:Number = -(aX * abX + aY * abY);
var sd:Number = (bX * abX + bY * abY);
//float32 tn = -b2Dot(a, ac), td = b2Dot(c, ac);
var tn:Number = -(aX * acX + aY * acY);
var td:Number = (cX * acX + cY * acY);
//float32 un = -b2Dot(b, bc), ud = b2Dot(c, bc);
var un:Number = -(bX * bcX + bY * bcY);
var ud:Number = (cX * bcX + cY * bcY);
// In vertex c region?
if (td <= 0.0 && ud <= 0.0)
{
// Single point
//*x1 = p1s[2];
x1.SetV(p1s_2);
//*x2 = p2s[2];
x2.SetV(p2s_2);
//p1s[0] = p1s[2];
p1s_0.SetV(p1s_2);
//p2s[0] = p2s[2];
p2s_0.SetV(p2s_2);
points_0.SetV(points_2);
return 1;
}
// Should not be in vertex a or b region.
//b2Settings.b2Assert(sn > 0.0 || tn > 0.0);
//b2Settings.b2Assert(sd > 0.0 || un > 0.0);
//float32 n = b2Cross(ab, ac);
var n:Number = abX * acY - abY * acX;
// Should not be in edge ab region.
//float32 vc = n * b2Cross(a, b);
var vc:Number = n * (aX * bY - aY * bX);
//b2Settings.b2Assert(vc > 0.0 || sn > 0.0 || sd > 0.0);
var lambda:Number;
// In edge bc region?
//float32 va = n * b2Cross(b, c);
var va:Number = n * (bX * cY - bY * cX);
if (va <= 0.0 && un >= 0.0 && ud >= 0.0 && (un+ud) > 0.0)
{
//b2Settings.b2Assert(un + ud > 0.0);
//float32 lambda = un / (un + ud);
lambda = un / (un + ud);
//*x1 = p1s[1] + lambda * (p1s[2] - p1s[1]);
x1.x = p1s_1.x + lambda * (p1s_2.x - p1s_1.x);
x1.y = p1s_1.y + lambda * (p1s_2.y - p1s_1.y);
//*x2 = p2s[1] + lambda * (p2s[2] - p2s[1]);
x2.x = p2s_1.x + lambda * (p2s_2.x - p2s_1.x);
x2.y = p2s_1.y + lambda * (p2s_2.y - p2s_1.y);
//p1s[0] = p1s[2];
p1s_0.SetV(p1s_2);
//p2s[0] = p2s[2];
p2s_0.SetV(p2s_2);
//points[0] = points[2];
points_0.SetV(points_2);
return 2;
}
// In edge ac region?
//float32 vb = n * b2Cross(c, a);
var vb:Number = n * (cX * aY - cY * aX);
if (vb <= 0.0 && tn >= 0.0 && td >= 0.0 && (tn+td) > 0.0)
{
//b2Settings.b2Assert(tn + td > 0.0);
//float32 lambda = tn / (tn + td);
lambda = tn / (tn + td);
//*x1 = p1s[0] + lambda * (p1s[2] - p1s[0]);
x1.x = p1s_0.x + lambda * (p1s_2.x - p1s_0.x);
x1.y = p1s_0.y + lambda * (p1s_2.y - p1s_0.y);
//*x2 = p2s[0] + lambda * (p2s[2] - p2s[0]);
x2.x = p2s_0.x + lambda * (p2s_2.x - p2s_0.x);
x2.y = p2s_0.y + lambda * (p2s_2.y - p2s_0.y);
//p1s[1] = p1s[2];
p1s_1.SetV(p1s_2);
//p2s[1] = p2s[2];
p2s_1.SetV(p2s_2);
//points[1] = points[2];
points_1.SetV(points_2);
return 2;
}
// Inside the triangle, compute barycentric coordinates
//float32 denom = va + vb + vc;
var denom:Number = va + vb + vc;
//b2Settings.b2Assert(denom > 0.0);
denom = 1.0 / denom;
//float32 u = va * denom;
var u:Number = va * denom;
//float32 v = vb * denom;
var v:Number = vb * denom;
//float32 w = 1.0f - u - v;
var w:Number = 1.0 - u - v;
//*x1 = u * p1s[0] + v * p1s[1] + w * p1s[2];
x1.x = u * p1s_0.x + v * p1s_1.x + w * p1s_2.x;
x1.y = u * p1s_0.y + v * p1s_1.y + w * p1s_2.y;
//*x2 = u * p2s[0] + v * p2s[1] + w * p2s[2];
x2.x = u * p2s_0.x + v * p2s_1.x + w * p2s_2.x;
x2.y = u * p2s_0.y + v * p2s_1.y + w * p2s_2.y;
return 3;
}
static public function InPoints(w:b2Vec2, points:Array, pointCount:int):Boolean
{
const k_tolerance:Number = 100.0 * Number.MIN_VALUE;
for (var i:int = 0; i < pointCount; ++i)
{
var points_i:b2Vec2 = points[i];
//b2Vec2 d = b2Abs(w - points[i]);
var dX:Number = Math.abs(w.x - points_i.x);
var dY:Number = Math.abs(w.y - points_i.y);
//b2Vec2 m = b2Max(b2Abs(w), b2Abs(points[i]));
var mX:Number = Math.max(Math.abs(w.x), Math.abs(points_i.x));
var mY:Number = Math.max(Math.abs(w.y), Math.abs(points_i.y));
if (dX < k_tolerance * (mX + 1.0) &&
dY < k_tolerance * (mY + 1.0)){
return true;
}
}
return false;
}
//
static private var s_p1s:Array = [new b2Vec2(), new b2Vec2(), new b2Vec2()];
static private var s_p2s:Array = [new b2Vec2(), new b2Vec2(), new b2Vec2()];
static private var s_points:Array = [new b2Vec2(), new b2Vec2(), new b2Vec2()];
//
static public function DistanceGeneric(x1:b2Vec2, x2:b2Vec2,
shape1:*, xf1:b2XForm,
shape2:*, xf2:b2XForm):Number
{
var tVec: b2Vec2;
//b2Vec2 p1s[3], p2s[3];
var p1s:Array = s_p1s;
var p2s:Array = s_p2s;
//b2Vec2 points[3];
var points:Array = s_points;
//int32 pointCount = 0;
var pointCount:int = 0;
//*x1 = shape1->GetFirstVertex(xf1);
x1.SetV(shape1.GetFirstVertex(xf1));
//*x2 = shape2->GetFirstVertex(xf2);
x2.SetV(shape2.GetFirstVertex(xf2));
var vSqr:Number = 0.0;
const maxIterations:int = 20;
for (var iter:int = 0; iter < maxIterations; ++iter)
{
//b2Vec2 v = *x2 - *x1;
var vX:Number = x2.x - x1.x;
var vY:Number = x2.y - x1.y;
//b2Vec2 w1 = shape1->Support(xf1, v);
var w1:b2Vec2 = shape1.Support(xf1, vX, vY);
//b2Vec2 w2 = shape2->Support(xf2, -v);
var w2:b2Vec2 = shape2.Support(xf2, -vX, -vY);
//float32 vSqr = b2Dot(v, v);
vSqr = (vX*vX + vY*vY);
//b2Vec2 w = w2 - w1;
var wX:Number = w2.x - w1.x;
var wY:Number = w2.y - w1.y;
//float32 vw = b2Dot(v, w);
var vw:Number = (vX*wX + vY*wY);
//if (vSqr - b2Dot(v, w) <= 0.01f * vSqr) // or w in points
if (vSqr - vw <= 0.01 * vSqr) // or w in points
{
if (pointCount == 0)
{
//*x1 = w1;
x1.SetV(w1);
//*x2 = w2;
x2.SetV(w2);
}
g_GJK_Iterations = iter;
return Math.sqrt(vSqr);
}
switch (pointCount)
{
case 0:
//p1s[0] = w1;
tVec = p1s[0];
tVec.SetV(w1);
//p2s[0] = w2;
tVec = p2s[0];
tVec.SetV(w2);
//points[0] = w;
tVec = points[0];
tVec.x = wX;
tVec.y = wY;
//*x1 = p1s[0];
x1.SetV(p1s[0]);
//*x2 = p2s[0];
x2.SetV(p2s[0]);
++pointCount;
break;
case 1:
//p1s[1] = w1;
tVec = p1s[1];
tVec.SetV(w1);
//p2s[1] = w2;
tVec = p2s[1];
tVec.SetV(w2);
//points[1] = w;
tVec = points[1];
tVec.x = wX;
tVec.y = wY;
pointCount = ProcessTwo(x1, x2, p1s, p2s, points);
break;
case 2:
//p1s[2] = w1;
tVec = p1s[2];
tVec.SetV(w1);
//p2s[2] = w2;
tVec = p2s[2];
tVec.SetV(w2);
//points[2] = w;
tVec = points[2];
tVec.x = wX;
tVec.y = wY;
pointCount = ProcessThree(x1, x2, p1s, p2s, points);
break;
}
// If we have three points, then the origin is in the corresponding triangle.
if (pointCount == 3)
{
g_GJK_Iterations = iter;
return 0.0;
}
//float32 maxSqr = -FLT_MAX;
var maxSqr:Number = -Number.MAX_VALUE;
for (var i:int = 0; i < pointCount; ++i)
{
//maxSqr = b2Math.b2Max(maxSqr, b2Dot(points[i], points[i]));
tVec = points[i];
maxSqr = b2Math.b2Max(maxSqr, (tVec.x*tVec.x + tVec.y*tVec.y));
}
if (pointCount == 3 || vSqr <= 100.0 * Number.MIN_VALUE * maxSqr)
{
g_GJK_Iterations = iter;
//v = *x2 - *x1;
vX = x2.x - x1.x;
vY = x2.y - x1.y;
//vSqr = b2Dot(v, v);
vSqr = (vX*vX + vY*vY);
return Math.sqrt(vSqr);
}
}
g_GJK_Iterations = maxIterations;
return Math.sqrt(vSqr);
}
static public function DistanceCC(
x1:b2Vec2, x2:b2Vec2,
circle1:b2CircleShape, xf1:b2XForm,
circle2:b2CircleShape, xf2:b2XForm) : Number
{
var tMat:b2Mat22;
var tVec:b2Vec2;
//b2Vec2 p1 = b2Mul(xf1, circle1->m_localPosition);
tMat = xf1.R;
tVec = circle1.m_localPosition;
var p1X:Number = xf1.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
var p1Y:Number = xf1.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
//b2Vec2 p2 = b2Mul(xf2, circle2->m_localPosition);
tMat = xf2.R;
tVec = circle2.m_localPosition;
var p2X:Number = xf2.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
var p2Y:Number = xf2.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
//b2Vec2 d = p2 - p1;
var dX:Number = p2X - p1X;
var dY:Number = p2Y - p1Y;
var dSqr:Number = (dX*dX + dY*dY);
var r1:Number = circle1.m_radius - b2Settings.b2_toiSlop;
var r2:Number = circle2.m_radius - b2Settings.b2_toiSlop;
var r:Number = r1 + r2;
if (dSqr > r * r)
{
//var dLen:Number = d.Normalize();
var dLen:Number = Math.sqrt(dSqr);
dX /= dLen;
dY /= dLen;
var distance:Number = dLen - r;
//*x1 = p1 + r1 * d;
x1.x = p1X + r1 * dX;
x1.y = p1Y + r1 * dY;
//*x2 = p2 - r2 * d;
x2.x = p2X - r2 * dX;
x2.y = p2Y - r2 * dY;
return distance;
}
else if (dSqr > Number.MIN_VALUE * Number.MIN_VALUE)
{
//d.Normalize();
dLen = Math.sqrt(dSqr);
dX /= dLen;
dY /= dLen;
//*x1 = p1 + r1 * d;
x1.x = p1X + r1 * dX;
x1.y = p1Y + r1 * dY;
//*x2 = *x1;
x2.x = x1.x;
x2.y = x1.y;
return 0.0;
}
//*x1 = p1;
x1.x = p1X;
x1.y = p1Y;
//*x2 = *x1;
x2.x = x1.x;
x2.y = x1.y;
return 0.0;
}
// GJK is more robust with polygon-vs-point than polygon-vs-circle.
// So we convert polygon-vs-circle to polygon-vs-point.
static private var gPoint:b2Point = new b2Point();
///
static public function DistancePC(
x1:b2Vec2, x2:b2Vec2,
polygon:b2PolygonShape, xf1:b2XForm,
circle:b2CircleShape, xf2:b2XForm) : Number
{
var tMat:b2Mat22;
var tVec:b2Vec2;
var point:b2Point = gPoint;
//point.p = b2Mul(xf2, circle->m_localPosition);
tVec = circle.m_localPosition;
tMat = xf2.R;
point.p.x = xf2.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
point.p.y = xf2.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
// Create variation of function to replace template
var distance:Number = DistanceGeneric(x1, x2, polygon, xf1, point, b2Math.b2XForm_identity);
var r:Number = circle.m_radius - b2Settings.b2_toiSlop;
if (distance > r)
{
distance -= r;
//b2Vec2 d = *x2 - *x1;
var dX:Number = x2.x - x1.x;
var dY:Number = x2.y - x1.y;
//d.Normalize();
var dLen:Number = Math.sqrt(dX*dX + dY*dY);
dX /= dLen;
dY /= dLen;
//*x2 -= r * d;
x2.x -= r * dX;
x2.y -= r * dY;
}
else
{
distance = 0.0;
//*x2 = *x1;
x2.x = x1.x;
x2.y = x1.y;
}
return distance;
}
static public function Distance(x1:b2Vec2, x2:b2Vec2,
shape1:b2Shape, xf1:b2XForm,
shape2:b2Shape, xf2:b2XForm) : Number
{
//b2ShapeType type1 = shape1->GetType();
var type1:int = shape1.m_type;
//b2ShapeType type2 = shape2->GetType();
var type2:int = shape2.m_type;
if (type1 == b2Shape.e_circleShape && type2 == b2Shape.e_circleShape)
{
//return DistanceCC(x1, x2, (b2CircleShape*)shape1, xf1, (b2CircleShape*)shape2, xf2);
return DistanceCC(x1, x2, shape1 as b2CircleShape, xf1, shape2 as b2CircleShape, xf2);
}
if (type1 == b2Shape.e_polygonShape && type2 == b2Shape.e_circleShape)
{
//return DistancePC(x1, x2, (b2PolygonShape*)shape1, xf1, (b2CircleShape*)shape2, xf2);
return DistancePC(x1, x2, shape1 as b2PolygonShape, xf1, shape2 as b2CircleShape, xf2);
}
if (type1 == b2Shape.e_circleShape && type2 == b2Shape.e_polygonShape)
{
return DistancePC(x2, x1, shape2 as b2PolygonShape, xf2, shape1 as b2CircleShape, xf1);
}
if (type1 == b2Shape.e_polygonShape && type2 == b2Shape.e_polygonShape)
{
return DistanceGeneric(x1, x2, shape1 as b2PolygonShape, xf1, shape2 as b2PolygonShape, xf2);
}
return 0.0;
}
static public var g_GJK_Iterations:int = 0;
};
} |
package com.gamesparks.api.requests
{
import com.gamesparks.api.responses.*;
import com.gamesparks.*;
/**
* Allows a message to be dismissed. Once dismissed the message will no longer appear in either ListMessageResponse or ListMessageSummaryResponse.
*/
public class DismissMessageRequest extends GSRequest
{
function DismissMessageRequest(gs:GS)
{
super(gs);
data["@class"] = ".DismissMessageRequest";
}
/**
* set the timeout for this request
*/
public function setTimeoutSeconds(timeoutSeconds:int=10):DismissMessageRequest
{
this.timeoutSeconds = timeoutSeconds;
return this;
}
/**
* Send the request to the server. The callback function will be invoked with the response
*/
public override function send (callback : Function) : String{
return super.send(
function(message:Object) : void{
if(callback != null)
{
callback(new DismissMessageResponse(message));
}
}
);
}
public function setScriptData(scriptData:Object):DismissMessageRequest{
data["scriptData"] = scriptData;
return this;
}
/**
* The messageId of the message to dismiss
*/
public function setMessageId( messageId : String ) : DismissMessageRequest
{
this.data["messageId"] = messageId;
return this;
}
}
}
|
/* See LICENSE for copyright and terms of use */
import org.actionstep.ASAnimation;
import org.actionstep.ASFieldEditor;
import org.actionstep.ASUtils;
import org.actionstep.constants.NSAnimationCurve;
import org.actionstep.constants.NSDragOperation;
import org.actionstep.constants.NSDrawerState;
import org.actionstep.constants.NSSelectionDirection;
import org.actionstep.constants.NSWindowOrderingMode;
import org.actionstep.NSApplication;
import org.actionstep.NSArray;
import org.actionstep.NSButton;
import org.actionstep.NSButtonCell;
import org.actionstep.NSColor;
import org.actionstep.NSDictionary;
import org.actionstep.NSDraggingDestination;
import org.actionstep.NSDraggingInfo;
import org.actionstep.NSDraggingSource;
import org.actionstep.NSDrawer;
import org.actionstep.NSEvent;
import org.actionstep.NSException;
import org.actionstep.NSImage;
import org.actionstep.NSNotification;
import org.actionstep.NSNotificationCenter;
import org.actionstep.NSPasteboard;
import org.actionstep.NSPoint;
import org.actionstep.NSRect;
import org.actionstep.NSResponder;
import org.actionstep.NSSize;
import org.actionstep.NSToolbar;
import org.actionstep.NSUndoManager;
import org.actionstep.NSView;
import org.actionstep.themes.ASTheme;
import org.actionstep.window.ASRootWindowView;
/**
* <p>
* An <code>NSWindow</code> represents an on-screen window. It manages its
* views, display and event handling.
* </p>
* <p>
* The <code>NSWindow</code> class defines objects that manage and coordinate
* the windows an application displays on the screen. A single
* <code>NSWindow</code> object corresponds to at most one onscreen window. The
* two principal functions of a window are to provide an area in which views can
* be placed and to accept and distribute, to the appropriate views, events the
* user instigates through actions with the mouse and keyboard.
* </p>
*
* @author Richard Kilmer
* @author Tay Ray Chuan
* @author Scott Hyndman
*/
class org.actionstep.NSWindow extends NSResponder {
//******************************************************
//* Styles
//******************************************************
/** Bit mask for a window without a border */
public static var NSBorderlessWindowMask:Number = 0;
/** Bit mask for a window with a title bar */
public static var NSTitledWindowMask:Number = 1;
/** Bit mask for a window with a close button */
public static var NSClosableWindowMask:Number = 2;
/** Bit mask for a window with a miniaturize button */
public static var NSMiniaturizableWindowMask:Number = 4;
/** Bit mask for a resizable window */
public static var NSResizableWindowMask:Number = 8;
/** Bit mask for a non-resizable window with a title bar and all buttons */
private static var ASAllButResizable:Number = 7;
/** This is used internally. */
public static var NSNotDraggableWindowMask:Number = 16;
//******************************************************
//* Window Levels
//******************************************************
/** GNUstep addition */
public static var NSDesktopWindowLevel:Number = -1000;
/** default level for NSWindow objects. */
public static var NSNormalWindowLevel:Number = 0;
/** Useful for floating palettes. */
public static var NSFloatingWindowLevel:Number = 3;
/**
* Reserved for submenus. Synonymous with NSTornOffMenuWindowLevel,
* which is preferred.
*/
public static var NSSubmenuWindowLevel:Number = 3;
/** The level for a torn-off menu. Synonymous with NSSubmenuWindowLevel. */
public static var NSTornOffMenuWindowLevel:Number = 3;
/** Reserved for the applications main menu. */
public static var NSMainMenuWindowLevel:Number = 20;
/** The level for status windows */
public static var NSStatusWindowLevel:Number = 21;
/** The level for modal panels */
public static var NSModalPanelWindowLevel:Number = 100;
/** The level for popup windows */
public static var NSPopUpMenuWindowLevel:Number = 101;
/** The level for screensavers (not used, obviously) */
public static var NSScreenSaverWindowLevel:Number = 1000;
//******************************************************
// Notifications
//******************************************************
/** Posted when the content swf of a window is loaded. */
public static var ASWindowContentSwfDidLoad:Number
= ASUtils.intern("ASWindowContentSwfDidLoad");
/** Posted whenever an NSWindow is about to close. */
public static var NSWindowWillCloseNotification:Number
= ASUtils.intern("NSWindowWillCloseNotification");
/** Posted when a window becomes the key window. */
public static var NSWindowDidBecomeKeyNotification:Number
= ASUtils.intern("NSWindowDidBecomeKeyNotification");
/** Posted when a window becomes the main window. */
public static var NSWindowDidBecomeMainNotification:Number
= ASUtils.intern("NSWindowDidBecomeMainNotification");
/** Posted when a window resigns its key status. */
public static var NSWindowDidResignKeyNotification:Number
= ASUtils.intern("NSWindowDidResignKeyNotification");
/** Posted when a window resigns its main status. */
public static var NSWindowDidResignMainNotification:Number
= ASUtils.intern("NSWindowDidResignMainNotification");
/** Posted when a window displays. */
public static var NSWindowDidDisplayNotification:Number
= ASUtils.intern("NSWindowDidDisplayNotification");
/** Posted whenever an NSWindow’s size changes. */
public static var NSWindowDidResizeNotification:Number
= ASUtils.intern("NSWindowDidResizeNotification");
/** Posted whenever an NSWindow is about to move. */
public static var NSWindowWillMoveNotification:Number
= ASUtils.intern("NSWindowWillMoveNotification");
/** Posted whenever an NSWindow is moved. */
public static var NSWindowDidMoveNotification:Number
= ASUtils.intern("NSWindowDidMoveNotification");
/** Posted whenever an NSWindow is about to be miniaturized. */
public static var NSWindowWillMiniaturizeNotification:Number
= ASUtils.intern("NSWindowWillMiniaturizeNotification");
/** Posted whenever an NSWindow is miniaturized. */
public static var NSWindowDidMiniaturizeNotification:Number
= ASUtils.intern("NSWindowDidMiniaturizeNotification");
/** Posted whenever an NSWindow is deminiaturized. */
public static var NSWindowDidDeminiaturizeNotification:Number
= ASUtils.intern("NSWindowDidDeminiaturizeNotification");
//******************************************************
//* Class members
//******************************************************
/** The default stage width */
private static var g_defaultStageWidth:Number = 550;
/** The default stage height */
private static var g_defaultStageHeight:Number = 400;
/** An array of all window instances in the application */
private static var g_instances:Array = new Array();
/** <code>true</code> if a drag and drop operation is in process */
private static var g_isDragging:Boolean;
/** The current drag and drop information object */
private static var g_currentDragInfo:NSDraggingInfo;
/** The starting point of the drag and drop operation */
private static var g_dragStartPt:NSPoint;
/** The last view under the mouse during the current drag and drop operation */
private static var g_lastDragView:NSView;
//******************************************************
//* Member Variables
//******************************************************
private var m_app:NSApplication;
private var m_notificationCenter:NSNotificationCenter;
private var m_windowNumber:Number;
private var m_delegate:Object;
private var m_frameRect:NSRect;
private var m_contentRect:NSRect;
private var m_contentOrigin:NSPoint;
private var m_firstResponder:NSResponder;
private var m_initialFirstResponder:NSView;
private var m_rootView:ASRootWindowView;
private var m_contentView:NSView;
private var m_styleMask:Number;
private var m_viewsNeedDisplay:Boolean;
private var m_fieldEditor:ASFieldEditor;
private var m_rootSwfURL:String;
private var m_title:String;
private var m_isKey:Boolean;
private var m_isMain:Boolean;
private var m_isVisible:Boolean;
private var m_canHide:Boolean;
private var m_lastEventView:NSView;
private var m_level:Number;
private var m_acceptsMouseMoved:Boolean;
private var m_lastPoint:NSPoint;
private var m_lastView:NSView;
private var m_cursorRectsEnabled:Boolean;
private var m_defButtonCell:NSButtonCell;
private var m_keyEquivForDefButton:Boolean;
private var m_selectionDirection:NSSelectionDirection;
private var m_backgroundColor:NSColor;
private var m_minFrameSize:NSSize;
private var m_maxFrameSize:NSSize;
private var m_isMini:Boolean;
private var m_preminiSize:NSSize;
private var m_preminiStyle:Number;
private var m_preminiResizeInd:Boolean;
private var m_undoManager:NSUndoManager;
private var m_backgroundMovable:Boolean;
private var m_registeredDraggedTypes:NSDictionary;
private var m_icon:NSImage;
private var m_viewClass:Function;
private var m_parentWindow:NSWindow;
private var m_childWindows:NSArray;
private var m_drawers:NSArray;
private var m_toolbar:NSToolbar;
private var m_releasedWhenClosed:Boolean;
private var m_makeMainAndKey:Boolean;
//
// Animation
//
private var m_isAnimating:Boolean;
private var m_xAnimator:ASAnimation;
private var m_yAnimator:ASAnimation;
private var m_wAnimator:ASAnimation;
private var m_hAnimator:ASAnimation;
private var m_displayViewsAfterAnimate:Boolean;
//******************************************************
//* Construction
//******************************************************
/**
* Constructs a new instance of the <code>NSWindow</code> class.
*
* Should be followed by a call to one of the initializer methods.
*/
public function NSWindow() {
m_app = NSApplication.sharedApplication();
m_viewsNeedDisplay = true;
m_fieldEditor= ASFieldEditor.instance();
m_title = "";
m_isKey = false;
m_isMain = false;
m_isVisible = true;
m_canHide = true;
m_acceptsMouseMoved = false;
m_cursorRectsEnabled = true;
m_releasedWhenClosed = true;
m_keyEquivForDefButton = true;
m_backgroundMovable = false;
m_isMini = false;
m_level = NSNormalWindowLevel;
m_registeredDraggedTypes = NSDictionary.dictionary();
m_backgroundColor = null;//NSColor.windowBackgroundColor();
m_icon = null;
m_windowNumber = g_instances.push(this)-1;
m_selectionDirection = NSSelectionDirection.NSDirectSelection;
m_minFrameSize = new NSSize(1,1);
m_maxFrameSize = new NSSize(10000, 10000);
m_drawers = NSArray.array();
m_childWindows = NSArray.array();
m_isAnimating = false;
m_displayViewsAfterAnimate = false;
}
/**
* Initializes a borderless window with a content rect of
* {@link NSRect#ZeroRect}.
*/
public function init():NSWindow {
return initWithContentRectStyleMaskSwf(NSRect.ZeroRect, NSBorderlessWindowMask, null);
}
/**
* Initializes a borderless window with a frame of {@link NSRect#ZeroRect}
* and begins loading its contents using the swf at <code>swf</code>.
*/
public function initWithSwf(swf:String):NSWindow {
return initWithContentRectStyleMaskSwf(NSRect.ZeroRect, NSBorderlessWindowMask, swf);
}
/**
* Initializes a borderless window with a content rect of
* <code>contentRect</code>.
*/
public function initWithContentRect(contentRect:NSRect):NSWindow {
return initWithContentRectStyleMaskSwf(contentRect, NSBorderlessWindowMask, null);
}
/**
* Initializes the window with a content rect of <code>contentRect</code>
* and a view class of <code>viewClass</code>.
*
* <code>viewClass</code> must be a subclass of ASRootWindowView. If it is
* not, and NSException is raised.
*/
public function initWithContentRectViewClass(contentRect:NSRect,
viewClass:Function):NSWindow {
return initWithContentRectStyleMaskSwfViewClass(contentRect,
NSBorderlessWindowMask,
null,
viewClass);
}
public function initWithContentRectSwf(contentRect:NSRect, swf:String):NSWindow {
return initWithContentRectStyleMaskSwf(contentRect, NSBorderlessWindowMask, swf);
}
public function initWithContentRectStyleMask(contentRect:NSRect, styleMask:Number):NSWindow {
return initWithContentRectStyleMaskSwf(contentRect, styleMask, null);
}
/**
* Initializes a window with a content rect of <code>contentRect</code>,
* using <code>styleMask</code> to define it's styles.
*
* <code>viewClass</code> is the class used to render the window. It must be
* a subclass of <code>ASRootWindowView</code>. If it is <code>null</code>,
* <code>ASRootWindowView</code> will be used. If <code>viewClass</code> is
* provided and is not a subclass of <code>ASRootWindowView</code>, an
* exception is raised.
*/
public function initWithContentRectStyleMaskViewClass(contentRect:NSRect,
styleMask:Number, viewClass:Function):NSWindow {
return initWithContentRectStyleMaskSwfViewClass(contentRect, styleMask,
null, viewClass);
}
public function initWithContentRectStyleMaskSwf(contentRect:NSRect, styleMask:Number, swf:String):NSWindow {
return initWithContentRectStyleMaskSwfViewClass(
contentRect, styleMask, swf, null);
}
/**
* Initializes a window with a content rect of <code>contentRect</code>,
* using <code>styleMask</code> to define it's styles.
*
* <code>swf</code> is loaded in as the window's base swf so that assets will
* be available for use. If <code>swf</code> is null, none is used.
*
* <code>viewClass</code> is the class used to render the window. It must be
* a subclass of <code>ASRootWindowView</code>. If it is <code>null</code>,
* <code>ASRootWindowView</code> will be used. If <code>viewClass</code> is
* provided and is not a subclass of <code>ASRootWindowView</code>, an
* exception is raised.
*/
public function initWithContentRectStyleMaskSwfViewClass(contentRect:NSRect,
styleMask:Number, swf:String, viewClass:Function):NSWindow {
super.init();
//
// Use the provided view class if one has been provided.
//
if (null != viewClass) {
m_viewClass = viewClass;
}
m_rootSwfURL = swf;
m_rootView = ASRootWindowView(ASUtils.createInstanceOf(this.viewClass()));
m_rootView.initWithFrameWindow(NSRect.ZeroRect, this);
//
// Throw an exception if viewClass is not a subclass of ASRootWindowView.
//
if (m_rootView == null) {
var e:NSException = NSException.exceptionWithNameReasonUserInfo(
"NSInvalidTypeException",
"The passed view class is not a subclass of ASRootWindowView",
null);
trace(e);
throw e;
}
m_notificationCenter = NSNotificationCenter.defaultCenter();
m_styleMask = styleMask;
m_contentRect = contentRect.clone();
m_frameRect = frameRectForContentRect();
m_rootView.setFrame(m_frameRect);
m_contentOrigin = convertScreenToBase(contentRect.origin.clone());
setContentView((new NSView()).initWithFrame(NSRect.withOriginSize(
convertScreenToBase(m_contentRect.origin), m_contentRect.size)));
return this;
}
//******************************************************
//* Describing the object
//******************************************************
/**
* Returns a string representation of the window.
*/
public function description():String {
return "NSWindow(number="+m_windowNumber+", view="+m_rootView+")";
}
//******************************************************
//* Getting the window number
//******************************************************
/**
* Returns the window's window number.
*/
public function windowNumber():Number {
return m_windowNumber;
}
//******************************************************
//* Getting the root view
//******************************************************
/**
* <p>Returns the view actually used to display the window.</p>
*
* The class of the view the window uses can be set using the
* {@link #initWithContentRectStyleMaskSwfViewClass()} and
* {@link #initWithContentRectViewClass()} initializers.
*
* <p>This method is ActionStep-specific.</p>
*/
public function rootView():ASRootWindowView {
return m_rootView;
}
//******************************************************
//* Getting the root swf
//******************************************************
/**
* <p>Returns this window's swf URL.</p>
*
* <p>This is the swf that the window is created within. The window, and all
* of its views, have full access to the library of swf.</p>
*/
public function swf():String {
return m_rootSwfURL;
}
//******************************************************
//* Calculating layout
//******************************************************
public static function contentRectForFrameRectStyleMask(frameRect:NSRect, styleMask:Number):NSRect {
return contentRectForWindowFrameRectStyleMask(null, frameRect, styleMask);
}
public static function contentRectForWindowFrameRectStyleMask(wnd:NSWindow, frameRect:NSRect, styleMask:Number):NSRect {
var rect:NSRect = frameRect.clone();
if (styleMask == NSBorderlessWindowMask) {
return rect;
}
if (styleMask & NSTitledWindowMask) {
var titleHeight:Number = wnd != null ? wnd.rootView().titleRect().size.height :
ASTheme.current().windowTitleBarHeight();
rect.origin.y += titleHeight + 1;
rect.size.height -= (titleHeight + 2);
rect.origin.x += 1;
rect.size.width -= 2;
}
return rect;
}
public static function frameRectForContentRectStyleMask(frameRect:NSRect, styleMask:Number):NSRect {
return frameRectForWindowContentRectStyleMask(null, frameRect, styleMask);
}
public static function frameRectForWindowContentRectStyleMask(wnd:NSWindow, contentRect:NSRect, styleMask:Number):NSRect {
var rect:NSRect = contentRect.clone();
if (styleMask == NSBorderlessWindowMask) {
return rect;
}
/*
public static var NSBorderlessWindowMask = 0
public static var NSTitledWindowMask = 1
public static var NSClosableWindowMask = 2
public static var NSMiniaturizableWindowMask = 4
public static var NSResizableWindowMask = 8
*/
//! Based on style masks reshape?
if (styleMask & NSTitledWindowMask) {
var titleHeight:Number = wnd != null ? wnd.rootView().titleRect().size.height :
ASTheme.current().windowTitleBarHeight();
rect.origin.y -= (titleHeight + 1);
rect.size.height += titleHeight + 2;
rect.origin.x -= 1;
rect.size.width += 2;
}
return rect;
}
public function contentRectForFrameRect():NSRect {
var rect:NSRect = NSWindow.contentRectForWindowFrameRectStyleMask(this, m_frameRect, m_styleMask);
if (m_toolbar != null && m_toolbar.isVisible()) {
var tbHeight:Number = ASTheme.current().toolbarHeightForToolbar(m_toolbar);
rect.origin.y += tbHeight;
rect.size.height -= tbHeight;
}
return rect;
}
public function frameRectForContentRect():NSRect {
var frm:NSRect = NSWindow.frameRectForWindowContentRectStyleMask(this, m_contentRect, m_styleMask);
if (m_toolbar != null && m_toolbar.isVisible()) {
var tbHeight:Number = ASTheme.current().toolbarHeightForToolbar(m_toolbar);
frm.origin.y -= tbHeight;
frm.size.height += tbHeight;
}
if (m_frameRect != null) {
frm.origin = m_frameRect.origin.clone();
}
return frm;
}
//******************************************************
//* Converting coordinates
//******************************************************
/**
* <p>
* Converts a given point from the screen coordinate system to the receiver’s
* base coordinate system.
* </p>
*
* @see #convertBaseToScreen()
*/
public function convertScreenToBase(point:NSPoint):NSPoint {
return new NSPoint(point.x - m_frameRect.origin.x, point.y - m_frameRect.origin.y);
}
/**
* <p>
* Converts a given point from the receiver’s base coordinate system to the
* screen coordinate system.
* </p>
*
* @see #convertScreenToBase()
*/
public function convertBaseToScreen(point:NSPoint):NSPoint {
return new NSPoint(m_frameRect.origin.x +point.x, m_frameRect.origin.y + point.y);
}
//******************************************************
//* Moving and resizing
//******************************************************
/**
* <p>Returns the receiver’s frame rectangle.</p>
*/
public function frame():NSRect {
return m_frameRect.clone();
}
/**
* <p>
* Sets the window's frame to <code>frame</code>, positioning and sizing
* the content and decorators appropriately.
* </p>
* <p>
* If the window is current smooth-resizing, the animation will be cancelled.
* </p>
*
* @see #setFrameDisplay()
* @see #setFrameDisplayAnimate()
*/
public function setFrame(frame:NSRect):Void {
setFrameWithNotifications(frame, true);
//
// Reset cursor rects
//
resetCursorRects();
}
/**
* <p>
* Sets the frame or the window to <code>frame</code>, and only dispatches
* notifications if <code>flag</code> is <code>true</code>.
* </p>
* <p>
* If the window is current smooth-resizing and <code>animate</code> is
* <code>false</code> or omitted, the animation will be cancelled.
* </p>
* <p>
* Intended for internal use only.
* </p>
*/
public function setFrameWithNotifications(frame:NSRect, flag:Boolean,
animate:Boolean):Void {
if (!animate) {
cancelAnimation();
}
frame = constrainFrameRect(frame.clone());
var sizeChange:Boolean = !frame.size.isEqual(m_frameRect.size);
var locChange:Boolean = !frame.origin.isEqual(m_frameRect.origin);
//
// Size change
//
if (sizeChange) { // Resize
if (m_delegate != null && typeof(m_delegate["windowWillResizeToSize"]) == "function") {
frame.size = m_delegate["windowWillResizeToSize"].call(m_delegate, this, frame.size);
}
}
else if (!locChange) {
return; // Same shape;
}
//
// Origin change
//
if (locChange) {
if (flag) {
m_notificationCenter.postNotificationWithNameObject(NSWindowWillMoveNotification, this);
}
m_rootView.setFrameOrigin(frame.origin);
if (flag) {
m_notificationCenter.postNotificationWithNameObject(NSWindowDidMoveNotification, this);
}
}
//
// Set the frame rect
//
m_frameRect = frame;
//
// Resize content
//
var cRect:NSRect = contentRectForFrameRect();
cRect.origin.x -= frame.origin.x;
cRect.origin.y -= frame.origin.y;
if (!m_contentRect.isEqual(cRect) || !m_rootView.isResizing()) {
m_contentView.setFrame(cRect);
m_contentView.setNeedsDisplay(true);
m_contentRect = cRect;
}
if (sizeChange) {
m_rootView.setFrameSize(frame.size);
if (flag) {
m_notificationCenter.postNotificationWithNameObject(NSWindowDidResizeNotification, this);
}
m_rootView.setNeedsDisplay(true);
}
}
/**
* <p>
* Sets the origin and size of the receiver’s frame rectangle according to a
* given frame rectangle, thereby setting its position and size onscreen.
* </p>
* <p>
* <code>displayViews</code> specifies whether the window redraws the views
* that need to be displayed. When <code>true</code> the window sends a
* <code>NSView#displayIfNeeded</code> message down its view hierarchy, thus
* redrawing all views.
* </p>
* <p>
* If the window is current smooth-resizing, the animation will be cancelled.
* </p>
*
* @see #setFrame()
* @see #setFrameOrigin()
* @see #setFrameDisplayAnimate()
*/
public function setFrameDisplay(rect:NSRect, displayViews:Boolean):Void {
setFrameDisplayAnimate(rect, displayViews, false);
}
/**
* <p>
* Sets the origin and size of the receiver’s frame rectangle, with optional
* animation, according to a given frame rectangle, thereby setting its
* position and size onscreen.
* </p>
* <p>
* <code>displayViews</code> specifies whether the window redraws the views
* that need to be displayed. When <code>true</code> the window sends a
* <code>NSView#displayIfNeeded</code> message down its view hierarchy, thus
* redrawing all views.
* </p>
* <p>
* <code>performAnimation</code> specifies whether the window performs a
* smooth resize.
* </p>
* <p>
* If the window is current smooth-resizing, the animation will be cancelled.
* </p>
*
* @see #setFrame()
* @see #setFrameOrigin()
* @see #setFrameDisplayAnimate()
*/
public function setFrameDisplayAnimate(rect:NSRect, displayViews:Boolean,
performAnimation:Boolean):Void {
if (!performAnimation) {
setFrame(rect);
if (displayViews) {
m_rootView.displayIfNeeded();
}
} else {
if (m_isAnimating) {
cancelAnimation();
}
var duration:Number = animationResizeTime();
var curve:NSAnimationCurve = animationCurve();
//
// Create animators
//
m_xAnimator = (new ASAnimation()).initWithDurationAnimationCurve(
duration, curve);
m_yAnimator = (new ASAnimation()).initWithDurationAnimationCurve(
duration, curve);
m_wAnimator = (new ASAnimation()).initWithDurationAnimationCurve(
duration, curve);
m_hAnimator = (new ASAnimation()).initWithDurationAnimationCurve(
duration, curve);
//
// Set endpoints
//
constrainFrameRect(rect);
m_xAnimator.setEndPoints(m_frameRect.origin.x, rect.origin.x);
m_yAnimator.setEndPoints(m_frameRect.origin.y, rect.origin.y);
m_wAnimator.setEndPoints(m_frameRect.size.width, rect.size.width);
m_hAnimator.setEndPoints(m_frameRect.size.height, rect.size.height);
//
// Create delegates
//
var self:NSWindow = this;
var aniRect:NSRect = NSRect.ZeroRect;
var xSet:Boolean = false, ySet:Boolean = false, wSet:Boolean = false, hSet:Boolean = false;
//
// X delegate (has stop methods)
//
var xDel:Object = {};
xDel.animationDidAdvance = function(ani:ASAnimation, val:Number):Void {
aniRect.origin.x = val;
if (xSet && ySet && wSet && hSet) {
self.setFrameWithNotifications(aniRect, false, true);
xSet = ySet = wSet = hSet = false;
} else {
xSet = true;
}
};
xDel.animationDidStop = function(ani:ASAnimation):Void {
self.setFrame(aniRect);
};
xDel.animationDidEnd = xDel.animationDidStop;
m_xAnimator.setDelegate(xDel);
//
// Y delegate
//
var yDel:Object = {};
yDel.animationDidAdvance = function(ani:ASAnimation, val:Number):Void {
aniRect.origin.y = val;
if (xSet && ySet && wSet && hSet) {
self.setFrameWithNotifications(aniRect, false, true);
xSet = ySet = wSet = hSet = false;
} else {
ySet = true;
}
};
m_yAnimator.setDelegate(yDel);
//
// Width delegate
//
var wDel:Object = {};
wDel.animationDidAdvance = function(ani:ASAnimation, val:Number):Void {
aniRect.size.width = val;
if (xSet && ySet && wSet && hSet) {
self.setFrameWithNotifications(aniRect, false, true);
xSet = ySet = wSet = hSet = false;
} else {
wSet = true;
}
};
m_wAnimator.setDelegate(wDel);
//
// Height delegate
//
var hDel:Object = {};
hDel.animationDidAdvance = function(ani:ASAnimation, val:Number):Void {
aniRect.size.height = val;
if (xSet && ySet && wSet && hSet) {
self.setFrameWithNotifications(aniRect, false, true);
xSet = ySet = wSet = hSet = false;
} else {
hSet = true;
}
};
m_hAnimator.setDelegate(hDel);
//
// Start animation
//
m_xAnimator.startAnimation();
m_yAnimator.startAnimation();
m_wAnimator.startAnimation();
m_hAnimator.startAnimation();
m_displayViewsAfterAnimate = displayViews;
}
}
/**
* <p>
* Returns the duration (in seconds) of a smooth frame-size change.
* </p>
* <p>
* This value is obtained from the current theme's
* <code>ASThemeProtocol#windowAnimationResizeTime()</code> method.
* </p>
*
* @see #setFrameDisplayAnimate()
*/
public function animationResizeTime():Number {
return ASTheme.current().windowAnimationResizeTime(this);
}
/**
* <p>
* Returns the animation curve of a smooth frame-size change.
* </p>
* <p>
* This value is obtained from the current theme's
* <code>ASThemeProtocol#windowAnimationResizeCurve()</code> method.
* </p>
*
* @see #setFrameDisplayAnimate()
*/
public function animationCurve():NSAnimationCurve {
return ASTheme.current().windowAnimationResizeCurve(this);
}
/**
* <p>
* Positions the top-left corner of the receiver’s frame rectangle at a given
* point in screen coordinates.
* </p>
* <p>
* This differs from the Cocoa implementation by positioning the window
* using the top-left corner of the frame, not the bottom-left.
* </p>
*
* @see #setFrame()
* @see #setFrameDisplay()
*/
public function setFrameOrigin(point:NSPoint):Void {
var oldOrigin:NSPoint = m_frameRect.origin;
var f:NSRect = m_frameRect.clone();
f.origin = point;
setFrame(f);
//
// Deal with child windows
//
if (m_childWindows.count() == 0 || oldOrigin.isEqual(m_frameRect.origin)) {
return;
}
var delta:NSPoint = oldOrigin.pointDistanceToPoint(m_frameRect.origin);
var arr:Array = m_childWindows.internalList();
var len:Number = arr.length;
for (var i:Number = 0; i < len; i++) {
var win:NSWindow = NSWindow(arr[i]);
win.setFrameOrigin(win.m_frameRect.origin.addPoint(delta));
}
}
/**
* <p>
* Returns the size of this window's content.
* </p>
*
* @see #setContentSize()
*/
public function contentSize():NSSize {
return contentRectForFrameRect().size;
}
/**
* <p>
* Sets the size of the receiver’s content view to a given size, which is
* expressed in the receiver’s base coordinate system.
* </p>
* <p>
* This size in turn alters the size of the <code>NSWindow</code> object
* itself, taking into account the size of the frame decorations and any
* window decorators. Note that window sizes are limited to 10,000; if
* necessary, be sure to limit <code>size</code> relative to the frame
* rectangle.
* </p>
*
* @see #contentSize()
*/
public function setContentSize(size:NSSize):Void {
m_contentRect.size.width = size.width;
m_contentRect.size.height = size.height;
sizeToFitContents();
}
/**
* <p>
* Positions the receiver's top left to <code>pt</code> and returns a
* point shifted by the height of the window's title bar. The return value
* can be passed to subsequent invocations of
* <code>#cascadeTopLeftFromPoint()</code> on other windows so all title
* bars are visible.
* </p>
*/
public function cascadeTopLeftFromPoint(pt:NSPoint):NSPoint {
var titleHeight:Number = this.rootView().titleRect().size.height;
setFrameOrigin(pt);
return pt.addSize(new NSSize(titleHeight + 2, titleHeight + 2));
}
/**
* <p>Sets the receiver’s location to the center of the screen.</p>
*/
public function center():Void {
var w:Number = Stage.width == 0 ? g_defaultStageWidth : Stage.width;
var h:Number = Stage.height == 0 ? g_defaultStageHeight : Stage.height;
setFrameOrigin(new NSPoint((w - m_frameRect.size.width)/2,
(h - m_frameRect.size.height)/2 - 10));
}
/**
* Returns whether the receiver’s resize indicator is visible.
*
* @see #setShowsResizeIndicator()
*/
public function showsResizeIndicator():Boolean {
return m_rootView.showsResizeIndicator();
}
/**
* <p>Sets whether the receiver’s resize indicator is visible to show.</p>
*
* <p>This method does not affect whether the receiver is resizable.</p>
*
* @see #showsResizeIndicator()
*/
public function setShowsResizeIndicator(value:Boolean):Void {
m_rootView.setShowsResizeIndicator(value);
}
/**
* <p>
* Returns a Boolean value that indicates whether the receiver is movable by
* clicking and dragging anywhere in its background.
* </p>
* <p>
* The default is <code>false</code>.
* </p>
*
* @see #setMovableByWindowBackground()
*/
public function isMovableByWindowBackground():Boolean {
return m_backgroundMovable;
}
/**
* <p>
* Sets whether the receiver is movable by clicking and dragging anywhere in
* its background.
* </p>
* <p>
* <code>flag</code> is <code>true</code> to specify that the window is
* movable by background, <code>false</code> to specify that the window is not
* movable by background.
* </p>
*
* @see #isMovableByWindowBackground()
*/
public function setMovableByWindowBackground(flag:Boolean):Void {
m_backgroundMovable = flag;
}
/**
* Called after a content size change, or when a decorator is added or
* removed from the window.
*/
private function sizeToFitContents():Void {
m_frameRect = frameRectForContentRect();
m_rootView.setFrame(m_frameRect);
m_contentView.setFrame(NSRect.withOriginSize(m_contentOrigin, m_contentRect.size));
}
/**
* Used to ensure the window frame is does not exceed minimums and maximums
* and is big enough to accommodate the title bar.
*/
private function constrainFrameRect(rect:NSRect):NSRect {
//
// Min max constraint
//
if (rect.size.width < m_minFrameSize.width) {
rect.size.width = m_minFrameSize.width;
}
if (rect.size.height < m_minFrameSize.height) {
rect.size.height = m_minFrameSize.height;
}
if (rect.size.width > m_maxFrameSize.width) {
rect.size.width = m_maxFrameSize.width;
}
if (rect.size.height > m_maxFrameSize.height) {
rect.size.height = m_maxFrameSize.height;
}
if (m_styleMask & NSTitledWindowMask) {
//
// Titlebar constraint
//
if (rect.size.width < 100) {
rect.size.width = 100;
}
var titleHeight:Number = this.rootView().titleRect().size.height;
if (rect.size.height < titleHeight + 2) {
rect.size.height = titleHeight + 2;
}
}
return rect;
}
/**
* Cancels a smoothe resize animation.
*/
private function cancelAnimation():Void {
if (!m_isAnimating) {
return;
}
m_isAnimating = false;
m_xAnimator.release();
m_yAnimator.release();
m_wAnimator.release();
m_hAnimator.release();
m_xAnimator = null;
m_yAnimator = null;
m_wAnimator = null;
m_hAnimator = null;
m_displayViewsAfterAnimate = false;
}
//******************************************************
//* Constraining window size
//******************************************************
/**
* Returns the maximum size to which this window's frame can be sized.
*/
public function maxSize():NSSize {
return m_maxFrameSize;
}
/**
* Returns the minimum size to which this window's frame can be sized.
*/
public function minSize():NSSize {
return m_minFrameSize;
}
/**
* Sets the maximum size to which this window's frame can be sized to
* <code>size</code>.
*/
public function setMaxSize(size:NSSize):Void {
if (size.width > 10000) {
size.width = 10000;
}
if (size.height > 10000) {
size.height = 10000;
}
m_maxFrameSize = size;
}
/**
* Sets the minimum size to which this window's frame can be sized to
* <code>size</code>.
*/
public function setMinSize(size:NSSize):Void {
if (size.width < 1) {
size.width = 1;
}
if (size.height < 1) {
size.height = 1;
}
m_minFrameSize = size;
}
/**
* This is a helper method. It uses {@link #setMinSize}.
*/
public function setMinWidth(width:Number):Void {
setMinSize(new NSSize(width, m_minFrameSize.height));
}
/**
* This is a helper method. It uses {@link #setMaxSize}.
*/
public function setMaxWidth(width:Number):Void {
setMaxSize(new NSSize(width, m_maxFrameSize.height));
}
/**
* This is a helper method. It uses {@link #setMinSize}.
*/
public function setMinHeight(height:Number):Void {
setMinSize(new NSSize(m_minFrameSize.width, height));
}
/**
* This is a helper method. It uses {@link #setMaxSize}.
*/
public function setMaxHeight(height:Number):Void {
setMaxSize(new NSSize(m_maxFrameSize.width, height));
}
// TODO setAspectRatio:
// TODO aspectRatio
// TODO resizeIncrements
// TODO setResizeIncrements:
// TODO constrainFrameRect:toScreen:
//******************************************************
//* Managing content size
//******************************************************
// TODO setContentAspectRatio:
// TODO contentAspectRatio
// TODO setContentResizeIncrements:
// TODO contentResizeIncrements
// TODO setContentMaxSize:
// TODO contentMaxSize
// TODO setContentMinSize:
// TODO contentMinSize
// TODO Entire "Saving the frame to user defaults" section
//******************************************************
//* Ordering Windows
//******************************************************
public function orderBack(sender:Object):Void {
m_rootView.extractView();
m_rootView.lowestViewOfLevel().setLowerView(m_rootView);
m_rootView.matchDepth();
}
public function orderFront(sender:Object):Void {
m_rootView.extractView();
m_rootView.setLowerView(m_rootView.highestViewOfLevel());
m_rootView.matchDepth();
}
public function orderFrontRegardless(sender:Object):Void {
orderFront();
}
public function orderOut(sender:Object):Void {
//! How to handle this?
}
public function orderWindowRelativeTo(positioned:NSWindowOrderingMode,
windowNumber:Number):Void {
var windowRoot:ASRootWindowView = g_instances[windowNumber].rootView();
switch(positioned) {
case NSWindowOrderingMode.NSWindowAbove:
m_rootView.extractView();
m_rootView.setLowerView(windowRoot);
m_rootView.matchDepth();
break;
case NSWindowOrderingMode.NSWindowBelow:
m_rootView.extractView();
windowRoot.setLowerView(m_rootView);
m_rootView.matchDepth();
break;
case NSWindowOrderingMode.NSWindowOut:
//! How to handle this?
break;
}
}
public function setLevel(newLevel:Number):Void {
m_level = newLevel;
orderFront();
}
public function level():Number {
return m_level;
}
public function isVisible():Boolean {
return m_isVisible;
}
//******************************************************
//* Attached windows
//******************************************************
/**
* <p><code>childWin</code> is ordered either above (
* {@link NSWindowOrderingMode#NSWindowAbove}) or below
* ({@link NSWindowOrderingMode#NSWindowBelow}) the receiver, and maintained
* in that relative place for subsequent ordering operations involving either
* window.</p>
*
* <p>While this attachment is active, moving <code>childWin</code> will not
* cause the receiver to move (as in sliding a drawer in or out), but moving
* the receiver will cause <code>childWin</code> to move.</p>
*
* <p>Note that you should not create cycles between parent and child windows.
* For example, you should not add window B as child of window A, then add
* window A as a child of window B.</p>
*
* @see #removeChildWindow()
* @see #childWindows()
* @see #parentWindow()
* @see #setParentWindow()
*/
public function addChildWindowOrdered(childWin:NSWindow,
place:NSWindowOrderingMode):Void {
if (!m_childWindows.containsObject(childWin)) {
m_childWindows.addObject(childWin);
}
childWin.setParentWindow(this);
// FIXME childWin.orderWindowRelativeTo(place, windowNumber());
// FIXME account for depth changes
}
/**
* Detaches <code>childWin</code> from the receiver.
*
* @see #addChildWindowOrdered()
* @see #childWindows()
* @see #parentWindow()
* @see #setParentWindow()
*/
public function removeChildWindow(childWin:NSWindow):Void {
if (childWin.parentWindow() != this) {
return;
}
m_childWindows.removeObject(childWin);
childWin.setParentWindow(null);
}
/**
* Returns an array of the receiver’s attached child windows.
*
* @see #addChildWindowOrdered()
* @see #removeChildWindow()
* @see #parentWindow()
* @see #setParentWindow()
*/
public function childWindows():NSArray {
return (new NSArray()).initWithArrayCopyItems(m_childWindows, false);
}
/**
* Returns the parent window to which the receiver is attached as a child.
*
* @see #addChildWindowOrdered()
* @see #removeChildWindow()
* @see #childWindows()
* @see #setParentWindow()
*/
public function parentWindow():NSWindow {
return m_parentWindow;
}
/**
* For use by subclasses when setting the parent window in the receiver.
*
* @see #addChildWindowOrdered()
* @see #removeChildWindow()
* @see #childWindows()
* @see #parentWindow()
*/
public function setParentWindow(window:NSWindow):Void {
// TODO consider removing from old parent, LOOP WARNING
m_parentWindow = window;
}
//******************************************************
//* Making key and main windows
//******************************************************
public function becomeKeyWindow():Void {
if (!m_isKey) {
m_isKey = true;
m_rootView.setNeedsDisplay(true);
if (m_firstResponder == null || m_firstResponder == this) {
if (m_initialFirstResponder != null) {
makeFirstResponder(m_initialFirstResponder);
}
}
m_firstResponder.becomeFirstResponder();
if (m_firstResponder != this) {
Object(m_firstResponder).becomeKeyWindow();
}
m_notificationCenter.postNotificationWithNameObject(NSWindowDidBecomeKeyNotification, this);
}
}
public function canBecomeKeyWindow():Boolean {
return true;
}
public function isKeyWindow():Boolean {
return m_isKey;
}
public function makeKeyAndOrderFront():Void {
makeKeyWindow();
orderFront(this);
}
public function makeKeyWindow():Void {
if (!m_isKey && m_isVisible && canBecomeKeyWindow()) {
m_app.keyWindow().resignKeyWindow();
becomeKeyWindow();
}
}
public function resignKeyWindow():Void {
if (m_isKey) {
if (m_firstResponder != this) {
Object(m_firstResponder).resignKeyWindow();
}
m_isKey = false;
m_rootView.setNeedsDisplay(true);
m_notificationCenter.postNotificationWithNameObject(NSWindowDidResignKeyNotification, this);
}
}
/**
* <p>Informs this window that it has become the main window.</p>
*
* <p>This method should never be called directly.</p>
*
* <p>This method posts a {@link #NSWindowDidBecomeMainNotification} to the
* notification center.</p>
*
* @see #makeMainWindow
* @see #isMainWindow
*/
public function becomeMainWindow():Void {
if (!isMainWindow()) {
m_isMain = true;
m_notificationCenter.postNotificationWithNameObject(NSWindowDidBecomeMainNotification, this);
}
}
public function canBecomeMainWindow():Boolean {
return m_isVisible;
}
/**
* Returns <code>true</code> if this window is the application's main window,
* or <code>false</code> otherwise.
*/
public function isMainWindow():Boolean {
return m_isMain;
}
/**
* Makes this window the main window. The main window is the standard window
* where the user is currently working. The main window is not always the key
* window.
*
* @see #becomeMainWindow
* @see #isMainWindow
*/
public function makeMainWindow():Void {
if (m_isVisible && !m_isMain && canBecomeMainWindow()) {
// trace(ASUtils.findMatch([NSWindow, org.actionstep.NSMenu, org.actionstep.test.ASTestMenu, NSApplication], arguments.caller, "prototype"));
m_app.mainWindow().resignMainWindow();
becomeMainWindow();
}
}
public function resignMainWindow():Void {
if (m_isMain) {
m_isMain = false;
m_notificationCenter.postNotificationWithNameObject(NSWindowDidResignMainNotification, this);
}
}
public function setMakeMainAndKey(f:Boolean):Void {
m_makeMainAndKey = f;
}
public function makeMainAndKey():Boolean {
return m_makeMainAndKey;
}
public function hide():Void {
if (m_isVisible && m_canHide) {
m_isVisible = false;
m_rootView.setHidden(true);
}
}
public function show():Void {
if (!m_isVisible) {
m_isVisible = true;
m_rootView.setHidden(false);
}
}
//******************************************************
//* Default push button
//******************************************************
/**
* Returns the button cell that will act as if it is clicked when the window
* recieves an Enter keyDown event.
*
* @see #setDefaultButtonCell
*/
public function defaultButtonCell():NSButtonCell {
return m_defButtonCell;
}
/**
* Sets the button cell that will act as if it is clicked when the window
* recieves an Enter keyDown event.
*
* TODO The button should have some visual indication that it is the
* default push button.
*/
public function setDefaultButtonCell(cell:NSButtonCell):Void {
m_defButtonCell = cell;
}
/**
* Enables the default button cell's key equivalent. That is, when Enter is
* pressed, the button cell's click will be performed.
*
* @see #disableKeyEquivalentForDefaultButtonCell
*/
public function enableKeyEquivalentForDefaultButtonCell():Void {
m_keyEquivForDefButton = true;
}
/**
* Disables the default button cell's key equivalent.
*
* @see #enableKeyEquivalentForDefaultButtonCell
*/
public function disableKeyEquivalentForDefaultButtonCell():Void {
m_keyEquivForDefButton = false;
}
//******************************************************
//* Display and drawing
//******************************************************
/**
* <p>Passes a display message down the receiver’s view hierarchy, thus
* redrawing all NSViews within the receiver, including the frame view that
* draws the border, title bar, and other peripheral elements.</p>
*
* <p>You rarely need to invoke this method. NSWindows normally record which
* of their NSViews need display and display them automatically on each
* pass through the event loop.</p>
*
* @see #displayIfNeeded()
* @see NSView#display()
*/
public function display():Void {
m_viewsNeedDisplay = false;
try {
m_rootView.display();
} catch (e:Error) {
trace(e.toString());
}
}
/**
* <p>Passes a displayIfNeeded message down the receiver’s view hierarchy,
* thus redrawing all NSViews that need to be displayed, including the frame
* view that draws the border, title bar, and other peripheral elements.</p>
*
* <p>This method is useful when you want to modify some number of NSViews
* and then display only the ones that were modified.</p>
*
* <p>You rarely need to invoke this method. NSWindows normally record which
* of their NSViews need display and display them automatically on each pass
* through the event loop.</p>
*
* @see #display()
* @see NSView#displayIfNeeded()
* @see NSView#setNeedsDisplay()
*/
public function displayIfNeeded():Void {
if (m_viewsNeedDisplay) {
m_viewsNeedDisplay = false;
try {
m_rootView.displayIfNeeded();
} catch (e:Error) {
trace(e.toString());
}
}
}
public function setViewsNeedDisplay(value:Boolean):Void {
m_viewsNeedDisplay = value;
}
public function viewsNeedDisplay():Boolean {
return m_viewsNeedDisplay;
}
// TODO update
/**
* <p>Posts a {@link #NSWindowDidDisplayNotification} to the default notification
* center.</p>
*
* <p>This method is ActionStep-specific.</p>
*/
public function windowDidDisplay():Void {
m_notificationCenter.postNotificationWithNameObject(NSWindowDidDisplayNotification, this);
}
//******************************************************
//* Working with the responder chain
//******************************************************
public function firstResponder():NSResponder {
return m_firstResponder;
}
/**
* <p>
* Attempts to make <code>aResponder</code> the first responder for the
* receiver.
* </p>
* <p>
* If <code>aResponder</code> isn’t already the first responder, this method
* first sends a <code>NSResponder#resignFirstResponder()</code> message to
* the object that is. If that object refuses to resign, it remains the first
* responder, and this method immediately returns <code>false</code>. If it
* returns <code>true</code>, this method sends an
* <code>NSResponder#becomeFirstResponder()</code> message to
* <code>aResponder</code>. If <code>aResponder</code> accepts first responder
* status, this method returns <code>true</code>. If it refuses, this method
* returns <code>false</code>, and the NSWindow object becomes first
* responder.
* </p>
* <p>
* If <code>aResponder</code> is <code>null</code>, this method still sends
* <code>NSResponder#resignFirstResponder()</code> to the current first
* responder. If the current first responder refuses to resign, it remains the
* first responder and this method immediately returns <code>false</code>. If
* the current first responder returns <code>true</code>, the receiver is made
* its own first responder and this method returns <code>true</code>.
* </p>
* <p>
* Use <code>#setInitialFirstResponder()</code> to the set the first responder
* to be used when the window is brought onscreen for the first time.
* </p>
*/
public function makeFirstResponder(aResponder:NSResponder):Boolean {
if(m_app.isRunningModal() && m_app.modalWindow()!=this) {
return false;
}
if (m_firstResponder == aResponder) {
return true;
}
if ((!(aResponder instanceof NSResponder) || !aResponder.acceptsFirstResponder()) && aResponder != null) {
return false;
}
if (m_firstResponder != null && !m_firstResponder.resignFirstResponder()) {
return false;
}
m_firstResponder = aResponder;
if (m_firstResponder == null || !m_firstResponder.becomeFirstResponder()) {
m_firstResponder = this;
m_firstResponder.becomeFirstResponder();
return aResponder == null;
}
return true;
}
public function acceptsFirstResponder():Boolean {
return true;
}
//******************************************************
//* Event handling
//******************************************************
/**
* Returns <code>true</code> if this window accepts and redistributes mouseMoved
* events among its responders.
*
* By default, this is set to <code>false</code>.
*/
public function acceptsMouseMovedEvents():Boolean {
return m_acceptsMouseMoved;
}
/**
* Sets whether this window accepts and redistributes mouseMoved events among
* its responders. If <code>flag</code> is <code>true</code>, then it does.
*
* By default, this is set to <code>false</code>.
*/
public function setAcceptsMouseMovedEvents(flag:Boolean):Void {
m_acceptsMouseMoved = flag;
}
public function currentEvent():NSEvent {
return m_app.currentEvent();
}
public function postEventAtStart(event:NSEvent, atStart:Boolean):Void {
m_app.postEventAtStart(event, atStart);
}
public function sendEvent(event:NSEvent):Void {
__sendEventBecomesKeyOnlyIfNeeded(event, false);
}
public function performKeyEquivalent(event:NSEvent):Boolean {
return m_rootView.performKeyEquivalent(event);
}
private function __sendEventBecomesKeyOnlyIfNeeded(event:NSEvent,
becomesKeyOnlyIfNeeded:Boolean):Void {
var wasKey:Boolean = m_isKey;
switch(event.type) {
case NSEvent.NSLeftMouseDown:
if (!wasKey && m_level != NSDesktopWindowLevel) {
if (!becomesKeyOnlyIfNeeded || event.view.needsPanelToBecomeKey()) {
makeKeyAndOrderFront();
if(makeMainAndKey) {
makeMainWindow();
}
}
}
// if (m_firstResponder != event.view) {
// makeFirstResponder(event.view);
// }
if (null != m_lastEventView) {
m_lastEventView = null;
}
if (wasKey || event.view.acceptsFirstMouse(event)) {
m_lastEventView = event.view;
event.view.mouseDown(event);
}
m_lastPoint = event.locationInWindow.clone();
break;
case NSEvent.NSLeftMouseUp:
//
// If we're dragging, let's do our thing.
//
if (g_isDragging) {
//
// Update the dest window
//
if (g_currentDragInfo.draggingDestinationWindow() != this) {
g_currentDragInfo.setDraggingDestinationWindow(this);
}
//
// Get destination
//
var dest:NSDraggingDestination = NSDraggingDestination(event.view);
var dragOp:NSDragOperation;
//
// Check if dragging is accepted by this destination, and that
// the operation is allowed.
//
if (g_currentDragInfo.doesViewHandleTypes(event.view)
&& null != (dragOp = dest.draggingUpdated(g_currentDragInfo))
&& g_currentDragInfo.draggingSourceOperationMask()
& dest.draggingUpdated(g_currentDragInfo).valueOf()
!= NSDragOperation.NSDragOperationNone.valueOf()) {
if (dest.prepareForDragOperation(g_currentDragInfo)) {
if (dest.performDragOperation(g_currentDragInfo)) {
dest.concludeDragOperation(g_currentDragInfo);
g_currentDragInfo.draggingSource().draggedImageEndedAtOperation(
g_currentDragInfo.draggedImage(), event.mouseLocation,
dragOp);
} else {
g_currentDragInfo.draggingSource().draggedImageEndedAtOperation(
g_currentDragInfo.draggedImage(), event.mouseLocation,
NSDragOperation.NSDragOperationNone);
}
} else {
g_currentDragInfo.draggingSource().draggedImageEndedAtOperation(
g_currentDragInfo.draggedImage(), event.mouseLocation,
NSDragOperation.NSDragOperationNone);
}
NSApplication.sharedApplication().draggingClip().clear();
} else {
//
// End the sequence, slide back if necessary.
//
if (g_currentDragInfo.slideBack()) {
g_currentDragInfo.slideDraggedImageTo(g_dragStartPt);
} else {
NSApplication.sharedApplication().draggingClip().clear();
}
g_currentDragInfo.draggingSource().draggedImageEndedAtOperation(
g_currentDragInfo.draggedImage(), event.mouseLocation,
NSDragOperation.NSDragOperationNone);
}
g_isDragging = false;
g_currentDragInfo = null;
}
//
// Send mouse up to the view that got mouse down
//
m_lastEventView.mouseUp(event);
m_lastPoint = event.locationInWindow.clone();
break;
case NSEvent.NSKeyDown:
//
// Check for default push button
//
var char:Number = event.keyCode;
if ((char == NSNewlineCharacter
|| char == NSEnterCharacter
|| char == NSCarriageReturnCharacter)
&& m_keyEquivForDefButton
&& defaultButtonCell() != null) {
defaultButtonCell().performClick();
} else {
m_firstResponder.keyDown(event);
}
break;
case NSEvent.NSKeyUp:
m_firstResponder.keyUp(event);
break;
case NSEvent.NSScrollWheel:
event.view.scrollWheel(event);
break;
case NSEvent.NSMouseMoved:
case NSEvent.NSLeftMouseDragged:
//
// If we're dragging, deal with it.
//
if (g_isDragging) {
//
// Update the dest window
//
if (g_currentDragInfo.draggingDestinationWindow() != this) {
g_currentDragInfo.setDraggingDestinationWindow(this);
}
//
// Inform source of movement.
//
g_currentDragInfo.draggingSource().draggedImageMovedTo(
g_currentDragInfo.draggedImage(), event.mouseLocation.clone());
//
// Send any draggingEntered, draggingUpdated or draggingExited
// messages.
//
var lastView:NSView = g_lastDragView;
if (lastView != event.view) {
if (g_currentDragInfo.doesViewHandleTypes(lastView)) {
lastView.draggingExited(g_currentDragInfo);
}
if (g_currentDragInfo.doesViewHandleTypes(event.view)) {
event.view.draggingEntered(g_currentDragInfo);
}
g_lastDragView = event.view;
} else {
if (g_currentDragInfo.doesViewHandleTypes(event.view)) {
event.view.draggingUpdated(g_currentDragInfo);
}
}
}
case NSEvent.NSRightMouseDragged:
case NSEvent.NSOtherMouseDragged:
switch (event.type) {
case NSEvent.NSLeftMouseDragged:
m_lastEventView.mouseDragged(event);
break;
case NSEvent.NSRightMouseDown:
m_lastEventView.rightMouseDragged(event);
break;
case NSEvent.NSOtherMouseDown:
m_lastEventView.otherMouseDragged(event);
break;
default:
break;
}
//
// Cycle through all views and determine if any have tracking rects, and
// if so, send them the appropriate mouseEntered or mouseExited events.
//
checkTrackingAndCursorRects(event.view, event);
if (event.view != m_lastView) {
checkTrackingForLastView(event);
m_lastView = event.view;
}
m_lastPoint = event.locationInWindow.clone();
break;
case NSEvent.NSOtherMouseDown:
event.view.otherMouseDown(event);
//! TODO does anything else need to be done here?
break;
case NSEvent.NSOtherMouseUp:
event.view.otherMouseUp(event);
//! TODO does anything else need to be done here?
break;
}
}
/**
* Called by NSApplication.
*/
public function checkTrackingForLastView(event:NSEvent):Void {
checkTrackingAndCursorRects(m_lastView, event);
}
/**
* Dispatches mouseEntered and mouseExited events amoung tracking, tool tip
* and cursor rectangles.
*/
private function checkTrackingAndCursorRects(aView:NSView, event:NSEvent):Void {
//
// Do nothing if there isn't a view.
//
if (null == aView || aView.window() == null) {
return;
}
//
// Remember the original mouse type
//
var origType:Number = event.type;
var origUserData:Object = event.userData;
//
// Check tracking rectangles on aView.
//
if (aView["m_hasTrackingRects"]
|| aView["m_hasCursorRects"]
|| aView["m_hasToolTips"]
|| aView["m_hasCursorAncestors"]
|| aView["m_hasTrackingAncestors"]) {
var rects:Array = [];
var cnt:Number;
//
// Check the tracking rects of ancestors if flagged
//
if (m_isKey && m_cursorRectsEnabled && aView["m_hasCursorAncestors"]) {
var ancestors:Array = NSArray(aView["m_cursorAncestors"]).internalList();
var len:Number = ancestors.length;
for (var i:Number = 0; i < len; i++) {
var ancRects:Array = NSArray(ancestors[i]["m_cursorRects"]).internalList();
var len2:Number = ancRects.length;
for (var j:Number = 0; j < len2; j++) {
ancRects[j].view = ancestors[i];
}
rects = rects.concat(ancRects);
}
}
if (aView["m_hasTrackingAncestors"]) {
var ancestors:Array = NSArray(aView["m_trackingAncestors"]).internalList();
var len:Number = ancestors.length;
for (var i:Number = 0; i < len; i++) {
var ancRects:Array = NSArray(ancestors[i]["m_trackingRects"]).internalList();
var len2:Number = ancRects.length;
for (var j:Number = 0; j < len2; j++) {
ancRects[j].view = ancestors[i];
}
rects = rects.concat(ancRects);
}
}
//
// Check for tracking rects
//
if (aView["m_hasTrackingRects"]) {
var tRects:Array = NSArray(aView["m_trackingRects"]).internalList();
if (aView["m_isTrackingAncestor"]) {
var len:Number = tRects.length;
for (var i:Number = 0; i < len; i++) {
tRects[i].view = aView;
}
}
rects = rects.concat(tRects);
}
//
// Check for cursor rects.
//
if (m_isKey && m_cursorRectsEnabled && aView["m_hasCursorRects"]) {
rects = rects.concat(NSArray(aView["m_cursorRects"]).internalList());
}
//
// Check for tooltips.
//
if (aView["m_hasToolTips"]) {
rects = rects.concat(NSArray(aView["m_toolTipRects"]).internalList());
}
cnt = rects.length;
var isViewDefault:Boolean;
var isView:Boolean = isViewDefault = aView == event.view;
var thisPt:NSPoint = m_rootView.convertPointToView(event.locationInWindow,
aView);
var lastPt:NSPoint = m_rootView.convertPointToView(m_lastPoint, aView);
//
// Loop through the rects and hitTest against the mouse location.
//
for (var i:Number = 0; i < cnt; i++) {
var then:Boolean, now:Boolean;
isView = isViewDefault;
var r:Object = rects[i];
var curRect:NSRect = r.rect;
event.userData = r.userData;
//
// Convert to the local coordinate system if required
//
if (r.view != null) {
curRect = aView.convertRectFromView(curRect, NSView(r.view));
isView = true;
}
now = curRect.pointInRect(thisPt);
then = curRect.pointInRect(lastPt);
//
// Determine whether the mouse has entered the rect, exited the rect
// or is just moving within the rect.
//
if (now && !r.hasEntered && isView) {
event.type = NSEvent.NSMouseEntered;
if (ASUtils.respondsToSelector(r.owner, "mouseEntered")) {
r.owner.mouseEntered(event);
}
r.hasEntered = true;
}
else if ((then && !now && r.hasEntered) || !isView) {
event.type = NSEvent.NSMouseExited;
if (ASUtils.respondsToSelector(r.owner, "mouseExited")) {
r.owner.mouseExited(event);
}
r.hasEntered = false;
}
else if (now && ASUtils.respondsToSelector(r.owner, "mouseMoved")) {
r.owner.mouseMoved(event);
}
}
//
// Reset event type
//
event.type = origType;
}
//
// Reset event user data
//
event.userData = origUserData;
}
public function keyDown(event:NSEvent):Void {
if (event.keyCode == NSTabCharacter) {
if (event.modifierFlags & NSEvent.NSShiftKeyMask) {
selectPreviousKeyView(this);
} else {
selectNextKeyView(this);
}
return;
}
if (event.keyCode == Key.ESCAPE) {
if (m_app.modalWindow() == this) {
m_app.stopModal(); //! Should be abortModal()?
}
return;
}
var char:Number = event.keyCode;
if ((char == NSNewlineCharacter
|| char == NSEnterCharacter
|| char == NSCarriageReturnCharacter)
&& m_keyEquivForDefButton
&& defaultButtonCell() != null) {
defaultButtonCell().performClick();
}
//! performKeyEquivalent
}
/**
* Overridden for background movement.
*/
public function mouseDown(event:NSEvent):Void {
if (isMovableByWindowBackground()) {
m_rootView.mouseDown(event);
} else {
super.mouseDown(event);
}
}
//******************************************************
//* Working with the field editor
//******************************************************
// TODO fieldEditor:forObject:
// TODO endEditingFor:
//******************************************************
//* Keyboard interface control
//******************************************************
/**
* <p>
* Sets <code>view</code> as the NSView that’s made first responder (also
* called the key view) the first time the receiver is placed onscreen.
* </p>
*
* @see #initialFirstResponder()
*/
public function setInitialFirstResponder(view:NSView):Void {
if (view instanceof NSView) {
m_initialFirstResponder = view;
}
}
/**
* <p>
* Returns the NSView that’s made first responder the first time the receiver
* is placed onscreen.
* </p>
*
* @see #setInitialFirstResponder()
* @see NSView#setNextKeyView()
*/
public function initialFirstResponder():NSView {
return m_initialFirstResponder;
}
/**
* <p>
* Sends the NSView message {@link NSView#nextValidKeyView()} to
* <code>view</code>, and if that message returns an NSView, invokes
* {@link #makeFirstResponder()} with the returned NSView.
* </p>
*
* @see #selectKeyViewPrecedingView()
*/
public function selectKeyViewFollowingView(view:NSView):Void {
var fView:NSView;
if (view instanceof NSView) {
fView = view.nextValidKeyView();
if (fView != null) {
makeFirstResponder(fView);
if (fView.respondsToSelector("selectText")) {
m_selectionDirection = NSSelectionDirection.NSSelectingNext;
Object(fView).selectText(this);
m_selectionDirection = NSSelectionDirection.NSDirectSelection;
}
}
}
}
/**
* <p>
* Sends the NSView message {@link NSView#previousValidKeyView()} to
* <code>view</code>, and if that message returns an NSView, invokes
* {@link #makeFirstResponder()} with the returned NSView.
* </p>
*
* @see #selectKeyViewFollowingView()
*/
public function selectKeyViewPrecedingView(view:NSView):Void {
var pView:NSView;
if (view instanceof NSView) {
pView = view.previousValidKeyView();
if (pView != null) {
makeFirstResponder(pView);
if (pView.respondsToSelector("selectText")) {
m_selectionDirection = NSSelectionDirection.NSSelectingPrevious;
Object(pView).selectText(this);
m_selectionDirection = NSSelectionDirection.NSDirectSelection;
}
}
}
}
/**
* <p>
* This action method searches for a candidate key view and, if it finds one,
* invokes {@link #makeFirstResponder()} to establish it as the first
* responder.
* </p>
* <p>
* The candidate is one of the following (searched for in this order):
* </p>
* <ul>
* <li>
* The current first responder’s next valid key view, as returned by
* NSView’s {@link NSView#nextValidKeyView()} method.
* </li>
* <li>
* The object designated as the receiver’s initial first responder (using
* {@link #setInitialFirstResponder()}) if it returns <code>true</code> to an
* {@link #acceptsFirstResponder()} message.
* </li>
* <li>
* Otherwise, the initial first responder’s next valid key view, which may end
* up being <code>null</code>.
* </li>
* </ul>
*
* @see #selectPreviousKeyView()
* @see #selectKeyViewFollowingView()
*/
public function selectNextKeyView(sender:Object):Void {
var result:NSView = null;
if (m_firstResponder instanceof NSView) {
result = NSView(m_firstResponder).nextValidKeyView();
}
if (result == null && m_initialFirstResponder != null) {
if (m_initialFirstResponder.acceptsFirstResponder()) {
result = m_initialFirstResponder;
} else {
result = m_initialFirstResponder.nextValidKeyView();
}
}
if (result != null) {
makeFirstResponder(result);
if (result.respondsToSelector("selectText")) {
m_selectionDirection = NSSelectionDirection.NSSelectingNext;
Object(result).selectText(this);
m_selectionDirection = NSSelectionDirection.NSDirectSelection;
}
}
}
/**
* <p>
* This action method searches for a candidate key view and, if it finds one,
* invokes {@link #makeFirstResponder()} to establish it as the first
* responder.
* </p>
* <p>
* The candidate is one of the following (searched for in this order):
* </p>
* <ul>
* <li>
* The current first responder’s previous valid key view, as returned by
* NSView’s {@link NSView#previousValidKeyView()} method.
* </li>
* <li>
* The object designated as the receiver’s initial first responder (using
* {@link #setInitialFirstResponder()}) if it returns <code>true</code> to an
* {@link #acceptsFirstResponder()} message.
* </li>
* <li>
* Otherwise, the initial first responder’s previous valid key view, which may
* end up being <code>null</code>.
* </li>
* </ul>
*
* @see #selectNextKeyView()
* @see #selectKeyViewPrecedingView()
*/
public function selectPreviousKeyView(sender:Object):Void {
var result:NSView = null;
if (m_firstResponder instanceof NSView) {
result = NSView(m_firstResponder).previousValidKeyView();
}
if (result == null && m_initialFirstResponder != null) {
if (m_initialFirstResponder.acceptsFirstResponder()) {
result = m_initialFirstResponder;
} else {
result = m_initialFirstResponder.previousValidKeyView();
}
}
if (result != null) {
makeFirstResponder(result);
if (result.respondsToSelector("selectText")) {
m_selectionDirection = NSSelectionDirection.NSSelectingPrevious;
Object(result).selectText(this);
m_selectionDirection = NSSelectionDirection.NSDirectSelection;
}
}
}
/**
* <p>
* Returns the direction the receiver is currently using to change the key
* view.
* </p>
*
* @see #selectNextKeyView()
* @see #selectPreviousKeyView()
*/
public function keyViewSelectionDirection():NSSelectionDirection {
return m_selectionDirection;
}
//******************************************************
//* Setting the title and filename
//******************************************************
/**
* Sets the text in this window's title bar to <code>aString</code>. If the
* window doesn't have a title bar, this text is not visible.
*/
public function setTitle(aString:String):Void {
m_title = aString;
m_rootView.setNeedsDisplay(true);
//!display
}
/**
* Returns the text that is shown in this window's title bar.
*/
public function title():String {
return m_title;
}
//******************************************************
//* Closing the window
//******************************************************
/**
* First posts an <code>NSWindowWillCloseNotification</code> notification
* to the default notification center, then closes the window.
*
* This method does not ask the delegate whether the window should close,
* nor does it simulate a button press on the close button. If you desire
* this functionality, use {@link #performClose} instead.
*/
public function close():Void {
m_notificationCenter.postNotificationWithNameObject(
NSWindowWillCloseNotification, this);
hide();
if (isReleasedWhenClosed()) {
release();
}
// m_nsapp.removeWindowsItem(); ???
// order out ???
}
/**
* Simulates a close as if the window pressed the close button. The close
* button is momentarily highlighted, then a <code>windowShouldClose</code>
* message is sent to the delegate. If the delegate returns <code>true</code>
* then the window is closed using {@link #close()}. If the delegate
* returns <code>false</code>, then the window remains open.
*/
public function performClose(sender:Object):Void {
//
// Beep if there is no close button.
//
if (!(styleMask() & NSWindow.NSClosableWindowMask)) {
beep();
return;
}
//
// Highlight the button.
//
if (sender != m_rootView.closeButton()) {
m_rootView.closeButton().performClick();
return;
}
var closeWnd:Boolean = true;
if (ASUtils.respondsToSelector(m_delegate, "windowShouldClose")) {
closeWnd = m_delegate.windowShouldClose(this);
}
if (closeWnd) {
close();
} else {
beep();
}
}
/**
* <p>Sets whether the receiver is merely hidden (<code>false</code>) or hidden
* and then released (<code>true</code>) when it receives a close message.</p>
*
* <p>The default is <code>true</code>.</p>
*
* @see #isReleasedWhenClosed()
*/
public function setReleasedWhenClosed(flag:Boolean):Void {
m_releasedWhenClosed = flag;
}
/**
* Returns <code>true</code> if the receiver is automatically released after
* being closed, <code>false</code> if it’s simply removed from the screen.
*
* @see #setReleasedWhenClosed()
*/
public function isReleasedWhenClosed():Boolean {
return m_releasedWhenClosed;
}
//******************************************************
//* Miniaturizing and miniaturized windows
//******************************************************
/**
* This method miniaturizes the window so that only the title bar is showing.
*
* This differs from the Cocoa implementation.
*/
public function miniaturize(sender:Object):Void {
if (m_isMini) {
return;
}
m_notificationCenter.postNotificationWithNameObject(
NSWindowWillMiniaturizeNotification, this);
m_preminiSize = contentSize();
m_preminiStyle = styleMask();
m_preminiResizeInd = m_rootView.showsResizeIndicator();
m_styleMask = ASAllButResizable & m_preminiStyle;
m_rootView.setShowsResizeIndicator(false);
setContentSize(new NSSize(m_frameRect.size.width, 0));
m_rootView.setNeedsDisplay(true);
m_isMini = true;
//
// Hide drawers
//
var drawers:Array = m_drawers.internalList();
var len:Number = drawers.length;
for (var i:Number = 0; i < len; i++) {
var drawer:NSDrawer = NSDrawer(drawers[i]);
if (drawer.state() == NSDrawerState.NSDrawerOpenState
|| drawer.state() == NSDrawerState.NSDrawerOpeningState) {
drawer.drawerWindow().hide();
}
}
var btn:NSButton = m_rootView.miniaturizeButton();
btn.setImage(NSImage.imageNamed("NSWindowRestoreIconRep"));
btn.setToolTip("Restore");
btn.setAction("deminiaturizeWindow");
m_notificationCenter.postNotificationWithNameObject(
NSWindowDidMiniaturizeNotification, this);
}
/**
* Simulates a click on the miniaturize button. If this window has no
* miniaturize button, the system will beep.
*/
public function performMiniaturize(sender:Object):Void {
//
// Beep if there is no miniaturize button.
//
if (!(styleMask() & NSWindow.NSMiniaturizableWindowMask)) {
beep();
return;
}
//
// Highlight the button.
//
if (sender != m_rootView.miniaturizeButton()) {
m_rootView.miniaturizeButton().performClick();
return;
}
//
// Miniaturize the window
//
miniaturize(this);
}
/**
* This method deminiaturizes this window.
*/
public function deminiaturize(sender:Object):Void {
if (!m_isMini) {
return;
}
m_styleMask = m_preminiStyle;
m_rootView.setShowsResizeIndicator(m_preminiResizeInd);
setContentSize(m_preminiSize);
m_rootView.setNeedsDisplay(true);
m_isMini = false;
//
// Show drawers
//
var drawers:Array = m_drawers.internalList();
var len:Number = drawers.length;
for (var i:Number = 0; i < len; i++) {
var drawer:NSDrawer = NSDrawer(drawers[i]);
if (drawer.state() == NSDrawerState.NSDrawerOpenState
|| drawer.state() == NSDrawerState.NSDrawerOpeningState) {
drawer.drawerWindow().show();
}
}
var btn:NSButton = m_rootView.miniaturizeButton();
btn.setImage(NSImage.imageNamed("NSWindowMiniaturizeIconRep"));
btn.setToolTip("Miniaturize");
btn.setAction("miniaturizeWindow");
m_notificationCenter.postNotificationWithNameObject(
NSWindowDidDeminiaturizeNotification, this);
}
/**
* Returns <code>true</code> if the window is miniaturized, or
* <code>false</code> otherwise.
*/
public function isMiniaturized():Boolean {
return m_isMini;
}
//******************************************************
//* Dealing with cursor rects
//******************************************************
/**
* Enables the ability for views inside this window to have cursor rectangles.
*
* @see #disableCursorRects
*/
public function enableCursorRects():Void {
m_cursorRectsEnabled = true;
}
/**
* Disables the ability for views inside this window to have cursor rects.
*
* @see #enableCursorRects
*/
public function disableCursorRects():Void {
m_cursorRectsEnabled = false;
}
/**
* Calls {@code #discardCursorRects}, then calls
* {@code NSView#resetCursorRects} for every view in the view hierarchy.
*/
public function resetCursorRects():Void {
discardCursorRects();
resetCursorRectsForTree(m_rootView);
}
/**
* Recursive function that will call {@code #invalidateCursorRectsForView} for
* <code>aView</code> and all of its subviews.
*/
private function resetCursorRectsForTree(aView:NSView):Void {
invalidateCursorRectsForView(aView);
var svs:Array = aView.subviews();
var cnt:Number = svs.length;
for (var i:Number = 0; i < cnt; i++) {
resetCursorRectsForTree(NSView(svs[i]));
}
}
/**
* Invalidates all cursor rects in the window.
*
* Do not call this method directly. Instead, override it to provide more
* specific functionality.
*/
public function discardCursorRects():Void {
// do nothing
}
/**
* Marks the cursor rectangles of <code>aView</code> invalid, and recalculates
* them immediately if this window is the key window.
*/
public function invalidateCursorRectsForView(aView:NSView):Void {
aView.discardCursorRects();
aView.resetCursorRects();
}
//******************************************************
//* Dragging
//******************************************************
/**
* This method is the same as
* <code>NSView.dragImageAtOffsetEventPasteboardSourceSlideBack</code> except
* <code>imageLoc</code> is expressed in the window's base coordinate system,
* not the view's.
*/
public function dragImageAtOffsetEventPasteboardSourceSlideBack(
image:NSImage, imageLoc:NSPoint, offset:NSSize, event:NSEvent,
pasteboard:NSPasteboard, source:NSDraggingSource, slideBack:Boolean)
:Void {
//
// We can't drag two things at once.
//
if (g_isDragging) {
return;
}
//
// Create the new dragging info.
//
var info:NSDraggingInfo;
g_currentDragInfo = info = NSDraggingInfo.
draggingInfoWithImageAtOffsetPasteboardSourceSlideBack(
image, imageLoc, offset, pasteboard, source, slideBack);
g_isDragging = true;
g_dragStartPt = event.mouseLocation.clone();
//
// Inform the source.
//
source.draggedImageBeganAt(image, event.mouseLocation.clone());
//
// Draw the image on the drag clip
//
var dragClip:MovieClip = NSApplication.sharedApplication().draggingClip();
dragClip.clear();
image.lockFocus(dragClip);
image.drawAtPoint(new NSPoint(offset.width, offset.height));
image.unlockFocus();
}
/**
* Registers <code>pboardTypes</code> as the types this window will accept
* as the destination of a dragging session.
*
* @see #unregisterDraggedTypes
*/
public function registerForDraggedTypes(pboardTypes:NSArray):Void {
rootView().registerForDraggedTypes(pboardTypes);
}
/**
* Unregisters this window as a destination for dragging operations.
*
* @see #registerDraggedTypes
*/
public function unregisterDraggedTypes():Void {
rootView().unregisterDraggedTypes();
}
/**
* Internal method. Registers a view <code>view</code> with a list of types,
* <code>pboardTypes</code>.
*/
public function registerViewForDraggedTypes(view:NSView, pboardTypes:NSArray)
:Void {
if (null == m_registeredDraggedTypes) {
m_registeredDraggedTypes = NSDictionary.dictionary();
}
m_registeredDraggedTypes.setObjectForKey(pboardTypes, view.viewNum()
.toString());
}
/**
* Internal method. Returns types registered to <code>view</code>.
*/
public function registeredDraggedTypesForView(view:NSView):NSArray {
return NSArray(m_registeredDraggedTypes.objectForKey(view.viewNum()
.toString()));
}
/**
* Unregisters all types registered with <code>view</code>.
*/
public function unregisterDraggedTypesForView(view:NSView):Void {
m_registeredDraggedTypes.removeObjectForKey(view.viewNum().toString());
}
//******************************************************
//* Controlling behavior
//******************************************************
/**
* Returns a Boolean value that indicates whether the receiver is able to
* receive keyboard and mouse events even when some other window is being run
* modally.
*/
public function worksWhenModal():Boolean {
return false;
}
public function canHide():Boolean {
return m_canHide;
}
public function setCanHide(value:Boolean):Void {
m_canHide = value;
}
//******************************************************
//* Working with display characteristics
//******************************************************
/**
* Returns this window's contentView, which is the top-most accessible view.
*/
public function contentView():NSView {
return m_contentView;
}
/**
* Sets this window's contentView, which is the top-most accessible view.
*/
public function setContentView(view:NSView):Void {
if (view == null) {
view = (new NSView()).initWithFrame(NSRect.withOriginSize(
convertScreenToBase(m_contentRect.origin), m_contentRect.size));
}
if (m_contentView != null) {
m_contentView.removeFromSuperview();
}
m_contentView = view;
m_rootView.setContentView(m_contentView);
m_contentView.setFrame(NSRect.withOriginSize(convertScreenToBase(
m_contentRect.origin), m_contentRect.size));
m_contentView.setNextResponder(this);
}
/**
* Sets this window's background color to <code>aColor</code>.
*/
public function setBackgroundColor(aColor:NSColor):Void {
m_backgroundColor = aColor;
m_rootView.setNeedsDisplay(true);
}
/**
* Returns this window's background color.
*/
public function backgroundColor():NSColor {
return m_backgroundColor;
}
/**
* Returns the receiver’s style mask, indicating what kinds of control items
* it displays.
*/
public function styleMask():Number {
return m_styleMask;
}
/**
* Sets whether the receiver has a shadow to <code>hasShadow</code>.
*/
public function setHasShadow(hasShadow:Boolean):Void {
m_rootView.setHasShadow(hasShadow);
}
/**
* Returns <code>true</code> if the window has a shadow; otherwise returns
* <code>false</code>.
*/
public function hasShadow():Boolean {
return m_rootView.hasShadow();
}
/**
* Sets the receiver’s alpha value to <code>windowAlpha</code>.
*/
public function setAlphaValue(windowAlpha:Number):Void {
trace(windowAlpha);
m_rootView.setAlphaValue(windowAlpha * 100);
}
/**
* Returns the receiver’s alpha value.
*/
public function alphaValue():Number {
return m_rootView.alphaValue() / 100;
}
//******************************************************
//* Working with icons
//******************************************************
/**
* Sets the icon of the window to <code>anImage</code>. This icon is resized
* as a square with side lengths of title bar's height.
*
* If <code>anImage</code> is <code>null</code>, the window will not use an
* icon.
*
* This method is actionstep only.
*/
public function setIcon(anImage:NSImage):Void {
NSNotificationCenter.defaultCenter().removeObserverNameObject(
this, NSImage.NSImageDidLoadNotification, icon());
m_icon = anImage;
NSNotificationCenter.defaultCenter().addObserverSelectorNameObject(
this, "iconDidLoad", NSImage.NSImageDidLoadNotification, anImage);
}
/**
* Returns the icon used for this window, or <code>null</code> if none exists.
*
* This method is actionstep only.
*/
public function icon():NSImage {
return m_icon;
}
/**
* Fired when this image view's image loads.
*/
private function iconDidLoad(ntf:NSNotification):Void {
rootView().setNeedsDisplay(true);
}
//******************************************************
//* Undo manager
//******************************************************
/**
* <p>Returns the undo manager for this responder.</p>
*
* <p><code>NSResponder</code>’s implementation simply passes this message to
* the next responder.</p>
*/
public function undoManager():NSUndoManager {
if (m_delegate != null && ASUtils.respondsToSelector(m_delegate,
"windowWillReturnUndoManager")) {
return NSUndoManager(m_delegate["windowWillReturnUndoManager"](this));
}
if (m_undoManager == null) {
m_undoManager = (new NSUndoManager()).init();
}
return m_undoManager;
}
//******************************************************
//* Sets the window view class
//******************************************************
/**
* Returns the view class used to draw this window.
*/
public function viewClass():Function {
if (m_viewClass == undefined) {
m_viewClass = ASRootWindowView;
}
return m_viewClass;
}
/**
* Disposes this window.
*/
public function release():Boolean {
super.release();
m_rootView.removeFromSuperview();
m_rootView.release();
m_drawers.makeObjectsPerformSelectorWithObject("setParentWindow", null);
m_drawers.removeAllObjects();
m_childWindows.makeObjectsPerformSelectorWithObject("setParentWindow", null);
m_childWindows.removeAllObjects();
delete m_rootView;
delete m_drawers;
delete m_childWindows;
resignKeyWindow();
resignMainWindow();
g_instances[m_windowNumber] = null;
return true;
}
public function mouseLocationOutsideOfEventStream():NSPoint {
return null;
}
//******************************************************
//* Field editor
//******************************************************
/*
public function fieldEditorCreateFlagForObject(createFlag:Boolean, object):NSText {
//! should delegate
if (m_fieldEditor == null && createFlag) {
m_fieldEditor = new NSTextView();
m_fieldEditor.setFieldEditor(true);
}
return m_fieldEditor;
}
public function endEditingForAnObject(object) {
var editor:NSText = fieldEditorCreateFlagForObject(false, object);
if (editor != null && (editor == m_firstResponder)) {
m_notificationCenter.postNotificationWithNameObject(NSTextView.NSTextDidEndEditingNotification, editor);
editor.setString("");
editor.setDelegate(null);
editor.removeFromSuperview();
m_firstResponder = this;
m_firstResponder.becomeFirstResponder();
}
}
*/
//******************************************************
//* Setting the delegate
//******************************************************
public function delegate():Object {
return m_delegate;
}
public function setDelegate(value:Object):Void {
if(m_delegate != null) {
m_notificationCenter.removeObserverNameObject(m_delegate, null, this);
}
m_delegate = value;
if (value == null) {
return;
}
mapDelegateNotification("DidBecomeKey");
mapDelegateNotification("DidBecomeMain");
mapDelegateNotification("DidResignKey");
mapDelegateNotification("DidResignMain");
mapDelegateNotification("WillMove");
mapDelegateNotification("DidResize");
mapDelegateNotification("WillClose");
mapDelegateNotification("WillMiniaturize");
mapDelegateNotification("DidMinitiaturize");
mapDelegateNotification("DidDeminiaturize");
mapDelegateNotification("DidDisplay");
}
private function mapDelegateNotification(name:String):Void {
if(typeof(m_delegate["window"+name]) == "function") {
m_notificationCenter.addObserverSelectorNameObject(m_delegate, "window"+name, ASUtils.intern("NSWindow"+name+"Notification"), this);
}
}
//******************************************************
//* Getting associated information
//******************************************************
/**
* Returns the collection of drawers associated with the receiver.
*/
public function drawers():NSArray {
return (new NSArray()).initWithArrayCopyItems(m_drawers, false);
}
/**
* For internal use only.
*/
public function addDrawer(drawer:NSDrawer):Void {
if (m_drawers.containsObject(drawer)) {
return;
}
// FIXME not sure if I should be using the child window array...
m_drawers.addObject(drawer);
addChildWindowOrdered(drawer.drawerWindow(), NSWindowOrderingMode.NSWindowBelow);
}
/**
* For internal use only.
*/
public function removeDrawer(drawer:NSDrawer):Void {
if (!m_drawers.containsObject(drawer)) {
return;
}
// FIXME not sure if I should be using the child window array...
m_drawers.removeObject(drawer);
removeChildWindow(drawer.drawerWindow());
}
// TODO setWindowController:
// TODO windowController
//******************************************************
//* Working with sheets
//******************************************************
/**
* Returns <code>true</code> if the receiver has ever run as a modal sheet.
* Sheets are created using the <code>NSPanel</code> subclass.
*/
public function isSheet():Boolean {
return false;
}
// TODO attachedSheet()
//******************************************************
//* Working with toolbars
//******************************************************
/**
* <p>Returns the receiver’s toolbar.</p>
*
* @see #setToolbar()
*/
public function toolbar():NSToolbar {
return m_toolbar;
}
/**
* <p>Sets the receiver’s toolbar to <code>toolbar</code>.</p>
*
* @see #toolbar()
*/
public function setToolbar(toolbar:NSToolbar):Void {
if (m_toolbar != null) {
m_toolbar.__setWindow(null);
}
m_toolbar = toolbar;
m_toolbar.__setWindow(this);
__adjustForToolbar();
}
/**
* Toggles the visibility of this window's toolbar, if one exists.
*/
public function toggleToolbarShown(sender:Object):Void {
if (m_toolbar == null) {
return;
}
m_toolbar.setVisible(!m_toolbar.isVisible());
}
/**
* <p>
* Called to adjust the window to accommodate the toolbar (or lack therof).
* </p>
* <p>
* For internal use only.
* </p>
*/
public function __adjustForToolbar():Void {
var frm:NSRect = frameRectForContentRect();
setFrameWithNotifications(frm, false);
m_rootView.setNeedsDisplay(true);
}
//******************************************************
//* Getting all window instances
//******************************************************
/**
* <p>
* Returns all window instances. This method is intended for internal use
* only.
* </p>
*/
public static function instances():Array {
return g_instances;
}
}
|
package cmodule.lua_wrapper
{
const __2E_str27286:int = gstaticInitter.alloc(9,1);
}
|
package {
import laya.display.Graphics;
import laya.display.Input;
import laya.display.Sprite;
import laya.display.Stage;
import laya.display.css.Font;
import laya.display.css.Style;
import laya.events.KeyBoardManager;
import laya.events.MouseManager;
import laya.media.SoundManager;
import laya.net.LoaderManager;
import laya.net.LocalStorage;
import laya.net.URL;
import laya.renders.Render;
import laya.renders.RenderSprite;
import laya.resource.Context;
import laya.resource.ResourceManager;
import laya.runtime.ICPlatformClass;
import laya.runtime.IMarket;
import laya.utils.Browser;
import laya.utils.CacheManager;
import laya.utils.Timer;
import laya.utils.WeakObject;
/**
* <code>Laya</code> 是全局对象的引用入口集。
* Laya类引用了一些常用的全局对象,比如Laya.stage:舞台,Laya.timer:时间管理器,Laya.loader:加载管理器,使用时注意大小写。
*/
public dynamic class Laya {
/*[COMPILER OPTIONS:normal]*/
/** 舞台对象的引用。*/
public static var stage:Stage = null;
/** 逻辑时间管理器的引用,不允许缩放。*/
public static var timer:Timer = null;
/** 表现时间管理器,可以用来控制渲染表现,可以通过scale缩放,来表现慢镜头*/
public static var scaleTimer:Timer = null;
/** 加载管理器的引用。*/
public static var loader:LoaderManager = null;
/** 当前引擎版本。*/
public static var version:String = "1.7.17";
/**@private Render 类的引用。*/
public static var render:Render;
/**@private */
public static var _currentStage:Sprite;
/**@private Market对象 只有加速器模式下才有值*/
public static var conchMarket:IMarket = __JS__("window.conch?conchMarket:null");
/**@private PlatformClass类,只有加速器模式下才有值 */
public static var PlatformClass:ICPlatformClass = __JS__("window.PlatformClass");
/**@private */
private static var _isinit:Boolean = false;
/**@private */
public static var MiniAdpter:Object = /*[STATIC SAFE]*/__JS__('{ init:function() { if (window.navigator && window.navigator.userAgent && window.navigator.userAgent.indexOf("MiniGame") >-1) console.error("请先引用小游戏适配库laya.wxmini.js,详细教程:https://ldc.layabox.com/doc/?nav=zh-ts-5-0-0") }};');
/**
* 初始化引擎。使用引擎需要先初始化引擎,否则可能会报错。
* @param width 初始化的游戏窗口宽度,又称设计宽度。
* @param height 初始化的游戏窗口高度,又称设计高度。
* @param plugins 插件列表,比如 WebGL(使用WebGL方式渲染)。
* @return 返回原生canvas引用,方便对canvas属性进行修改
*/
public static function init(width:Number, height:Number, ... plugins):* {
if (_isinit) return;
ArrayBuffer.prototype.slice || (ArrayBuffer.prototype.slice = _arrayBufferSlice);
_isinit = true;
Browser.__init__();
Context.__init__();
Graphics.__init__();
timer = new Timer();
scaleTimer = new Timer();
loader = new LoaderManager();
/*[IF-FLASH]*/
width = Browser.clientWidth;
/*[IF-FLASH]*/
height = Browser.clientHeight;
WeakObject.__init__();
for (var i:int = 0, n:int = plugins.length; i < n; i++) {
if (plugins[i].enable) plugins[i].enable();
}
Font.__init__();
Style.__init__();
ResourceManager.__init__();
CacheManager.beginCheck();
_currentStage = stage = new Stage();
stage.conchModel && stage.conchModel.setRootNode();
//forxiaochengxu
getUrlPath();
/*[IF-FLASH]*/
render = new Render(50, 50);
//[IF-JS]render = new Render(0, 0);
stage.size(width, height);
RenderSprite.__init__();
KeyBoardManager.__init__();
MouseManager.instance.__init__(stage, Render.canvas);
Input.__init__();
SoundManager.autoStopMusic = true;
LocalStorage.__init__();
return Render.canvas;
}
public static function getUrlPath():void
{
var location:* = Browser.window.location;
var pathName:String = location.pathname;
// 索引为2的字符如果是':'就是windows file协议
pathName = pathName.charAt(2) == ':' ? pathName.substring(1) : pathName;
URL.rootPath = URL.basePath = URL.getPath(location.protocol == "file:" ? pathName : location.protocol + "//" + location.host + location.pathname);
}
/**@private */
private static function _arrayBufferSlice(start:int, end:int):ArrayBuffer {
var arr:*= __JS__("this");
var arrU8List:Uint8Array = new Uint8Array(arr,start,end-start);
var newU8List:Uint8Array=new Uint8Array(arrU8List.length);
newU8List.set(arrU8List);
return newU8List.buffer;
}
/**
* 表示是否捕获全局错误并弹出提示。默认为false。
* 适用于移动设备等不方便调试的时候,设置为true后,如有未知错误,可以弹窗抛出详细错误堆栈。
*/
public static function set alertGlobalError(value:Boolean):void {
var erralert:int = 0;
if (value) {
Browser.window.onerror = function(msg:String, url:String, line:String, column:String, detail:*):void {
if (erralert++ < 5 && detail)
alert("出错啦,请把此信息截图给研发商\n" + msg + "\n" + detail.stack||detail);
}
} else {
Browser.window.onerror = null;
}
}
/**@private */
public static function _runScript(script:String):*
{
return Browser.window["e"+String.fromCharCode(100+10+8)+"a"+"l"](script);
}
}
} |
////////////////////////////////////////////////////////////////////////////////
//
// 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.binding
{
/**
* The WatcherBase class is the base class for data-binding classes that watch
* various properties and styles for changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.0
*
* @royalesuppresspublicvarwarning
*/
public class WatcherBase
{
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 1.0.0
*/
public function WatcherBase()
{
super();
}
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
/**
* The binding objects that are listening to this Watcher.
* The standard event mechanism isn't used because it's too heavyweight.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.0
*/
protected var listeners:Array;
/**
* Children of this watcher are watching sub values. For example, if watching
* {a.b.c} and this watcher is watching "b", then it is the watchers watching
* "c" and "d" if there is an {a.b.d} being watched.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.0
*/
protected var children:Array;
/**
* The value of whatever it is we are watching. For example, if watching
* {a.b.c} and this watcher is watching "b", then it is the value of "a.b".
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.0
*/
public var value:Object;
//--------------------------------------------------------------------------
//
// Methods
//
//--------------------------------------------------------------------------
/**
* This is an abstract method that subclasses implement. Implementations
* handle changes in the parent chain. For example, if watching
* {a.b.c} and this watcher is watching "b", then handle "a" changing.
*
* @param parent The new parent.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.0
*/
public function parentChanged(parent:Object):void
{
}
/**
* Add a child to this watcher, meaning that the child
* is watching a sub value of ours. For example, if watching
* {a.b.c} and this watcher is watching "b", then this method
* is called to add the watcher watching "c".
*
* @param child The new child
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.0
*/
public function addChild(child:WatcherBase):void
{
if (!children)
children = [ child ];
else
children.push(child);
child.parentChanged(this);
}
/**
* Add a binding to this watcher, meaning that the binding
* is notified when our value changes. Bindings are classes
* that actually perform the change based on changes
* detected to this portion of the chain.
*
* @param binding The new binding.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.0
*/
public function addBinding(binding:GenericBinding):void
{
if (!listeners)
listeners = [ binding ];
else
listeners.push(binding);
binding.valueChanged(value, false);
}
/**
* This method is called when the value
* might have changed and goes through
* and makes sure the children are updated.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.0
*/
public function updateChildren():void
{
if (children)
{
var n:int = children.length;
for (var i:int = 0; i < n; ++i)
{
children[i].parentChanged(this);
}
}
}
/**
* @private
*/
private function valueChanged(oldval:Object):Boolean
{
if (oldval == null && value == null)
return false;
var valType:String = typeof(value);
// The first check is meant to catch the delayed instantiation case
// where a control comes into existence but its value is still
// the equivalent of not having been filled in.
// Otherwise we simply return whether the value has changed.
if (valType == "string")
{
if (oldval == null && value == "")
return false;
else
return oldval != value;
}
if (valType == "number")
{
if (oldval == null && value == 0)
return false;
else
return oldval != value;
}
if (valType == "boolean")
{
if (oldval == null && value == false)
return false;
else
return oldval != value;
}
return true;
}
/**
* Calls a function inside a try catch block to try to
* update the value.
*
* @param wrappedFunction The function to call.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.0
*/
protected function wrapUpdate(wrappedFunction:Function):void
{
try
{
wrappedFunction.apply(this);
}
catch(error:Error)
{
var n:int = allowedErrorTypes.length;
for (var i:int = 0; i < n; i++)
{
if (error is allowedErrorTypes[i].type)
{
var handler:Function = allowedErrorTypes[i].handler;
if (handler != null)
value = handler(this, wrappedFunction);
else
value = null;
}
}
COMPILE::SWF
{
if (allowedErrors.indexOf(error.errorID) == -1)
throw error;
}
COMPILE::JS
{
var s:String = error.message;
n = allowedErrors.length;
for (i = 0; i < n; i++)
{
if (s.indexOf(allowedErrors[i]) != -1)
return;
}
throw error;
}
}
}
/**
* Certain errors are normal when executing an update, so we swallow them.
* Feel free to add more errors if needed.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.0
*/
COMPILE::SWF
public static var allowedErrors:Array = [
1006, // Error #1006: Call attempted on an object that is not a function.
1009, // Error #1009: null has no properties.
1010, // Error #1010: undefined has no properties.
1055, // Error #1055: - has no properties.
1069, // Error #1069: Property - not found on - and there is no default value
1507 // Error #1507: - invalid null argument.
];
COMPILE::JS
public static var allowedErrors:Array = [
"Call attempted on an object that is not a function.",
"null has no properties.",
"undefined has no properties.",
"undefined is not an object",
"has no properties.",
"and there is no default value",
"invalid null argument."
];
/**
* Certain errors classes are normal when executing an update, so we swallow all
* errors they represent. Feel free to add more errors if needed.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.0
*/
public static var allowedErrorTypes:Array = [
{ type: RangeError /*, handler: function(w:WatcherBase, wrappedFunction:Function):Object { return null }*/ }
];
/**
* Notify the various bindings that the value has changed so they can update
* their data binding expressions.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.0
*/
public function notifyListeners():void
{
if (listeners)
{
var n:int = listeners.length;
for (var i:int = 0; i < n; i++)
{
listeners[i].valueChanged(value, false);
}
}
}
}
}
|
package com.gestureworks.cml.layouts
{
import com.gestureworks.cml.core.CMLObject;
import com.gestureworks.cml.interfaces.ILayout;
import com.greensock.easing.Ease;
import com.greensock.plugins.TransformMatrixPlugin;
import com.greensock.plugins.TweenPlugin;
import com.greensock.TimelineLite;
import com.greensock.TweenLite;
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.geom.Matrix;
import flash.utils.getDefinitionByName;
/**
* The Layout is the base class for all Layouts.
* It is an abstract class that is not meant to be called directly.
*
* @author Charles and Shaun
* @see com.gestureworks.cml.elements.Container
* @see com.gestureworks.cml.elements.TouchContainer
*/
public class Layout extends CMLObject implements ILayout
{
protected var childTransformations:Array;
private var layoutTween:TimelineLite;
private var tweenedObjects:Array;
/**
* Constructor
*/
public function Layout()
{
super();
childTransformations = new Array();
TweenPlugin.activate([TransformMatrixPlugin]);
}
private var _originX:Number = 0;
/**
* Starting x coordinate of layout relative to the container
* @default 0
*/
public function get originX():Number { return _originX; }
public function set originX(x:Number):void
{
_originX = x;
}
public var _originY:Number = 0;
/**
* Starting y coordinate of layout relative to the container
* @default 0
*/
public function get originY():Number { return _originY; }
public function set originY(y:Number):void
{
_originY = y;
}
private var _spacingX:Number = 100;
/**
* Horizontal distance between the origins of two objects
* @default 100
*/
public function get spacingX():Number { return _spacingX; }
public function set spacingX(s:Number):void
{
_spacingX = s;
}
private var _spacingY:Number = 100;
/**
* Vertical distance between the origins of two objects
* @default 100
*/
public function get spacingY():Number { return _spacingY; }
public function set spacingY(s:Number):void
{
_spacingY = s;
}
/**
* Spacing added to the width of an object
* @default 10
*/
private var _marginX:Number = 10;
public function get marginX():Number { return _marginX; }
public function set marginX(m:Number):void
{
_marginX = m;
}
private var _marginY:Number = 10;
/**
* Spacing added to the height of an object
* @default 10
*/
public function get marginY():Number { return _marginY; }
public function set marginY(m:Number):void
{
_marginY = m;
}
private var _useMargins:Boolean = false;
/**
* Flag indicating the use of margins or spacing
* @default false
*/
public function get useMargins():Boolean { return _useMargins; }
public function set useMargins(um:Boolean):void
{
_useMargins = um;
}
private var _centerColumn:Boolean = false;
/**
* Flag indicating the alignment of the objects' centers with the center of the column. Column width is determined by greatest width
* of the display objects.
* @default false
*/
public function get centerColumn():Boolean { return _centerColumn; }
public function set centerColumn(x:Boolean):void
{
_centerColumn = x;
}
private var _centerRow:Boolean = false;
/**
* Flag indicating the alignment of the objects' centers with the center of the row. Row height is determined by greatest height
* of the display objects.
* @default false
*/
public function get centerRow():Boolean { return _centerRow; }
public function set centerRow(x:Boolean):void
{
_centerRow = x;
}
private var _type:String;
/**
* Specifies a layout subtype
* @default null
*/
public function get type():String { return _type; }
public function set type(t:String):void
{
_type = t;
}
private var _alpha:Number = 1
/**
* Specifies the alpha value of the display objects in the layout
* @default 1
*/
public function get alpha():Number { return _alpha; }
public function set alpha(a:Number):void
{
_alpha = a > 1 ? 1 : a < 0 ? 0 : a;
}
private var _scale:Number;
/**
* Specifies the scale value of the display objects in the layout
*/
public function get scale():Number { return _scale; }
public function set scale(s:Number):void
{
_scale = s;
}
private var _rotation:Number;
/**
* Specifies the rotation value of the display objects in the layout
*/
public function get rotation():Number { return _rotation; }
public function set rotation(r:Number):void
{
_rotation = r;
}
private var _tween:Boolean = false;
/**
* Flag indicating the display objects will animate to their layout positions. If false,
* the objects will be positioned at initialization.
* @default true
*/
public function get tween():Boolean { return _tween; }
public function set tween(t:Boolean):void
{
_tween = t;
}
private var _tweenTime:Number = 500;
/**
* The time(ms) the display objects will take to move into positions
* @default 500
*/
public function get tweenTime():Number { return _tweenTime; }
public function set tweenTime(t:Number):void
{
_tweenTime = t;
}
private var _easing:Ease;
/**
* Specifies the easing equation. Argument must be an Ease instance or a String defining the Ease class
* either by property syntax or class name (e.g. Expo.easeOut or ExpoOut).
*/
public function get easing():* { return _easing; }
public function set easing(e:*):void
{
if (!(e is Ease))
{
var value:String = e.toString();
if (value.indexOf(".ease") != -1)
value = value.replace(".ease", "");
var easingType:Class = getDefinitionByName("com.greensock.easing." + value) as Class;
e = new easingType();
}
if (e is Ease)
_easing = e;
}
private var _onComplete:Function;
/**
* Function to call on layout complete
*/
public function get onComplete():Function { return _onComplete; }
public function set onComplete(f:Function):void
{
_onComplete = f;
}
private var _onCompleteParams:Array;
/**
* Parameters for onComplete function
*/
public function get onCompleteParams():Array { return _onCompleteParams; }
public function set onCompleteParams(value:Array):void {
_onCompleteParams = value;
}
private var _onUpdate:Function;
/**
* Function to call on layout update
*/
public function get onUpdate():Function { return _onUpdate; }
public function set onUpdate(f:Function):void
{
_onUpdate = f;
}
private var _onUpdateParams:Array;
/**
* Parameters for onUpdate function
*/
public function get onUpdateParams():Array { return _onUpdateParams; }
public function set onUpdateParams(value:Array):void {
_onUpdateParams = value;
}
private var _continuousTransform:Boolean = true;
/**
* Flag indicating the application of a transform relative to the current transform. If this flag is turned off, the transformation is
* reset with the principle layout attributes. (e.g. Given an object with a rotation of 45 degrees, applying a rotation of 10 in continuous mode
* will set the object's rotation to 55. In non-continuous mode, applying a rotation of 10 degrees will set the object's rotation to 10).
* @default true;
*/
public function get continuousTransform():Boolean { return _continuousTransform; }
public function set continuousTransform(c:Boolean):void
{
_continuousTransform = c;
}
private var _exclusions:Array = new Array();
/**
* An array of objects to exclude from the layout application
*/
public function get exclusions():Array { return _exclusions; }
public function set exclusions(e:Array):void
{
_exclusions = e;
}
private var _cacheTransforms:Boolean = true;
/**
* Flag indicating the childTransformations are to be cached and reapplied for convenience. If this flag is disabled, the transformations
* will need to be recreated for each child.
* @default true
*/
public function get cacheTransforms():Boolean { return _cacheTransforms; }
public function set cacheTransforms(c:Boolean):void
{
_cacheTransforms = c;
}
/**
* The object distribution function. If tween is on, creates a tween for each child and applies the child transformations. If tween is off,
* assigns the child transformations to the corresponding children.
* @param container
*/
public function layout(container:DisplayObjectContainer):void
{
var childTweens:Array;
var tIndex:int = 0;
var transformation:Matrix;
if (tween)
{
if (layoutTween && layoutTween._active)
{
layoutTween.eventCallback("onUpdate", onUpdate, onUpdateParams);
layoutTween.eventCallback("onComplete", onComplete, onCompleteParams );
return;
}
childTweens = new Array();
tweenedObjects = new Array();
for (var i:int = 0; i < container.numChildren; i++)
{
var child:* = container.getChildAt(i);
if(!validObject(child)) continue;
if (tIndex < childTransformations.length)
{
transformation = childTransformations[tIndex];
if (!isNaN(rotation))
rotateTransform(transformation, degreesToRadians(rotation));
if (!isNaN(scale))
scaleTransform(transformation, scale);
childTweens.push(TweenLite.to(child, tweenTime / 1000, {transformMatrix: getMatrixObj(transformation), alpha:alpha, ease: easing}));
tweenedObjects.push(child);
}
tIndex++;
}
layoutTween = new TimelineLite( { onComplete:onComplete, onCompleteParams:onCompleteParams, onUpdate:onUpdate, onUpdateParams:onUpdateParams } );
layoutTween.appendMultiple(childTweens);
layoutTween.play();
}
else
{
for (var j:int = 0; j < container.numChildren; j++)
{
child = container.getChildAt(j);
if (!validObject(child)) continue;
transformation = childTransformations[tIndex];;
if (!isNaN(rotation))
rotateTransform(transformation, degreesToRadians(rotation));
if (!isNaN(scale))
scaleTransform(transformation, scale);
child.transform.matrix = transformation;
child.alpha = alpha;
tIndex++;
}
if (onComplete != null) onComplete.call(onCompleteParams);
if (onUpdate != null) onUpdate.call(onUpdateParams);
}
if (!cacheTransforms)
childTransformations = new Array();
}
/**
* Determines if an object meets the criteria to be included in the layout
* @param obj the object to check
* @return true if valid, false otherwise
*/
protected function validObject(obj:*):Boolean
{
return obj && obj is DisplayObject && (exclusions.indexOf(obj) == -1);
}
/**
* Kills the tweening of the provided child. If a child is not provided, the group tween is killed.
* @param child
*/
public function killTween(child:*=null):void
{
if (layoutTween)
{
if(!child)
layoutTween.kill();
else
layoutTween.kill(null, child);
}
}
/**
* Apply a translation to the provided transformation matrix
* @param m the transformation matrix
* @param x the x value of the translation
* @param y the y value of the translation
*/
protected function translateTransform(m:Matrix, x:Number, y:Number):void
{
if (continuousTransform)
m.translate(x, y);
else
{
m.tx = x;
m.ty = y;
}
}
/**
* Apply a rotation to the provided transformation matrix
* @param m the transformation matrix
* @param rot the rotation (in radians) to apply
*/
protected function rotateTransform(m:Matrix, rot:Number):void
{
if (continuousTransform)
m.rotate(rot);
else
{
m.a = Math.cos(rot);
m.b = Math.sin(rot);
m.c = -Math.sin(rot);
m.d = Math.cos(rot);
}
}
/**
* Apply a scale to the provided transformation matrix
* @param m the transformation matrix
* @param s the scale to apply
*/
protected function scaleTransform(m:Matrix, s:Number):void
{
if (continuousTransform)
m.scale(s, s);
else
{
m.a = s;
m.d = s;
}
}
/**
* Generates a reandom number between min and max
* @param min the bottom limit
* @param max the top limit
* @return a random number
*/
protected static function randomMinMax(min:Number, max:Number):Number
{
return min + Math.random() * (max - min);
}
/**
* Converts degrees to radians
* @param degrees value in degrees
* @return value in radians
*/
protected static function degreesToRadians(degrees:Number):Number
{
return Math.PI * degrees / 180;
}
/**
* Rotates an object around a spcecific point at a specific angle of rotation
* @param obj the object to rotate
* @param angle the angle of rotation
* @param aroundX the x coordinate of the point to rotate around
* @param aroundY the y coordinate of the point to rotate around
*/
protected static function rotateAroundPoint(obj:*, angle:Number, aroundX:Number, aroundY:Number):void
{
var m:Matrix = obj.transform.matrix;
m = pointRotateMatrix(angle, aroundX, aroundY, m);
obj.transform.matrix = m;
}
/**
* Returns a matrix rotated around a specific point at a specific angle
* @param angle the angle of rotation
* @param aroundX the x coordinate of the point to rotate around
* @param aroundY the y coordinate of the point to rotate around
* @param m the matrix to rotate
* @return
*/
protected static function pointRotateMatrix(angle:Number, aroundX:Number, aroundY:Number, m:Matrix=null):Matrix
{
if (!m) m = new Matrix();
m.translate( -aroundX, -aroundY );
m.rotate(degreesToRadians(angle));
m.translate( aroundX, aroundY );
return m;
}
/**
* Converts transformation matrix to TweenMax syntax
* @param mtx transformation matrix
* @return tween matrix
*/
protected static function getMatrixObj(mtx:Matrix):Object
{
return { a:mtx.a, b:mtx.b, c:mtx.c, d:mtx.d, tx:mtx.tx, ty:mtx.ty };
}
/**
* Returns the max width of the container's children
* @param c the container
* @return the max width
*/
protected static function getMaxWidth(c:DisplayObjectContainer):Number
{
var maxWidth:Number = 0;
for (var i:int = 0; i < c.numChildren; i++)
maxWidth = c.getChildAt(i).width > maxWidth ? c.getChildAt(i).width : maxWidth;
return maxWidth;
}
/**
* Returns the max height of the container's children
* @param c the container
* @return the max height
*/
protected static function getMaxHeight(c:DisplayObjectContainer):Number
{
var maxHeight:Number = 0;
for (var i:int = 0; i < c.numChildren; i++)
maxHeight = c.getChildAt(i).height > maxHeight ? c.getChildAt(i).height : maxHeight;
return maxHeight;
}
/**
* Destructor
*/
override public function dispose():void
{
super.dispose();
childTransformations = null;
layoutTween = null;
tweenedObjects = null;
onComplete = null;
onUpdate = null;
exclusions = null;
}
}
} |
table broadPeak
"ENCODE broadPeak"
(
string chrom; "Reference sequence chromosome or scaffold"
uint chromStart; "Start position of feature on chromosome"
uint chromEnd; "End position of feature on chromosome"
string name; "Name of gene"
uint score; "Score"
char[1] strand; "+ or - for strand"
float SignalValue; "Measurement of overall (usually, average) enrichment for the region. "
float pValue; "-log10 p value"
float qValue; "-log10 q value"
) |
package sh.saqoo.format {
import flash.display.BitmapData;
import flash.utils.ByteArray;
import flash.utils.Endian;
/**
* Pure AS3 JPEG decoder ported from C++ version of NanoJPEG.
* @author Saqoosha
* @see http://keyj.s2000.ws/?p=137
* @see http://www.h4ck3r.net/2009/12/02/mini-jpeg-decoder/
*/
public class NanoJPEG {
public static const RESULT_OK:String = 'OK';
public static const RESULT_NOT_A_JPEG:String = 'Not a JPEG';
public static const RESULT_UNSUPPORTED:String = 'Unsupported';
public static const RESULT_OUT_OF_MEMORY:String = 'Out of memory';
public static const RESULT_INTERNAL_ERROR:String = 'Internal error';
public static const RESULT_SYNTAX_ERROR:String = 'Syntax error';
public static const RESULT_INTERNAL_FINISHED:String = 'Internal finished';
//
private static const ZZ:Vector.<int> = Vector.<int>([
0, 1, 8, 16, 9, 2, 3, 10,
17, 24, 32, 25, 18, 11, 4, 5,
12, 19, 26, 33, 40, 48, 41, 34,
27, 20, 13, 6, 7, 14, 21, 28,
35, 42, 49, 56, 57, 50, 43, 36,
29, 22, 15, 23, 30, 37, 44, 51,
58, 59, 52, 45, 38, 31, 39, 46,
53, 60, 61, 54, 47, 55, 62, 63
]);
//
private var ctx:Context;
public function NanoJPEG() {
ctx = new Context();
}
public function decode(jpegData:ByteArray):BitmapData {
ctx.data = jpegData;
ctx.data.position = 0;
ctx.data.endian = Endian.BIG_ENDIAN;
ctx.size = jpegData.length;
if (ctx.size < 2) { throw new Error(RESULT_NOT_A_JPEG); }
if ((ctx.data.readUnsignedByte() ^ 0xff) | (ctx.data.readUnsignedByte() ^ 0xD8)) { throw new Error(RESULT_NOT_A_JPEG); }
_Skip(2);
while (!ctx.completed) {
if ((ctx.size < 2) || (ctx.data.readUnsignedByte() != 0xff)) { throw new Error(RESULT_SYNTAX_ERROR); }
var b:int = ctx.data.readUnsignedByte();
_Skip(2);
switch (b) {
case 0xC0: _DecodeSOF(); break;
case 0xC4: _DecodeDHT(); break;
case 0xDB: _DecodeDQT(); break;
case 0xDD: _DecodeDRI(); break;
case 0xDA: _DecodeScan(); break;
case 0xFE: _SkipMarker(); break;
default:
if ((b & 0xF0) == 0xE0) {
_SkipMarker();
} else {
throw new Error(RESULT_UNSUPPORTED);
}
}
}
_Convert();
return ctx.image;
}
private function _DecodeSOF():void {
var i:int;
var ssxmax:int = 0;
var ssymax:int = 0;
var c:Component;
_DecodeLength();
if (ctx.length < 9) { throw new Error(RESULT_SYNTAX_ERROR); }
if (ctx.data.readUnsignedByte() != 8) { throw new Error(RESULT_SYNTAX_ERROR); }
ctx.height = ctx.data.readUnsignedShort();
ctx.width = ctx.data.readUnsignedShort();
ctx.ncomp = ctx.data.readUnsignedByte();
_Skip(6);
switch (ctx.ncomp) {
case 1:
case 3:
break;
default:
throw new Error(RESULT_UNSUPPORTED);
}
if (ctx.length < ctx.ncomp * 3) { throw new Error(RESULT_SYNTAX_ERROR); }
for (i = 0; i < ctx.ncomp; ++i) {
c = ctx.comp[i];
c.cid = ctx.data.readUnsignedByte();
var b:int = ctx.data.readUnsignedByte();
if (!(c.ssx = b >> 4)) { throw new Error(RESULT_SYNTAX_ERROR); }
if (c.ssx & (c.ssx - 1)) { throw new Error(RESULT_UNSUPPORTED); }
if (!(c.ssy = b & 15)) { throw new Error(RESULT_SYNTAX_ERROR); }
if (c.ssy & (c.ssy - 1)) { throw new Error(RESULT_UNSUPPORTED); }
if ((c.qtsel = ctx.data.readUnsignedByte()) & 0xFC) { throw new Error(RESULT_SYNTAX_ERROR); }
_Skip(3);
ctx.qtused |= 1 << c.qtsel;
if (c.ssx > ssxmax) ssxmax = c.ssx;
if (c.ssy > ssymax) ssymax = c.ssy;
}
ctx.mbsizex = ssxmax << 3;
ctx.mbsizey = ssymax << 3;
ctx.mbwidth = (ctx.width + ctx.mbsizex - 1) / ctx.mbsizex;
ctx.mbheight = (ctx.height + ctx.mbsizey - 1) / ctx.mbsizey;
for (i = 0; i < ctx.ncomp; ++i) {
c = ctx.comp[i];
c.width = (ctx.width * c.ssx + ssxmax - 1) / ssxmax;
c.stride = (c.width + 7) & 0x7FFFFFF8;
c.height = (ctx.height * c.ssy + ssymax - 1) / ssymax;
c.stride = ctx.mbwidth * ctx.mbsizex * c.ssx / ssxmax;
if (((c.width < 3) && (c.ssx != ssxmax)) || ((c.height < 3) && (c.ssy != ssymax))) { throw new Error(RESULT_UNSUPPORTED); }
c.pixels = new ByteArray();
c.pixels.length = c.stride * (ctx.mbheight * ctx.mbsizey * c.ssy / ssymax);
}
if (ctx.ncomp == 3) {
ctx.rgb = new ByteArray();
ctx.rgb.length = ctx.width * ctx.height * 4;
}
ctx.data.position += ctx.length;
_Skip(ctx.length);
}
private function _DecodeDHT():void {
var codelen:int, currcnt:int, remain:int, spread:int, i:int, j:int;
var counts:ByteArray = new ByteArray();
_DecodeLength();
while (ctx.length >= 17) {
i = ctx.data.readUnsignedByte();
if (i & 0xEC) { throw new Error(RESULT_SYNTAX_ERROR); }
if (i & 0x02) { throw new Error(RESULT_UNSUPPORTED); }
i = (i | (i >> 3)) & 3; // combined DC/AC + tableid value
ctx.data.readBytes(counts, 0, 16);
_Skip(17);
var vlcs:Vector.<VlcCode> = ctx.vlctab[i];
remain = spread = 65536;
for (codelen = 1; codelen <= 16; ++codelen) {
spread >>= 1;
currcnt = counts[codelen - 1];
if (!currcnt) continue;
if (ctx.length < currcnt) { throw new Error(RESULT_SYNTAX_ERROR); }
remain -= currcnt << (16 - codelen);
if (remain < 0) { throw new Error(RESULT_SYNTAX_ERROR); }
for (i = 0; i < currcnt; ++i) {
var code:int = ctx.data.readUnsignedByte();
for (j = spread; j; --j) {
vlcs.push(new VlcCode(codelen, code));
}
}
_Skip(currcnt);
}
while (remain--) {
vlcs.push(new VlcCode());
}
}
if (ctx.length) { throw new Error(RESULT_SYNTAX_ERROR); }
}
private function _DecodeDQT():void {
var i:int;
var t:ByteArray;
_DecodeLength();
while (ctx.length >= 65) {
i = ctx.data.readUnsignedByte();
if (i & 0xFC) { throw new Error(RESULT_SYNTAX_ERROR); }
ctx.qtavail |= 1 << i;
t = ctx.qtab[i];
ctx.data.readBytes(t, 0, 64);
_Skip(65);
}
if (ctx.length) { throw new Error(RESULT_SYNTAX_ERROR); }
}
private function _DecodeDRI():void {
_DecodeLength();
if (ctx.length < 2) { throw new Error(RESULT_SYNTAX_ERROR); }
ctx.rstinterval = ctx.data.readUnsignedShort();
ctx.data.position += ctx.length - 2;
_Skip(ctx.length);
}
private function _DecodeScan():void {
var i:int, mbx:int, mby:int, sbx:int, sby:int;
var rstcount:int = ctx.rstinterval, nextrst:int = 0;
var c:Component;
var b:int;
_DecodeLength();
if (ctx.length < (4 + 2 * ctx.ncomp)) { throw new Error(RESULT_SYNTAX_ERROR); }
if (ctx.data.readUnsignedByte() != ctx.ncomp) { throw new Error(RESULT_UNSUPPORTED); }
_Skip(1);
for (i = 0; i < ctx.ncomp; ++i) {
c = ctx.comp[i];
if (ctx.data.readUnsignedByte() != c.cid) { throw new Error(RESULT_SYNTAX_ERROR); }
if ((b = ctx.data.readUnsignedByte()) & 0xEE) { throw new Error(RESULT_SYNTAX_ERROR); }
c.dctabsel = b >> 4;
c.actabsel = (b & 1) | 2;
_Skip(2);
}
var d0:int = ctx.data.readUnsignedByte();
var d1:int = ctx.data.readUnsignedByte();
var d2:int = ctx.data.readUnsignedByte();
if (d0 || (d1 != 63) || d2) { throw new Error(RESULT_UNSUPPORTED); }
_Skip(ctx.length);
for (mby = 0; mby < ctx.mbheight; ++mby) {
for (mbx = 0; mbx < ctx.mbwidth; ++mbx) {
for (i = 0; i < ctx.ncomp; ++i) {
c = ctx.comp[i];
for (sby = 0; sby < c.ssy; ++sby) {
for (sbx = 0; sbx < c.ssx; ++sbx) {
c.pixels.position = ((mby * c.ssy + sby) * c.stride + mbx * c.ssx + sbx) << 3;
_DecodeBlock(c, c.pixels);
}
}
}
if (ctx.rstinterval && !(--rstcount)) {
_ByteAlign();
i = _GetBits(16);
if (((i & 0xFFF8) != 0xFFD0) || ((i & 7) != nextrst)) { throw new Error(RESULT_SYNTAX_ERROR); }
nextrst = (nextrst + 1) & 7;
rstcount = ctx.rstinterval;
for (i = 0; i < 3; ++i) {
ctx.comp[i].dcpred = 0;
}
}
}
}
ctx.completed = true;
}
private function _DecodeBlock(c:Component, out:ByteArray):void {
var code:IntValue = new IntValue();
var value:int, coef:int = 0;
ctx.block = Vector.<int>(new Array(64));
c.dcpred += _GetVLC(ctx.vlctab[c.dctabsel], null);
ctx.block[0] = c.dcpred * ctx.qtab[c.qtsel][0];
do {
value = _GetVLC(ctx.vlctab[c.actabsel], code);
if (!code.value) break;
if (!(code.value & 0x0F) && (code.value != 0xF0)) { throw new Error(RESULT_SYNTAX_ERROR); }
coef += (code.value >> 4) + 1;
if (coef > 63) { throw new Error(RESULT_SYNTAX_ERROR); }
ctx.block[int(ZZ[coef])] = value * ctx.qtab[c.qtsel][coef];
} while (coef < 63);
for (coef = 0; coef < 64; coef += 8) {
_RowIDCT(ctx.block, coef);
}
for (coef = 0; coef < 8; ++coef) {
_ColIDCT(ctx.block, out, coef, c.stride);
}
}
private function _GetVLC(vlc:Vector.<VlcCode>, code:IntValue):int {
var value:int = _ShowBits(16);
var bits:int = vlc[value].bits;
if (!bits) { throw new Error(RESULT_SYNTAX_ERROR); }
_SkipBits(bits);
value = vlc[value].code;
if (code) code.value = value;
bits = value & 15;
if (!bits) return 0;
value = _GetBits(bits);
if (value < (1 << (bits - 1)))
value += ((-1) << bits) + 1;
return value;
}
private static const W1:int = 2841;
private static const W2:int = 2676;
private static const W3:int = 2408;
private static const W5:int = 1609;
private static const W6:int = 1108;
private static const W7:int = 565;
private function _RowIDCT(blk:Vector.<int>, offset:int):void {
var x0:int, x1:int, x2:int, x3:int, x4:int, x5:int, x6:int, x7:int, x8:int;
var i0:int = offset;
var i1:int = offset + 1;
var i2:int = offset + 2;
var i3:int = offset + 3;
var i4:int = offset + 4;
var i5:int = offset + 5;
var i6:int = offset + 6;
var i7:int = offset + 7;
if (!((x1 = blk[i4] << 11)
| (x2 = blk[i6])
| (x3 = blk[i2])
| (x4 = blk[i1])
| (x5 = blk[i7])
| (x6 = blk[i5])
| (x7 = blk[i3])))
{
blk[i0] = blk[i1] = blk[i2] = blk[i3] = blk[i4] = blk[i5] = blk[i6] = blk[i7] = blk[i0] << 3;
return;
}
x0 = (blk[i0] << 11) + 128;
x8 = W7 * (x4 + x5);
x4 = x8 + (W1 - W7) * x4;
x5 = x8 - (W1 + W7) * x5;
x8 = W3 * (x6 + x7);
x6 = x8 - (W3 - W5) * x6;
x7 = x8 - (W3 + W5) * x7;
x8 = x0 + x1;
x0 -= x1;
x1 = W6 * (x3 + x2);
x2 = x1 - (W2 + W6) * x2;
x3 = x1 + (W2 - W6) * x3;
x1 = x4 + x6;
x4 -= x6;
x6 = x5 + x7;
x5 -= x7;
x7 = x8 + x3;
x8 -= x3;
x3 = x0 + x2;
x0 -= x2;
x2 = (181 * (x4 + x5) + 128) >> 8;
x4 = (181 * (x4 - x5) + 128) >> 8;
blk[i0] = (x7 + x1) >> 8;
blk[i1] = (x3 + x2) >> 8;
blk[i2] = (x0 + x4) >> 8;
blk[i3] = (x8 + x6) >> 8;
blk[i4] = (x8 - x6) >> 8;
blk[i5] = (x0 - x4) >> 8;
blk[i6] = (x3 - x2) >> 8;
blk[i7] = (x7 - x1) >> 8;
}
private function _ColIDCT(blk:Vector.<int>, out:ByteArray, offset:int, stride:int):void {
var x0:int, x1:int, x2:int, x3:int, x4:int, x5:int, x6:int, x7:int, x8:int;
var p:int = out.position + offset;
if (!((x1 = blk[8*4+offset] << 8)
| (x2 = blk[8*6+offset])
| (x3 = blk[8*2+offset])
| (x4 = blk[8*1+offset])
| (x5 = blk[8*7+offset])
| (x6 = blk[8*5+offset])
| (x7 = blk[8*3+offset])))
{
x1 = _Clip(((blk[offset] + 32) >> 6) + 128);
for (x0 = 8; x0; --x0) {
out[p] = x1;
p += stride;
}
return;
}
x0 = (blk[offset] << 8) + 8192;
x8 = W7 * (x4 + x5) + 4;
x4 = (x8 + (W1 - W7) * x4) >> 3;
x5 = (x8 - (W1 + W7) * x5) >> 3;
x8 = W3 * (x6 + x7) + 4;
x6 = (x8 - (W3 - W5) * x6) >> 3;
x7 = (x8 - (W3 + W5) * x7) >> 3;
x8 = x0 + x1;
x0 -= x1;
x1 = W6 * (x3 + x2) + 4;
x2 = (x1 - (W2 + W6) * x2) >> 3;
x3 = (x1 + (W2 - W6) * x3) >> 3;
x1 = x4 + x6;
x4 -= x6;
x6 = x5 + x7;
x5 -= x7;
x7 = x8 + x3;
x8 -= x3;
x3 = x0 + x2;
x0 -= x2;
x2 = (181 * (x4 + x5) + 128) >> 8;
x4 = (181 * (x4 - x5) + 128) >> 8;
out[p] = _Clip(((x7 + x1) >> 14) + 128); p += stride;
out[p] = _Clip(((x3 + x2) >> 14) + 128); p += stride;
out[p] = _Clip(((x0 + x4) >> 14) + 128); p += stride;
out[p] = _Clip(((x8 + x6) >> 14) + 128); p += stride;
out[p] = _Clip(((x8 - x6) >> 14) + 128); p += stride;
out[p] = _Clip(((x0 - x4) >> 14) + 128); p += stride;
out[p] = _Clip(((x3 - x2) >> 14) + 128); p += stride;
out[p] = _Clip(((x7 - x1) >> 14) + 128);
}
private function _Convert():void {
var i:int;
var c:Component;
for (i = 0; i < ctx.ncomp; ++i) {
c = ctx.comp[i];
while ((c.width < ctx.width) || (c.height < ctx.height)) {
if (c.height < ctx.height) _UpsampleV(c);
if (c.width < ctx.width) _UpsampleH(c);
}
if ((c.width < ctx.width) || (c.height < ctx.height)) { throw new Error(RESULT_INTERNAL_ERROR); }
}
if (ctx.ncomp == 3) {
// convert to RGB
var x:int, yy:int;
const prgb:ByteArray = ctx.rgb;
const py:ByteArray = ctx.comp[0].pixels;
const pcb:ByteArray = ctx.comp[1].pixels;
const pcr:ByteArray = ctx.comp[2].pixels;
var iprgb:int = 0;
var ipy:int = 0;
var ipcb:int = 0;
var ipcr:int = 0;
for (yy = ctx.height; yy; --yy) {
for (x = 0; x < ctx.width; ++x) {
var y:int = py[ipy + x] << 8;
var cb:int = pcb[ipcb + x] - 128;
var cr:int = pcr[ipcr + x] - 128;
prgb[iprgb++] = 255; // alpha
prgb[iprgb++] = _Clip((y + 359 * cr + 128) >> 8); // red
prgb[iprgb++] = _Clip((y - 88 * cb - 183 * cr + 128) >> 8); // green
prgb[iprgb++] = _Clip((y + 454 * cb + 128) >> 8); // blue
}
ipy += ctx.comp[0].stride;
ipcb += ctx.comp[1].stride;
ipcr += ctx.comp[2].stride;
}
ctx.image = new BitmapData(ctx.width, ctx.height, true, 0x0);
ctx.image.setPixels(ctx.image.rect, ctx.rgb);
} else if (ctx.comp[0].width != ctx.comp[0].stride) {
throw new Error(RESULT_UNSUPPORTED);
// // grayscale -> only remove stride
// unsigned char *pin = &ctx.comp[0].pixels[ctx.comp[0].stride];
// unsigned char *pout = &ctx.comp[0].pixels[ctx.comp[0].width];
// int y;
// for (y = ctx.comp[0].height - 1; y; --y) {
// memcpy(pout, pin, ctx.comp[0].width);
// pin += ctx.comp[0].stride;
// pout += ctx.comp[0].width;
// }
// ctx.comp[0].stride = ctx.comp[0].width;
}
}
private static const CF4A:int = -9;
private static const CF4B:int = 111;
private static const CF4C:int = 29;
private static const CF4D:int = -3;
private static const CF3A:int = 28;
private static const CF3B:int = 109;
private static const CF3C:int = -9;
private static const CF3X:int = 104;
private static const CF3Y:int = 27;
private static const CF3Z:int = -3;
private static const CF2A:int = 139;
private static const CF2B:int = -11;
private function CF(x:int):int {
return _Clip((x + 64) >> 7);
}
private function _UpsampleH(c:Component):void {
const xmax:int = c.width - 3;
var x:int, y:int;
var org:ByteArray = c.pixels;
var out:ByteArray = new ByteArray();
out.length = ((c.width * c.height) << 1) * 4;
var iorg:int = 0;
var iout:int = 0;
for (y = c.height; y; --y) {
out[iout + 0] = CF(CF2A * org[iorg + 0] + CF2B * org[iorg + 1]);
out[iout + 1] = CF(CF3X * org[iorg + 0] + CF3Y * org[iorg + 1] + CF3Z * org[iorg + 2]);
out[iout + 2] = CF(CF3A * org[iorg + 0] + CF3B * org[iorg + 1] + CF3C * org[iorg + 2]);
for (x = 0; x < xmax; ++x) {
out[iout + (x << 1) + 3] = CF(CF4A * org[iorg + x] + CF4B * org[iorg + x + 1] + CF4C * org[iorg + x + 2] + CF4D * org[iorg + x + 3]);
out[iout + (x << 1) + 4] = CF(CF4D * org[iorg + x] + CF4C * org[iorg + x + 1] + CF4B * org[iorg + x + 2] + CF4A * org[iorg + x + 3]);
}
iorg += c.stride;
iout += c.width << 1;
out[iout - 3] = CF(CF3A * org[iorg - 1] + CF3B * org[iorg - 2] + CF3C * org[iorg - 3]);
out[iout - 2] = CF(CF3X * org[iorg - 1] + CF3Y * org[iorg - 2] + CF3Z * org[iorg - 3]);
out[iout - 1] = CF(CF2A * org[iorg - 1] + CF2B * org[iorg - 2]);
}
c.width <<= 1;
c.stride = c.width;
c.pixels = out;
}
private function _UpsampleV(c:Component):void {
const w:int = c.width;
const s1:int = c.stride;
const s2:int = s1 + s1;
var x:int, y:int;
var org:ByteArray = c.pixels;
var out:ByteArray = new ByteArray();
out.length = ((c.width * c.height) << 1) * 4;
var iorg:int = 0;
var iout:int = 0;
for (x = 0; x < w; ++x) {
iorg = x;
iout = x;
out[iout] = CF(CF2A * org[iorg + 0] + CF2B * org[iorg + s1]); iout += w;
out[iout] = CF(CF3X * org[iorg + 0] + CF3Y * org[iorg + s1] + CF3Z * org[iorg + s2]); iout += w;
out[iout] = CF(CF3A * org[iorg + 0] + CF3B * org[iorg + s1] + CF3C * org[iorg + s2]); iout += w;
iorg += s1;
for (y = c.height - 3; y; --y) {
out[iout] = CF(CF4A * org[iorg - s1] + CF4B * org[iorg + 0] + CF4C * org[iorg + s1] + CF4D * org[iorg + s2]); iout += w;
out[iout] = CF(CF4D * org[iorg - s1] + CF4C * org[iorg + 0] + CF4B * org[iorg + s1] + CF4A * org[iorg + s2]); iout += w;
iorg += s1;
}
iorg += s1;
out[iout] = CF(CF3A * org[iorg + 0] + CF3B * org[iorg - s1] + CF3C * org[iorg - s2]); iout += w;
out[iout] = CF(CF3X * org[iorg + 0] + CF3Y * org[iorg - s1] + CF3Z * org[iorg - s2]); iout += w;
out[iout] = CF(CF2A * org[iorg + 0] + CF2B * org[iorg - s1]);
}
c.height <<= 1;
c.stride = c.width;
c.pixels = out;
}
//
private function _Clip(x:int):int {
return (x < 0) ? 0 : ((x > 0xFF) ? 0xFF : x);
}
private function _SkipMarker():void {
_DecodeLength();
ctx.data.position += ctx.length;
_Skip(ctx.length);
}
private function _Skip(count:int):void {
// bytearray automaticaly increments its position during readBytes method. (or anoter read methods)
// so, I don't increment position in this method.
// ctx.pos += count;
ctx.size -= count;
ctx.length -= count;
if (ctx.size < 0) { throw new Error(RESULT_SYNTAX_ERROR); }
}
private function _DecodeLength():void {
if (ctx.size < 2) { throw new Error(RESULT_SYNTAX_ERROR); }
ctx.length = ctx.data.readUnsignedShort();
if (ctx.length > ctx.size) { throw new Error(RESULT_SYNTAX_ERROR); }
_Skip(2);
}
private function _ByteAlign():void {
ctx.bufbits &= 0xF8;
}
private function _ShowBits(bits:int):int {
var newbyte:int;
if (!bits) return 0;
while (ctx.bufbits < bits) {
if (ctx.size <= 0) {
ctx.buf = (ctx.buf << 8) | 0xFF;
ctx.bufbits += 8;
continue;
}
newbyte = ctx.data.readUnsignedByte();
ctx.size--;
ctx.bufbits += 8;
ctx.buf = (ctx.buf << 8) | newbyte;
if (newbyte == 0xFF) {
if (ctx.size) {
var marker:int = ctx.data.readUnsignedByte();
ctx.size--;
switch (marker) {
case 0: break;
case 0xD9: ctx.size = 0; break;
default:
if ((marker & 0xF8) != 0xD0) {
throw new Error(RESULT_SYNTAX_ERROR);
} else {
ctx.buf = (ctx.buf << 8) | marker;
ctx.bufbits += 8;
}
}
} else {
throw new Error(RESULT_SYNTAX_ERROR);
}
}
}
return (ctx.buf >> (ctx.bufbits - bits)) & ((1 << bits) - 1);
}
private function _GetBits(bits:int):int {
var res:int = _ShowBits(bits);
_SkipBits(bits);
return res;
}
private function _SkipBits(bits:int):void {
if (ctx.bufbits < bits) {
_ShowBits(bits);
}
ctx.bufbits -= bits;
}
}
}
import flash.display.BitmapData;
import flash.utils.ByteArray;
class Context {
public var completed:Boolean = false;
public var data:ByteArray = null;
public var size:int = 0;
public var length:int = 0;
public var width:int = 0;
public var height:int = 0;
public var mbwidth:int = 0;
public var mbheight:int = 0;
public var mbsizex:int = 0;
public var mbsizey:int = 0;
public var ncomp:int = 0;
public var comp:Vector.<Component>;
public var qtused:int;
public var qtavail:int;
public var qtab:Vector.<ByteArray>;
public var vlctab:Vector.<Vector.<VlcCode>>;
public var buf:int;
public var bufbits:int;
public var block:Vector.<int>;
public var rstinterval:int;
public var rgb:ByteArray;
public var image:BitmapData;
public function Context() {
var i:int;
comp = new Vector.<Component>();
for (i = 0; i < 4; ++i) {
comp.push(new Component());
}
qtab = new Vector.<ByteArray>();
for (i = 0; i < 4; ++i) {
qtab.push(new ByteArray());
}
vlctab = new Vector.<Vector.<VlcCode>>();
for (i = 0; i < 4; ++i) {
vlctab.push(new Vector.<VlcCode>());
}
}
}
class Component {
public var cid:int;
public var ssx:int;
public var ssy:int;
public var width:int;
public var height:int;
public var stride:int;
public var qtsel:int;
public var actabsel:int;
public var dctabsel:int;
public var dcpred:int;
public var pixels:ByteArray;
}
class VlcCode {
public var bits:int;
public var code:int;
public function VlcCode(bits:int = 0, code:int = 0):void {
this.bits = bits;
this.code = code;
}
}
class IntValue {
public var value:int;
public function IntValue(value:int = 0) {
this.value = value;
}
}
|
package com.registerguard.peel {
import flash.display.MovieClip;
import flash.display.Loader;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.ProgressEvent;
import flash.net.URLRequest;
public class Load extends EventDispatcher {
// Constant:
public static const LOAD_COMPLETE:String = 'load_completed';
// Private:
private var _this:Object;
private var _clip:MovieClip;
private var _ldr:Loader;
/**
* Load()
* About: Class constructor.
* Returns: Nothing.
*/
public function Load(t:Object) {
trace('Load() instantiated...');
_this = t;
};
public function loadThis(f:String):void {
var file:String = f;
var req:URLRequest = new URLRequest(f);
_ldr = new Loader();
_ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
_ldr.load(req);
};
private function onComplete(e:Event):void {
_ldr.removeEventListener(Event.COMPLETE, onComplete); // GC.
// http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00000216.html
_clip = MovieClip(e.currentTarget.content); // Cast 'DisplayObject' to 'MovieClip'.
//_this.addChild(c); // Add to stage.
this.dispatchEvent(new Event(Load.LOAD_COMPLETE)); // Dispatch event.
};
public function get clip():MovieClip {
return _clip;
};
};
}; |
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.validators
{
import flash.globalization.Collator;
import flash.globalization.LocaleID;
import flash.globalization.StringTools;
import mx.resources.IResourceManager;
import mx.resources.ResourceManager;
import mx.validators.Validator;
import mx.validators.ValidationResult;
[ResourceBundle("apache")]
/**
* The PostCodeValidator class validates that a String
* has the correct length and format for a post code.
*
* <p>Postcode formats consists of the letters C, N, A and spaces or hyphens
* <ul>
* <li>CC or C is the country code (required for some postcodes).</li>
* <li>N is a number 0-9.</li>
* <li>A is a letter A-Z or a-z.</li>
* </ul></p>
*
* <p>Country codes one be one or two digits.</p>
*
* <p>For example "NNNN" is a four digit numeric postcode, "CCNNNN" is country code
* followed by four digits and "AA NNNN" is two letters, followed by a space then
* followed by four digits.</p>
*
* <p>More than one format can be specified by setting the <code>formats</code>
* property to an array of format Strings.</p>
*
* <p>The validator can suggest postcode formats for small set of know locales by calling the
* <code>suggestFormat</code> method.</p>
*
* <p>Postcodes can be further validated by setting the <code>extraValidation</code>
* property to a user defined method that performs further checking on the postcode
* digits.</p>
*
* <p>Fullwidth numbers and letters are supported in postcodes by ignoring character
* width via the <code>flash.globalization.Collator</code> <code>equals</code> method.</p>
*
* @mxml
*
* <p>The <code><mx:PostCodeValidator></code> tag
* inherits all of the tag attributes of its superclass,
* and adds the following tag attributes:</p>
*
* <pre>
* <mx:PostCodeValidator
* countryCode="CC"
* format="NNNNN"
* formats="['NNNNN', 'NNNNN-NNNN']"
* wrongFromatError="The postcode code must be correctly formatted."
* invalidFormatError="The postcode format string is incorrect."
* invalidCharError="The postcode contains invalid characters."
* wrongLengthError="The postcode is the wrong length."
* />
* </pre>
*
* @see org.apache.flex.formatters.PostCodeFormatter
*
* @langversion 3.0
* @playerversion Flash 10.2
* @productversion ApacheFlex 4.8
*/
public class PostCodeValidator extends Validator
{
include "../../../../core/Version.as";
/**
* Name of the bundle file error resource strings can be found.
* Also defined in matadata tag [ResourceBundle("validators")]
*/
private static const BUNDLENAME:String = "validators";
/**
* Value <code>errorCode</code> of a ValidationResult is set to when
* the postcode contains an invalid charater.
*/
public static const ERROR_INVALID_CHAR:String = "invalidChar";
/**
* Value <code>errorCode</code> of a ValidationResult is set to when
* the postcode is of the wrong length.
*/
public static const ERROR_WRONG_LENGTH:String = "wrongLength";
/**
* Value <code>errorCode</code> of a ValidationResult is set to when
* the postcode is of the wrong format.
*/
public static const ERROR_WRONG_FORMAT:String = "wrongFormat";
/**
* Value <code>errorCode</code> of a ValidationResult is set to when
* the format contains unknown format characters.
*/
public static const ERROR_INCORRECT_FORMAT:String = "incorrectFormat";
/**
* Symbol used in postcode formats representing a single digit.
*/
public static const FORMAT_NUMBER:String = "N";
/**
* Symbol used in postcode formats representing a single character.
*/
public static const FORMAT_LETTER:String = "A";
/**
* Symbol used in postcode formats representing a letter of a country
* code.
*/
public static const FORMAT_COUNTRY_CODE:String = "C";
/**
* Valid spacer character in postcode formats.
*/
public static const FORMAT_SPACERS:String = " -";
//--------------------------------------------------------------------------
//
// Class methods
//
//--------------------------------------------------------------------------
/**
* @private
* Simulate String.indexOf but ignore wide characters.
* TODO move to StringValidator or Collator?
*
* @return Index of char in string or -1 if char not in string.
*
*/
protected function indexOf(string:String, char:String):int
{
var length:int = string.length;
var collate:Collator = new Collator(LocaleID.DEFAULT);
collate.ignoreCharacterWidth = true;
for (var i:int = 0; i < length; i++)
{
if (collate.equals(string.charAt(i), char))
return i;
}
return -1;
}
/**
* @private
* Compares if two characters are equal ignoring wide characters.
* TODO move to StringValidator or Collator?
*
* @return True is charA is the same as charB, false if they are not.
*
*/
protected function equals(charA:String, charB:String):Boolean
{
var collate:Collator = new Collator(LocaleID.DEFAULT);
collate.ignoreCharacterWidth = true;
return collate.equals(charA, charB);
}
/**
* @private
*
* @param char to check
* @return True if the char is not a valid format character.
*
*/
protected function notFormatChar(char:String):Boolean
{
return indexOf(FORMAT_SPACERS, char) == -1 && char != FORMAT_NUMBER &&
char != FORMAT_LETTER && char != FORMAT_COUNTRY_CODE;
}
/**
* @private
*
* @param char to check
* @return True if the char is not a valid digit.
*
*/
protected function noDecimalDigits(char:String):Boolean
{
return indexOf(DECIMAL_DIGITS, char) == -1;
}
/**
* @private
*
* @param char to check
* @return True if the char is not a valid letter.
*
*/
protected function noRomanLetters(char:String):Boolean
{
return indexOf(ROMAN_LETTERS, char) == -1;
}
/**
* @private
*
* @param char to check
* @return True if the char is not a valid spacer.
*
*/
protected function noSpacers(char:String):Boolean
{
return indexOf(FORMAT_SPACERS, char) == -1;
}
/**
* @private
*
* A wrong format ValidationResult is added to the results array
* if the extraValidation user supplied function returns an error.
* An error is added when there is a user defined issue with the
* supplied postCode.
*
*/
protected function userValidationResults(validator:PostCodeValidator, baseField:String,
postCode:String, results:Array):void
{
if (validator && validator.extraValidation != null)
{
var extraError:String = validator.extraValidation(postCode);
if (extraError)
results.push(new ValidationResult(true, baseField, ERROR_WRONG_FORMAT, extraError));
}
}
/**
* @private
*
* Based on flags in the error object new ValidationResults are
* added the the results array.
*
* Note that the only first ValidationResult is typically shown
* to the user in validation errors.
*
*/
protected function errorValidationResults(validator:PostCodeValidator, baseField:String,
error:Object, results:Array):void
{
if (error)
{
if (error.incorrectFormat)
results.push(new ValidationResult(true, baseField, ERROR_INCORRECT_FORMAT,
validator.incorrectFormatError));
if (error.invalidChar)
results.push(new ValidationResult(true, baseField, ERROR_INVALID_CHAR,
validator.invalidCharError));
if (error.wrongLength)
results.push(new ValidationResult(true, baseField, ERROR_WRONG_LENGTH,
validator.wrongLengthError));
if (error.invalidFormat)
results.push(new ValidationResult(true, baseField, ERROR_WRONG_FORMAT,
validator.wrongFormatError));
}
}
/**
* @private
*
* Check thats a postCode is valid and matches a certain format.
*
* @return An error object containing flags for each type of error
* and an indication of invalidness (used later to sort errors).
*
*/
protected function checkPostCodeFormat(postCode:String, format:String,
countryCode:String):Object
{
var invalidChar:Boolean;
var invalidFormat:Boolean;
var wrongLength:Boolean;
var incorrectFormat:Boolean;
var formatLength:int;
var postCodeLength:int;
var noChars:int;
var countryIndex:int;
if (format)
formatLength = format.length;
if (formatLength == 0)
incorrectFormat = true;
if (postCode)
postCodeLength = postCode.length;
noChars = Math.min(formatLength, postCodeLength);
for (var postcodeIndex:int = 0; postcodeIndex < noChars; postcodeIndex++)
{
var char:String = postCode.charAt(postcodeIndex);
var formatChar:String = format.charAt(postcodeIndex);
if (postcodeIndex < postCodeLength)
char = postCode.charAt(postcodeIndex);
if (notFormatChar(formatChar))
incorrectFormat = true;
if (noDecimalDigits(char) && noRomanLetters(char) && noSpacers(char))
{
if (!countryCode || indexOf(countryCode, char) == -1)
invalidChar = true;
}
else if (formatChar == FORMAT_NUMBER && noDecimalDigits(char))
{
invalidFormat = true;
}
else if (formatChar == FORMAT_LETTER && noRomanLetters(char))
{
invalidFormat = true;
}
else if (formatChar == FORMAT_COUNTRY_CODE)
{
if (countryIndex >= 2 || !countryCode ||
!equals(char, countryCode.charAt(countryIndex)))
invalidFormat = true;
countryIndex++;
}
else if (indexOf(FORMAT_SPACERS, formatChar) >= 0 && !equals(formatChar, char))
{
invalidFormat = true;
}
}
wrongLength = (postCodeLength != formatLength);
// We want invalid char and invalid format errors to show in preference
// so give wrong length errors a higher value
if (incorrectFormat || invalidFormat || invalidChar || wrongLength)
return { invalidFormat: invalidFormat, incorrectFormat: incorrectFormat,
invalidChar: invalidChar, wrongLength: wrongLength,
invalidness: Number(invalidFormat) + Number(invalidChar) +
Number(incorrectFormat) + Number(wrongLength) * 1.5 };
else
return null;
}
/**
* Convenience method for calling a validator.
* Each of the standard Flex validators has a similar convenience method.
*
* @param validator The PostCodeValidator instance.
*
* @param value A field to validate.
*
* @param baseField Text representation of the subfield
* specified in the <code>value</code> parameter.
* For example, if the <code>value</code> parameter specifies value.postCode,
* the <code>baseField</code> value is <code>"postCode"</code>.
*
* @return An Array of ValidationResult objects, with one ValidationResult
* object for each field examined by the validator.
*
* @see mx.validators.ValidationResult
*
* @langversion 3.0
* @playerversion Flash 10.2
* @productversion ApacheFlex 4.8
*/
public static function validatePostCode(validator:PostCodeValidator, postCode:String,
baseField:String):Array
{
var numberFormats:int;
var errors:Array = [];
var results:Array = [];
if (!validator)
return [];
numberFormats = validator.formats.length;
for (var formatIndex:int = 0; formatIndex < numberFormats; formatIndex++)
{
var error:Object =
validator.checkPostCodeFormat(postCode, validator.formats[formatIndex],
validator.countryCode);
if (error)
{
errors.push(error);
}
else
{
errors = [];
break;
}
}
// return result with least number of errors
errors.sortOn("invalidness", Array.NUMERIC);
validator.userValidationResults(validator, baseField, postCode, results);
// TODO return/remember closest format or place in results?
validator.errorValidationResults(validator, baseField, errors[0], results);
return results;
}
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @productversion ApacheFlex 4.8
*/
public function PostCodeValidator()
{
super();
}
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
/**
* @private
* The two letter country code used in some postcode formats
*/
private var _countryCode:String;
/**
* @private
* An array of the postcode formats to check against.
*/
private var _formats:Array = [];
/**
* Valid postcode format that postcodes will be compaired against.
*
* <p>The format string consists of the letters C, N, A and spaces
* or hyphens:
* <ul>
* <li>CC or C is country code (required for some postcodes).</li>
* <li>N is a number 0-9.</li>
* <li>A is a letter A-Z or a-z.</li>
* </ul></p>
*
* @default null
*
* @langversion 3.0
* @playerversion Flash 10.2
* @productversion ApacheFlex 4.8
*/
public function get format():String
{
if (_formats && _formats.length == 1)
return _formats[0];
return null;
}
/**
* @private
*/
public function set format(value:String):void
{
if (value != null)
_formats = [ value ];
else
_formats = [];
}
/**
* Optional 1 or 2 letter country code in postcode format
*
* @default null
*
* @langversion 3.0
* @playerversion Flash 10.2
* @productversion ApacheFlex 4.8
*/
public function get countryCode():String
{
return _countryCode;
}
/**
* @private
*/
public function set countryCode(value:String):void
{
// Length is usually 2 character but can use 〒 in Japan
if (value == null || value && value.length <= 2)
_countryCode = value;
}
/**
* An array of valid format strings to compare postcodes against.
*
* <p>Use for locales where more than one format is required.
* eg en_UK</p>
*
* <p>See <code>format</code> for format of the format
* strings.</p>
*
* @default []
*
* @langversion 3.0
* @playerversion Flash 10.2
* @productversion ApacheFlex 4.8
*/
public function get formats():Array
{
return _formats;
}
/**
* @private
*/
public function set formats(value:Array):void
{
_formats = value;
}
/**
* A user supplied method that performs further validation on a postcode.
*
* <p>The user supplied method should have the following signature:
* <code>function validatePostcode(postcode:String):String</code></p>
*
* <p>The method is passed the postcode to be validated and should
* return either:
* <ol>
* <li>A null string indicating the postcode is valid.</li>
* <li>A non empty string describing why the postcode is invalid.</li>
* </ol></p>
*
* <p>The error string will be converted into a ValidationResult when
* doValidation is called by Flex as part of the normal validation
* process.</p>
*
* @langversion 3.0
* @playerversion Flash 10.2
* @productversion ApacheFlex 4.8
*/
public var extraValidation:Function;
//--------------------------------------------------------------------------
//
// Properties: Errors
//
//--------------------------------------------------------------------------
//----------------------------------
// invalidCharError
//----------------------------------
/**
* @private
* Storage for the invalidCharError property.
*/
private var _invalidCharError:String;
/**
* @private
*/
private var invalidCharErrorOverride:String;
[Inspectable(category = "Errors", defaultValue = "null")]
/**
* Error message when the post code contains invalid characters.
*
* @default "The postcode code contains invalid characters."
*
* @langversion 3.0
* @playerversion Flash 10.2
* @productversion ApacheFlex 4.8
*/
public function get invalidCharError():String
{
if (invalidCharErrorOverride)
return invalidCharErrorOverride;
return _invalidCharError;
}
/**
* @private
*/
public function set invalidCharError(value:String):void
{
invalidCharErrorOverride = value;
if (!value)
_invalidCharError = resourceManager.getString(BUNDLENAME, "invalidCharPostcodeError");
}
//----------------------------------
// wrongLengthError
//----------------------------------
/**
* @private
* Storage for the wrongLengthError property.
*/
private var _wrongLengthError:String;
/**
* @private
*/
private var wrongLengthErrorOverride:String;
[Inspectable(category = "Errors", defaultValue = "null")]
/**
* Error message for an invalid postcode.
*
* @default "The postcode is invalid."
*
* @langversion 3.0
* @playerversion Flash 10.2
* @productversion ApacheFlex 4.8
*/
public function get wrongLengthError():String
{
if (wrongLengthErrorOverride)
return wrongLengthErrorOverride;
return _wrongLengthError;
}
/**
* @private
*/
public function set wrongLengthError(value:String):void
{
wrongLengthErrorOverride = value;
if (!value)
_wrongLengthError = resourceManager.getString(BUNDLENAME, "wrongLengthPostcodeError");
}
//----------------------------------
// wrongFormatError
//----------------------------------
/**
* @private
* Storage for the wrongFormatError property.
*/
private var _wrongFormatError:String;
/**
* @private
*/
private var wrongFormatErrorOverride:String;
[Inspectable(category = "Errors", defaultValue = "null")]
/**
* Error message for an incorrectly formatted postcode.
*
* @default "The postcode code must be correctly formatted."
*
* @langversion 3.0
* @playerversion Flash 10.2
* @productversion ApacheFlex 4.8
*/
public function get wrongFormatError():String
{
if (wrongFormatErrorOverride)
return wrongFormatErrorOverride;
return _wrongFormatError;
}
/**
* @private
*/
public function set wrongFormatError(value:String):void
{
wrongFormatErrorOverride = value;
if (!value)
_wrongFormatError = resourceManager.getString(BUNDLENAME, "wrongFormatPostcodeError");
}
//----------------------------------
// incorrectFormatError
//----------------------------------
/**
* @private
* Storage for the incorrectFormatError property.
*/
private var _incorrectFormatError:String;
/**
* @private
*/
private var incorrectFormatErrorOverride:String;
[Inspectable(category = "Errors", defaultValue = "null")]
/**
* Error message for an incorrect format string.
*
* @default "The postcode format string is incorrect"
*
* @langversion 3.0
* @playerversion Flash 10.2
* @productversion ApacheFlex 4.8
*/
public function get incorrectFormatError():String
{
if (incorrectFormatErrorOverride)
return incorrectFormatErrorOverride;
return _incorrectFormatError;
}
/**
* @private
*/
public function set incorrectFormatError(value:String):void
{
incorrectFormatErrorOverride = value;
if (!value)
_incorrectFormatError =
resourceManager.getString(BUNDLENAME, "incorrectFormatPostcodeError");
}
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
/**
* @private
* Changes error strings when the locale changes.
*/
override protected function resourcesChanged():void
{
super.resourcesChanged();
invalidCharError = invalidCharErrorOverride;
wrongLengthError = wrongLengthErrorOverride;
wrongFormatError = wrongFormatErrorOverride;
incorrectFormatError = incorrectFormatErrorOverride;
}
/**
* Override of the base class <code>doValidation()</code> method
* to validate a postcode.
*
* <p>You do not call this method directly;
* Flex calls it as part of performing a validation.
* If you create a custom Validator class, you must implement this method.</p>
*
* @param value Object to validate.
*
* @return An Array of ValidationResult objects, with one ValidationResult
* object for each field examined by the validator.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @productversion ApacheFlex 4.8
*/
override protected function doValidation(value:Object):Array
{
var results:Array = super.doValidation(value);
// Return if there are errors
// or if the required property is set to false and length is 0.
var val:String = value ? String(value) : "";
if (results.length > 0 || ((val.length == 0) && !required))
return results;
else
return PostCodeValidator.validatePostCode(this, val, null);
}
//--------------------------------------------------------------------------
//
// Methods
//
//--------------------------------------------------------------------------
/**
* @private
* Returns the region (usually country) from a locale string.
* If no loacle is provided the default locale is used.
*
* @param locale locale to obtain region from.
* @return Region string.
*
*/
protected function getRegion(locale:String):String
{
var localeID:LocaleID;
if (locale == null)
{
var tool:StringTools = new StringTools(LocaleID.DEFAULT);
localeID = new LocaleID(tool.actualLocaleIDName);
}
else
{
localeID = new LocaleID(locale);
}
return localeID.getRegion();
}
/**
* Sets the error strings to be from a another locale.
*
* <p>When validating other countries postcode you may want to set the
* validation message to be from that country but not change the
* applications locale.</p>
*
* <p>To work the locale must be in the locale chain.</p>
*
* @param locale locale to obtain region from.
*
* @return True if error message have been changed otherwise false.
*
*/
public function errorsToLocale(locale:String):Boolean
{
if (resourceManager.getResourceBundle(locale, BUNDLENAME) == null)
return false;
invalidCharErrorOverride =
resourceManager.getString(BUNDLENAME, "invalidCharPostcodeError", null, locale);
wrongLengthErrorOverride =
resourceManager.getString(BUNDLENAME, "wrongLengthPostcodeError", null, locale);
wrongFormatErrorOverride =
resourceManager.getString(BUNDLENAME, "wrongFormatPostcodeError", null, locale);
incorrectFormatErrorOverride =
resourceManager.getString(BUNDLENAME, "incorrectFormatPostcodeError", null, locale);
return true;
}
/**
* Sets the suggested postcode formats for a given <code>locale</code>.
*
* <p>If no locale is supplied the default locale is used.</p>
*
* <p>Currently only a limited set of locales are supported.</p>
*
* @param locale Locale to obtain formats for.
* @param changeError If true change error message to match local.
*
* @return The suggested format (an array of strings) or an empty
* array if the locale is not supported.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @productversion ApacheFlex 4.8
*/
public function suggestFormat(locale:String = null, changeErrors:Boolean = false):Array
{
var region:String = getRegion(locale);
switch (region)
{
case "AU":
case "CH":
case "DK":
case "NO":
formats = [ "NNNN" ];
break;
case "BR":
formats = [ "NNNNN-NNN" ];
break;
case "CN":
case "DE":
formats = [ "NNNNNN" ];
break;
case "CA":
formats = [ "ANA NAN" ];
break;
case "ES":
formats = [ "NNNNN" ];
break;
case "FI":
case "FR":
case "IT":
case "TW":
formats = [ "NNNNN" ];
break;
case "GB":
formats = [ "AN NAA", "ANN NAA", "AAN NAA", "ANA NAA", "AANN NAA", "AANA NAA" ];
break;
case "JP":
formats = [ "NNNNNNN", "NNN-NNNN", "C NNNNNNN", "C NNN-NNNN" ];
break;
case "KR":
formats = [ "NNNNNN", "NNN-NNN" ];
break;
case "NL":
formats = [ "NNNN AA" ];
break;
case "PT":
formats = [ "NNNN-NNN", "NNNN NNN", "NNNN" ];
break;
case "RU":
formats = [ "NNNNNN" ];
break;
case "SE":
formats = [ "NNNNN", "NNN NN" ];
break;
case "US":
formats = [ "NNNNN", "NNNNN-NNNN" ];
break;
default:
formats = [];
break;
}
if (changeErrors)
errorsToLocale(locale);
return formats;
}
/**
* Sets the suggested country code for for a given <code>locale</code>.
*
* <p>If no locale is supplied the default locale is used.</p>
*
* <p>Currently only a limited set of locales are supported.</p>
*
* @param Locale Locale to obtain country code for.
*
* @return The suggested code or an null string if the
* locale is not supported or has no country code.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @productversion ApacheFlex 4.8
*/
public function suggestCountryCode(locale:String = null):String
{
var region:String = getRegion(locale);
if (region == "JP")
countryCode = "〒";
return countryCode;
}
}
}
|
// Decompiled by AS3 Sorcerer 6.08
// www.as3sorcerer.com
//io.decagames.rotmg.dailyQuests.view.list.DailyQuestsList
package io.decagames.rotmg.dailyQuests.view.list
{
import flash.display.Sprite;
import io.decagames.rotmg.ui.tabs.UITabs;
import io.decagames.rotmg.ui.tabs.TabButton;
import io.decagames.rotmg.ui.sliceScaling.SliceScalingBitmap;
import io.decagames.rotmg.ui.texture.TextureParser;
import io.decagames.rotmg.ui.tabs.UITab;
import io.decagames.rotmg.ui.scroll.UIScrollbar;
import io.decagames.rotmg.ui.buttons.BaseButton;
import io.decagames.rotmg.ui.tabs.*;
public class DailyQuestsList extends Sprite
{
public static const QUEST_TAB_LABEL:String = "Quests";
public static const EVENT_TAB_LABEL:String = "Events";
public static const SCROLL_BAR_HEIGHT:int = 345;
private var questLinesPosition:int = 0;
private var eventLinesPosition:int = 0;
private var questsContainer:Sprite;
private var eventsContainer:Sprite;
private var _tabs:UITabs;
private var eventsTab:TabButton;
private var contentTabs:SliceScalingBitmap;
private var contentInset:SliceScalingBitmap;
private var _dailyQuestElements:Vector.<DailyQuestListElement>;
private var _eventQuestElements:Vector.<DailyQuestListElement>;
public function DailyQuestsList()
{
this.init();
}
private function init():void
{
this.createContentTabs();
this.createContentInset();
this.createTabs();
}
private function createTabs():void
{
this._tabs = new UITabs(230, true);
this._tabs.addTab(this.createQuestsTab(), true);
this._tabs.addTab(this.createEventsTab());
this._tabs.y = 1;
addChild(this._tabs);
}
private function createContentInset():void
{
this.contentInset = TextureParser.instance.getSliceScalingBitmap("UI", "popup_content_inset", 230);
this.contentInset.height = 360;
this.contentInset.y = 35;
addChild(this.contentInset);
}
private function createContentTabs():void
{
this.contentTabs = TextureParser.instance.getSliceScalingBitmap("UI", "tab_inset_content_background", 230);
this.contentTabs.height = 45;
addChild(this.contentTabs);
}
private function createQuestsTab():UITab
{
var _local_4:Sprite;
var _local_1:UITab = new UITab(QUEST_TAB_LABEL);
var _local_2:Sprite = new Sprite();
this.questsContainer = new Sprite();
this.questsContainer.x = this.contentInset.x;
this.questsContainer.y = 10;
_local_2.addChild(this.questsContainer);
var _local_3:UIScrollbar = new UIScrollbar(SCROLL_BAR_HEIGHT);
_local_3.mouseRollSpeedFactor = 1;
_local_3.scrollObject = _local_1;
_local_3.content = this.questsContainer;
_local_2.addChild(_local_3);
_local_3.x = ((this.contentInset.x + this.contentInset.width) - 25);
_local_3.y = 7;
_local_4 = new Sprite();
_local_4.graphics.beginFill(0);
_local_4.graphics.drawRect(0, 0, 230, SCROLL_BAR_HEIGHT);
_local_4.x = this.questsContainer.x;
_local_4.y = this.questsContainer.y;
this.questsContainer.mask = _local_4;
_local_2.addChild(_local_4);
_local_1.addContent(_local_2);
return (_local_1);
}
private function createEventsTab():UITab
{
var _local_1:UITab;
_local_1 = new UITab("Events");
var _local_2:Sprite = new Sprite();
this.eventsContainer = new Sprite();
this.eventsContainer.x = this.contentInset.x;
this.eventsContainer.y = 10;
_local_2.addChild(this.eventsContainer);
var _local_3:UIScrollbar = new UIScrollbar(SCROLL_BAR_HEIGHT);
_local_3.mouseRollSpeedFactor = 1;
_local_3.scrollObject = _local_1;
_local_3.content = this.eventsContainer;
_local_2.addChild(_local_3);
_local_3.x = ((this.contentInset.x + this.contentInset.width) - 25);
_local_3.y = 7;
var _local_4:Sprite = new Sprite();
_local_4.graphics.beginFill(0);
_local_4.graphics.drawRect(0, 0, 230, SCROLL_BAR_HEIGHT);
_local_4.x = this.eventsContainer.x;
_local_4.y = this.eventsContainer.y;
this.eventsContainer.mask = _local_4;
_local_2.addChild(_local_4);
_local_1.addContent(_local_2);
return (_local_1);
}
public function addIndicator(_arg_1:Boolean):void
{
this.eventsTab = this._tabs.getTabButtonByLabel(EVENT_TAB_LABEL);
if (this.eventsTab)
{
this.eventsTab.showIndicator = _arg_1;
this.eventsTab.clickSignal.add(this.onEventsClick);
}
}
private function onEventsClick(_arg_1:BaseButton):void
{
if (TabButton(_arg_1).hasIndicator)
{
TabButton(_arg_1).showIndicator = false;
}
}
public function addQuestToList(_arg_1:DailyQuestListElement):void
{
if (!this._dailyQuestElements)
{
this._dailyQuestElements = new Vector.<DailyQuestListElement>(0);
}
_arg_1.x = 10;
_arg_1.y = (this.questLinesPosition * 35);
this.questsContainer.addChild(_arg_1);
this.questLinesPosition++;
this._dailyQuestElements.push(_arg_1);
}
public function addEventToList(_arg_1:DailyQuestListElement):void
{
if (!this._eventQuestElements)
{
this._eventQuestElements = new Vector.<DailyQuestListElement>(0);
}
_arg_1.x = 10;
_arg_1.y = (this.eventLinesPosition * 35);
this.eventsContainer.addChild(_arg_1);
this.eventLinesPosition++;
this._eventQuestElements.push(_arg_1);
}
public function get list():Sprite
{
return (this.questsContainer);
}
public function get tabs():UITabs
{
return (this._tabs);
}
public function clearQuestLists():void
{
var _local_1:DailyQuestListElement;
while (this.questsContainer.numChildren > 0)
{
_local_1 = (this.questsContainer.removeChildAt(0) as DailyQuestListElement);
_local_1 = null;
}
this.questLinesPosition = 0;
((this._dailyQuestElements) && (this._dailyQuestElements.length = 0));
while (this.eventsContainer.numChildren > 0)
{
_local_1 = (this.eventsContainer.removeChildAt(0) as DailyQuestListElement);
_local_1 = null;
}
this.eventLinesPosition = 0;
((this._eventQuestElements) && (this._eventQuestElements.length = 0));
}
public function getCurrentlySelected(_arg_1:String):DailyQuestListElement
{
var _local_2:DailyQuestListElement;
var _local_3:DailyQuestListElement;
var _local_4:DailyQuestListElement;
if (_arg_1 == QUEST_TAB_LABEL)
{
for each (_local_3 in this._dailyQuestElements)
{
if (_local_3.isSelected)
{
_local_2 = _local_3;
break;
}
}
}
else
{
if (_arg_1 == EVENT_TAB_LABEL)
{
for each (_local_4 in this._eventQuestElements)
{
if (_local_4.isSelected)
{
_local_2 = _local_4;
break;
}
}
}
}
return (_local_2);
}
}
}//package io.decagames.rotmg.dailyQuests.view.list
|
package com.hendrix.http.common.mime
{
import com.hendrix.http.common.error.HttpError;
/**
* Mime Header
* @author Tomer Shalev
*
*/
public class MimeHeader
{
public static const MIME_Version: String = "MIME-Version";
public static const Content_Type: String = "Content-Type";
public static const Content_Transfer_Encoding: String = "Content-Transfer-Encoding";
public static const Content_Description: String = "Content-Description";
public static const Content_ID: String = "Content-ID";
public static const Content_Location: String = "Content-Location";
public static const Content_Disposition: String = "Content-Disposition";
protected var _name: String;
protected var _value: String;
protected var _parameters: String = "";
/**
* Mime Header
* @param name the name of the MIME header
* @param value it's value
* @param params extra MIME header parameters
* @throws com.hendrix.http.common.error.HttpError
*/
public function MimeHeader(name:String = "", value:String = "", ...params)
{
_name = name;
_value = value;
var cParmas: uint = params[0].length;
if(cParmas%2 == 1)
throw new HttpError("some parameter key is missing a value");
for(var ix:uint = 0; ix <= cParmas - 2; ix += 2)
{
addParameter(params[0][ix], params[0][ix + 1]);
}
}
/**
* ass mime type parameter. please follow [RFC 2183]
* @param param
* @param value
*
*/
public function addParameter(param:String, value:String):void
{
_parameters += "; " + param + "=" + value;
}
public function toString():String
{
return _name + ":" + _value + _parameters;
}
/**
* the name of the Mime Type
*/
public function get name():String
{
return _name;
}
/**
* the value of the header
*/
public function get value():String
{
return _value;
}
/**
* @private
*/
public function set value(value:String):void
{
_value = value;
}
}
} |
/**
* Morn UI Version 3.2 http://www.mornui.com/
* Feedback yungvip@163.com weixin:yungzhu
*/
package morn.core.components {
import morn.editor.core.IRender;
/**视图*/
public class View extends Box {
/**存储UI配置数据(用于加载模式)*/
public static var uiMap:Object = {};
protected static var uiClassMap:Object = {"Box": Box, "Button": Button, "CheckBox": CheckBox, "Clip": Clip, "ComboBox": ComboBox, "Component": Component, "Container": Container, "FrameClip": FrameClip, "HScrollBar": HScrollBar, "HSlider": HSlider, "Image": Image, "Label": Label, "LinkButton": LinkButton, "List": List, "Panel": Panel, "ProgressBar": ProgressBar, "RadioButton": RadioButton, "RadioGroup": RadioGroup, "ScrollBar": ScrollBar, "Slider": Slider, "Tab": Tab, "TextArea": TextArea, "TextInput": TextInput, "View": View, "ViewStack": ViewStack, "VScrollBar": VScrollBar, "VSlider": VSlider, "HBox": HBox, "VBox": VBox, "Tree": Tree};
protected static var viewClassMap:Object = {};
protected function createView(uiView:Object):void {
createComp(uiView, this, this);
}
/**加载UI(用于加载模式)*/
protected function loadUI(path:String):void {
var uiView:Object = uiMap[path];
if (uiView) {
createView(uiView);
}
}
/** 根据UI数据实例组件
* @param uiView UI数据
* @param comp 组件本体,如果为空,会新创建一个
* @param view 组件所在的视图实例,用来注册var全局变量,为空则不注册*/
public static function createComp(uiView:Object, comp:Component = null, view:View = null):Component {
if (uiView is XML) {
return createCompByXML(uiView as XML, comp, view);
} else {
return createCompByJSON(uiView, comp, view);
}
}
protected static function createCompByJSON(json:Object, comp:Component = null, view:View = null):Component {
comp = comp || getCompInstanceByJSON(json);
comp.comJSON = json;
var child:Array = json.child;
if (child) {
for each (var note:Object in child) {
if (comp is IRender && note.props.name == "render") {
IRender(comp).itemRender = note;
} else {
comp.addChild(createCompByJSON(note, null, view));
}
}
}
var props:Object = json.props;
for (var prop:String in props) {
var value:String = props[prop];
setCompValue(comp, prop, value, view);
}
if (comp is IItem) {
IItem(comp).initItems();
}
return comp;
}
protected static function createCompByXML(xml:XML, comp:Component = null, view:View = null):Component {
comp = comp || getCompInstanceByXML(xml);
comp.comXml = xml;
var list:XMLList = xml.children();
//[IF-SCRIPT]for (var i:int = 0, m:int = list.lengths(); i < m; i++) {
/*[IF-FLASH]*/for (var i:int = 0, m:int = list.length(); i < m; i++) {
var node:XML = list[i];
if (comp is IRender && node.@name == "render") {
IRender(comp).itemRender = node;
} else {
comp.addChild(createComp(node, null, view));
}
}
var list2:XMLList = xml.attributes();
for each (var attrs:XML in list2) {
var prop:String = attrs.name().toString();
var value:String = attrs.toString();
setCompValue(comp, prop, value, view);
}
if (comp is IItem) {
IItem(comp).initItems();
}
return comp;
}
private static function setCompValue(comp:Component, prop:String, value:String, view:View = null):void {
//if (comp.hasOwnProperty(prop)) {
/*[IF-SCRIPT-BEGIN]
if (prop=="width" || prop=="height" || comp[prop] is Number) {
comp[prop]=Number(value);
}else
[IF-SCRIPT-END]*/
// comp[prop] = (value == "true" ? true : (value == "false" ? false : value))
//} else if (prop == "var" && view && view.hasOwnProperty(value)) {
// view[value] = comp;
//}
if (prop == "var" && view /*&& view.hasOwnProperty(value)*/) {
view[value] = comp;
}else{
comp[prop] = (value == "true" ? true : (value == "false" ? false : value))
}
}
/**获得组件实例*/
protected static function getCompInstanceByJSON(json:Object):Component {
var runtime:String = json.props ? json.props.runtime : "";
var compClass:Class = Boolean(runtime) ? viewClassMap[runtime] : uiClassMap[json.type];
return compClass ? new compClass() : null;
}
/**获得组件实例*/
protected static function getCompInstanceByXML(xml:XML):Component {
var runtime:String = xml.@runtime;
var compClass:Class = Boolean(runtime) ? viewClassMap[runtime] : uiClassMap[xml.name()];
return compClass ? new compClass() : null;
}
/**重新创建组件(通过修改组件的数据,实现动态更改UI视图)
* @param comp 需要重新生成的组件 comp为null时,重新创建整个视图*/
public function reCreate(comp:Component = null):void {
comp = comp || this;
var dataSource:Object = comp.dataSource;
if (comp is Box) {
Box(comp).removeAllChild();
}
createComp(comp.comJSON || comp.comXml, comp, this);
comp.dataSource = dataSource;
}
/**注册组件(用于扩展组件及修改组件对应关系)*/
public static function registerComponent(key:String, compClass:Class):void {
uiClassMap[key] = compClass;
}
/**注册runtime解析*/
public static function registerViewRuntime(key:String, compClass:Class):void {
viewClassMap[key] = compClass;
}
}
} |
package kabam.rotmg.classes.control {
import org.osflash.signals.Signal;
public class ParseClassesXMLSignal extends Signal {
public function ParseClassesXMLSignal() {
super(XML);
}
}
}//package kabam.rotmg.classes.control
|
package io.decagames.rotmg.seasonalEvent.signals {
import org.osflash.signals.Signal;
public class ShowSeasonHasEndedPopupSignal extends Signal {
public function ShowSeasonHasEndedPopupSignal() {
super();
}
}
}
|
package flashx.textLayout.operations
{
import flashx.textLayout.edit.IMemento;
import flashx.textLayout.edit.ModelEdit;
import flashx.textLayout.edit.SelectionState;
import flashx.textLayout.edit.TextFlowEdit;
import flashx.textLayout.elements.FlowLeafElement;
import flashx.textLayout.elements.LinkElement;
public class ApplyLinkOperation extends FlowTextOperation
{
private var _hrefString:String;
private var _target:String;
private var _extendToLinkBoundary:Boolean;
private var _memento:IMemento;
private var _linkElement:LinkElement;
public function ApplyLinkOperation(operationState:SelectionState, href:String, target:String, extendToLinkBoundary:Boolean)
{
super(operationState);
this._hrefString = href;
this._target = target;
this._extendToLinkBoundary = extendToLinkBoundary;
}
public function get href() : String
{
return this._hrefString;
}
public function set href(value:String) : void
{
this._hrefString = value;
}
public function get target() : String
{
return this._target;
}
public function set target(value:String) : void
{
this._target = value;
}
public function get extendToLinkBoundary() : Boolean
{
return this._extendToLinkBoundary;
}
public function set extendToLinkBoundary(value:Boolean) : void
{
this._extendToLinkBoundary = value;
}
public function get newLinkElement() : LinkElement
{
return this._linkElement;
}
override public function doOperation() : Boolean
{
var leaf:FlowLeafElement = null;
var link:LinkElement = null;
var madeLink:Boolean = false;
if(absoluteStart == absoluteEnd)
{
return false;
}
if(this._extendToLinkBoundary)
{
leaf = textFlow.findLeaf(absoluteStart);
link = leaf.getParentByType(LinkElement) as LinkElement;
if(link)
{
absoluteStart = link.getAbsoluteStart();
}
leaf = textFlow.findLeaf(absoluteEnd - 1);
link = leaf.getParentByType(LinkElement) as LinkElement;
if(link)
{
absoluteEnd = link.getAbsoluteStart() + link.textLength;
}
}
this._memento = ModelEdit.saveCurrentState(textFlow,absoluteStart,absoluteEnd);
if(this._hrefString && this._hrefString != "")
{
madeLink = TextFlowEdit.makeLink(textFlow,absoluteStart,absoluteEnd,this._hrefString,this._target);
if(!madeLink)
{
this._memento = null;
return false;
}
leaf = textFlow.findLeaf(absoluteStart);
this._linkElement = leaf.getParentByType(LinkElement) as LinkElement;
}
else
{
TextFlowEdit.removeLink(textFlow,absoluteStart,absoluteEnd);
}
return true;
}
override public function undo() : SelectionState
{
if(this._memento)
{
this._memento.undo();
}
return originalSelectionState;
}
override public function redo() : SelectionState
{
if(absoluteStart != absoluteEnd && this._memento)
{
if(this._hrefString != "")
{
TextFlowEdit.makeLink(textFlow,absoluteStart,absoluteEnd,this._hrefString,this._target);
}
else
{
TextFlowEdit.removeLink(textFlow,absoluteStart,absoluteEnd);
}
}
return originalSelectionState;
}
}
}
|
package scenes
{
// Game Events Includes
import events.GameEvent;
import events.GameState;
// Game UI Models Includes
import models.ui.SceneBackground;
import models.ui.SceneHeader;
import models.ui.controls.FuncButton;
// Starling Includes
import starling.display.Sprite;
import starling.events.Event;
// Game Utils Includes
import utils.AdsManager;
import utils.SpriteUtl;
/**
* Home Scene Class<br/>
* The class will construct and manage the Home Scene
*
* @author Code Alchemy
**/
public class HomeScene extends Sprite
{
// Tag Constant for log
private const LOG_TAG:String ='[HomeScene] ';
/**
* Home Scene constructor
*
**/
public function HomeScene()
{
// Debug Logger
Root.log(LOG_TAG,"Constructor");
// Add loading and unloading event listeners
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
addEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
}
/**
* Event listener for Scene added to stage <br/>
*
* @param e Event Object
**/
private function onAddedToStage(e:Event):void
{
// Debug Logger
Root.log(LOG_TAG,"onAddedToStage");
// Remove unnecessary event listeners
removeEventListeners(Event.ADDED_TO_STAGE);
// Init the scene
init();
}
/**
* Event listener for Scene removed from stage <br/>
*
* @param e Event Object
**/
private function onRemovedFromStage(e:Event):void
{
// Debug Logger
Root.log(LOG_TAG,"onRemovedFromStage");
// Remove all the event listeners
removeEventListeners();
}
/**
* Initialize the Home Scene
*
**/
private function init():void
{
// Debug Logger
Root.log(LOG_TAG,"Initializing...");
// Add the Scene Background
var sceneBackground:SceneBackground = new SceneBackground();
addChild(sceneBackground);
// Add the Scene Header
var sceneHeader:SceneHeader = new SceneHeader();
addChild(sceneHeader);
// Add the offline banner instance and activate the banner
addChild(AdsManager.offlineBanner);
AdsManager.activateAppBanner();
// Add the Scene Context
var mainConsole:Sprite = createMainConsole();
SpriteUtl.setPivot(mainConsole,SpriteUtl.CENTER);
var posY:uint = sceneHeader.height+((Constants.STAGE_HEIGHT-50-sceneHeader.height)/2);
SpriteUtl.setPosition(mainConsole,Constants.STAGE_WIDTH/2,posY,false);
addChild(mainConsole);
}
/**
* Create the Scene main Console
*
* @return Main context Sprite instance
**/
private function createMainConsole():Sprite
{
// Debug Logger
Root.log(LOG_TAG,"createMainConsole");
// Console proprierty
var container:Sprite = new Sprite();
var label:String;
var yPos:uint = 0;
var yOffset:uint = 2;
// Create Each Button
for (var i:uint = 1; i <= 7; i++)
{
// Create the button
var button:FuncButton = new FuncButton(Root.getMsg(Constants.MSG_MENU_FUNC+i),null,true,SpriteUtl.TOPLEFT);
SpriteUtl.setPosition(button,0,yPos,false);
// Enable the button according to function lock state
button.name = i.toString();
button.addEventListener(Event.TRIGGERED,onButtonTrigged);
container.addChild(button);
// Update next button Position
yPos += button.height+yOffset;
}
// Return the Container
return container;
}
/**
* onButtonTrigged Event Listener
*
* @param e Event Object
**/
private function onButtonTrigged(e:Event):void
{
// Debug Logger
Root.log(LOG_TAG,"onButtonTrigged");
// Get the button Instance
var button:FuncButton = e.target as FuncButton;
// Get the Function Destination
var destination:String;
if (button.name == "1") destination = GameState.STATE_GAME;
else if (button.name == "2") destination = GameState.STATE_SINGLE_BANNER;
else if (button.name == "3") destination = GameState.STATE_MULTI_BANNER;
else if (button.name == "4") destination = GameState.STATE_MOVE_BANNER;
else if (button.name == "5") destination = GameState.STATE_ROTATE_BANNER;
else if (button.name == "6") destination = GameState.STATE_INTERSTITIAL;
else if (button.name == "7") destination = GameState.STATE_CONFIG;
else if (button.name == "8") destination = GameState.STATE_CREDITS;
else return;
// Dispatch Scene Change Event
dispatchEventWith(GameEvent.GAME_STATE_CHANGE, true, destination);
}
}
} |
package serverProto.task
{
import com.netease.protobuf.Message;
import com.netease.protobuf.fieldDescriptors.FieldDescriptor$TYPE_MESSAGE;
import com.netease.protobuf.fieldDescriptors.RepeatedFieldDescriptor$TYPE_INT32;
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 ProtoGetFixNinjaListRsp extends Message
{
public static const RET:FieldDescriptor$TYPE_MESSAGE = new FieldDescriptor$TYPE_MESSAGE("serverProto.task.ProtoGetFixNinjaListRsp.ret","ret",1 << 3 | WireType.LENGTH_DELIMITED,ProtoRetInfo);
public static const NINJA_LIST:RepeatedFieldDescriptor$TYPE_INT32 = new RepeatedFieldDescriptor$TYPE_INT32("serverProto.task.ProtoGetFixNinjaListRsp.ninja_list","ninjaList",2 << 3 | WireType.VARINT);
public var ret:ProtoRetInfo;
[ArrayElementType("int")]
public var ninjaList:Array;
public function ProtoGetFixNinjaListRsp()
{
this.ninjaList = [];
super();
}
override final function writeToBuffer(param1:WritingBuffer) : void
{
var _loc3_:* = undefined;
WriteUtils.writeTag(param1,WireType.LENGTH_DELIMITED,1);
WriteUtils.write$TYPE_MESSAGE(param1,this.ret);
var _loc2_:uint = 0;
while(_loc2_ < this.ninjaList.length)
{
WriteUtils.writeTag(param1,WireType.VARINT,2);
WriteUtils.write$TYPE_INT32(param1,this.ninjaList[_loc2_]);
_loc2_++;
}
for(_loc3_ in this)
{
super.writeUnknown(param1,_loc3_);
}
}
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");
}
}
}
|
package devoron.data.core.base
{
/**
* IDataContainersManager
* Служит интерфейсом для DataStructur.
* Способен добавлять в себя контейнеры данных.
* @author Devoron
*/
public interface IDataContainersManager
{
function addDataContainer(dataContainer:IDataContainer):void;
function removeDataContainer(dataContainer:IDataContainer):void;
function removeDataByContainerName(dataContainerName:String):void
function getDataContainersNames():Array;
function getDataByContainerName(dataContainerName:String):Object;
function getDataContainer(dataContainerName:String):IDataContainer;
function setDataByName(data:Object, dataName:String):void
function clone():IDataContainersManager;
}
} |
////////////////////////////////////////////////////////////////////////////////
//
// 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.effects
{
import mx.effects.effectClasses.SequenceInstance;
/**
* The Sequence effect plays multiple child effects one after the other,
* in the order in which they are added.
*
* <p>You can create a Sequence effect in MXML,
* as the following example shows:</p>
*
* <pre>
* <mx:Sequence id="WipeRightUp">
* <mx:children>
* <mx:WipeRight duration="1000"/>
* <mx:WipeUp duration="1000"/>
* </mx:children>
* </mx:Sequence>
*
* <mx:VBox id="myBox" hideEffect="{WipeRightUp}">
* <mx:TextArea id="aTextArea" text="hello"/>
* </mx:VBox>
* </pre>
*
* <p>Notice that the <code><mx:children></code> tag is optional.</p>
*
* <p>Starting a composite effect in ActionScript is usually
* a five-step process:</p>
*
* <ol>
* <li>Create instances of the effect objects to be composited together;
* for example:
* <pre>myFadeEffect = new mx.effects.Fade(target);</pre></li>
* <li>Set properties, such as <code>duration</code>, on the individual effect objects.</li>
* <li>Create an instance of the Sequence effect object;
* for example:
* <pre>mySequenceEffect = new mx.effects.Sequence();</pre></li>
* <li>Call the <code>addChild()</code> method for each of the effect objects;
* for example:
* <pre>mySequenceEffect.addChild(myFadeEffect);</pre></li>
* <li>Invoke the Sequence effect's <code>play()</code> method;
* for example:
* <pre>mySequenceEffect.play();</pre></li>
* </ol>
*
* @mxml
*
* <p>The <code><mx:Sequence></code> tag
* inherits all of the tag attributes of its superclass,
* and adds the following tag attributes:</p>
*
* <pre>
* <mx:Sequence id="<i>identifier</i>">
* <mx:children>
* <!-- Specify child effect tags -->
* </mx:children>
* </mx:Sequence>
* </pre>
*
* @see mx.effects.effectClasses.SequenceInstance
*
* @includeExample examples/SequenceEffectExample.mxml
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public class Sequence extends CompositeEffect
{
include "../core/Version.as";
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @param target This argument is ignored for Sequence effects.
* It is included only for consistency with other types of effects.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function Sequence(target:Object = null)
{
super(target);
instanceClass = SequenceInstance;
}
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
override protected function initInstance(instance:IEffectInstance):void
{
super.initInstance(instance);
}
/**
* @inheritDoc
*
* Sequence calculates this number to be the duration of each
* child effect, played one after the other.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
override public function get compositeDuration():Number
{
var sequenceDuration:Number = 0;
for (var i:int = 0; i < children.length; ++i)
{
var childDuration:Number;
var child:Effect = Effect(children[i]);
if (child is CompositeEffect)
childDuration = CompositeEffect(child).compositeDuration;
else
childDuration = child.duration;
childDuration =
childDuration * child.repeatCount +
(child.repeatDelay * (child.repeatCount - 1)) +
child.startDelay;
sequenceDuration += childDuration;
}
return sequenceDuration;
}
}
}
|
package com.company.assembleegameclient.account.ui {
import com.company.assembleegameclient.ui.ClickableText;
import com.company.ui.SimpleText;
import com.company.util.GraphicsUtil;
import flash.display.CapsStyle;
import flash.display.DisplayObject;
import flash.display.GraphicsPath;
import flash.display.GraphicsSolidFill;
import flash.display.GraphicsStroke;
import flash.display.IGraphicsData;
import flash.display.JointStyle;
import flash.display.LineScaleMode;
import flash.display.Sprite;
import flash.events.Event;
import flash.filters.DropShadowFilter;
import kabam.rotmg.account.web.view.LabeledField;
public class Frame extends Sprite {
private var graphicsData_:Vector.<IGraphicsData>;
public function Frame(title:String, leftButton:String, rightButton:String, w:int = 288) {
this.titleFill_ = new GraphicsSolidFill(5066061, 1);
this.backgroundFill_ = new GraphicsSolidFill(3552822, 1);
this.outlineFill_ = new GraphicsSolidFill(16777215, 1);
this.lineStyle_ = new GraphicsStroke(1, false, LineScaleMode.NORMAL, CapsStyle.NONE, JointStyle.ROUND, 3, this.outlineFill_);
this.path1_ = new GraphicsPath(new Vector.<int>(), new Vector.<Number>());
this.path2_ = new GraphicsPath(new Vector.<int>(), new Vector.<Number>());
this.textInputFields_ = new Vector.<TextInputField>();
this.navigationLinks_ = new Vector.<ClickableText>();
this.graphicsData_ = new <IGraphicsData>[this.backgroundFill_, this.path2_, GraphicsUtil.END_FILL, this.titleFill_, this.path1_, GraphicsUtil.END_FILL, this.lineStyle_, this.path2_, GraphicsUtil.END_STROKE];
super();
this.w_ = w;
this.titleText_ = new SimpleText(12, 11776947, false, 0, 0);
this.titleText_.text = title;
this.titleText_.updateMetrics();
this.titleText_.filters = [new DropShadowFilter(0, 0, 0)];
this.titleText_.x = 5;
this.titleText_.filters = [new DropShadowFilter(0, 0, 0, 0.5, 12, 12)];
addChild(this.titleText_);
this.leftButton_ = new ClickableText(18, true, leftButton);
if (leftButton != "") {
this.leftButton_.buttonMode = true;
this.leftButton_.x = 109;
addChild(this.leftButton_);
}
this.rightButton_ = new ClickableText(18, true, rightButton);
this.rightButton_.buttonMode = true;
this.rightButton_.x = this.w_ - this.rightButton_.width - 26;
addChild(this.rightButton_);
filters = [new DropShadowFilter(0, 0, 0, 0.5, 12, 12)];
addEventListener(Event.ADDED_TO_STAGE, this.onAddedToStage);
addEventListener(Event.REMOVED_FROM_STAGE, this.onRemovedFromStage);
}
public var titleText_:SimpleText;
public var leftButton_:ClickableText;
public var rightButton_:ClickableText;
public var textInputFields_:Vector.<TextInputField>;
public var navigationLinks_:Vector.<ClickableText>;
public var w_:int = 288;
public var h_:int = 100;
private var titleFill_:GraphicsSolidFill;
private var backgroundFill_:GraphicsSolidFill;
private var outlineFill_:GraphicsSolidFill;
private var lineStyle_:GraphicsStroke;
private var path1_:GraphicsPath;
private var path2_:GraphicsPath;
public function addLabeledField(labeledField:LabeledField):void {
addChild(labeledField);
labeledField.y = this.h_ - 60;
labeledField.x = 17;
this.h_ = this.h_ + labeledField.getHeight();
}
public function addTextInputField(textInputField:TextInputField):void {
this.textInputFields_.push(textInputField);
addChild(textInputField);
textInputField.y = this.h_ - 60;
textInputField.x = 17;
this.h_ = this.h_ + TextInputField.HEIGHT;
}
public function addNavigationText(navigationLink:ClickableText):void {
this.navigationLinks_.push(navigationLink);
addChild(navigationLink);
navigationLink.y = this.h_ - 66;
navigationLink.x = 17;
this.h_ = this.h_ + 20;
}
public function addComponent(component:DisplayObject, offsetX:int = 8):void {
addChild(component);
component.y = this.h_ - 66;
component.x = offsetX;
this.h_ = this.h_ + component.height;
}
public function addPlainText(plainText:String):void {
var text:SimpleText = new SimpleText(12, 16777215, false, 0, 0);
text.text = plainText;
text.updateMetrics();
text.filters = [new DropShadowFilter(0, 0, 0)];
addChild(text);
text.y = this.h_ - 66;
text.x = 17;
this.h_ = this.h_ + 20;
}
public function addTitle(title:String):void {
var text:SimpleText = null;
text = new SimpleText(20, 11711154, false, 0, 0);
text.text = title;
text.setBold(true);
text.updateMetrics();
text.filters = [new DropShadowFilter(0, 0, 0, 0.5, 12, 12)];
addChild(text);
text.y = this.h_ - 60;
text.x = 15;
this.h_ = this.h_ + 40;
}
public function addCheckBox(checkBox:CheckBoxField):void {
addChild(checkBox);
checkBox.y = this.h_ - 66;
checkBox.x = 17;
this.h_ = this.h_ + 44;
}
public function addRadioBox(radioBox:PaymentMethodRadioButtons):void {
addChild(radioBox);
radioBox.y = this.h_ - 66;
radioBox.x = 18;
this.h_ = this.h_ + radioBox.height;
}
public function addSpace(space:int):void {
this.h_ = this.h_ + space;
}
public function disable():void {
var navigationLink:ClickableText = null;
mouseEnabled = false;
mouseChildren = false;
for each(navigationLink in this.navigationLinks_) {
navigationLink.setDefaultColor(11776947);
}
this.leftButton_.setDefaultColor(11776947);
this.rightButton_.setDefaultColor(11776947);
}
public function enable():void {
var navigationLink:ClickableText = null;
mouseEnabled = true;
mouseChildren = true;
for each(navigationLink in this.navigationLinks_) {
navigationLink.setDefaultColor(16777215);
}
this.leftButton_.setDefaultColor(16777215);
this.rightButton_.setDefaultColor(16777215);
}
private function draw():void {
graphics.clear();
GraphicsUtil.clearPath(this.path1_);
GraphicsUtil.drawCutEdgeRect(-6, -6, this.w_, 20 + 12, 4, [1, 1, 0, 0], this.path1_);
GraphicsUtil.clearPath(this.path2_);
GraphicsUtil.drawCutEdgeRect(-6, -6, this.w_, this.h_, 4, [1, 1, 1, 1], this.path2_);
this.leftButton_.y = this.h_ - 52;
this.rightButton_.y = this.h_ - 52;
graphics.drawGraphicsData(this.graphicsData_);
}
protected function onAddedToStage(event:Event):void {
this.draw();
this.x = 400 - (this.w_ - 6) / 2;
this.y = 300 - this.h_ / 2;
if (this.textInputFields_.length > 0) {
stage.focus = this.textInputFields_[0].inputText_;
}
}
private function onRemovedFromStage(event:Event):void {
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 "Licens"); 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.supportClasses.datagrid
{
import org.apache.royale.jewel.Container;
public class VirtualDataGridListArea extends DataGridListArea
{
public function VirtualDataGridListArea()
{
super();
typeNames = 'listarea';
}
}
} |
/*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.spicefactory.parsley.core.registry.impl {
import flash.utils.Dictionary;
import org.spicefactory.lib.errors.IllegalStateError;
import org.spicefactory.lib.reflect.ClassInfo;
import org.spicefactory.parsley.core.processor.ObjectProcessorConfig;
import org.spicefactory.parsley.core.registry.ContainerObjectInstantiator;
import org.spicefactory.parsley.core.registry.ObjectDefinition;
import org.spicefactory.parsley.core.registry.ObjectDefinitionRegistry;
import org.spicefactory.parsley.core.registry.ObjectInstantiator;
/**
* Abstract base class for all ObjectDefinition implementations.
*
* @author Jens Halm
*/
public class AbstractObjectDefinition implements ObjectDefinition {
private var _type:ClassInfo;
private var _id:String;
private var attributes:Dictionary = new Dictionary();
private var _registry:ObjectDefinitionRegistry;
private var _instantiator:ObjectInstantiator;
private var _processors:Array = new Array();
private var _frozen:Boolean;
/**
* Creates a new instance.
*
* @param type the type to create a definition for
* @param id the id the object should be registered with
* @param registry the registry this definition belongs to
* @param parent the parent definition containing shared configuration for this definition
*/
function AbstractObjectDefinition (type:ClassInfo, id:String,
registry:ObjectDefinitionRegistry) {
_type = type;
_id = id;
_registry = registry;
}
/**
* @inheritDoc
*/
public function get type () : ClassInfo {
return _type;
}
/**
* @inheritDoc
*/
public function get id () : String {
return _id;
}
/**
* @inheritDoc
*/
public function getAttribute (key: Object): Object {
return attributes[key];
}
/**
* @inheritDoc
*/
public function setAttribute (key: Object, value: Object): void {
attributes[key] = value;
}
/**
* @inheritDoc
*/
public function get registry () : ObjectDefinitionRegistry {
return _registry;
}
/**
* @inheritDoc
*/
public function get instantiator () : ObjectInstantiator {
return _instantiator;
}
/**
* @inheritDoc
*/
public function addProcessor (processor:ObjectProcessorConfig) : void {
_processors.push(processor);
}
/**
* @inheritDoc
*/
public function get processors () : Array {
return _processors.concat();
}
/**
* @inheritDoc
*/
public function set instantiator (value:ObjectInstantiator) : void {
checkState();
if (instantiator != null && (instantiator is ContainerObjectInstantiator)) {
throw new IllegalStateError("Instantiator has been set by the container and cannot be overwritten");
}
_instantiator = value;
}
private function checkState () : void {
if (frozen) {
throw new IllegalStateError(toString() + " is frozen");
}
}
/**
* @inheritDoc
*/
public function freeze () : void {
_frozen = true;
}
/**
* @inheritDoc
*/
public function get frozen () : Boolean {
return _frozen;
}
/**
* Populates this definition with all configuration artifacts from the specified source.
*
* @param source the definition to copy all configuration artifacts from
*/
public function populateFrom (source:ObjectDefinition) : void {
instantiator = source.instantiator;
for each (var config:ObjectProcessorConfig in source.processors) {
addProcessor(config);
}
}
/**
* @private
*/
public function toString () : String {
return "[ObjectDefinition(type = " + _type.name + ", id = " + _id + ")]";
}
}
}
|
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.filters.BlurFilter;
import flash.text.TextFormat;
import org.flintparticles.common.counters.Blast;
import org.flintparticles.common.debug.Stats;
import org.flintparticles.common.initializers.AlphaInit;
import org.flintparticles.common.initializers.ApplyFilter;
import org.flintparticles.common.initializers.ColorInit;
import org.flintparticles.common.initializers.ImageClass;
import org.flintparticles.twoD.actions.ApproachNeighbours;
import org.flintparticles.twoD.actions.BoundingBox;
import org.flintparticles.twoD.actions.Friction;
import org.flintparticles.twoD.actions.Move;
import org.flintparticles.twoD.actions.ScaleAll;
import org.flintparticles.twoD.emitters.Emitter2D;
import org.flintparticles.twoD.initializers.Position;
import org.flintparticles.twoD.renderers.DisplayObjectRenderer;
import org.flintparticles.twoD.zones.RectangleZone;
import org.flintparticles.common.displayObjects.Dot;
import org.flintparticles.common.displayObjects.Ring;
/**
* ...
* @author illuzor // illuzor@gmail.com
*/
public class Main extends Sprite {
public function Main():void {
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void {
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
var emitter:Emitter2D = new Emitter2D();
emitter.counter = new Blast(500);
emitter.addInitializer(new ColorInit(0xFF0000, 0x00FF00));
emitter.addInitializer(new ApplyFilter(new BlurFilter(2, 2, 3)));
emitter.addInitializer(new AlphaInit(0.9, 1));
emitter.addInitializer(new ImageClass(Dot,[1.5]));
//emitter.addInitializer(new ImageClass(Ring,[8]));
emitter.addInitializer(new Position(new RectangleZone(0, 0, stage.stageWidth, stage.stageHeight)));
emitter.addAction(new Move());
emitter.addAction(new ApproachNeighbours(100, 90));
emitter.addAction(new ScaleAll(2,10));
//emitter.addAction(new Friction(100));
var renderer:DisplayObjectRenderer= new DisplayObjectRenderer();
renderer.addEmitter(emitter);
addChild(renderer);
emitter.start();
var statistic:Stats = new Stats(0xFFFFFFFF, 0x00000000); //Создаем Stats (цвет текста, цвет фона)
statistic.defaultTextFormat = new TextFormat("Arial", 13); //форматируем (не обязательно)
addChild(statistic); //добавляем на сцену (по умолчанию в верхний левый угол)
addEventListener(Event.ENTER_FRAME, update);
}
private function update(e:Event):void{
}
}
} |
/*
* 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.
*/
// MediaInfo.as
// John Maloney, December 2011
//
// This object represent a sound, image, or script. It is used:
// * to represent costumes, backdrops, or sounds in a MediaPane
// * to represent images, sounds, and sprites in the backpack (a BackpackPart)
// * to drag between the backpack and the media pane
package ui.media {
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.Graphics;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.geom.Matrix;
import flash.geom.Rectangle;
import flash.net.FileReference;
import flash.text.TextField;
import assets.Resources;
import blocks.Block;
import blocks.BlockIO;
import scratch.ScratchCostume;
import scratch.ScratchObj;
import scratch.ScratchSound;
import scratch.ScratchSprite;
import translation.Translator;
import ui.parts.UIPart;
import uiwidgets.DialogBox;
import uiwidgets.IconButton;
import uiwidgets.Menu;
public class MediaInfo extends Sprite {
public var frameWidth:int = 81;
private var frameHeight:int = 94;
protected var thumbnailWidth:int = 68;
protected var thumbnailHeight:int = 51;
// at most one of the following is non-null:
public var mycostume:ScratchCostume;
public var mysprite:ScratchSprite;
public var mysound:ScratchSound;
public var scripts:Array;
public var objType:String = 'unknown';
public var objName:String = '';
public var objWidth:int = 0;
public var md5:String;
public var owner:ScratchObj; // object owning a sound or costume in MediaPane; null for other cases
public var isBackdrop:Boolean;
public var forBackpack:Boolean;
private var frame:Shape; // visible when selected
private var thumbnail:Bitmap;
private var label:TextField;
private var info:TextField;
private var deleteButton:IconButton;
// For Game Snap
public var allowGrabbing:Boolean = true;
public var clickCallback:Function;
public function MediaInfo(obj:*, owningObj:ScratchObj = null) {
owner = owningObj;
mycostume = obj as ScratchCostume;
mysound = obj as ScratchSound;
mysprite = obj as ScratchSprite;
if (mycostume) {
objType = 'image';
objName = mycostume.costumeName;
md5 = mycostume.baseLayerMD5;
} else if (mysound) {
objType = 'sound';
objName = mysound.soundName;
md5 = mysound.md5;
if (owner) frameHeight = 75; // use a shorter frame for sounds in a MediaPane
} else if (mysprite) {
objType = 'sprite';
objName = mysprite.objName;
md5 = null; // initially null
} else if ((obj is Block) || (obj is Array)) {
// scripts holds an array of blocks, stacks, and comments in Array form
// initialize script list from either a stack (Block) or an array of stacks already in array form
objType = 'script';
objName = '';
scripts = (obj is Block) ? [BlockIO.stackToArray(obj)] : obj;
md5 = null; // scripts don't have an MD5 hash
} else {
// initialize from a JSON object
objType = obj.type ? obj.type : '';
objName = obj.name ? obj.name : '';
objWidth = obj.width ? obj.width : 0;
scripts = obj.scripts;
md5 = ('script' != objType) ? obj.md5 : null;
}
addFrame();
addThumbnail();
addLabelAndInfo();
unhighlight();
addDeleteButton();
updateLabelAndInfo(false);
}
public static function strings():Array {
return ['Backdrop', 'Costume', 'Script', 'Sound', 'Sprite', 'save to local file'];
}
// -----------------------------
// Highlighting (for MediaPane)
//------------------------------
public function highlight():void {
if (frame.alpha != 1) { frame.alpha = 1; showDeleteButton(true) }
}
public function unhighlight():void {
if (frame.alpha != 0) { frame.alpha = 0; showDeleteButton(false) }
}
private function showDeleteButton(flag:Boolean):void {
if (deleteButton) {
deleteButton.visible = flag;
if (flag && mycostume && owner && (owner.costumes.length < 2)) deleteButton.visible = false;
}
}
// -----------------------------
// Thumbnail
//------------------------------
public function updateMediaThumbnail():void { /* xxx */ }
public function thumbnailX():int { return thumbnail.x }
public function thumbnailY():int { return thumbnail.y }
public function computeThumbnail():Boolean {
if (mycostume) setLocalCostumeThumbnail();
else if (mysprite) setLocalSpriteThumbnail();
else if (scripts) setScriptThumbnail();
else return false;
return true;
}
private function setLocalCostumeThumbnail():void {
// Set the thumbnail for a costume local to this project (and not necessarily saved to the server).
var forStage:Boolean = owner && owner.isStage;
var bm:BitmapData = mycostume.thumbnail(thumbnailWidth, thumbnailHeight, forStage);
isBackdrop = forStage;
setThumbnailBM(bm);
}
private function setLocalSpriteThumbnail():void {
// Set the thumbnail for a sprite local to this project (and not necessarily saved to the server).
setThumbnailBM(mysprite.currentCostume().thumbnail(thumbnailWidth, thumbnailHeight, false));
}
protected function fileType(s:String):String {
if (!s) return '';
var i:int = s.lastIndexOf('.');
return (i < 0) ? '' : s.slice(i + 1);
}
private function setScriptThumbnail():void {
if (!scripts || (scripts.length < 1)) return; // no scripts
var script:Block = BlockIO.arrayToStack(scripts[0]);
var scale:Number = Math.min(thumbnailWidth / script.width, thumbnailHeight / script.height);
var bm:BitmapData = new BitmapData(thumbnailWidth, thumbnailHeight, true, 0);
var m:Matrix = new Matrix();
m.scale(scale, scale);
bm.draw(script, m);
setThumbnailBM(bm);
}
protected function setThumbnailBM(bm:BitmapData):void {
thumbnail.bitmapData = bm;
thumbnail.x = (frameWidth - thumbnail.width) / 2;
}
protected function setInfo(s:String):void {
info.text = s;
info.x = Math.max(0, (frameWidth - info.textWidth) / 2);
}
// -----------------------------
// Label and Info
//------------------------------
public function updateLabelAndInfo(forBackpack:Boolean):void {
this.forBackpack = forBackpack;
setText(label, (forBackpack ? backpackTitle() : objName));
label.x = ((frameWidth - label.textWidth) / 2) - 2;
setText(info, (forBackpack ? objName: infoString()));
info.x = Math.max(0, (frameWidth - info.textWidth) / 2);
}
public function hideTextFields():void {
setText(label, '');
setText(info, '');
}
private function backpackTitle():String {
if ('image' == objType) return Translator.map(isBackdrop ? 'Backdrop' : 'Costume');
if ('script' == objType) return Translator.map('Script');
if ('sound' == objType) return Translator.map('Sound');
if ('sprite' == objType) return Translator.map('Sprite');
return objType;
}
private function infoString():String {
if (mycostume) return costumeInfoString();
if (mysound) return soundInfoString(mysound.getLengthInMsec());
return '';
}
private function costumeInfoString():String {
// Use the actual dimensions (rounded up to an integer) of my costume.
var w:int, h:int;
var dispObj:DisplayObject = mycostume.displayObj();
if (dispObj is Bitmap) {
w = dispObj.width;
h = dispObj.height;
} else {
var r:Rectangle = dispObj.getBounds(dispObj);
w = Math.ceil(r.width);
h = Math.ceil(r.height);
}
return w + 'x' + h;
}
private function soundInfoString(msecs:Number):String {
// Return a formatted time in MM:SS.HH (where HH is hundredths of a second).
function twoDigits(n:int):String { return (n < 10) ? '0' + n : '' + n }
var secs:int = msecs / 1000;
var hundredths:int = (msecs % 1000) / 10;
return twoDigits(secs / 60) + ':' + twoDigits(secs % 60) + '.' + twoDigits(hundredths);
}
// -----------------------------
// Backpack Support
//------------------------------
public function objToGrab(evt:MouseEvent):* {
// Added this check for Game Snap
if(!allowGrabbing) {
return null;
}
var result:MediaInfo = Scratch.app.createMediaInfo({
type: objType,
name: objName,
width: objWidth,
md5: md5
});
if (mycostume) result = Scratch.app.createMediaInfo(mycostume, owner);
if (mysound) result = Scratch.app.createMediaInfo(mysound, owner);
if (mysprite) result = Scratch.app.createMediaInfo(mysprite);
if (scripts) result = Scratch.app.createMediaInfo(scripts);
result.removeDeleteButton();
if (thumbnail.bitmapData) result.thumbnail.bitmapData = thumbnail.bitmapData;
result.hideTextFields();
return result;
}
public function addDeleteButton():void {
removeDeleteButton();
deleteButton = new IconButton(deleteMe, Resources.createBmp('removeItem'));
deleteButton.x = frame.width - deleteButton.width + 5;
deleteButton.y = 3;
deleteButton.visible = false;
addChild(deleteButton);
}
public function removeDeleteButton():void {
if (deleteButton) {
removeChild(deleteButton);
deleteButton = null;
}
}
public function backpackRecord():Object {
// Return an object to be saved in the backpack.
var result:Object = {
type: objType,
name: objName,
md5: md5
};
if (mycostume) {
result.width = mycostume.width();
result.height = mycostume.height();
}
if (mysound) {
result.seconds = mysound.getLengthInMsec() / 1000;
}
if (scripts) {
result.scripts = scripts;
delete result.md5;
}
return result;
}
// -----------------------------
// Parts
//------------------------------
private function addFrame():void {
frame = new Shape();
var g:Graphics = frame.graphics;
g.lineStyle(3, CSS.overColor, 1, true);
g.beginFill(CSS.itemSelectedColor);
g.drawRoundRect(0, 0, frameWidth, frameHeight, 12, 12);
g.endFill();
addChild(frame);
}
private function addThumbnail():void {
if ('sound' == objType) {
thumbnail = Resources.createBmp('speakerOff');
thumbnail.x = 18;
thumbnail.y = 16;
} else {
thumbnail = Resources.createBmp('questionMark');
thumbnail.x = (frameWidth - thumbnail.width) / 2;
thumbnail.y = 13;
}
addChild(thumbnail);
if (owner) computeThumbnail();
}
private function addLabelAndInfo():void {
label = Resources.makeLabel('', CSS.thumbnailFormat);
label.y = frameHeight - 28;
addChild(label);
info = Resources.makeLabel('', CSS.thumbnailExtraInfoFormat);
info.y = frameHeight - 14;
addChild(info);
}
private function setText(tf:TextField, s:String):void {
// Set the text of the given TextField, truncating if necessary.
var desiredWidth:int = frame.width - 6;
tf.text = s;
while ((tf.textWidth > desiredWidth) && (s.length > 0)) {
s = s.substring(0, s.length - 1);
tf.text = s + '\u2026'; // truncated name with ellipses
}
}
// -----------------------------
// User interaction
//------------------------------
public function click(evt:MouseEvent):void {
if (!getBackpack()) {
var app:Scratch = Scratch.app;
if (mycostume) {
app.viewedObj().showCostumeNamed(mycostume.costumeName);
app.selectCostume();
}
if (mysound) app.selectSound(mysound);
// For Game Snap
if(clickCallback != null) {
clickCallback(this);
}
}
}
public function handleTool(tool:String, evt:MouseEvent):void {
if (tool == 'copy') duplicateMe();
if (tool == 'cut') deleteMe();
if (tool == 'help') Scratch.app.showTip('scratchUI'); }
public function menu(evt:MouseEvent):Menu {
var m:Menu = new Menu();
addMenuItems(m);
return m;
}
protected function addMenuItems(m:Menu):void {
if (!getBackpack()) m.addItem('duplicate', duplicateMe);
m.addItem('delete', deleteMe);
// Added for Game Snap
if (mycostume || mysound) {
m.addItem('rename', renameMe);
}
m.addLine();
if (mycostume) {
m.addItem('save to local file', exportCostume);
}
if (mysound) {
m.addItem('save to local file', exportSound);
}
}
protected function duplicateMe():void {
if (owner && !getBackpack()) {
if (mycostume) Scratch.app.addCostume(mycostume.duplicate());
if (mysound) Scratch.app.addSound(mysound.duplicate());
}
}
protected function deleteMe(ignore:* = null):void {
if (owner) {
Scratch.app.runtime.recordForUndelete(this, 0, 0, 0, owner);
if (mycostume) {
owner.deleteCostume(mycostume);
Scratch.app.refreshImageTab(false);
}
if (mysound) {
owner.deleteSound(mysound);
Scratch.app.refreshSoundTab();
}
}
}
// Added for Game Snap
protected function renameMe():void {
function changeName(s:String):void {
if(s.length > 0) {
objName = s;
if(mycostume) {
mycostume.costumeName = s;
}
else if(mysound) {
mysound.soundName = s;
}
updateLabelAndInfo(false);
}
}
if(owner) {
DialogBox.askOkCancel('Please enter a new name', objName, 200, Scratch.app.stage, changeName);
}
}
private function exportCostume():void {
if (!mycostume) return;
mycostume.prepareToSave();
var ext:String = ScratchCostume.fileExtension(mycostume.baseLayerData);
var defaultName:String = mycostume.costumeName + ext;
new FileReference().save(mycostume.baseLayerData, defaultName);
}
private function exportSound():void {
if (!mysound) return;
mysound.prepareToSave();
var defaultName:String = mysound.soundName + '.wav';
new FileReference().save(mysound.soundData, defaultName);
}
protected function getBackpack():UIPart {
return null;
}
}}
|
/*
* 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.
*/
// LooksPrims.as
// John Maloney, April 2010
//
// Looks primitives.
package primitives {
import flash.utils.Dictionary;
import blocks.*;
import interpreter.*;
import scratch.*;
public class LooksPrims {
private var app:Scratch;
private var interp:Interpreter;
public function LooksPrims(app:Scratch, interpreter:Interpreter) {
this.app = app;
this.interp = interpreter;
}
public function addPrimsTo(primTable:Dictionary):void {
primTable['lookLike:'] = primShowCostume;
primTable['nextCostume'] = primNextCostume;
primTable['costumeIndex'] = primCostumeIndex;
primTable['costumeName'] = primCostumeName;
primTable['showBackground:'] = primShowCostume; // used by Scratch 1.4 and earlier (doesn't start scene hats)
primTable['nextBackground'] = primNextCostume; // used by Scratch 1.4 and earlier (doesn't start scene hats)
primTable['backgroundIndex'] = primSceneIndex;
primTable['sceneName'] = primSceneName;
primTable['nextScene'] = function(b:*):* { startScene('next backdrop', false) };
primTable['startScene'] = function(b:*):* { startScene(interp.arg(b, 0), false) };
primTable['startSceneAndWait'] = function(b:*):* { startScene(interp.arg(b, 0), true) };
primTable['say:duration:elapsed:from:'] = function(b:*):* { showBubbleAndWait(b, 'talk') };
primTable['say:'] = function(b:*):* { showBubble(b, 'talk') };
primTable['think:duration:elapsed:from:'] = function(b:*):* { showBubbleAndWait(b, 'think') };
primTable['think:'] = function(b:*):* { showBubble(b, 'think') };
primTable['changeGraphicEffect:by:'] = primChangeEffect;
primTable['setGraphicEffect:to:'] = primSetEffect;
primTable['filterReset'] = primClearEffects;
primTable['changeSizeBy:'] = primChangeSize;
primTable['setSizeTo:'] = primSetSize;
primTable['scale'] = primSize;
primTable['show'] = primShow;
primTable['hide'] = primHide;
// primTable['hideAll'] = primHideAll;
primTable['comeToFront'] = primGoFront;
primTable['goBackByLayers:'] = primGoBack;
primTable['setVideoState'] = primSetVideoState;
primTable['setVideoTransparency'] = primSetVideoTransparency;
// primTable['scrollAlign'] = primScrollAlign;
// primTable['scrollRight'] = primScrollRight;
// primTable['scrollUp'] = primScrollUp;
// primTable['xScroll'] = function(b:*):* { return app.stagePane.xScroll };
// primTable['yScroll'] = function(b:*):* { return app.stagePane.yScroll };
primTable['setRotationStyle'] = primSetRotationStyle;
}
private function primNextCostume(b:Block):void {
var s:ScratchObj = interp.targetObj();
if (s != null) s.showCostume(s.currentCostumeIndex + 1);
if (s.visible) interp.redraw();
}
private function primShowCostume(b:Block):void {
var s:ScratchObj = interp.targetObj();
if (s == null) return;
var arg:* = interp.arg(b, 0);
if (typeof(arg) == 'number') {
s.showCostume(arg - 1);
} else {
var i:int = s.indexOfCostumeNamed(arg);
if (i >= 0) {
s.showCostume(i);
} else if ('previous costume' == arg) {
s.showCostume(s.currentCostumeIndex - 1);
} else if ('next costume' == arg) {
s.showCostume(s.currentCostumeIndex + 1);
} else {
var n:Number = Interpreter.asNumber(arg);
if (!isNaN(n)) s.showCostume(n - 1);
else return; // arg did not match a costume name nor is it a valid number
}
}
if (s.visible) interp.redraw();
}
private function primCostumeIndex(b:Block):Number {
var s:ScratchObj = interp.targetObj();
return (s == null) ? 1 : s.costumeNumber();
}
private function primCostumeName(b:Block):String {
var s:ScratchObj = interp.targetObj();
return (s == null) ? '' : s.currentCostume().costumeName;
}
private function primSceneIndex(b:Block):Number {
return app.stagePane.costumeNumber();
}
private function primSceneName(b:Block):String {
return app.stagePane.currentCostume().costumeName;
}
private function startScene(s:*, waitFlag:Boolean):void {
if (typeof(s) == 'number') {
s = backdropNameAt(s - 1);
} else if ('next backdrop' == s) {
s = backdropNameAt(app.stagePane.currentCostumeIndex + 1);
} else if ('previous backdrop' == s) {
s = backdropNameAt(app.stagePane.currentCostumeIndex - 1);
} else {
var i:int = app.stagePane.indexOfCostumeNamed(s);
if (i >= 0) {
s = backdropNameAt(i);
} else {
var n:Number = Interpreter.asNumber(s);
if (!isNaN(n)) s = backdropNameAt(n - 1);
}
}
interp.startScene(s, waitFlag);
}
private function backdropNameAt(i:int):String {
var costumes:Array = app.stagePane.costumes;
return costumes[(i + costumes.length) % costumes.length].costumeName;
}
private function showBubbleAndWait(b:Block, type:String):void {
var text:*, secs:Number;
var s:ScratchSprite = interp.targetSprite();
if (s == null) return;
if (interp.activeThread.firstTime) {
text = interp.arg(b, 0);
secs = interp.numarg(b, 1);
s.showBubble(text, type, b);
if (s.visible) interp.redraw();
interp.startTimer(secs);
} else {
if (interp.checkTimer() && s.bubble && (s.bubble.getSource() == b)) {
s.hideBubble();
}
}
}
private function showBubble(b:Block, type:String = null):void {
var text:*, secs:Number;
var s:ScratchSprite = interp.targetSprite();
if (s == null) return;
if (type == null) { // combined talk/think/shout/whisper command
type = interp.arg(b, 0);
text = interp.arg(b, 1);
} else { // talk or think command
text = interp.arg(b, 0);
}
s.showBubble(text, type, b);
if (s.visible) interp.redraw();
}
private function primChangeEffect(b:Block):void {
var s:ScratchObj = interp.targetObj();
if (s == null) return;
var filterName:String = interp.arg(b, 0);
var delta:Number = interp.numarg(b, 1);
if(delta == 0) return;
var newValue:Number = s.filterPack.getFilterSetting(filterName) + delta;
s.filterPack.setFilter(filterName, newValue);
s.applyFilters();
if (s.visible || s == Scratch.app.stagePane) interp.redraw();
}
private function primSetEffect(b:Block):void {
var s:ScratchObj = interp.targetObj();
if (s == null) return;
var filterName:String = interp.arg(b, 0);
var newValue:Number = interp.numarg(b, 1);
if(s.filterPack.setFilter(filterName, newValue))
s.applyFilters();
if (s.visible || s == Scratch.app.stagePane) interp.redraw();
}
private function primClearEffects(b:Block):void {
var s:ScratchObj = interp.targetObj();
s.clearFilters();
s.applyFilters();
if (s.visible || s == Scratch.app.stagePane) interp.redraw();
}
private function primChangeSize(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if (s == null) return;
var oldScale:Number = s.scaleX;
s.setSize(s.getSize() + interp.numarg(b, 0));
if (s.visible && (s.scaleX != oldScale)) interp.redraw();
}
private function primSetRotationStyle(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
var newStyle:String = interp.arg(b, 0) as String;
if ((s == null) || (newStyle == null)) return;
s.setRotationStyle(newStyle);
}
private function primSetSize(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if (s == null) return;
s.setSize(interp.numarg(b, 0));
if (s.visible) interp.redraw();
}
private function primSize(b:Block):Number {
var s:ScratchSprite = interp.targetSprite();
if (s == null) return 100;
return Math.round(s.getSize()); // reporter returns rounded size, as in Scratch 1.4
}
private function primShow(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if (s == null) return;
s.visible = true;
if(!app.isIn3D) s.applyFilters();
s.updateBubble();
if (s.visible) interp.redraw();
}
private function primHide(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if ((s == null) || !s.visible) return;
s.visible = false;
if(!app.isIn3D) s.applyFilters();
s.updateBubble();
interp.redraw();
}
private function primHideAll(b:Block):void {
// Hide all sprites and delete all clones. Only works from the stage.
if (!interp.targetObj().isStage) return;
app.stagePane.deleteClones();
for (var i:int = 0; i < app.stagePane.numChildren; i++) {
var o:* = app.stagePane.getChildAt(i);
if (o is ScratchSprite) {
o.visible = false;
o.updateBubble();
}
}
interp.redraw();
}
private function primGoFront(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if ((s == null) || (s.parent == null)) return;
s.parent.setChildIndex(s, s.parent.numChildren - 1);
if (s.visible) interp.redraw();
}
private function primGoBack(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if ((s == null) || (s.parent == null)) return;
var newIndex:int = s.parent.getChildIndex(s) - interp.numarg(b, 0);
newIndex = Math.max(minSpriteLayer(), Math.min(newIndex, s.parent.numChildren - 1));
if (newIndex > 0 && newIndex < s.parent.numChildren) {
s.parent.setChildIndex(s, newIndex);
if (s.visible) interp.redraw();
}
}
private function minSpriteLayer():int {
// Return the lowest sprite layer.
var stg:ScratchStage = app.stagePane;
return stg.getChildIndex(stg.videoImage ? stg.videoImage : stg.penLayer) + 1;
}
private function primSetVideoState(b:Block):void {
app.stagePane.setVideoState(interp.arg(b, 0));
}
private function primSetVideoTransparency(b:Block):void {
app.stagePane.setVideoTransparency(interp.numarg(b, 0));
app.stagePane.setVideoState('on');
}
private function primScrollAlign(b:Block):void {
if (!interp.targetObj().isStage) return;
app.stagePane.scrollAlign(interp.arg(b, 0));
}
private function primScrollRight(b:Block):void {
if (!interp.targetObj().isStage) return;
app.stagePane.scrollRight(interp.numarg(b, 0));
}
private function primScrollUp(b:Block):void {
if (!interp.targetObj().isStage) return;
app.stagePane.scrollUp(interp.numarg(b, 0));
}
}}
|
package flash.net
{
import flash.utils.*;
public class GroupSpecifier extends Object
{
private var m_routing:String;
private var m_multicast:String;
private var m_objectReplication:String;
private var m_posting:String;
private var m_publishAuthHash:String;
private var m_postingAuthHash:String;
private var m_ipMulticastAddresses:String;
private var m_bootstrapPeers:String;
private var m_openServerChannel:String;
private var m_disablePeerToPeer:String;
private var m_tag:String;
private var m_unique:String;
private var m_publishAuth:String;
private var m_postingAuth:String;
private var m_ipMulticastMemberUpdates:String;
private var m_minGroupspecVersion:int;
public function GroupSpecifier(param1:String)
{
if (param1)
{
this.m_tag = toOption(14, byteArrayToHex(stringToBytes(param1)));
}
else
{
throw new ArgumentError("Name can not be empty");
}
this.m_unique = "";
this.routingEnabled = false;
this.multicastEnabled = false;
this.objectReplicationEnabled = false;
this.postingEnabled = false;
this.setPublishPassword(null);
this.setPostingPassword(null);
this.clearIPMulticastAddresses();
this.clearBootstrapPeers();
this.serverChannelEnabled = false;
this.peerToPeerDisabled = false;
this.ipMulticastMemberUpdatesEnabled = false;
if (this.swfVersion >= 18)
{
this.m_minGroupspecVersion = 2;
}
else
{
this.m_minGroupspecVersion = 1;
}
return;
}// end function
public function makeUnique() : void
{
this.m_unique = toOption(14, GetCryptoRandomString(32));
return;
}// end function
public function get routingEnabled() : Boolean
{
return this.m_routing != "";
}// end function
public function set routingEnabled(param1:Boolean) : void
{
if (param1)
{
this.m_routing = "0100";
}
else
{
this.m_routing = "";
}
return;
}// end function
public function get multicastEnabled() : Boolean
{
return this.m_multicast != "";
}// end function
public function set multicastEnabled(param1:Boolean) : void
{
if (param1)
{
this.m_multicast = "0101";
}
else
{
this.m_multicast = "";
}
return;
}// end function
public function get objectReplicationEnabled() : Boolean
{
return this.m_objectReplication != "";
}// end function
public function set objectReplicationEnabled(param1:Boolean) : void
{
if (param1)
{
this.m_objectReplication = "0102";
}
else
{
this.m_objectReplication = "";
}
return;
}// end function
public function get postingEnabled() : Boolean
{
return this.m_posting != "";
}// end function
public function set postingEnabled(param1:Boolean) : void
{
if (param1)
{
this.m_posting = "0103";
}
else
{
this.m_posting = "";
}
return;
}// end function
private function clearIPMulticastAddresses() : void
{
this.m_ipMulticastAddresses = "";
return;
}// end function
private function clearBootstrapPeers() : void
{
this.m_bootstrapPeers = "";
return;
}// end function
public function get peerToPeerDisabled() : Boolean
{
return this.m_disablePeerToPeer != "";
}// end function
public function set peerToPeerDisabled(param1:Boolean) : void
{
if (param1)
{
this.m_disablePeerToPeer = "010d";
}
else
{
this.m_disablePeerToPeer = "";
}
return;
}// end function
public function get ipMulticastMemberUpdatesEnabled() : Boolean
{
return this.m_ipMulticastMemberUpdates != "";
}// end function
public function set ipMulticastMemberUpdatesEnabled(param1:Boolean) : void
{
if (param1)
{
this.m_ipMulticastMemberUpdates = "011b";
}
else
{
this.m_ipMulticastMemberUpdates = "";
}
return;
}// end function
public function setPublishPassword(param1:String = null, param2:String = null) : void
{
var _loc_3:* = null;
if (param1)
{
_loc_3 = stringToBytes(param1);
_loc_3.position = 0;
this.m_publishAuth = toOption(21, byteArrayToHex(_loc_3));
this.m_publishAuthHash = toOption(5, this.SaltedSHA256(param2, _loc_3));
}
else
{
this.m_publishAuthHash = "";
this.m_publishAuth = "";
}
return;
}// end function
public function setPostingPassword(param1:String = null, param2:String = null) : void
{
var _loc_3:* = null;
if (param1)
{
_loc_3 = stringToBytes(param1);
_loc_3.position = 0;
this.m_postingAuth = toOption(23, byteArrayToHex(_loc_3));
this.m_postingAuthHash = toOption(7, this.SaltedSHA256(param2, _loc_3));
}
else
{
this.m_postingAuthHash = "";
this.m_postingAuth = "";
}
return;
}// end function
public function get serverChannelEnabled() : Boolean
{
return this.m_openServerChannel != "";
}// end function
public function set serverChannelEnabled(param1:Boolean) : void
{
if (param1)
{
this.m_openServerChannel = "010c";
}
else
{
this.m_openServerChannel = "";
}
return;
}// end function
public function addBootstrapPeer(param1:String) : void
{
this.m_bootstrapPeers = this.m_bootstrapPeers + toOption(11, param1);
return;
}// end function
public function addIPMulticastAddress(param1:String, param2 = null, param3:String = null) : void
{
this.m_ipMulticastAddresses = this.m_ipMulticastAddresses + encodeIPMulticastAddress(param1, param2, param3);
return;
}// end function
public function toString() : String
{
return this.groupspecWithAuthorizations();
}// end function
public function groupspecWithoutAuthorizations() : String
{
var _loc_1:* = "";
var _loc_2:* = this.minGroupspecVersion;
if (_loc_2 > 1)
{
_loc_1 = toOption(127, vlu(_loc_2));
}
return "G:" + _loc_1 + this.m_routing + this.m_multicast + this.m_objectReplication + this.m_posting + this.m_publishAuthHash + this.m_postingAuthHash + this.m_openServerChannel + this.m_disablePeerToPeer + this.m_tag + this.m_unique + this.m_ipMulticastMemberUpdates + "00" + this.groupspecExtras();
}// end function
private function groupspecExtras() : String
{
return this.m_ipMulticastAddresses + this.m_bootstrapPeers;
}// end function
public function groupspecWithAuthorizations() : String
{
return this.groupspecWithoutAuthorizations() + this.authorizations();
}// end function
public function authorizations() : String
{
return this.m_publishAuth + this.m_postingAuth;
}// end function
public function get minGroupspecVersion() : int
{
return this.m_minGroupspecVersion;
}// end function
public function set minGroupspecVersion(param1:int) : void
{
this.m_minGroupspecVersion = Math.max(param1, 1);
return;
}// end function
private function get swfVersion() : int;
public static function encodePostingAuthorization(param1:String) : String
{
return toOption(23, byteArrayToHex(stringToBytes(param1)));
}// end function
public static function encodePublishAuthorization(param1:String) : String
{
return toOption(21, byteArrayToHex(stringToBytes(param1)));
}// end function
public static function encodeIPMulticastAddressSpec(param1:String, param2 = null, param3:String = null) : String
{
return encodeIPMulticastAddress(param1, param2, param3);
}// end function
public static function encodeBootstrapPeerIDSpec(param1:String) : String
{
return toOption(11, param1);
}// end function
public static function get maxSupportedGroupspecVersion() : int
{
return 2;
}// end function
private static function SaltedSHA256(param1:String, param2:ByteArray) : String
{
var _loc_3:* = null;
var _loc_4:* = null;
if (param1)
{
_loc_3 = stringToBytes(param1);
_loc_4 = byteArrayToHex(_loc_3);
_loc_3.writeBytes(param2);
_loc_3.position = 0;
return _loc_4 + GroupSpecifier.SHA256(_loc_3);
}
return GroupSpecifier.SHA256(param2);
}// end function
private static function encodeIPMulticastAddress(param1:String, param2, param3:String) : String
{
var val:String;
var address:* = param1;
var port:* = param2;
var source:* = param3;
var is6:Boolean;
try
{
val = inet_ptohex6(address, port);
is6;
}
catch (e:Error)
{
val = inet_ptohex4(address, port);
}
if (source)
{
val = val + (is6 ? (inet_ptohex6(source, 0)) : (inet_ptohex4(source, 0))).substr(0, -4);
}
return toOption(10, val);
}// end function
private static function hexByte(param1:uint) : String
{
var _loc_2:* = null;
if (param1 > 255)
{
throw new RangeError();
}
_loc_2 = param1.toString(16);
if (_loc_2.length < 2)
{
_loc_2 = "0" + _loc_2;
}
return _loc_2;
}// end function
private static function vlu(param1:uint) : String
{
var _loc_3:* = 0;
var _loc_2:* = "";
do
{
_loc_3 = param1 & 127;
if (_loc_2.length > 0)
{
_loc_3 = _loc_3 | 128;
}
_loc_2 = hexByte(_loc_3) + _loc_2;
param1 = param1 >> 7;
}while (param1)
return _loc_2;
}// end function
private static function toOption(param1:uint, param2:String) : String
{
var _loc_3:* = null;
_loc_3 = vlu(param1) + param2;
return vlu(_loc_3.length / 2) + _loc_3;
}// end function
private static function inet_ptohex4(param1:String, param2 = null) : String
{
var _loc_3:* = null;
var _loc_4:* = null;
var _loc_5:* = null;
var _loc_6:* = null;
var _loc_7:* = null;
var _loc_8:* = null;
var _loc_9:* = 0;
if (param2 == null)
{
_loc_3 = /\[(\d+)\.(\d+)\.(\d+)\.(\d+)\]:(\d+)/;
_loc_4 = /(\d+)\.(\d+)\.(\d+)\.(\d+):(\d+)/;
_loc_5 = _loc_3.exec(param1);
if (!_loc_5)
{
_loc_5 = _loc_4.exec(param1);
}
if (_loc_5)
{
return hexByte(_loc_5[1]) + hexByte(_loc_5[2]) + hexByte(_loc_5[3]) + hexByte(_loc_5[4]) + hexByte(_loc_5[5] / 256) + hexByte(_loc_5[5] & 255);
}
throw new ArgumentError("Invalid address");
}
else
{
_loc_6 = /\[(\d+)\.(\d+)\.(\d+)\.(\d+)\]/;
_loc_7 = /(\d+)\.(\d+)\.(\d+)\.(\d+)/;
_loc_9 = int(param2);
_loc_8 = _loc_6.exec(param1);
if (!_loc_8)
{
_loc_8 = _loc_7.exec(param1);
}
if (_loc_8)
{
return hexByte(_loc_8[1]) + hexByte(_loc_8[2]) + hexByte(_loc_8[3]) + hexByte(_loc_8[4]) + hexByte(_loc_9 / 256) + hexByte(_loc_9 & 255);
}
throw new ArgumentError("Invalid address");
}
}// end function
private static function inet_ptohex6(param1:String, param2 = null) : String
{
var _loc_8:* = 0;
var _loc_11:* = null;
var _loc_12:* = 0;
var _loc_13:* = 0;
var _loc_15:* = null;
var _loc_16:* = null;
var _loc_17:* = 0;
var _loc_3:* = /(::)|([:\[\]])|(\d+\.\d+\.\d+\.\d+)|([0-9a-fA-F]+)/g;
var _loc_4:* = /(\d+)\.(\d+)\.(\d+)\.(\d+)/;
var _loc_5:* = param1.match(_loc_3);
var _loc_6:* = "";
var _loc_7:* = "";
var _loc_9:* = false;
var _loc_10:* = false;
var _loc_14:* = false;
if (_loc_5 == null)
{
throw new ArgumentError();
}
_loc_8 = 0;
while (_loc_8 < _loc_5.length)
{
_loc_15 = _loc_5[_loc_8];
if (_loc_15 == "]")
{
_loc_9 = true;
}
else if (_loc_15 == "::")
{
if (_loc_10)
{
throw new RangeError();
}
_loc_10 = true;
_loc_14 = true;
}
else if (_loc_15 == ":")
{
_loc_14 = true;
}
else if (_loc_15 != "[")
{
if (_loc_9)
{
if (param2)
{
throw new ArgumentError();
}
param2 = _loc_15;
}
else
{
_loc_11 = _loc_4.exec(_loc_15);
if (_loc_11)
{
if (_loc_14)
{
if (!_loc_10)
{
}
}
if (_loc_6.length != 28)
{
throw new ArgumentError();
}
_loc_9 = true;
_loc_7 = _loc_7 + hexByte(_loc_11[1]) + hexByte(_loc_11[2]) + hexByte(_loc_11[3]) + hexByte(_loc_11[4]);
}
else
{
_loc_17 = parseInt(_loc_15, 16);
if (_loc_17 > 65535)
{
throw new RangeError();
}
_loc_16 = hexByte(_loc_17 / 256) + hexByte(_loc_17 & 255);
if (_loc_10)
{
_loc_7 = _loc_7 + _loc_16;
}
else
{
_loc_6 = _loc_6 + _loc_16;
}
}
}
}
_loc_8 = _loc_8 + 1;
}
if (!_loc_14)
{
throw new ArgumentError();
}
_loc_13 = _loc_6.length + _loc_7.length;
if (_loc_13 > 32)
{
throw new RangeError();
}
while (_loc_13++ < 32)
{
_loc_6 = _loc_6 + "0";
}
if (param2 == null)
{
throw new ArgumentError();
}
_loc_12 = int(param2);
if (_loc_12 >= 0)
{
}
if (_loc_12 > 65535)
{
throw new RangeError();
}
_loc_7 = _loc_7 + hexByte(_loc_12 / 256) + hexByte(_loc_12 & 255);
return _loc_6 + _loc_7;
}// end function
private static function byteArrayToHex(param1:ByteArray) : String
{
var _loc_3:* = 0;
var _loc_2:* = "";
_loc_3 = 0;
while (_loc_3 < param1.length)
{
_loc_2 = _loc_2 + hexByte(param1[_loc_3]);
_loc_3 = _loc_3 + 1;
}
return _loc_2;
}// end function
private static function stringToBytes(param1:String) : ByteArray
{
var _loc_2:* = new ByteArray();
_loc_2.writeUTFBytes(param1);
return _loc_2;
}// end function
private static function SHA256(param1:ByteArray) : String
{
return calcSHA256Digest(param1);
}// end function
private static function calcSHA256Digest(param1:ByteArray) : String;
private static function GetCryptoRandomString(param1:uint) : String;
}
}
|
// =================================================================================================
//
// Starling Framework
// Copyright Gamua GmbH. All Rights Reserved.
//
// This program is free software. You can redistribute and/or modify it
// in accordance with the terms of the accompanying license agreement.
//
// =================================================================================================
package starling.utils
{
/** Converts an angle from radians into degrees. */
public function rad2deg(rad:Number):Number
{
return rad / Math.PI * 180.0;
}
} |
/**
* Created by a.krasovsky on 04.11.2014.
*/
package core.global {
import core.global.listeners.GameManagerListener;
import flash.events.EventDispatcher;
public class GlobalDispatcherSingleton extends EventDispatcher{
private static var _instance:GlobalDispatcherSingleton;
private var listeners:Array = [];
public function GlobalDispatcherSingleton(instance:PrivateClass) {
}
public static function get instance():GlobalDispatcherSingleton {
if(!_instance){
_instance = new GlobalDispatcherSingleton(new PrivateClass());
}
return _instance;
}
public function newEvent(type:String, data:Object):void {
for (var i:int = 0; i < listeners.length; i++) {
var item:IGlobalListener = listeners[i];
if(item.listener.collection[type]){
item.listener.collection[type](data);
}
}
}
public function addGlobalListener(listener:IGlobalListener):void{
listeners.push(listener);
}
}
}
class PrivateClass{
}
|
package org.spicefactory.parsley.coretag.inject.model {
/**
* @author Jens Halm
*/
public class InjectedDependency {
}
}
|
package com.ankamagames.dofus.network.messages.game.context.roleplay.havenbag
{
import com.ankamagames.jerakine.network.CustomDataWrapper;
import com.ankamagames.jerakine.network.ICustomDataInput;
import com.ankamagames.jerakine.network.ICustomDataOutput;
import com.ankamagames.jerakine.network.INetworkMessage;
import com.ankamagames.jerakine.network.NetworkMessage;
import com.ankamagames.jerakine.network.utils.FuncTree;
import flash.utils.ByteArray;
public class HavenBagFurnituresRequestMessage extends NetworkMessage implements INetworkMessage
{
public static const protocolId:uint = 8486;
private var _isInitialized:Boolean = false;
public var cellIds:Vector.<uint>;
public var funitureIds:Vector.<int>;
public var orientations:Vector.<uint>;
private var _cellIdstree:FuncTree;
private var _funitureIdstree:FuncTree;
private var _orientationstree:FuncTree;
public function HavenBagFurnituresRequestMessage()
{
this.cellIds = new Vector.<uint>();
this.funitureIds = new Vector.<int>();
this.orientations = new Vector.<uint>();
super();
}
override public function get isInitialized() : Boolean
{
return this._isInitialized;
}
override public function getMessageId() : uint
{
return 8486;
}
public function initHavenBagFurnituresRequestMessage(cellIds:Vector.<uint> = null, funitureIds:Vector.<int> = null, orientations:Vector.<uint> = null) : HavenBagFurnituresRequestMessage
{
this.cellIds = cellIds;
this.funitureIds = funitureIds;
this.orientations = orientations;
this._isInitialized = true;
return this;
}
override public function reset() : void
{
this.cellIds = new Vector.<uint>();
this.funitureIds = new Vector.<int>();
this.orientations = new Vector.<uint>();
this._isInitialized = false;
}
override public function pack(output:ICustomDataOutput) : void
{
var data:ByteArray = new ByteArray();
this.serialize(new CustomDataWrapper(data));
writePacket(output,this.getMessageId(),data);
}
override public function unpack(input:ICustomDataInput, length:uint) : void
{
this.deserialize(input);
}
override public function unpackAsync(input:ICustomDataInput, length:uint) : FuncTree
{
var tree:FuncTree = new FuncTree();
tree.setRoot(input);
this.deserializeAsync(tree);
return tree;
}
public function serialize(output:ICustomDataOutput) : void
{
this.serializeAs_HavenBagFurnituresRequestMessage(output);
}
public function serializeAs_HavenBagFurnituresRequestMessage(output:ICustomDataOutput) : void
{
output.writeShort(this.cellIds.length);
for(var _i1:uint = 0; _i1 < this.cellIds.length; _i1++)
{
if(this.cellIds[_i1] < 0)
{
throw new Error("Forbidden value (" + this.cellIds[_i1] + ") on element 1 (starting at 1) of cellIds.");
}
output.writeVarShort(this.cellIds[_i1]);
}
output.writeShort(this.funitureIds.length);
for(var _i2:uint = 0; _i2 < this.funitureIds.length; _i2++)
{
output.writeInt(this.funitureIds[_i2]);
}
output.writeShort(this.orientations.length);
for(var _i3:uint = 0; _i3 < this.orientations.length; _i3++)
{
if(this.orientations[_i3] < 0)
{
throw new Error("Forbidden value (" + this.orientations[_i3] + ") on element 3 (starting at 1) of orientations.");
}
output.writeByte(this.orientations[_i3]);
}
}
public function deserialize(input:ICustomDataInput) : void
{
this.deserializeAs_HavenBagFurnituresRequestMessage(input);
}
public function deserializeAs_HavenBagFurnituresRequestMessage(input:ICustomDataInput) : void
{
var _val1:uint = 0;
var _val2:int = 0;
var _val3:uint = 0;
var _cellIdsLen:uint = input.readUnsignedShort();
for(var _i1:uint = 0; _i1 < _cellIdsLen; _i1++)
{
_val1 = input.readVarUhShort();
if(_val1 < 0)
{
throw new Error("Forbidden value (" + _val1 + ") on elements of cellIds.");
}
this.cellIds.push(_val1);
}
var _funitureIdsLen:uint = input.readUnsignedShort();
for(var _i2:uint = 0; _i2 < _funitureIdsLen; _i2++)
{
_val2 = input.readInt();
this.funitureIds.push(_val2);
}
var _orientationsLen:uint = input.readUnsignedShort();
for(var _i3:uint = 0; _i3 < _orientationsLen; _i3++)
{
_val3 = input.readByte();
if(_val3 < 0)
{
throw new Error("Forbidden value (" + _val3 + ") on elements of orientations.");
}
this.orientations.push(_val3);
}
}
public function deserializeAsync(tree:FuncTree) : void
{
this.deserializeAsyncAs_HavenBagFurnituresRequestMessage(tree);
}
public function deserializeAsyncAs_HavenBagFurnituresRequestMessage(tree:FuncTree) : void
{
this._cellIdstree = tree.addChild(this._cellIdstreeFunc);
this._funitureIdstree = tree.addChild(this._funitureIdstreeFunc);
this._orientationstree = tree.addChild(this._orientationstreeFunc);
}
private function _cellIdstreeFunc(input:ICustomDataInput) : void
{
var length:uint = input.readUnsignedShort();
for(var i:uint = 0; i < length; i++)
{
this._cellIdstree.addChild(this._cellIdsFunc);
}
}
private function _cellIdsFunc(input:ICustomDataInput) : void
{
var _val:uint = input.readVarUhShort();
if(_val < 0)
{
throw new Error("Forbidden value (" + _val + ") on elements of cellIds.");
}
this.cellIds.push(_val);
}
private function _funitureIdstreeFunc(input:ICustomDataInput) : void
{
var length:uint = input.readUnsignedShort();
for(var i:uint = 0; i < length; i++)
{
this._funitureIdstree.addChild(this._funitureIdsFunc);
}
}
private function _funitureIdsFunc(input:ICustomDataInput) : void
{
var _val:int = input.readInt();
this.funitureIds.push(_val);
}
private function _orientationstreeFunc(input:ICustomDataInput) : void
{
var length:uint = input.readUnsignedShort();
for(var i:uint = 0; i < length; i++)
{
this._orientationstree.addChild(this._orientationsFunc);
}
}
private function _orientationsFunc(input:ICustomDataInput) : void
{
var _val:uint = input.readByte();
if(_val < 0)
{
throw new Error("Forbidden value (" + _val + ") on elements of orientations.");
}
this.orientations.push(_val);
}
}
}
|
package idv.cjcat.stardust.twoD.actions.waypoints {
/**
* Waypoint used by the <code>FollowWaypoints</code> action.
*
* @see idv.cjcat.stardust.twoD.actions.FollowWaypoints
*/
public class Waypoint {
/**
* The X coordinate of the center of the waypoint.
*/
public var x:Number;
/**
* The Y coordinate of the center of the waypoint.
*/
public var y:Number;
/**
* The radius of the waypoint.
*/
public var radius:Number;
/**
* The strength of the waypoint. This value must be positive.
*/
public var strength:Number;
/**
* The attenuation power of the waypoint, in powers per pixel.
*/
public var attenuationPower:Number;
/**
* If a point is closer to the center than this value,
* it's treated as if it's this far from the center.
* This is to prevent simulation from blowing up for points too near to the center.
*/
public var epsilon:Number;
public function Waypoint(x:Number = 0, y:Number = 0, radius:Number = 20, strength:Number = 1, attenuationPower:Number = 0, epsilon:Number = 1) {
this.x = x;
this.y = y;
this.radius = radius;
this.strength = strength;
this.attenuationPower = attenuationPower;
this.epsilon = epsilon;
}
}
} |
package fearful_fla
{
import flash.display.MovieClip;
public dynamic class theUpper_1 extends MovieClip
{
public var theProp:MovieClip;
public var shaderObj:MovieClip;
public function theUpper_1()
{
super();
addFrameScript(59,frame60);
}
function frame60() : *
{
stop();
}
}
}
|
/**
* Created by zan on 05/02/2014.
*/
package com.mands.raygunas.utils
{
public class Constants
{
public static const RAYGUN_APIKEY_HEADER:String = "X-ApiKey";
public static const RAYGUN_ADDRESS:String = "https://api.raygun.io/entries";
public static const TEST_API_KEY:String = "REPLACE_WITH_YOUR_API_KEY"
}
}
|
/**
* CHANGELOG:
*
* <ul>
* <li><b>1.0</b> - 2012-10-15 12:45</li>
* <ul>
* <li>Create file</li>
* </ul>
* </ul>
* @author Piotr Paczkowski - kontakt@trzeci.eu
*/
package pl.asria.tools.utils
{
/**
* flash2cartesian -
* @usage -
* @version - 1.0
* @author - Piotr Paczkowski - kontakt@trzeci.eu
* @param angle in degrees
* @return cartesian angle from flash angle
*/
public function flash2cartesian(angle:Number):Number
{
angle = Math.abs(angle - 180);
angle %= 360;
angle-= 90;
if (angle < 0) angle += 360;
return angle;
}
} |
package
{
//Imports
import flash.display.GradientType;
import flash.display.Shape;
import flash.display.Sprite;
import flash.geom.ColorTransform;
import flash.geom.Matrix;
//Class
internal final class GradientOverlay extends Sprite
{
//Properties
private var widthProperty:Number;
private var heightProperty:Number;
private var colorProperty:uint;
//Variables
public var colorGradient:Shape;
public var colorGradientMask:Shape;
private var colorGradientBox:Matrix;
private var horizontalShadowGradientBox:Matrix;
private var horizontalShadowGradient:Shape;
private var verticalShadowGradientBox:Matrix;
private var verticalShadowGradient:Shape;
private var colorTransform:ColorTransform;
//Constructor
public function GradientOverlay(width:Number, height:Number, color:uint)
{
widthProperty = width;
heightProperty = height;
colorProperty = color;
init();
}
//Initialize
private function init():void
{
colorGradientBox = new Matrix();
colorGradient = new Shape();
horizontalShadowGradientBox = new Matrix();
horizontalShadowGradient = new Shape();
verticalShadowGradientBox = new Matrix();
verticalShadowGradient = new Shape();
colorGradientMask = new Shape();
colorTransform = new ColorTransform();
addChild(colorGradient);
addChild(horizontalShadowGradient);
addChild(verticalShadowGradient);
addChild(colorGradientMask);
draw(true);
}
//Draw
private function draw(drawMask:Boolean = false):void
{
colorGradientBox.createGradientBox(widthProperty, heightProperty);
colorGradient.graphics.clear();
colorGradient.graphics.beginGradientFill(GradientType.LINEAR, [colorProperty, colorProperty], [0.5, 0.0], [128, 255], colorGradientBox);
colorGradient.graphics.drawRect(0, 0, widthProperty, heightProperty);
colorGradient.graphics.endFill();
horizontalShadowGradientBox.createGradientBox(widthProperty, heightProperty);
horizontalShadowGradient.graphics.clear();
horizontalShadowGradient.graphics.beginGradientFill(GradientType.LINEAR, [0x000000, 0x000000], [0.9, 0.0], [0, 128], horizontalShadowGradientBox);
horizontalShadowGradient.graphics.drawRect(0, 0, widthProperty, heightProperty);
horizontalShadowGradient.graphics.endFill();
verticalShadowGradientBox.createGradientBox(widthProperty, heightProperty, -90 * Math.PI / 180);
verticalShadowGradient.graphics.clear();
verticalShadowGradient.graphics.beginGradientFill(GradientType.LINEAR, [0x000000, 0x000000], [0.9, 0.0], [0, 255], verticalShadowGradientBox);
verticalShadowGradient.graphics.drawRect(0, 0, widthProperty, heightProperty);
verticalShadowGradient.graphics.endFill();
if (drawMask)
{
colorGradientMask.graphics.clear();
colorGradientMask.graphics.beginFill(0x000000, 1.0);
colorGradientMask.graphics.drawRect(0, 0, widthProperty, heightProperty);
colorGradientMask.graphics.endFill();
}
}
//Dispose
public function dispose():void
{
while (numChildren)
{
removeChildAt(numChildren - 1);
}
colorGradientBox = null;
horizontalShadowGradientBox = null;
verticalShadowGradientBox = null;
}
//Set Width
override public function set width(value:Number):void
{
widthProperty = value;
draw();
}
//Get Width
override public function get width():Number
{
return widthProperty;
}
//Set Height
override public function set height(value:Number):void
{
heightProperty = value;
draw();
}
//Get Height
override public function get height():Number
{
return heightProperty;
}
//Set Color
public function set color(value:uint):void
{
colorProperty = colorTransform.color = value;
colorGradient.transform.colorTransform = colorTransform;
}
//Get Color
public function get color():uint
{
return colorProperty;
}
}
} |
/**
* <p>Original Author: Daniel Freeman</p>
*
* <p>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:</p>
*
* <p>The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.</p>
*
* <p>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.</p>
*
* <p>Licensed under The MIT License</p>
* <p>Redistributions of files must retain the above copyright notice.</p>
*/
package com.danielfreeman.extendedMadness {
import flash.text.TextFormat;
import com.danielfreeman.extendedMadness.*;
import flash.events.TimerEvent;
import flash.display.Sprite;
import flash.display.DisplayObject;
import com.danielfreeman.madcomponents.*;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.display.InteractiveObject;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.geom.Rectangle;
import flash.geom.Matrix;
/**
* ScrollDatagrid component
* <pre>
* <scrollDataGrids
* id = "IDENTIFIER"
* colour = "#rrggbb"
* background = "#rrggbb, #rrggbb, ..."
* visible = "true|false"
* widths = "p,q,r..."
* alignH = "scroll|no scroll"
* alignV = "scroll|no scroll"
* editable = "true|false"
* widths = "i(%),j(%),k(%)…"
* multiline = "true|false"
* titleBarColour = "#rrggbb"
* gapV = "NUMBER"
* gapH = "NUMBER"
* border = "true|false"
* autoLayout = "true|false"
* tapToScale = "NUMBER"
* auto = "true|false"
* fixedColumns = "n"
* fixedColumnsColours = "#rrggbb, #rrggbb, ..."
* alignGridWidths = "true|false"
* headerLines = "true|false"
* status = "TEXT"
* statusColour = "#rrggbb"
* slideFixedColumns = "true|false"
* lockSides = "true|false"
* lockTopBottom = "true|false"
* />
* </pre>
*/
public class UIScrollDataGrids extends UIScrollDataGrid {
protected static const EXTRA:Number = 32.0;
protected static const STATUS_STYLE:TextFormat = new TextFormat('Arial', 13, 0xFFFFFF);
protected static const HEADER_NAME:String = "#header";
protected var _dataGrids:Vector.<UISimpleDataGrid> = new Vector.<UISimpleDataGrid>();
protected var _fixedColumnLayers:Vector.<Sprite> = new Vector.<Sprite>();
protected var _currentHeading:int = 0;
protected var _titleSlider:Sprite = null;
protected var _headerTitleSlider:Sprite = null;
protected var _alignGridWidths:Boolean = false;
protected var _statusFormat:TextFormat = STATUS_STYLE;
protected var _status:UILabel;
protected var _screen:Sprite;
protected var _gridColumns:Array = [];
protected var _headerLines:Boolean = false;
public function UIScrollDataGrids(screen : Sprite, xml : XML, attributes : Attributes) {
_screen = screen;
xml = xml.copy();
_headerLines = xml.@headerLines == "true";
_alignGridWidths = xml.@alignGridWidths == "true";
initialiseLayers(xml);
// if (xml.statusFont.length() > 0) {
// _statusFormat = UIe.toTextFormat(xml.statusFont[0], _statusFormat);
// delete xml.statusFont;
// }
if (xml.@statusColour.length() > 0) {
_statusFormat = new TextFormat(null, null, UI.toColourValue(xml.@statusColour));
}
super(screen, xml, attributes);
this.setChildIndex(_slider, 0);
_status = new UILabel(this, 0, 0, xml.@status, _statusFormat);
_status.x = attributes.width - _status.width;
doLayout();
}
public function gridFixedColumns(gridIndex:int = -1, row:int = -1):void {
if (gridIndex < 0) {
_gridColumns = [];
}
else {
_gridColumns[gridIndex] = row;
}
}
/**
* Set status label at top-right of datagrids
*/
public function set status(value:String):void {
_status.xmlText = value;
_status.x = attributes.width - _status.width;
}
protected function reposition(cell:UICell):void {
var globalPoint:Point = cell.localToGlobal(new Point(0,0));
var sliderPoint:Point = _slider.globalToLocal(globalPoint);
cell.x = sliderPoint.x;
cell.y = sliderPoint.y;
}
/**
* Create all the layers which slide in different ways for scrolling the grid.
*/
protected function initialiseLayers(xml:XML):void {
addChild(_headerSlider = new Sprite());
_headerSlider.name = "_headerSlider";
if (xml.@fixedColumns.length() > 0) {
_fixedColumns = parseInt(xml.@fixedColumns);
addChild(_fixedColumnSlider = new Sprite());
_fixedColumnSlider.name = "_fixedColumnSlider";
}
addChild(_titleSlider = new Sprite());
_titleSlider.name = "_titleSlider";
addChild(_headerFixedColumnSlider = new Sprite());
_headerFixedColumnSlider.name = "_headerFixedColumnSlider";
addChild(_headerTitleSlider = new Sprite());
_headerTitleSlider.name = "_headerTitleSlider";
}
override public function set xml(value:XML):void {
_dataGridXML = value;
clear();
createSlider(value, _attributes);
}
override protected function sliceTable(dataGrid:UISimpleDataGrid):void {
}
/**
* Put headers, fixed columns, and grid cells all within their appropriate layers
*/
protected function sliceTables(dataGrid:UISimpleDataGrid, index:int = 0):void {
var fixedColumnLayer:Sprite;
if (!_fixedColumnSlider) {
addChild(_fixedColumnSlider = new Sprite());
}
if (_fixedColumnLayers.length == index) {
_fixedColumnSlider.addChild(fixedColumnLayer = new Sprite());
var dataGridGlobalPoint:Point = dataGrid.localToGlobal(new Point(0,0));
fixedColumnLayer.y = _slider.globalToLocal(dataGridGlobalPoint).y;
_fixedColumnLayers.push(fixedColumnLayer);
}
else {
fixedColumnLayer = _fixedColumnLayers[index];
}
var fixedColumns:int = (_gridColumns[index] !== undefined) ? _gridColumns[index] : _fixedColumns;
if (fixedColumns > 0 && dataGrid.tableCells.length > 0) {
var rowIndex:int = 0;
var start:int = dataGrid.hasHeader ? 1 : 0;
for (var i:int = 0; i < dataGrid.tableCells.length; i++) {
var tableRow:Vector.<UICell> = dataGrid.tableCells[i];
for (var j:int = 0; j < fixedColumns; j++) {
var cell:UICell = tableRow[j];
// if (i < start) {
// cell.defaultColour = dataGrid.headerColour;
// }
// else if (_fixedColumnColours) {
// cell.defaultColour = _fixedColumnColours[(rowIndex - start) % _fixedColumnColours.length];
// }
fixedColumnLayer.addChild(cell);
}
rowIndex++;
}
}
colourFixedColumns(dataGrid);
if (dataGrid.titleCell) {
_titleSlider.addChild(dataGrid.titleCell);
dataGrid.titleCell.y = fixedColumnLayer.y;
}
if (dataGrid is UISpecialDataGrid) {
UISpecialDataGrid(dataGrid).copyColumns(fixedColumnLayer, fixedColumns);
}
}
/**
* Put headers, fixed columns, and grid cells all within their appropriate layers
*/
protected function sliceAllTables():void {
for (var i:int = 0; i < _slider.numChildren; i++) {
var child:DisplayObject = _slider.getChildAt(i);
if (child is UISimpleDataGrid) {
if (i < _fixedColumnLayers.length) {
_fixedColumnLayers[i].visible = UISimpleDataGrid(child).includeInLayout;
}
if (UISimpleDataGrid(child).titleCell) {
UISimpleDataGrid(child).titleCell.visible = UISimpleDataGrid(child).includeInLayout;
}
if (UISimpleDataGrid(child).includeInLayout) {
sliceTables(UISimpleDataGrid(child), i);
}
}
}
_slider.cacheAsBitmap = true;
if (_fixedColumnSlider) {
_fixedColumnSlider.cacheAsBitmap = true;
}
if (_headerSlider) {
_headerSlider.cacheAsBitmap = true;
}
_headerFixedColumnSlider.cacheAsBitmap = true;
_titleSlider.cacheAsBitmap = true;
}
protected function copyText(parent:Sprite, source:UICell, yPosition:Number = 0, colour:uint = uint.MAX_VALUE):UICell {
var copyText:UICell = new UICell(parent, source.x, yPosition, source.text, source.width, source.getTextFormat(), source.multiline, source.wordWrap, source.borderColor);
copyText.height = source.height;
copyText.backgroundColor = colour == uint.MAX_VALUE ? source.backgroundColor : colour;
copyText.background = colour == uint.MAX_VALUE ? source.background : true;
copyText.y = yPosition;
copyText.borderColor = source.borderColor;
copyText.border = source.border;
return copyText;
}
protected function copyRow(parent:Sprite, row:Vector.<UICell>, start:int, end:int, yPosition:Number, colour:uint):void {
for (var i:int = start; i < end; i++) {
copyText(parent, row[i], yPosition, colour);
}
}
/**
* The top header doesn't move, and changes to row headings depending on which datagrid is
* beneath it. This method pre-renders all column headers for the datagrids
*/
protected function preExtractHeadersCells():void {
_headerTitleSlider.removeChildren();
_headerFixedColumnSlider.removeChildren();
_headerSlider.removeChildren();
_headerTitleSlider.name = HEADER_NAME;
_headerFixedColumnSlider.name = HEADER_NAME;
_headerSlider.name = HEADER_NAME;
var i:int = 0;
for each (var dataGrid:UISimpleDataGrid in _dataGrids) {
var cellTitle:UICell = null;
if (dataGrid.titleCell && dataGrid.includeInLayout) {
cellTitle = copyText(_headerTitleSlider, dataGrid.titleCell);
cellTitle.visible = i == 0;
}
if (dataGrid.hasHeader && dataGrid.tableCells.length > 0) {
var row:Vector.<UICell> = dataGrid.tableCells[0];
var fixedColumns:int = (_gridColumns[i] !== undefined) ? _gridColumns[i] : _fixedColumns;
if (fixedColumns > 0 && _headerFixedColumnSlider) {
var spriteFixedHeader:Sprite = new Sprite();
copyRow(spriteFixedHeader, row, 0, fixedColumns, cellTitle ? cellTitle.height : 0, dataGrid.headerColour);
_headerFixedColumnSlider.addChild(spriteFixedHeader);
spriteFixedHeader.visible = i == 0;
}
var spriteHeader:Sprite = new Sprite();
copyRow(spriteHeader, row, fixedColumns, row.length, cellTitle ? cellTitle.height : 0, dataGrid.headerColour);
_headerSlider.addChild(spriteHeader);
spriteHeader.visible = i == 0;
}
i++;
}
}
/**
* When the datagrid is scrolled - possibly change top column headings
*/
protected function swapCellHeaders():void {
var index:int = -1;
if (_slider.y < 0 && _dataGrids.length > 0) {
while (index + 1 < _fixedColumnLayers.length && index + 1 < _dataGrids.length && _dataGrids[index + 1].includeInLayout && -_slider.y + (_currentHeading >=0 ? _headerSlider.getBounds(this).bottom / 2 : 0) > _fixedColumnLayers[index + 1].y) {
index++;
}
}
var fixedColumns:int = (_gridColumns[index] !== undefined) ? _gridColumns[index] : _fixedColumns;
if (index >= 0 && index != _currentHeading) {
if (_currentHeading >= 0 && _currentHeading < _headerSlider.numChildren) {
if (_currentHeading < _headerTitleSlider.numChildren) {
UICell(_headerTitleSlider.getChildAt(_currentHeading)).visible = false;
}
Sprite(_headerSlider.getChildAt(_currentHeading)).visible = false;
if (fixedColumns > 0) {
Sprite(_headerFixedColumnSlider.getChildAt(_currentHeading)).visible = false;
}
}
if (index >= 0 && index < _headerSlider.numChildren) {
if (index < _headerTitleSlider.numChildren) {
UICell(_headerTitleSlider.getChildAt(index)).visible = true;
}
Sprite(_headerSlider.getChildAt(index)).visible = true;
if (fixedColumns > 0) {
Sprite(_headerFixedColumnSlider.getChildAt(index)).visible = true;
}
headerFixedColumnLine(index);
}
_currentHeading = index;
}
}
override protected function set sliderX(value:Number):void {
super.sliderX = value;
_titleSlider.x = value > 0 ? value : 0;
_headerTitleSlider.x = value > 0 ? value : 0;
}
override public function set sliderY(value:Number):void {
super.sliderY = value;
_titleSlider.y = value;
_headerTitleSlider.y = value > 0 ? value : 0;
if (_status) {
_status.y = _headerTitleSlider.y;
}
swapCellHeaders();
}
/**
* Create sliding parts of container
*/
override protected function createSlider(xml:XML, attributes:Attributes):void {
_slider = new UI.FormClass(this, _dataGridXML, sliderAttributes(attributes));
_slider.name = "-";
adjustMaximumSlide();
_dataGrids = new <UISimpleDataGrid>[];
for (var i:int = 0; i < _slider.numChildren; i++) {
var child:DisplayObject = _slider.getChildAt(i);
if (child is UISimpleDataGrid && UISimpleDataGrid(child).includeInLayout) {
_dataGrids.push(UISimpleDataGrid(child));
}
}
sliceAllTables();
}
protected function headerFixedColumnLine(index:int):void {
if (_dataGrids.length > index && _currentHeading >= 0) {
var dataGrid:UISimpleDataGrid = _dataGrids[index];
var fixedColumns:int = (_gridColumns[index] !== undefined) ? _gridColumns[index] : _fixedColumns;
_headerFixedColumnSlider.graphics.clear();
if (fixedColumns > 0 && dataGrid.includeInLayout && dataGrid.tableCells.length > 0 && dataGrid.tableCells[0].length > fixedColumns) {
_headerFixedColumnSlider.graphics.beginFill(dataGrid.attributes.colour);
_headerFixedColumnSlider.graphics.drawRect(dataGrid.tableCells[0][fixedColumns].x, _headerFixedColumnSlider.getBounds(this).top, 2.0, _headerFixedColumnSlider.height);
_headerFixedColumnSlider.graphics.endFill();
}
}
}
public function set selectDataGrid(value:int):void {
_dataGrid = _dataGrids[value];
}
public function get dataGrids():Vector.<UISimpleDataGrid> {
return _dataGrids;
}
protected function doAlignGridWidths():void {
var newWidth:Number = 0;//_slider.getBounds(_slider).right + EXTRA;
var numberOfGrids:int = 0;
for each (var dataGrid0:UISimpleDataGrid in _dataGrids) {
if (dataGrid0.includeInLayout) {
numberOfGrids++;
dataGrid0.graphics.clear();
if (dataGrid0.getBounds(dataGrid0).right > newWidth) {
newWidth = dataGrid0.getBounds(dataGrid0).right;
}
}
}
newWidth += EXTRA;
for each (var dataGrid:UISimpleDataGrid in _dataGrids) {
if (dataGrid.includeInLayout) {
if (numberOfGrids > 1 && dataGrid.tableCells.length > 0) {
// dataGrid.lastColumnWidth = (newWidth - dataGrid.lastColumnPosition);
dataGrid.fixwidth = newWidth;
}
dataGrid.drawBackground();
}
}
}
public function drawRowColours():void {
var gridIndex:int = 0;
for each(var fixedColumnLayer:Sprite in _fixedColumnLayers) {
var fixedColumns:int = (_gridColumns[gridIndex] !== undefined) ? _gridColumns[gridIndex] : _fixedColumns;
var dataGrid:UISimpleDataGrid = _dataGrids[gridIndex++];
var colour:uint = dataGrid.hasHeader ? dataGrid.headerColour : Colour.darken(dataGrid.colours[0], DARKEN);
var index:int = dataGrid.hasHeader ? 0 : 1;
fixedColumnLayer.graphics.clear();
for each(var row:Vector.<UICell> in dataGrid.tableCells) {
if (row.length > 0) {
fixedColumnLayer.graphics.beginFill(colour);
fixedColumnLayer.graphics.drawRect(0, row[0].y, fixedColumnLayer.width, row[0].height);
fixedColumnLayer.graphics.endFill();
colour = Colour.darken(dataGrid.colours[index++ % dataGrid.colours.length], DARKEN);
}
}
if (fixedColumns > 0) {
fixedColumnLayer.graphics.beginFill(dataGrid.attributes.colour);
fixedColumnLayer.graphics.drawRect(fixedColumnLayer.width, fixedColumnLayer.getBounds(fixedColumnLayer).top, 2.0, fixedColumnLayer.height);
fixedColumnLayer.graphics.endFill();
}
}
}
protected function relayout(adjust:Boolean = false):void {
drawRowColours();
if (_alignGridWidths) {
doAlignGridWidths();
}
headerFixedColumnLine(_currentHeading);
drawComponent();
if (adjust) {
adjustMaximumSlide();
}
refreshMasking();
preExtractHeadersCells();
}
override protected function autoScrollEnabled():void {
if (_autoScrollEnabledX) {
_scrollEnabledX = false;
for each (var dataGrid:UISimpleDataGrid in _dataGrids) {
_scrollEnabledX = _scrollEnabledX || (!dataGrid.fits && dataGrid.visible);
}
}
}
/**
* Rearrange the layout to new screen dimensions
*/
override public function layout(attributes:Attributes):void {
_attributes = attributes;
if (!_fastLayout) { //fastLayout is yet implemented in this release
IContainerUI(_slider).layout(sliderAttributes(attributes));
relayout(true);
// _fastLayout = _xml.@fastLayout == "true";
}
_status.x = attributes.width - _status.width;
autoScrollEnabled();
}
public function set fixheight(value:Number):void {
_attributes.height = value;
super.adjustMaximumSlide();
}
public function set alignGridWidths(value:Boolean):void {
_alignGridWidths = value;
}
protected function realignColumnLayers():void {
var index:int = 0;
for each (var dataGrid:UISimpleDataGrid in _dataGrids) {
if (dataGrid.includeInLayout) {
var dataGridGlobalPoint:Point = dataGrid.localToGlobal(new Point(0,0));
if (dataGrid.titleCell) {
_titleSlider.addChild(dataGrid.titleCell);
dataGrid.titleCell.y = _slider.globalToLocal(dataGridGlobalPoint).y;
}
if (index < _fixedColumnLayers.length) {
_fixedColumnLayers[index++].y = _slider.globalToLocal(dataGridGlobalPoint).y;
}
}
}
}
override protected function adjustVerticalSlide():void {
var sliderHeight:Number = 0;
if (_scrollerHeight > 0) {
sliderHeight = _scrollerHeight*_scale;
}
else {
for each (var dataGrid:UISimpleDataGrid in _dataGrids) {
if (dataGrid.includeInLayout && dataGrid.getBounds(_slider).bottom > sliderHeight){
sliderHeight = dataGrid.getBounds(_slider).bottom;
}
}
}
_maximumSlide = sliderHeight - _height + PADDING * (_border=="false" ? 0 : 1);
if (_maximumSlide < 0) {
_maximumSlide = 0;
}
if (_autoScrollEnabled) {
_noScroll = _maximumSlide == 0;
}
if (sliderY < -_maximumSlide) {
sliderY = -_maximumSlide;
}
}
override protected function adjustMaximumSlide():void {
sliderX = 0;
sliderY = 0;
var index:int = 0;
var width:Number = 0;
for each (var dataGrid:UISimpleDataGrid in _dataGrids) {
if (dataGrid.includeInLayout) {
if (dataGrid.getBounds(dataGrid).right > width) {
width = dataGrid.getBounds(dataGrid).right;
}
}
else {
dataGrid.y = 0;
if (index < _fixedColumnLayers.length) {
_fixedColumnLayers[index].y = 0;
}
if (dataGrid.titleCell) {
dataGrid.titleCell.y = 0;
}
}
index++;
}
adjustVerticalSlide();
adjustHorizontalSlide(width);
hideScrollBar();
}
override public function doLayout():void {
_delta = 0;
_deltaX = 0;
var y:Number = sliderY;
sliceAllTables();
IContainerUI(_slider).layout(sliderAttributes(attributes));
relayout(true);
// _status.x = attributes.width - _status.width;
realignColumnLayers();
adjustMaximumSlide();
sliderY = y;
autoScrollEnabled();
}
/**
* Find a particular row,column (group) inside the grid
*/
override public function findViewById(id:String, row:int = -1, group:int = -1):DisplayObject {
if (id == "") {
return _status;
}
else {
for each (var dataGrid:UISimpleDataGrid in _dataGrids) {
if (dataGrid.name == id) {
return (row < 0 && group < 0) ? dataGrid : dataGrid.findViewById(id, row, group);
}
}
return null;
}
}
override public function set textSize(value:Number):void {
for each (var dataGrid:UIFastDataGrid in _dataGrids) {
dataGrid.textSize = value;
}
IContainerUI(_slider).layout(sliderAttributes(attributes));
for each (var layer:Sprite in _fixedColumnLayers) {
_fixedColumnSlider.removeChild(layer);
}
if (_alignGridWidths) {
doAlignGridWidths();
}
adjustMaximumSlide();
_fixedColumnLayers = new Vector.<Sprite>();
sliceAllTables();
relayout(false);
}
override public function clear():void {
for each (var dataGrid:UIFastDataGrid in _dataGrids) {
dataGrid.clear();
}
}
override public function destructor():void {
super.destructor();
}
}
}
|
package com.playata.application.ui.elements.leaderboard
{
import com.playata.application.data.leaderboard.MovieLeaderboardContext;
import com.playata.application.data.movie.LeaderboardMovie;
import com.playata.application.data.tournament.MovieTournament;
import com.playata.application.ui.elements.generic.dialog.UiInfoDialog;
import com.playata.framework.application.Environment;
import com.playata.framework.application.request.ActionRequestResponse;
import com.playata.framework.core.util.TimeUtil;
import com.playata.framework.localization.LocText;
import visuals.ui.elements.leaderboard.SymbolLeaderboardMovieContentGeneric;
public class UiLeaderboardMovieContent
{
public static const MAX_LINES:int = 10;
private static const MOVIE_LEADERBOARD_REFRESH_TIME:int = 30;
private var _content:SymbolLeaderboardMovieContentGeneric = null;
private var _refreshButtons:Function = null;
private var _onClick:Function = null;
private var _context:MovieLeaderboardContext = null;
private var _selectedMovieLine:UiLeaderboardMovieLine = null;
private var _movieLine1:UiLeaderboardMovieLine = null;
private var _movieLine2:UiLeaderboardMovieLine = null;
private var _movieLine3:UiLeaderboardMovieLine = null;
private var _movieLine4:UiLeaderboardMovieLine = null;
private var _movieLine5:UiLeaderboardMovieLine = null;
private var _movieLine6:UiLeaderboardMovieLine = null;
private var _movieLine7:UiLeaderboardMovieLine = null;
private var _movieLine8:UiLeaderboardMovieLine = null;
private var _movieLine9:UiLeaderboardMovieLine = null;
private var _movieLine10:UiLeaderboardMovieLine = null;
private var _lastSearched:String = "";
private var _searchCount:int = 0;
public function UiLeaderboardMovieContent(param1:SymbolLeaderboardMovieContentGeneric, param2:Function, param3:Function, param4:MovieLeaderboardContext)
{
super();
_content = param1;
_refreshButtons = param2;
_onClick = param3;
_context = param4;
param1.txtNoMovies.text = LocText.current.text("dialog/leaderboard_movie/no_movies");
param1.txtPositionCaption.text = LocText.current.text("dialog/leaderboard_movie/column_rank");
param1.txtNameCaption.text = LocText.current.text("dialog/leaderboard_movie/column_name");
param1.txtCharacterCaption.text = LocText.current.text("dialog/leaderboard_movie/column_character");
param1.txtRewardCaption.text = LocText.current.text("dialog/leaderboard_movie/column_reward");
param1.txtTournamentInfo.visible = false;
param1.txtNoMovies.visible = false;
_movieLine1 = new UiLeaderboardMovieLine(param1.line1,1,selectMovieLine,doubleClickMovieLine);
_movieLine2 = new UiLeaderboardMovieLine(param1.line2,2,selectMovieLine,doubleClickMovieLine);
_movieLine3 = new UiLeaderboardMovieLine(param1.line3,3,selectMovieLine,doubleClickMovieLine);
_movieLine4 = new UiLeaderboardMovieLine(param1.line4,4,selectMovieLine,doubleClickMovieLine);
_movieLine5 = new UiLeaderboardMovieLine(param1.line5,5,selectMovieLine,doubleClickMovieLine);
_movieLine6 = new UiLeaderboardMovieLine(param1.line6,6,selectMovieLine,doubleClickMovieLine);
_movieLine7 = new UiLeaderboardMovieLine(param1.line7,7,selectMovieLine,doubleClickMovieLine);
_movieLine8 = new UiLeaderboardMovieLine(param1.line8,8,selectMovieLine,doubleClickMovieLine);
_movieLine9 = new UiLeaderboardMovieLine(param1.line9,9,selectMovieLine,doubleClickMovieLine);
_movieLine10 = new UiLeaderboardMovieLine(param1.line10,10,selectMovieLine,doubleClickMovieLine);
}
public function dispose() : void
{
_movieLine1.dispose();
_movieLine1 = null;
_movieLine2.dispose();
_movieLine2 = null;
_movieLine3.dispose();
_movieLine3 = null;
_movieLine4.dispose();
_movieLine4 = null;
_movieLine5.dispose();
_movieLine5 = null;
_movieLine6.dispose();
_movieLine6 = null;
_movieLine7.dispose();
_movieLine7 = null;
_movieLine8.dispose();
_movieLine8 = null;
_movieLine9.dispose();
_movieLine9 = null;
_movieLine10.dispose();
_movieLine10 = null;
}
public function show() : void
{
var _loc1_:Boolean = false;
if(_context.lastMovieLeaderboardRefresh < TimeUtil.now - 30)
{
_loc1_ = true;
_lastSearched = "";
_searchCount = 0;
}
_content.txtNoMovies.visible = false;
if(_context.currentMovie == null)
{
Environment.application.sendActionRequest("retrieveMovieTournamentLeaderboard",{},handleRequests);
}
else if(_loc1_ || _context.maxMovies == 0)
{
Environment.application.sendActionRequest("retrieveMovieTournamentLeaderboard",{"rank":_context.currentMovie.rank},handleRequests);
}
else
{
refreshMovieList();
}
}
public function get currentMovie() : LeaderboardMovie
{
return _context.currentMovie;
}
public function set currentMovie(param1:LeaderboardMovie) : void
{
_context.currentMovie = param1;
}
private function getMovieLine(param1:int) : UiLeaderboardMovieLine
{
switch(int(param1) - 1)
{
case 0:
return _movieLine1;
case 1:
return _movieLine2;
case 2:
return _movieLine3;
case 3:
return _movieLine4;
case 4:
return _movieLine5;
case 5:
return _movieLine6;
case 6:
return _movieLine7;
case 7:
return _movieLine8;
case 8:
return _movieLine9;
case 9:
return _movieLine10;
}
}
public function get movieCount() : int
{
return _context.movies.length;
}
private function selectMovieLine(param1:UiLeaderboardMovieLine) : void
{
_selectedMovieLine = param1;
if(_selectedMovieLine != null)
{
_context.currentMovie = _selectedMovieLine.movie;
}
_movieLine1.highlight(_movieLine1 == _selectedMovieLine);
_movieLine2.highlight(_movieLine2 == _selectedMovieLine);
_movieLine3.highlight(_movieLine3 == _selectedMovieLine);
_movieLine4.highlight(_movieLine4 == _selectedMovieLine);
_movieLine5.highlight(_movieLine5 == _selectedMovieLine);
_movieLine6.highlight(_movieLine6 == _selectedMovieLine);
_movieLine7.highlight(_movieLine7 == _selectedMovieLine);
_movieLine8.highlight(_movieLine8 == _selectedMovieLine);
_movieLine9.highlight(_movieLine9 == _selectedMovieLine);
_movieLine10.highlight(_movieLine10 == _selectedMovieLine);
}
private function doubleClickMovieLine(param1:UiLeaderboardMovieLine) : void
{
selectMovieLine(param1);
}
public function scrollToTop() : void
{
_context.selectMovieLine = true;
Environment.application.sendActionRequest("retrieveMovieTournamentLeaderboard",{"rank":1},handleRequests);
}
public function refreshMovieList() : void
{
if(!_movieLine1)
{
return;
}
_content.txtNoMovies.visible = movieCount == 0;
_content.txtTournamentInfo.visible = MovieTournament.movieTournamentEndTimestamp > 0;
_content.txtTournamentInfo.text = LocText.current.text("dialog/leadboard_movie/end_datetime",MovieTournament.tournamentEndDateTime);
if(_refreshButtons != null)
{
_refreshButtons();
}
if(_selectedMovieLine != null)
{
_context.currentMovie = _selectedMovieLine.movie;
}
_movieLine1.refresh(_context.movies.length >= _context.offsetMovies + 1?_context.movies[_context.offsetMovies + 0]:null,1);
_movieLine2.refresh(_context.movies.length >= _context.offsetMovies + 2?_context.movies[_context.offsetMovies + 1]:null,2);
_movieLine3.refresh(_context.movies.length >= _context.offsetMovies + 3?_context.movies[_context.offsetMovies + 2]:null,3);
_movieLine4.refresh(_context.movies.length >= _context.offsetMovies + 4?_context.movies[_context.offsetMovies + 3]:null,4);
_movieLine5.refresh(_context.movies.length >= _context.offsetMovies + 5?_context.movies[_context.offsetMovies + 4]:null,5);
_movieLine6.refresh(_context.movies.length >= _context.offsetMovies + 6?_context.movies[_context.offsetMovies + 5]:null,6);
_movieLine7.refresh(_context.movies.length >= _context.offsetMovies + 7?_context.movies[_context.offsetMovies + 6]:null,7);
_movieLine8.refresh(_context.movies.length >= _context.offsetMovies + 8?_context.movies[_context.offsetMovies + 7]:null,8);
_movieLine9.refresh(_context.movies.length >= _context.offsetMovies + 9?_context.movies[_context.offsetMovies + 8]:null,9);
_movieLine10.refresh(_context.movies.length >= _context.offsetMovies + 10?_context.movies[_context.offsetMovies + 9]:null,10);
if(_context.currentMovie)
{
if(_movieLine1.movie && _movieLine1.movie.id == _context.currentMovie.id)
{
selectMovieLine(_movieLine1);
}
else if(_movieLine2.movie && _movieLine2.movie.id == _context.currentMovie.id)
{
selectMovieLine(_movieLine2);
}
else if(_movieLine3.movie && _movieLine3.movie.id == _context.currentMovie.id)
{
selectMovieLine(_movieLine3);
}
else if(_movieLine4.movie && _movieLine4.movie.id == _context.currentMovie.id)
{
selectMovieLine(_movieLine4);
}
else if(_movieLine5.movie && _movieLine5.movie.id == _context.currentMovie.id)
{
selectMovieLine(_movieLine5);
}
else if(_movieLine6.movie && _movieLine6.movie.id == _context.currentMovie.id)
{
selectMovieLine(_movieLine6);
}
else if(_movieLine7.movie && _movieLine7.movie.id == _context.currentMovie.id)
{
selectMovieLine(_movieLine7);
}
else if(_movieLine8.movie && _movieLine8.movie.id == _context.currentMovie.id)
{
selectMovieLine(_movieLine8);
}
else if(_movieLine9.movie && _movieLine9.movie.id == _context.currentMovie.id)
{
selectMovieLine(_movieLine9);
}
else if(_movieLine10.movie && _movieLine10.movie.id == _context.currentMovie.id)
{
selectMovieLine(_movieLine10);
}
else
{
selectMovieLine(null);
}
}
else if(_movieLine1.movie)
{
selectMovieLine(_movieLine1);
}
}
public function scrollUp(param1:int, param2:Boolean) : void
{
var _loc3_:* = null;
if(_context.movies.length <= 0)
{
return;
}
_context.offsetMovies = _context.offsetMovies - param1;
if(_context.offsetMovies < 0 && _context.movies.length > 0)
{
_context.offsetMovies = 0;
_loc3_ = _context.movies[0];
if(_loc3_.rank <= 1)
{
refreshMovieList();
return;
}
if(param2)
{
Environment.audio.playFX("ui_button_click.mp3");
}
_context.scrollUp = true;
_context.selectMovieLine = false;
Environment.application.sendActionRequest("retrieveMovieTournamentLeaderboard",{"rank":_loc3_.rank - 1},handleRequests);
return;
}
if(param2)
{
Environment.audio.playFX("ui_button_click.mp3");
}
refreshMovieList();
}
public function scrollDown(param1:int, param2:Boolean) : void
{
var _loc3_:* = null;
if(_context.movies.length <= 0)
{
return;
}
_context.offsetMovies = _context.offsetMovies + param1;
if(_context.offsetMovies > movieCount - 10)
{
_context.offsetMovies = movieCount - 10;
_loc3_ = _context.movies[_context.movies.length - 1];
if(_loc3_.rank >= _context.maxMovies)
{
refreshMovieList();
return;
}
if(param2)
{
Environment.audio.playFX("ui_button_click.mp3");
}
_context.scrollUp = false;
_context.selectMovieLine = false;
Environment.application.sendActionRequest("retrieveMovieTournamentLeaderboard",{"rank":_loc3_.rank + 1},handleRequests);
return;
}
if(param2)
{
Environment.audio.playFX("ui_button_click.mp3");
}
refreshMovieList();
}
public function search(param1:String) : void
{
var _loc2_:int = 0;
_context.selectMovieLine = true;
if(param1 == _lastSearched)
{
_searchCount = _searchCount + 1;
}
else
{
_searchCount = 0;
}
_lastSearched = param1;
if(isNaN(parseInt(param1)))
{
Environment.application.sendActionRequest("retrieveMovieTournamentLeaderboard",{
"character_name":param1,
"entry":_searchCount
},handleRequests);
}
else
{
_loc2_ = parseInt(param1);
if(_loc2_.toString() != param1)
{
_loc2_ = 2147483647;
}
Environment.application.sendActionRequest("retrieveMovieTournamentLeaderboard",{
"rank":_loc2_,
"entry":_searchCount
},handleRequests);
}
}
private function handleRequests(param1:ActionRequestResponse) : void
{
var _loc4_:* = null;
var _loc6_:int = 0;
var _loc5_:int = 0;
var _loc8_:* = param1.action;
if("retrieveMovieTournamentLeaderboard" !== _loc8_)
{
throw new Error("Unsupported request action \'" + param1.action + "\'!");
}
if(param1.error == "")
{
Environment.application.updateData(param1.data);
if(!_movieLine1)
{
return;
}
_context.lastMovieLeaderboardRefresh = TimeUtil.now;
_context.movies = new Vector.<LeaderboardMovie>();
_loc8_ = 0;
var _loc7_:* = param1.appResponse.leaderboard_movies;
for each(var _loc2_ in param1.appResponse.leaderboard_movies)
{
_loc4_ = new LeaderboardMovie(_loc2_);
_context.movies.push(_loc4_);
}
_context.maxMovies = param1.appResponse.max_movies;
_loc6_ = param1.appResponse.centered_rank;
refreshMovieList();
_loc5_ = 1;
if(_context.selectMovieLine)
{
var _loc10_:int = 0;
var _loc9_:* = _context.movies;
for each(var _loc3_ in _context.movies)
{
if(_loc3_.rank == _loc6_)
{
if(_loc5_ > 10)
{
_context.offsetMovies = _loc5_ - 10 / 2 + 1;
if(_context.offsetMovies > movieCount - 10)
{
_context.offsetMovies = movieCount - 10;
}
refreshMovieList();
}
else
{
_context.offsetMovies = 0;
refreshMovieList();
}
selectMovieLine(getMovieLine(_loc5_ - _context.offsetMovies));
break;
}
_loc5_++;
}
}
else if(param1.request.hasData("rank"))
{
_loc5_ = 1;
var _loc12_:int = 0;
var _loc11_:* = _context.movies;
for each(_loc3_ in _context.movies)
{
if(_loc3_.rank == param1.request.getInt("rank"))
{
if(_loc5_ > 10)
{
if(_context.scrollUp)
{
_context.offsetMovies = _loc5_ - 1;
}
else
{
_context.offsetMovies = _loc5_ - 10;
}
if(_context.offsetMovies > movieCount - 10)
{
_context.offsetMovies = movieCount - 10;
}
refreshMovieList();
}
else
{
_context.offsetMovies = 0;
refreshMovieList();
}
break;
}
_loc5_++;
}
}
}
else if(param1.error == "errTournamentLocked")
{
refreshMovieList();
}
else if(param1.error == "errRetrieveLeaderboardEmpty")
{
refreshMovieList();
}
else if(param1.error == "errRetrieveLeaderboardInvalidCharacter")
{
Environment.panelManager.showDialog(new UiInfoDialog(LocText.current.text("error/retrieve_movie_leaderboard_invalid_character_title"),LocText.current.text("error/retrieve_movie_leaderboard_invalid_character_text",param1.request.getString("character_name")),LocText.current.text("general/button_ok")));
}
else if(param1.error == "errRetrieveLeaderboardInvalidRank")
{
Environment.panelManager.showDialog(new UiInfoDialog(LocText.current.text("error/retrieve_movie_leaderboard_invalid_rank_title"),LocText.current.text("error/retrieve_movie_leaderboard_invalid_rank_text"),LocText.current.text("general/button_ok")));
}
else
{
Environment.reportError(param1.error,param1.request);
}
}
}
}
|
/*****************************************************
*
* Copyright 2009 Adobe Systems Incorporated. All Rights Reserved.
*
*****************************************************
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
*
* The Initial Developer of the Original Code is Adobe Systems Incorporated.
* Portions created by Adobe Systems Incorporated are Copyright (C) 2009 Adobe Systems
* Incorporated. All Rights Reserved.
*
*****************************************************/
package org.osmf.logging
{
/**
* Log is the central access point for logging messages.
*
* @includeExample LoggerExample.as -noswf
* @includeExample ExampleLoggerFactory.as -noswf
* @includeExample ExampleLogger.as -noswf
*
* @see org.osmf.logging.Logger
* @see org.osmf.logging.LoggerFactory
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion OSMF 1.0
*/
public class Log
{
/**
* The LoggerFactory used across the application.
*
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion OSMF 1.0
*/
public static function get loggerFactory():LoggerFactory
{
return _loggerFactory;
}
public static function set loggerFactory(value:LoggerFactory):void
{
_loggerFactory = value;
}
/**
* Returns a logger for the specified category.
*
* @param category The category that identifies a particular logger
* @return the logger identified by the category
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion OSMF 1.0
*/
public static function getLogger(category:String):Logger
{
CONFIG::LOGGING
{
if (_loggerFactory == null)
{
_loggerFactory = new TraceLoggerFactory();
}
}
return (_loggerFactory == null)? null : _loggerFactory.getLogger(category);
}
// Internals
//
private static var _loggerFactory:LoggerFactory;
}
} |
/*
* Copyright (c) 2010 the original author or authors
*
* Permission is hereby granted to use, modify, and distribute this file
* in accordance with the terms of the license agreement accompanying it.
*/
package org.robotlegs.oil.pool
{
[Suite]
[RunWith("org.flexunit.runners.Suite")]
public class PoolTestSuite
{
public var recyclingCommandMapTest:RecyclingCommandMapTests;
public var recyclingMediatorMapTest:RecyclingMediatorMapTest;
}
} |
/*
* =BEGIN CLOSED LICENSE
*
* Copyright (c) 2013-2014 Andras Csizmadia
* http://www.vpmedia.eu
*
* For information about the licensing and copyright please
* contact Andras Csizmadia at andras@vpmedia.eu
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* =END CLOSED LICENSE
*/
package hu.vpmedia.entity.core {
import hu.vpmedia.framework.IBaseDisposable;
import org.osflash.signals.Signal;
/**
* TBD
*/
public class BaseEntityNodeList implements IBaseDisposable {
/**
* TBD
*/
public var head:BaseEntityNode;
/**
* TBD
*/
public var tail:BaseEntityNode;
/**
* TBD
*/
public var nodeAdded:Signal;
/**
* TBD
*/
public var nodeRemoved:Signal;
/**
* Constructor
*/
public function BaseEntityNodeList() {
nodeAdded = new Signal(BaseEntityNode);
nodeRemoved = new Signal(BaseEntityNode);
}
/**
* TBD
*/
public function add(node:BaseEntityNode):void {
if (!head) {
head = tail = node;
node.next = node.previous = null;
}
else {
tail.next = node;
node.previous = tail;
node.next = null;
tail = node;
}
nodeAdded.dispatch(node);
}
/**
* TBD
*/
public function remove(node:BaseEntityNode):void {
if (head == node) {
head = head.next;
}
if (tail == node) {
tail = tail.previous;
}
if (node.previous) {
node.previous.next = node.next;
}
if (node.next) {
node.next.previous = node.previous;
}
node.previous = null;
node.next = null;
nodeRemoved.dispatch(node);
}
/**
* TBD
*/
public function dispose():void {
while (head) {
var node:BaseEntityNode = head;
head = node.next;
node.previous = null;
node.next = null;
nodeRemoved.dispatch(node);
}
tail = null;
}
/**
* TBD
*/
public function get length():uint {
var result:uint = 0;
var item:BaseEntityNode = head;
while (item) {
item = item.next;
result++;
}
return result;
}
}
}
|
package lev
{
import flash.display.BitmapData;
import lev.gen.Generator;
import lev.gen.PartySetuper;
public class PartyTime extends LevelStage
{
public var gen:Generator;
public var setuper:PartySetuper;
private var danger:int;
public function PartyTime(args:Array)
{
super(1);
goalTime = args[0];
danger = args[1];
}
override public function start():void
{
var y:Number = 350.0;
var x0:Number = 40.0;
var dx:Number = 110.0;
var dy:Number = 30.0
super.start();
setuper = new PartySetuper();
if(danger==0)
{
//setuper.sleeps = 1.0;
//setuper.toxics = 1.0;
//setuper.sleeps = 1.0;
setuper.dangerH = 0.0;
setuper.jump = 0.1;
}
else if(danger==1)
{
setuper.powers = 0.8;
setuper.sleeps = 0.9;
setuper.toxics = 1.0;
setuper.dangerH = 200.0;
setuper.jump = 0.1;
}
else if(danger==2)
{
setuper.powers = 0.6;
setuper.sleeps = 0.8;
setuper.toxics = 1.0;
setuper.dangerH = 300.0;
setuper.jump = 0.1;
}
gen = new Generator();
gen.regen = true;
gen.speed = 8.0;
while(y>=50)
{
gen.addLine(setuper, x0+dx*0.5, y, dx, 0, 5);
gen.addLine(setuper, x0, y-dy, dx, 0, 6);
y-=dy*2;
}
gen.start();
startX = 20.0 + 600.0*Math.random();
//startPause = true;
}
override public function onWin():void
{
//gen.finish();
gen.regen = false;
}
override public function update(dt:Number):void
{
var o:*;
var i:int = 0;
super.update(dt);
if(gen.speed>2.0)
{
gen.speed-=dt*0.5;
if(gen.speed<2.0) gen.speed = 2.0;
}
gen.update(dt);
}
override public function draw1(canvas:BitmapData):void
{
}
}
} |
package com.hurlant.crypto.prng {
import flash.utils.*;
import flash.text.*;
import com.hurlant.util.*;
import flash.system.*;
public class Random {
private var psize:int;
private var ready:Boolean = false;
private var seeded:Boolean = false;
private var state:IPRNG;
private var pool:ByteArray;
private var pptr:int;
public function Random(_arg1:Class=null){
var _local2:uint;
ready = false;
seeded = false;
super();
if (_arg1 == null){
_arg1 = ARC4;
};
state = (new (_arg1)() as IPRNG);
psize = state.getPoolSize();
pool = new ByteArray();
pptr = 0;
while (pptr < psize) {
_local2 = (65536 * Math.random());
var _local3 = pptr++;
pool[_local3] = (_local2 >>> 8);
var _local4 = pptr++;
pool[_local4] = (_local2 & 0xFF);
};
pptr = 0;
seed();
}
public function seed(_arg1:int=0):void{
if (_arg1 == 0){
_arg1 = new Date().getTime();
};
var _local2 = pptr++;
pool[_local2] = (pool[_local2] ^ (_arg1 & 0xFF));
var _local3 = pptr++;
pool[_local3] = (pool[_local3] ^ ((_arg1 >> 8) & 0xFF));
var _local4 = pptr++;
pool[_local4] = (pool[_local4] ^ ((_arg1 >> 16) & 0xFF));
var _local5 = pptr++;
pool[_local5] = (pool[_local5] ^ ((_arg1 >> 24) & 0xFF));
pptr = (pptr % psize);
seeded = true;
}
public function toString():String{
return (("random-" + state.toString()));
}
public function dispose():void{
var _local1:uint;
_local1 = 0;
while (_local1 < pool.length) {
pool[_local1] = (Math.random() * 0x0100);
_local1++;
};
pool.length = 0;
pool = null;
state.dispose();
state = null;
psize = 0;
pptr = 0;
Memory.gc();
}
public function autoSeed():void{
var _local1:ByteArray;
var _local2:Array;
var _local3:Font;
_local1 = new ByteArray();
_local1.writeUnsignedInt(System.totalMemory);
_local1.writeUTF(Capabilities.serverString);
_local1.writeUnsignedInt(getTimer());
_local1.writeUnsignedInt(new Date().getTime());
_local2 = Font.enumerateFonts(true);
for each (_local3 in _local2) {
_local1.writeUTF(_local3.fontName);
_local1.writeUTF(_local3.fontStyle);
_local1.writeUTF(_local3.fontType);
};
_local1.position = 0;
while (_local1.bytesAvailable >= 4) {
seed(_local1.readUnsignedInt());
};
}
public function nextByte():int{
if (!ready){
if (!seeded){
autoSeed();
};
state.init(pool);
pool.length = 0;
pptr = 0;
ready = true;
};
return (state.next());
}
public function nextBytes(_arg1:ByteArray, _arg2:int):void{
while (_arg2--) {
_arg1.writeByte(nextByte());
};
}
}
}//package com.hurlant.crypto.prng
|
/*
ADOBE SYSTEMS INCORPORATED
Copyright © 2008 Adobe Systems Incorporated. All Rights Reserved.
NOTICE: This software code file is provided by Adobe as a Sample
under the terms of the Adobe AIR SDK license agreement. Adobe permits
you to use, modify, and distribute this file only in accordance with
the terms of that agreement. You may have received this file from a
source other than Adobe. Nonetheless, you may use, modify, and/or
distribute this file only in accordance with the Adobe AIR SDK license
agreement.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
package {
import flash.display.SimpleButton;
import flash.display.MovieClip;
import flash.display.Loader;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.net.URLRequest;
import flash.system.LoaderContext;
import flash.system.ApplicationDomain;
import flash.text.TextField;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import adobe.utils.ProductManager;
import flash.system.Capabilities;
import flash.external.ExternalInterface;
import com.google.analytics.AnalyticsTracker;
import com.google.analytics.GATracker;
public class AIRInstallBadge extends MovieClip {
// Constants:
public static const AIR_SWF_URL:String = "http://airdownload.adobe.com/air/browserapi/air.swf";
public static const VALID_PROTOCOLS:Array = ["http","https"];
// Public Properties:
// ui:
public var imageHolder:MovieClip;
public var dialog:MovieClip;
public var distractor:MovieClip;
public var light:MovieClip;
public var imageAltFld:TextField;
public var actionBtn:SimpleButton;
public var actionFld:TextField;
public var helpBtn:SimpleButton;
// Private Properties:
// parameters:
protected var airVersion:String;
protected var appInstallArg:Array;
protected var appLaunchArg:Array;
protected var appID:String;
protected var appName:String;
protected var appURL:String;
protected var appVersion:String;
protected var helpURL:String;
protected var hideHelp:Boolean;
protected var image:String;
protected var pubID:String;
protected var skipTransition:Boolean;
protected var trackName:String;
protected var tracker:AnalyticsTracker;
//
protected var installedAIRVersion:String;
protected var airSWFLoader:Loader;
protected var airSWF:Object;
protected var action:String;
protected var prevAction:String;
protected var timer:Timer;
protected var productManager:ProductManager;
// Initialization:
public function AIRInstallBadge() {
configUI();
// set up the timer that will be used to check for installation progress:
timer = new Timer(10000,0);
timer.addEventListener(TimerEvent.TIMER,handleTimer);
// set up a product manager for AIR:
productManager = new ProductManager('airappinstaller' );
// read params (except strings) from FlashVars:
var params:Object = loaderInfo.parameters;
airVersion = validateString(params.airversion);
appInstallArg = (validateString(params.appinstallarg)==null) ? null : [params.appinstallarg];
appLaunchArg = (validateString(params.applauncharg)==null) ? null : [params.applauncharg];
appID = validateString(params.appid);
appName = validateString(params.appname);
appURL = validateURL(params.appurl);
appVersion = validateString(params.appversion);
helpURL = validateURL(params.helpurl);
hideHelp = (params.hidehelp != null && params.hidehelp.toLowerCase() == "true");
image = validateURL(params.image);
pubID = validateString(params.pubid);
skipTransition = (params.skiptransition != null && params.skiptransition.toLowerCase() == "true");
dialog.titleFld.textColor = (params.titlecolor != null) ? parseInt(params.titlecolor.replace(/[^0-9A-F]*/ig,""),16) : 0xff0000;
actionFld.textColor = (params.buttonlabelcolor != null) ? parseInt(params.buttonlabelcolor.replace(/[^0-9A-F]*/ig,""),16) : 0xffffff;
imageAltFld.textColor = (params.appnamecolor != null) ? parseInt(params.appnamecolor.replace(/[^0-9A-F]*/ig,""),16) : 0xffffff;
trackName = params.trackName; // google analytics param
//trackID = params.trackID;
// verify all required params are accounted for:
if (!verifyParams()) {
showDialog(getText("error"),getText("err_params"));
actionFld.text = "";
return;
}
// strip tags out of the appName:
appName = appName.replace(/(<.*?>|<)/g,"");
// load the image:
var imageLoader:Loader = new Loader();
imageLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,handleImageError);
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,handleImageLoadComplete);
try {
imageLoader.load(new URLRequest(image));
imageHolder.addChild(imageLoader);
} catch (e:*) {
handleImageError(null);
}
// load the AIR proxy swf:
airSWFLoader = new Loader();
airSWFLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,handleAIRSWFError);
airSWFLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, handleAIRSWFInit);
try {
airSWFLoader.load(new URLRequest(AIR_SWF_URL))//, loaderContext);
} catch (e:*) {
handleAIRSWFError(null);
}
// google analytics tracking
if (!trackName)
return;
tracker = new GATracker(this, "UA-28006448-4", "AS3");
}
// Public Methods:
// Protected Methods:
// called when there is an error loading the application image. Displays alt text (app name and version) instead.
protected function handleImageError(evt:IOErrorEvent):void {
imageAltFld.text = (appVersion != null && appVersion != "") ? appName+" v"+appVersion : appName;
distractor.visible = false;
}
// called when the application image loads. Displays the image and begins the transition.
protected function handleImageLoadComplete(evt:Event):void {
imageHolder.visible = true;
distractor.visible = false;
if (skipTransition) {
gotoAndPlay("transitionEnd");
} else {
play();
}
}
// called when there is an error loading the airSWF
protected function handleAIRSWFError(evt:IOErrorEvent):void {
showDialog(getText("error"),getText("err_airswf"));
actionFld.text = "";
}
// called when the airSWF loads and inits
protected function handleAIRSWFInit(evt:Event):void {
airSWF = airSWFLoader.content;
if (airSWF.getStatus() == "unavailable") {
showDialog(getText("error"),getText("err_airunavailable"));
return;
}
var version:String = null;
if (appID && pubID) {
// check if the application is already installed:
try {
airSWF.getApplicationVersion(appID, pubID, appVersionCallback);
return;
} catch (e:*) {}
}
enableAction("install");
helpBtn.visible = !hideHelp;
}
// callback from the airSWF when requesting application version
protected function appVersionCallback(version:String):void {
if (version == null) {
// application is not installed
enableAction("install");
} else if (appVersion && (checkVersion(appVersion,version)==1)) {
// old version is installed
enableAction("upgrade");
} else {
// current version is probably installed
enableAction("launch");
}
helpBtn.visible = !hideHelp;
}
// handles clicks on the action button
protected function handleActionClick(evt:MouseEvent):void {
gaTracking(action);
if (action == "close") {
hideDialog();
enableAction(prevAction);
} else if (action == "install" || action == "upgrade" || action == "tryagain") {
showDialog(getText("installing"),getText("installingtext"));
disableAction();
// check if it's installed every 5 seconds:
timer.reset();
timer.start();
airSWF.installApplication(appURL, airVersion, appInstallArg);
} else if (action == "launch") {
airSWF.launchApplication(appID, pubID, appLaunchArg);
showDialog(getText("launching"),getText("launchingtext"));
enableAction("close");
}
}
// triggered every 5 seconds after installing or upgrading.
// checks to see if the expected version of the application was successfully installed.
protected function handleTimer(evt:TimerEvent):void {
try {
airSWF.getApplicationVersion(appID, pubID, tryAgainVersionCallback);
} catch (e:*) {
enableAction("tryagain");
}
}
// call back from version check in handleTimer
// verifies that version is appVersion, and provides option to launch the app if it is.
protected function tryAgainVersionCallback(version:String):void {
if (version != null && (appVersion == null || !(checkVersion(appVersion,version)==1))) {
// current version is probably installed
timer.stop();
enableAction("launch");
} else {
enableAction("tryagain");
}
}
// show help
protected function handleHelpClick(evt:MouseEvent):void {
showDialog(getText("help"),getText("helptext"));
enableAction("close");
}
// enables the action button with the appropriate label, and sets the action property
protected function enableAction(action:String):void {
if (action == null) {
disableAction();
actionFld.text = getText("loading");
prevAction = null;
} else {
if (this.action != "close") { prevAction = this.action; }
actionBtn.addEventListener(MouseEvent.CLICK,handleActionClick);
actionBtn.enabled = true;
actionFld.alpha = 1;
actionFld.text = getText(action);
}
this.action = action;
}
// disables the action button
protected function disableAction():void {
actionBtn.removeEventListener(MouseEvent.CLICK,handleActionClick);
actionBtn.enabled = false;
actionFld.alpha = 0.2;
}
// shows the dialog, and hides the help button
protected function showDialog(title:String,content:String):void {
dialog.titleFld.text = title;
dialog.contentFld.htmlText = content;
dialog.visible = true;
helpBtn.visible = false;
}
// hides the dialog, and shows the help button
protected function hideDialog():void {
dialog.visible = false;
helpBtn.visible = !hideHelp;
}
// return if all required parameters are present, false if not:
protected function verifyParams():Boolean {
return !(appName == null || appURL == null || airVersion == null);
}
// return null if not a valid URL, only allow HTTP, HTTPS scheme or relative path
protected function validateURL(url:String):String {
if (url == null) { return null; }
var markerIndex:int = url.search(/:|%3a/i);
if (markerIndex > 0) {
var scheme:String = url.substr(0, markerIndex).toLowerCase();
if (VALID_PROTOCOLS.indexOf(scheme) == -1) { return null; }
}
if (url.indexOf("<") >= 0 || url.indexOf(">") >= 0) {
return null;
}
return url;
}
// returns null if the string is empty or null.
protected function validateString(str:String):String {
return (str == null || str.length < 1 || str.indexOf("<") >= 0 || str.indexOf(">") >= 0) ? null : str;
}
// returns the specified string from FlashVars (passed as "str_strcode") if available, or the default string if not.
protected function getText(strCode:String):String {
var str:String = loaderInfo.parameters["str_"+strCode];
if (str != null && str.length > 1) {
return str;
}
switch (strCode) {
case "error": return "Error!";
case "err_params": return "Invalid installer parameters.";
case "err_airunavailable": return "Adobe® AIR™ is not available for your system.";
case "err_airswf": return "Unable to load the Adobe® AIR™ Browser API swf.";
case "loading": return "Loading...";
case "install": return "Install Now";
case "launch": return "Launch Now";
case "upgrade": return "Upgrade Now";
case "close": return "Close";
case "launching": return "Launching Application";
case "launchingtext": return "Please wait while the application launches.";
case "installing": return "Installing Application";
case "installingtext": return "Please wait while the application installs.";
case "tryagain": return "Try Again";
case "help": return "Help";
case "helptext": return getHelpText();
}
return "";
}
// assembles help text based on the current badge state.
// ex. Click the 'Install Now' button to install My Fun Application. The Adobe® AIR™ runtime will be installed automatically.
protected function getHelpText():String {
var helpText:String = "Click the '"+getText(action)+"' button to "+action+" "+appName;
if (action == "upgrade") { helpText += " to version "+appVersion; }
else if (action == "install") { helpText += ". The Adobe® AIR™ Runtime will be installed automatically if needed"; }
helpText += ".";
if (helpURL != null) { helpText += "\n<a href='"+helpURL+"'><font color='#2288FF'>Click here for additional help</font></a>"; }
return helpText;
}
// returns true if the first version number is greater than the second, or false if it is lesser or indeterminate:
// works with most common versions strings: ex. 1.0.2.27 < 1.0.3.2, 1.0b3 < 1.0b5, 1.0a12 < 1.0b7, 1.0b3 < 1.0
protected function checkVersion(v1:String,v2:String):int {
var arr1:Array = v1.replace(/^v/i,"").match(/\d+|[^\.,\d\s]+/ig);
var arr2:Array = v2.replace(/^v/i,"").match(/\d+|[^\.,\d\s]+/ig);
var l:uint = Math.max(arr1.length,arr2.length);
for (var i:uint=0; i<l; i++) {
var sub:int = checkSubVersion(arr1[i],arr2[i])
if (sub == 0) { continue; }
return sub;
}
return 0;
}
// return 1 if the sub version element v1 is greater than v2, -1 if v2 is greater than v1, and 0 if they are equal
protected function checkSubVersion(v1:String,v2:String):int {
v1 = (v1 == null) ? "" : v1.toUpperCase();
v2 = (v2 == null) ? "" : v2.toUpperCase();
if (v1 == v2) { return 0; }
var num1:Number = parseInt(v1);
var num2:Number = parseInt(v2);
if (isNaN(num2) && isNaN(num1)) {
return (v1 == "") ? 1 : (v2 == "") ? -1 : (v1 > v2) ? 1 : -1;
}
else if (isNaN(num2)) { return 1; }
else if (isNaN(num1)) { return -1; }
else { return (num1 > num2) ? 1 : -1; }
}
// ** this is the public API we expose so the badge configuration application can work with this badge **
// returns an object containing the basic properties of the badge. The configurator expects minWidth, maxWidth, minHeight and maxHeight.
public function getProps():Object {
return {minWidth:215,maxWidth:430,minHeight:180,maxHeight:320};
}
// returns an array of objects describing the parameters supported by this badge.
// parameters will be displayed in the configurator in the same order they are in the array.
// If you add a toolTip paramater, that value will be used as the paramaters label toolTip, otherwise the label will be used.
// supported parameter types and associated properties:
// - string (name, label, default, maxChars, toolTip)
// - boolean (name, label, default, toolTip)
// - color (name, label, default, toolTip)
// - number (name, label, default, required, minValue, maxValue, toolTip)
// - image (name, label, default, toolTip) - Creates an image browse field. Types are restricted to png, gif, and jpeg
// - heading (label) – displays a heading above a parameter group
public function getParams():Array {
var params:Array = [
{name:"helpurl",label:"help url",type:"string",maxChars:200,def:"help.html"},
{name:"hidehelp",label:"hide help?",type:"boolean",def:false},
{name:"skiptransition",label:"skip transition?",type:"boolean",def:false},
{name:"titlecolor",label:"title color",type:"color",def:"FF0000"},
{name:"buttonlabelcolor",label:"button label color",type:"color",def:"FFFFFF"},
{label:"Strings",type:"heading"},
{name:"str_error",label:"error title",type:"string",def:getText("error")},
{name:"str_err_params",label:"invalid params error",type:"string",def:getText("err_params")},
{name:"str_err_airunavailable",label:"AIR unavailable error",type:"string",def:getText("err_airunavailable")},
{name:"str_err_airswf",label:"loading AIR swf failed error",type:"string",def:getText("err_airswf")},
{name:"str_loading",label:"loading label",type:"string",def:getText("loading")},
{name:"str_install",label:"install button label",type:"string",def:getText("install")},
{name:"str_launch",label:"launch button label",type:"string",def:getText("launch")},
{name:"str_upgrade",label:"upgrade button label",type:"string",def:getText("upgrade")},
{name:"str_close",label:"close button label",type:"string",def:getText("close")},
{name:"str_tryagain",label:"try again button label",type:"string",def:getText("tryagain")},
{name:"str_launching",label:"launching title",type:"string",def:getText("launching")},
{name:"str_launchingtext",label:"launching text",type:"string",def:getText("launchingtext")},
{name:"str_installing",label:"installing title",type:"string",def:getText("installing")},
{name:"str_installingtext",label:"installing text",type:"string",def:getText("installingtext")},
{name:"str_help",label:"help title",type:"string",def:getText("help")},
{name:"str_helptext",label:"help text",type:"string",def:""},
];
return params;
}
// return an object representing the dimensions of the image to export for this badge.
// This is called when the badge is exported by the configurator so that it can vary dynamically depending on the badge's current dimensions.
public function getImageSize():Object {
return {width:205,height:170};
}
// handles initial UI setup.
protected function configUI():void {
stop();
actionFld.text = getText("loading");
actionFld.mouseEnabled = false;
disableAction();
hideDialog();
helpBtn.addEventListener(MouseEvent.CLICK,handleHelpClick);
// allow clicks to pass through the light overlay:
light.mouseEnabled = false;
// get rid of the default frame for imageHolder:
imageHolder.removeChildAt(0);
// and hide it until the image is loaded:
imageHolder.visible = false;
// hide the help button until the air proxy swf is loaded:
helpBtn.visible = false;
}
private function gaTracking(action:String):void {
tracker.trackEvent(trackName, "Install", action);
}
}
} |
package com.codeazur.as3swf.tags
{
import com.codeazur.as3swf.SWFData;
public class TagProductInfo implements ITag
{
public static const TYPE:uint = 41;
private static const UINT_MAX_CARRY:Number = uint.MAX_VALUE + 1;
public var productId:uint;
public var edition:uint;
public var majorVersion:uint;
public var minorVersion:uint;
public var build:Number;
public var compileDate:Date;
public function TagProductInfo() {}
public function parse(data:SWFData, length:uint, version:uint, async:Boolean = false):void {
productId = data.readUI32();
edition = data.readUI32();
majorVersion = data.readUI8();
minorVersion = data.readUI8();
build = data.readUI32()
+ data.readUI32() * UINT_MAX_CARRY;
var sec:Number = data.readUI32()
+ data.readUI32() * UINT_MAX_CARRY;
compileDate = new Date(sec);
}
public function publish(data:SWFData, version:uint):void {
var body:SWFData = new SWFData();
body.writeUI32(productId);
body.writeUI32(edition);
body.writeUI8(majorVersion);
body.writeUI8(minorVersion);
body.writeUI32(build);
body.writeUI32(build / UINT_MAX_CARRY);
body.writeUI32(compileDate.time);
body.writeUI32(compileDate.time / UINT_MAX_CARRY);
data.writeTagHeader(type, body.length);
data.writeBytes(body);
}
public function get type():uint { return TYPE; }
public function get name():String { return "ProductInfo"; }
public function get version():uint { return 3; }
public function get level():uint { return 1; }
public function toString(indent:uint = 0, flags:uint = 0):String {
return Tag.toStringCommon(type, name, indent) +
"ProductID: " + productId + ", " +
"Edition: " + edition + ", " +
"Version: " + majorVersion + "." + minorVersion + " r" + build + ", " +
"CompileDate: " + compileDate.toString();
}
}
}
|
package org.bigbluebutton.core.model.users
{
public class UserBuilder
{
internal var id : String;
internal var name : String;
internal var externalId : String;
internal var token : String;
internal var welcome : String;
internal var avatarUrl : String;
internal var layout : String;
internal var logoutUrl: String;
public function UserBuilder(id: String, name: String) {
}
public function withAvatar(value: String):UserBuilder {
return this;
}
public function withExternalId(value: String):UserBuilder {
return this;
}
public function withToken(value: String):UserBuilder {
return this;
}
public function withLayout(value: String):UserBuilder {
return this;
}
public function withWelcome(value: String):UserBuilder {
return this;
}
public function withDialNumber(value: String):UserBuilder {
return this;
}
public function withRole(value: String):UserBuilder {
return this;
}
public function withCustomData(value: String):UserBuilder {
return this;
}
public function build():User {
return null;
}
}
} |
/*
* Copyright the original author or authors.
*
* Licensed under 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/MPL-1.1.html
*
* 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.idmedia.as3commons.util {
import org.idmedia.as3commons.lang.UnsupportedOperationException;
import org.idmedia.as3commons.lang.IndexOutOfBoundsException;
/**
* This class provides a skeletal implementation of the <tt>List</tt>
* interface to minimize the effort required to implement this interface
* backed by a "random access" data store (such as an array). For sequential
* access data (such as a linked list), <tt>AbstractSequentialList</tt> should
* be used in preference to this class.<p>
*
* To implement an unmodifiable list, the programmer needs only to extend this
* class and provide implementations for the <tt>get(int index)</tt> and
* <tt>size()</tt> methods.<p>
*
* To implement a modifiable list, the programmer must additionally override
* the <tt>set(int index, Object element)</tt> method (which otherwise throws
* an <tt>UnsupportedOperationException</tt>. If the list is variable-size
* the programmer must additionally override the <tt>add(int index, Object
* element)</tt> and <tt>remove(int index)</tt> methods.<p>
*
* Unlike the other abstract collection implementations, the programmer does
* <i>not</i> have to provide an iterator implementation; the iterator and
* list iterator are implemented by this class, on top the "random access"
* methods: <tt>get(index:int)</tt>, <tt>setAt(index:int, value:*)</tt>,
* <tt>set(int index, Object element)</tt>, <tt>add(int index, Object
* element)</tt> and <tt>remove(int index)</tt>.<p>
*
* The documentation for each non-abstract methods in this class describes its
* implementation in detail. Each of these methods may be overridden if the
* collection being implemented admits a more efficient implementation.<p>
*
* @author sleistner
* @see Collection
* @see List
* @see AbstractCollection
*/
public class AbstractList extends AbstractCollection implements List {
private var modCount:int = 0;
/**
* Sole constructor. (For invocation by subclass constructors, typically
* implicit.)
*/
function AbstractList() {
}
/**
* Appends the specified element to the end of this List (optional
* operation). <p>
*
* This implementation calls <tt>addAt(size(), value)</tt>.<p>
*
* Note that this implementation throws an
* <tt>UnsupportedOperationException</tt> unless <tt>add(int, Object)</tt>
* is overridden.
*
* @param value element to be appended to this list.
*
* @return <tt>true</tt> (as per the general contract of
* <tt>Collection.add</tt>).
*
* @throws UnsupportedOperationException if the <tt>add</tt> method is not
* supported by this Set.
*
* @throws IllegalArgumentException some aspect of this element prevents
* it from being added to this collection.
*/
override public function add(value:*):Boolean {
return addAt(size(), value);
}
/**
* Returns the element at the specified position in this list.
*
* @param index index of element to return.
*
* @return the element at the specified position in this list.
* @throws IndexOutOfBoundsException if the given index is out of range
* (<tt>index < 0 || index >= size()</tt>).
*/
public function get(index:int):* {
return null;
}
/**
* Inserts the specified element at the specified position in this list
* (optional operation). Shifts the element currently at that position
* (if any) and any subsequent elements to the right (adds one to their
* indices).<p>
*
* This implementation always throws an UnsupportedOperationException.
*
* @param index index at which the specified element is to be inserted.
* @param value element to be inserted.
*
* @throws UnsupportedOperationException if the <tt>add</tt> method is not
* supported by this list.
* @throws IllegalArgumentException if some aspect of the specified
* element prevents it from being added to this list.
* @throws IndexOutOfBoundsException index is out of range (<tt>index <
* 0 || index > size()</tt>).
*/
public function addAt(index:int, value:*):Boolean {
throw new UnsupportedOperationException();
}
/**
* Replaces the element at the specified position in this list with the
* specified element (optional operation). <p>
*
* This implementation always throws an
* <tt>UnsupportedOperationException</tt>.
*
* @param index index of element to replace.
* @param value element to be stored at the specified position.
* @return the element previously at the specified position.
*
* @throws UnsupportedOperationException if the <tt>set</tt> method is not
* supported by this List.
* @throws IllegalArgumentException if some aspect of the specified
* element prevents it from being added to this list.
*
* @throws IndexOutOfBoundsException if the specified index is out of
* range (<tt>index < 0 || index >= size()</tt>).
*/
public function setAt(index:int, value:*):Boolean {
throw new UnsupportedOperationException();
}
/**
* Adds all of the elements in the specified collection to this collection
* (optional operation). The behavior of this operation is undefined if
* the specified collection is modified while the operation is in
* progress. (This implies that the behavior of this call is undefined if
* the specified collection is this collection, and this collection is
* nonempty.) <p>
*
* This implementation iterates over the specified collection, and adds
* each object returned by the iterator to this collection, in turn.<p>
*
* Note that this implementation will throw an
* <tt>UnsupportedOperationException</tt> unless <tt>add</tt> is
* overridden (assuming the specified collection is non-empty).
*
* @param c collection whose elements are to be added to this collection.
* @return <tt>true</tt> if this collection changed as a result of the
* call.
* @throws UnsupportedOperationException if this collection does not
* support the <tt>addAll</tt> method.
* @throws NullPointerException if the specified collection is null.
*
* @see #add(Object)
*/
override public function addAll(collection:Collection):Boolean {
throw new UnsupportedOperationException();
}
/**
* Removes all of the elements from this collection (optional operation).
* The collection will be empty after this call returns (unless it throws
* an exception).<p>
*
* This implementation iterates over this collection, removing each
* element using the <tt>Iterator.remove</tt> operation. Most
* implementations will probably choose to override this method for
* efficiency.<p>
*
* Note that this implementation will throw an
* <tt>UnsupportedOperationException</tt> if the iterator returned by this
* collection's <tt>iterator</tt> method does not implement the
* <tt>remove</tt> method and this collection is non-empty.
*
* @throws UnsupportedOperationException if the <tt>clear</tt> method is
* not supported by this collection.
*/
override public function clear():void {
removeRange(0, size());
}
/**
* Returns an iterator over the elements in this list in proper
* sequence. <p>
*
* This implementation returns a straightforward implementation of the
* iterator interface, relying on the backing list's <tt>size()</tt>,
* <tt>get(int)</tt>, and <tt>remove(int)</tt> methods.<p>
*
* Note that the iterator returned by this method will throw an
* <tt>UnsupportedOperationException</tt> in response to its
* <tt>remove</tt> method unless the list's <tt>remove(int)</tt> method is
* overridden.<p>
*
* @return an iterator over the elements in this list in proper sequence.
*/
override public function iterator():Iterator {
return new ListIteratorImpl(this);
}
/**
* Returns an iterator of the elements in this list (in proper sequence).
* This implementation returns <tt>listIterator(0)</tt>.
*
* @return an iterator of the elements in this list (in proper sequence).
*
* @see #indexedListIterator(int)
*/
public function listIterator():ListIterator {
return new ListIteratorImpl(this);
}
/**
* Returns a list iterator of the elements in this list (in proper
* sequence), starting at the specified position in the list. The
* specified index indicates the first element that would be returned by
* an initial call to the <tt>next</tt> method. An initial call to
* the <tt>previous</tt> method would return the element with the
* specified index minus one.<p>
*
* This implementation returns a straightforward implementation of the
* <tt>ListIterator</tt> interface that extends the implementation of the
* <tt>Iterator</tt> interface returned by the <tt>iterator()</tt> method.
* The <tt>ListIterator</tt> implementation relies on the backing list's
* <tt>getAt(int)</tt>, <tt>setAt(int, *)</tt>, <tt>addAt(int, *)</tt>
* and <tt>remove(int)</tt> methods.<p>
*
* Note that the list iterator returned by this implementation will throw
* an <tt>UnsupportedOperationException</tt> in response to its
* <tt>remove</tt>, <tt>set</tt> and <tt>add</tt> methods unless the
* list's <tt>removeAt(int)</tt>, <tt>setAt(int, *)</tt>, and
* <tt>addAt(int, *)</tt> methods are overridden.<p>
*
* This implementation can be made to throw runtime exceptions in the
* face of concurrent modification, as described in the specification for
* the (protected) <tt>modCount</tt> field.
*
* @param index index of the first element to be returned from the list
* iterator (by a call to the <tt>next</tt> method).
*
* @return a list iterator of the elements in this list (in proper
* sequence), starting at the specified position in the list.
*
* @throws IndexOutOfBoundsException if the specified index is out of
* range (<tt>index < 0 || index > size()</tt>).
*
*/
public function indexedListIterator(index:uint):ListIterator {
if(index < 0 || index > size()) {
throw new IndexOutOfBoundsException('Index: ' + index);
}
var iter:ListIterator = listIterator();
iter.setIndex(index);
return iter;
}
/**
* Removes the element at the specified position in this list (optional
* operation). Shifts any subsequent elements to the left (subtracts one
* from their indices). Returns the element that was removed from the
* list.<p>
*
* This implementation always throws an
* <tt>UnsupportedOperationException</tt>.
*
* @param index the index of the element to remove.
* @return the element previously at the specified position.
*
* @throws UnsupportedOperationException if the <tt>remove</tt> method is
* not supported by this list.
* @throws IndexOutOfBoundsException if the specified index is out of
* range (<tt>index < 0 || index >= size()</tt>).
*/
public function removeAt(index:int):Boolean {
throw new UnsupportedOperationException();
}
public function removeAtAndReturn(index:int):* {
throw new UnsupportedOperationException();
}
public function removeAtTo(index:int, toPos:int):Boolean {
throw new UnsupportedOperationException();
}
private function removeRange(fromIndex:int, toIndex:int):void {
var listIter:ListIterator = indexedListIterator(fromIndex);
for(var i:int = 0, n:int = toIndex - fromIndex;i < n; i++) {
listIter.next();
listIter.remove();
}
}
/**
* Returns the index in this list of the first occurence of the specified
* element, or -1 if the list does not contain this element. More
* formally, returns the lowest index <tt>i</tt> such that <tt>(o==null ?
* get(i)==null : o.equals(get(i)))</tt>, or -1 if there is no such
* index.<p>
*
* This implementation first gets a list iterator (with
* <tt>listIterator()</tt>). Then, it iterates over the list until the
* specified element is found or the end of the list is reached.
*
* @param value element to search for.
*
* @return the index in this List of the first occurence of the specified
* element, or -1 if the List does not contain this element.
*/
public function indexOf(elem:* = null):int {
return toArray().indexOf(elem);
}
}
}
import org.idmedia.as3commons.util.List;
import org.idmedia.as3commons.util.ListIterator;
import org.idmedia.as3commons.util.Iterator;
import org.idmedia.as3commons.lang.IndexOutOfBoundsException;
import org.idmedia.as3commons.lang.IllegalStateException;
import org.idmedia.as3commons.lang.NoSuchElementException;
import org.idmedia.as3commons.lang.ConcurrentModificationException;
internal class IteratorImpl implements Iterator {
protected var cursor:int = 0;
protected var lastRet:int = -1;
protected var list:List;
function IteratorImpl(list:List) {
this.list = list;
}
public function hasNext():Boolean {
return cursor < list.size();
}
public function next():* {
try {
var nextValue:* = list.get(cursor);
lastRet = cursor;
cursor++;
return nextValue;
} catch(e:IndexOutOfBoundsException) {
throw new NoSuchElementException();
}
}
public function remove():void {
if (lastRet == -1) {
throw new IllegalStateException();
}
try {
list.removeAt(lastRet);
if (lastRet < cursor) {
cursor--;
}
lastRet = -1;
} catch(e:IndexOutOfBoundsException) {
throw new ConcurrentModificationException(e.getMessage());
}
}
}
internal class ListIteratorImpl extends IteratorImpl implements ListIterator {
function ListIteratorImpl(list:List) {
super(list);
}
public function hasPrevious():Boolean {
return cursor != 0;
}
public function previous():* {
try {
var i:int = cursor - 1;
var previousValue:* = list.get(i);
lastRet = cursor = i;
return previousValue;
} catch(e:IndexOutOfBoundsException) {
throw new NoSuchElementException();
}
}
public function nextIndex():int {
return cursor;
}
public function previousIndex():int {
return cursor - 1;
}
public function setValue(object:*):void {
if(lastRet == -1) {
throw new IllegalStateException();
}
try {
list.setAt(lastRet, object);
} catch(e:IndexOutOfBoundsException) {
throw new ConcurrentModificationException();
}
}
public function add(object:*):void {
try {
list.addAt(cursor++, object);
lastRet = -1;
} catch(e:IndexOutOfBoundsException) {
throw new ConcurrentModificationException();
}
}
public function setIndex(index:int):void {
if(index < 0 || index >= list.size()) {
throw new IndexOutOfBoundsException('Index: ' + index);
}
cursor = index;
}
}
|
/**
* Created by singuerinc on 08/05/2014.
*/
package models {
public class UserModel {
public function UserModel() {
}
}
}
|
package game
{
import flash.events.TimerEvent;
import flash.utils.Timer;
import org.osflash.signals.Signal;
import game.states.AbstractState;
import game.states.Matcher;
import game.states.Destroyer;
import game.states.FallerAndFiller;
import game.states.InputListener;
import game.states.Swapper;
import starling.core.Starling;
/**
* Main controller of the game.
* It handles the transition between the differents states/sub-controllers,
* depending on the signals they dispatch.
* It also handles score and time.
* @author damrem
*/
public class GameController
{
public static var verbose:Boolean;
// score management
private var _score:uint;
public const SCORE_UPDATED:Signal = new Signal();
// time management
public static const GAME_DURATION_MIN:Number = 1.0;
private var timer:Timer;
private var _timeLeft_sec:int;
public const TIME_LEFT_UPDATED:Signal = new Signal();
public const TIME_S_UP:Signal = new Signal();
// the board containing the pawns
private var _board:Board;
// the current sub-controller
private var currentState:AbstractState;
// the sub-controllers
private var matcher:Matcher;
private var destroyer:Destroyer;
private var fallerAndFiller:FallerAndFiller;
private var inputListener:InputListener;
private var swapper:Swapper;
public function GameController()
{
if (verbose) trace(this + "GameController(" + arguments);
this.timer = new Timer(1000, 5 * 60);
this._board = new Board();
this.fallerAndFiller = new FallerAndFiller(this._board);
this.inputListener = new InputListener(this._board);
this.swapper = new Swapper(this._board);
this.matcher = new Matcher(this._board);
this.destroyer = new Destroyer(this._board);
}
public function start():void
{
if (verbose) trace(this + "start(" + arguments);
this.fallerAndFiller.FILLED.add(this.gotoMatcher);
this.inputListener.SWAP_REQUESTED.addOnce(this.reallyStartPlaying);
this.inputListener.SWAP_REQUESTED.add(this.gotoSwapper);
this.swapper.SWAPPED.add(this.gotoMatcher);
this.swapper.UNSWAPPED.add(this.gotoInputListener);
this.updateScore("GameController");
// this will be plugged only after a 1st swipe, to prevent scoring during initial board filling
//this.matcher.MATCHES_FOUND.add(this.updateScore);
this.matcher.MATCHES_FOUND.add(this.gotoDestroyer);
this.matcher.INVALID_SWAP.add(this.gotoSwapper);
this.matcher.NO_MATCHES_FOUND.add(this.gotoInputListener);
this.destroyer.ALL_ARE_DESTROYED.add(this.gotoFillerAndFaller);
this._timeLeft_sec = GAME_DURATION_MIN * 60;
this.timer.addEventListener(TimerEvent.TIMER, this.updateTimeLeft);
this._score = 0;
this.updateScore("start");
this.updateTimeLeft();
this.board.fillWithHoles();
this.gotoFillerAndFaller();
}
// At the beginning, there are matches, destructions, fallings and fillings:
// we wait for this first wave of actions to start timer and score.
public function reallyStartPlaying():void
{
this.timer.start();
this.matcher.MATCHES_FOUND.add(this.updateScore);
}
/**
* Unset the state and unplug all the signals.
*/
public function stop():void
{
if (verbose) trace(this + "stop(" + arguments);
this.timer.stop();
this.timer.removeEventListener(TimerEvent.TIMER, this.updateTimeLeft);
this.setState(null);
this.destroyer.exit();
this.fallerAndFiller.exit();
this.inputListener.exit();
this.matcher.exit();
this.swapper.exit();
Pawn.unselect();
this.fallerAndFiller.FILLED.removeAll();
this.inputListener.SWAP_REQUESTED.removeAll();
this.swapper.SWAPPED.removeAll();
this.swapper.UNSWAPPED.removeAll();
this.matcher.MATCHES_FOUND.removeAll();
this.matcher.INVALID_SWAP.removeAll();
this.matcher.NO_MATCHES_FOUND.removeAll();
this.destroyer.ALL_ARE_DESTROYED.removeAll();
this.board.reset();
}
private function updateScore(caller:String="other"):void
{
if (verbose) trace(this + "updateScore(" + arguments);
var matchScore:int = this.board.destroyablePawns.length;
matchScore -= 2;
matchScore = Math.max(matchScore, 0);
matchScore *= Math.min(3, matchScore);
matchScore *= 10;
this._score += matchScore;
this.SCORE_UPDATED.dispatch(this.score);
}
private function updateTimeLeft(e:TimerEvent=null):void
{
if (verbose) trace(this + "updateTimer(" + arguments);
this._timeLeft_sec --;
if(this._timeLeft_sec < 0)
{
this.TIME_S_UP.dispatch();
//this.stop();
}
else
{
this.TIME_LEFT_UPDATED.dispatch(this.timeLeft_sec);
}
}
/**
* Defines the current state, by exiting the previous one, and entering the specified one.
* @param state
*/
private function setState(state:AbstractState):void
{
if (verbose) trace(this + "setState(" + arguments);
if (currentState)
{
currentState.exit();
}
currentState = state;
if (currentState)
{
currentState.enter("gameController.setState");
}
}
/**
* Enter the input state.
* @param caller
*/
private function gotoInputListener(caller:String="other"):void
{
if (verbose) trace(this + "gotoInputListener(" + arguments);
this.setState(this.inputListener);
}
/**
* Depending on from what's just happened, we will swap or unswap.
* @param isUnswapping
*/
private function gotoSwapper(isUnswapping:Boolean=false):void
{
if (verbose) trace(this + "gotoSwapper(" + arguments);
this.swapper.isUnswapping = isUnswapping;
this.setState(this.swapper);
}
/**
* Enter the states which detects matches.
*/
private function gotoMatcher():void
{
if (verbose) trace(this + "gotoMatcher(" + arguments);
this.setState(this.matcher);
}
/**
* Enter the states which destroys pawns.
*/
private function gotoDestroyer():void
{
if (verbose) trace(this + "gotoDestroyer(" + arguments);
this.setState(this.destroyer);
}
/**
* Enter the states which generates pawns and make them fall.
*/
private function gotoFillerAndFaller():void
{
if (verbose) trace(this + "gotoFillAndFall(" + arguments);
this.setState(this.fallerAndFiller);
}
public function get board():Board
{
return _board;
}
public function get score():uint
{
return _score;
}
public function get timeLeft_sec():int
{
return _timeLeft_sec;
}
}
} |
package com.zf.managers
{
import com.zf.core.Config;
import com.zf.utils.ZFGameData;
import flash.net.SharedObject;
public class SharedObjectManager
{
public var so:SharedObject;
private static var instance : SharedObjectManager;
private static var allowInstantiation : Boolean;
private const LOCAL_OBJECT_NAME : String = 'zombieflambe_demo';
/***
* Gets the singleton instance of SharedObjectManager or creates a new one
*/
public static function getInstance():SharedObjectManager {
if (instance == null) {
allowInstantiation = true;
instance = new SharedObjectManager();
allowInstantiation = false;
}
return instance;
}
public function SharedObjectManager() {
if (!allowInstantiation) {
throw new Error("Error: Instantiation failed: Use SharedObjectManager.getInstance() instead of new.");
} else {
init();
}
}
/**
* Initializes the class, if gameOptions hasn't been set before, create gameOptions
* Otherwise it initializes Config gameOptions from the shared object
*/
public function init():void {
so = SharedObject.getLocal(LOCAL_OBJECT_NAME);
if(!so.data.hasOwnProperty('gameOptions')) {
// set up the global game options
so.data.gameOptions = {
musicVolume: Config.DEFAULT_SOUND_VOLUME,
sfxVolume: Config.DEFAULT_SOUND_VOLUME
};
Config.musicVolume = Config.DEFAULT_SOUND_VOLUME
Config.sfxVolume = Config.DEFAULT_SOUND_VOLUME
} else {
Config.musicVolume = so.data.gameOptions.musicVolume;
Config.sfxVolume = so.data.gameOptions.sfxVolume;
}
}
/**
* Create a new ZFdata object in name's place in data
*
* @param {String} name the current game name
* @param {Boolean} updateThenSave if true, the function will call save, otherwise the user can save manually
*/
public function createGameData(name:String, updateThenSave:Boolean = false):void {
so.data[name] = new ZFGameData();
so.data.gameOptions = {
musicVolume: Config.DEFAULT_SOUND_VOLUME,
sfxVolume: Config.DEFAULT_SOUND_VOLUME
};
// Reset config values
Config.musicVolume = Config.DEFAULT_SOUND_VOLUME;
Config.sfxVolume = Config.DEFAULT_SOUND_VOLUME;
if(updateThenSave) {
save();
}
}
/**
* Gets a whole block of game data
*
* @param {String} name the current game name
* @returns {Object} the game data Object requested by game name
*/
public function getGameData(name:String):Object {
return (so.data[name]) ? so.data[name] : {};
}
/**
* Sets a whole block of game data
*
* @param {Object} data the data we want to add
* @param {String} name the current game name or blank to use Config.currentGameSOID
* @param {Boolean} updateThenSave if true, the function will call save, otherwise the user can save manually
*/
public function setGameData(data:Object, name:String = '', updateThenSave:Boolean = false):void {
if(name == '') {
name = Config.currentGameSOID;
}
so.data[name] = Object(data);
if(updateThenSave) {
save();
}
}
/**
* Sets a single property from game data
*
* @param {*} data the data we want to add
* @param {String} prop the name of the property to update
* @param {String} name the current game name or blank to use Config.currentGameSOID
* @param {Boolean} updateThenSave if true, the function will call save, otherwise the user can save manually
*/
public function setGameDataProperty(data:*, prop:String, name:String = '', updateThenSave:Boolean = false):void {
if(name == '') {
name = Config.currentGameSOID;
}
// check for nested property
if(prop.indexOf('.') != -1) {
// happens when you pass in 'upgrades.ptsTotal' will split by the . and
// pass data in to so.data[name]['upgrades']['ptsTotal']
var props:Array = prop.split('.');
so.data[name][props[0]][props[1]] = data;
} else {
so.data[name][prop] = data;
}
if(updateThenSave) {
save();
}
}
/**
* Gets a single property from game data
*
* @param {String} prop the name of the property to update
* @param {String} name the current game name or blank to use Config.currentGameSOID
* @returns {*} the game data property requested
*/
public function getGameDataProperty(prop:String, name:String = ''):* {
if(name == '') {
name = Config.currentGameSOID;
}
return so.data[name][prop];
}
/**
* Sets the global gameOptions Object on the SO
*
* @param {Object} data the gameOptions data we want to add
* @param {Boolean} updateThenSave if true, the function will call save, otherwise the user can save manually
*/
public function setGameOptions(data:Object, updateThenSave:Boolean = false):void {
so.data.gameOptions.musicVolume = (!isNaN(data.musicVolume)) ? data.musicVolume : 0;
so.data.gameOptions.sfxVolume = (!isNaN(data.sfxVolume)) ? data.sfxVolume : 0;
if(updateThenSave) {
trace("Saving game options: music: " + data.musicVolume + " -- sfx: " + data.sfxVolume);
save();
}
}
public function dev_WipeAllMem():void {
createGameData('game1', true);
createGameData('game2', true);
createGameData('game3', true);
}
/**
* Gets the global gameOptions Object from the SO
*
* @returns {Object} the saved gameOptions data
*/
public function getGameOptions():Object {
return so.data.gameOptions;
}
/**
* Checks to see if a game name exists on the SO
*
* @param {String} name the game name we want to check for to see if it exists
* @returns {Boolean} if the game exists or not
*/
public function gameExists(name:String):Boolean {
return (so.data[name])
}
/**
* Saves the SO to the user's HD
*/
public function save():void {
so.flush();
}
}
} |
package com.tonybeltramelli.lib.utils.color {
import flash.display.DisplayObject;
import flash.filters.ColorMatrixFilter;
/**
* @author Tony Beltramelli - www.tonybeltramelli.com
*/
public class Color
{
public static function fix(xmlColor : String) : String
{
var submittedColor : String = xmlColor;
var validColor : String;
var pattern : RegExp = /#/;
submittedColor = xmlColor.replace(pattern, "");
pattern = /0x/;
if (submittedColor.substring(0, 2) != "0x")
{
validColor = "0x" + submittedColor;
} else {
validColor = submittedColor;
}
return validColor;
}
public static function convertIt(c : uint) : Object
{
var hsvColor : Object;
var rgb : Array;
var hexColor : String;
hsvColor = {};
rgb = [0, 0, 0];
hexColor = c.toString(16);
if (hexColor.length == 1)
{
hexColor = "000000";
} else if (hexColor.length == 4)
{
hexColor = "00" + hexColor;
}
rgb[0] = parseInt(hexColor.substr(0, 2), 16) / 255;
rgb[1] = parseInt(hexColor.substr(2, 2), 16) / 255;
rgb[2] = parseInt(hexColor.substr(4, 2), 16) / 255;
var min : Number = rgb[0];
if (rgb[1] < min)
{
min = rgb[1];
}
if (rgb[2] < min)
{
min = rgb[2];
}
var max : Number = rgb[0];
if (rgb[1] > max)
{
max = rgb[1];
}
if (rgb[2] > max)
{
max = rgb[2];
}
hsvColor.v = max * 100;
var deltaColor : Number = max - min;
if (max != 0)
{
hsvColor.s = deltaColor / max * 100;
} else {
hsvColor.s = 0;
hsvColor.h = -1;
}
if ( rgb[0] == max )
{
hsvColor.h = ( rgb[1] - rgb[2] ) / deltaColor;
} else if ( rgb[1] == max )
{
hsvColor.h = 2 + ( rgb[2] - rgb[0] ) / deltaColor;
} else {
hsvColor.h = 4 + ( rgb[0] - rgb[1] ) / deltaColor;
}
hsvColor.h *= 60;
if ( hsvColor.h < 0 )
{
hsvColor.h += 360;
}
return hsvColor;
}
public static function getColorMatrix(mc : DisplayObject) : Array
{
var f : Array = mc.filters, i : uint;
for (i = 0; i < f.length; i++) {
if (f[i] is ColorMatrixFilter)
{
return f[i].matrix;
}
}
return null;
}
}
}
|
package com.ixiyou.utils.text
{
/**
* 对XML对象的操作
* @author spe
*/
public class XMLUtil
{
/**
* 给XML添加属性
* @param xml
* @param name
* @param property
* @return
*/
public static function setProperty(xml:XML,name:String, property:String):XML {
return xml
}
}
} |
table delHinds2
"Deletions from Hinds with frequency"
(
string chrom; "Reference sequence chromosome or scaffold"
uint chromStart; "Start position in chrom"
uint chromEnd; "End position in chrom"
string name; "Name"
float frequency; "Frequency"
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.