text,length,is_long_context,metric_val,label_metric "//////////////////////////////////////////////////////////////////////////////// // // 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.containers { import flash.display.DisplayObject; import flash.events.Event; import flash.events.MouseEvent; import flash.geom.Point; import mx.containers.dividedBoxClasses.BoxDivider; import mx.core.EdgeMetrics; import mx.core.IFlexDisplayObject; import mx.core.IFlexModuleFactory; import mx.core.IInvalidating; import mx.core.IUIComponent; import mx.core.UIComponent; import mx.core.mx_internal; import mx.events.ChildExistenceChangedEvent; import mx.events.DividerEvent; import mx.managers.CursorManager; import mx.managers.CursorManagerPriority; import mx.styles.IStyleManager2; import mx.styles.StyleManager; use namespace mx_internal; //-------------------------------------- // Events //-------------------------------------- /** * Dispatched multiple times as the user drags any divider. * * The dividerDrag event is dispatched * after the dividerPress event * and before the dividerRelease event. * * @eventType mx.events.DividerEvent.DIVIDER_DRAG * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""dividerDrag"", type=""mx.events.DividerEvent"")] /** * Dispatched when the user presses any divider in this container. * * The dividerPress event is dispatched * before any dividerDrag events are dispatched. * * @eventType mx.events.DividerEvent.DIVIDER_PRESS * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""dividerPress"", type=""mx.events.DividerEvent"")] /** * Dispatched when the user releases a divider. * * The dividerRelease event is dispatched * after the dividerDrag events, * but before the container's children are resized. * The divider's x and y properties are not updated until * after this event is triggered. As a result, a call to * hDividerBox.getDividerAt(0).x will return * the value of the original x position of the first divider. If you want the * position of the divider after the move, you can access it when the * DividerBox's updateComplete event has been triggered. * * @eventType mx.events.DividerEvent.DIVIDER_RELEASE * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""dividerRelease"", type=""mx.events.DividerEvent"")] //-------------------------------------- // Styles //-------------------------------------- /** * Thickness in pixels of the area where the user can click to drag a * divider. * This area is centered in the gaps between the container's children, * which are determined by the horizontalGap or * verticalGap style property. * The affordance cannot be set to a value larger than the gap size. * A resize cursor appears when the mouse is over this area. * * @default 6 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""dividerAffordance"", type=""Number"", format=""Length"", inherit=""no"")] /** * The alpha value that determines the transparency of the dividers. * A value of 0.0 means completely transparent * and a value of 1.0 means completely opaque. * * @default 0.75 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""dividerAlpha"", type=""Number"", inherit=""no"")] /** * Color of the dividers when the user presses or drags the dividers * if the liveDragging property is set to false. * If the liveDragging property is set to true, * only the divider's knob is shown. * * @default 0x6F7777 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""dividerColor"", type=""uint"", format=""Color"", inherit=""yes"")] /** * The divider skin. * * The default value is the ""mx.skin.BoxDividerSkin"" symbol in the Assets.swf file. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""dividerSkin"", type=""Class"", inherit=""no"")] /** * Thickness in pixels of the dividers when the user presses or drags the * dividers, if the liveDragging property is set to false. * (If the liveDragging property is set to true, * only the divider's knob is shown.) * The visible thickness cannot be set to a value larger than the affordance. * * @default 3 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""dividerThickness"", type=""Number"", format=""Length"", inherit=""no"")] /** * The cursor skin for a horizontal DividedBox. * * The default value is the ""mx.skins.cursor.HBoxDivider"" symbol in the Assets.swf file. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""horizontalDividerCursor"", type=""Class"", inherit=""no"")] /** * The cursor skin for a vertical DividedBox. * * The default value is the ""mx.skins.cursor.VBoxDivider"" symbol in the Assets.swf file. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""verticalDividerCursor"", type=""Class"", inherit=""no"")] //-------------------------------------- // Excluded APIs //-------------------------------------- [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 //-------------------------------------- [IconFile(""DividedBox.png"")] /** * A DividedBox container measures and lays out its children * horizontally or vertically in exactly the same way as a * Box container, but it inserts * draggable dividers in the gaps between the children. * Users can drag any divider to resize the children on each side. * *

The DividedBox class is the base class for the more commonly used * HDividedBox and VDividedBox classes.

* *

The direction property of a DividedBox container, inherited * from Box container, determines whether it has horizontal * or vertical layout.

* *

A DividedBox, HDividedBox, or VDividedBox container has the following default sizing characteristics:

* * * * * * * * * * * * * * * * * *
CharacteristicDescription
Default sizeVertical DividedBox Height is large enough to hold all of its children at the default or explicit * heights of the children, plus any vertical gap between the children, plus the top and bottom padding of the * container. The width is the default or explicit width of the widest child, plus the left and right padding of * the container. *
Horizontal DividedBox Width is large enough to hold all of its children at the * default or explicit widths of the children, plus any horizontal gap between the children, plus the left and * right padding of the container. Height is the default or explicit height of the tallest child * plus the top and bottom padding of the container.
Default padding0 pixels for the top, bottom, left, and right values.
Default gap10 pixels for the horizontal and vertical gaps.
* * @mxml * *

The <mx:DividedBox> tag inherits all of the tag * attributes of its superclass, and adds the following tag attributes:

* *
 *  <mx:DividedBox
 *    Properties
 *    liveDragging=""false|true""
 *    resizeToContent=""false|true""
 *  
 *    Styles
 *    dividerAffordance=""6""
 *    dividerAlpha=""0.75""
 *    dividerColor=""0x6F7777""
 *    dividerSkin=""'mx.skins.BoxDividerSkin' symbol in Assets.swf""
 *    dividerThickness=""3""
 *    horizontalDividerCursor=""'mx.skins.cursor.HBoxDivider' symbol in Assets.swf""
 *    verticalDividerCursor=""'mx.skins.cursor.VBoxDivider' symbol in Assets.swf""
 * 
 *    Events
 *    dividerPress=""No default""
 *    dividerDrag=""No default""
 *    dividerRelease=""No default""
 *    >
 *      ...
 *      child tags
 *      ...
 *  </mx:DividedBox>
 *  
* * @see mx.containers.HDividedBox * @see mx.containers.VDividedBox * * @includeExample examples/DividedBoxExample.mxml * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class DividedBox extends Box { include ""../core/Version.as""; //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * @private */ private static const PROXY_DIVIDER_INDEX:int = 999; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function DividedBox() { super(); addEventListener(ChildExistenceChangedEvent.CHILD_ADD, childAddHandler); addEventListener(ChildExistenceChangedEvent.CHILD_REMOVE, childRemoveHandler); // make divided box visible in automation by default because // users interact with the dividers showInAutomationHierarchy = true; } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * Container for holding divider objects. */ private var dividerLayer:UIComponent = null; /** * @private */ mx_internal var activeDivider:BoxDivider; /** * @private */ private var activeDividerIndex:int = -1; /** * @private */ private var activeDividerStartPosition:Number; /** * @private */ private var dragStartPosition:Number; /** * @private */ private var dragDelta:Number; /** * @private */ private var oldChildSizes:Array /* of ChildSizeInfo */; /** * @private */ private var minDelta:Number; /** * @private */ private var maxDelta:Number; /** * @private * Only allow a single divider to move at a time. */ private var dontCoalesceDividers:Boolean; /** * @private */ private var cursorID:int = CursorManager.NO_CURSOR; /** * @private * We'll measure ourselves once and then store the results here * for the lifetime of the DividedBox. */ private var dbMinWidth:Number; private var dbMinHeight:Number; private var dbPreferredWidth:Number; private var dbPreferredHeight:Number; /** * @private */ private var layoutStyleChanged:Boolean = false; /** * @private */ private var _resizeToContent:Boolean = false; /** * @private * Number of children with their includeInLayout set to true. The rest of * the children don't count. */ private var numLayoutChildren:int = 0; //-------------------------------------------------------------------------- // // Overridden Properties // //-------------------------------------------------------------------------- /** * @private */ override public function set moduleFactory(moduleFactory:IFlexModuleFactory):void { super.moduleFactory = moduleFactory; styleManager.registerSizeInvalidatingStyle(""dividerAffordance""); styleManager.registerSizeInvalidatingStyle(""dividerThickness""); } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // direction //---------------------------------- /** * @private */ override public function set direction(value:String):void { if (super.direction != value) { super.direction = value; // Need to invalidate all our dividers if (dividerLayer) { for (var i:int = 0; i < dividerLayer.numChildren; i++) getDividerAt(i).invalidateDisplayList(); } } } //---------------------------------- // dividerClass //---------------------------------- /** * The class for the divider between the children. * * @default mx.containers.dividedBoxClasses.BoxDivider * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected var dividerClass:Class = BoxDivider; //---------------------------------- // liveDragging //---------------------------------- [Inspectable(category=""General"")] /** * If true, the children adjacent to a divider * are continuously resized while the user drags it. * If false, they are not resized * until the user releases the divider. * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var liveDragging:Boolean = false; //---------------------------------- // numDividers //---------------------------------- /** * The number of dividers. * The count is always numChildren - 1. * * @return The number of dividers. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get numDividers():int { if (dividerLayer) if (!liveDragging && activeDivider) return dividerLayer.numChildren-1; else return dividerLayer.numChildren; else return 0; } //---------------------------------- // resizeToContent //---------------------------------- /** * If true, the DividedBox automatically resizes to the size * of its children. * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get resizeToContent():Boolean { return _resizeToContent; } /** * @private */ public function set resizeToContent(value:Boolean):void { if (value != _resizeToContent) { _resizeToContent = value; if (value) invalidateSize(); } } //-------------------------------------------------------------------------- // // Overridden methods // //-------------------------------------------------------------------------- /** * @private * Override of the measure method of Box. * *

This function is almost identical to the Box version except * that more extensive testing of the min, max * boundary conditions is performed. This is because the DividedBox allows * default values to be less than the min value of a control.

*/ override protected function measure():void { super.measure(); // We only measure ourselves once, since as we change the // size of children, they in turn change the preferred sizes // // We need to copy the cached values into the measured fields // again to handle the case where scaleX or scaleY is not 1.0. // When the ViewStack is zoomed, code in UIComponent.measureSizes // scales the measuredWidth/Height values every time that // measureSizes is called. (Bug 100749) if (!isNaN(dbPreferredWidth) && !_resizeToContent && !layoutStyleChanged) { measuredMinWidth = dbMinWidth; measuredMinHeight = dbMinHeight; measuredWidth = dbPreferredWidth; measuredHeight = dbPreferredHeight; return; } layoutStyleChanged = false; var isVertical:Boolean = this.isVertical(); var minWidth:Number = 0; var minHeight:Number = 0; var preferredWidth:Number = 0; var preferredHeight:Number = 0; var n:int = numChildren; for (var i:int = 0; i < n; i++) { var child:IUIComponent = getLayoutChildAt(i); if (!child.includeInLayout) continue; var prefW:Number = child.getExplicitOrMeasuredWidth(); var prefH:Number = child.getExplicitOrMeasuredHeight(); var minW:Number = child.minWidth; var minH:Number = child.minHeight; var wFlex:Boolean = !isNaN(child.percentWidth); var hFlex:Boolean = !isNaN(child.percentHeight); // Make sure we take the lowest of the low, since pref < min. var smallestMinW:Number = Math.min(prefW, minW); var smallestMinH:Number = Math.min(prefH, minH); if (isVertical) { minWidth = Math.max(wFlex ? minW : prefW, minWidth); preferredWidth = Math.max(prefW, preferredWidth); minHeight += hFlex ? smallestMinH : prefH; preferredHeight += prefH; } else { minWidth += wFlex ? smallestMinW : prefW; preferredWidth += prefW; minHeight = Math.max(hFlex ? minH : prefH, minHeight); preferredHeight = Math.max(prefH, preferredHeight); } } var wPadding:Number = layoutObject.widthPadding(numLayoutChildren); var hPadding:Number = layoutObject.heightPadding(numLayoutChildren); measuredMinWidth = dbMinWidth = minWidth + wPadding; measuredMinHeight = dbMinHeight = minHeight + hPadding; measuredWidth = dbPreferredWidth = preferredWidth + wPadding; measuredHeight = dbPreferredHeight = preferredHeight + hPadding; } /** * @private */ override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void { var n:int; var i:int; // This method gets called while dragging a divider, // but we don't want to do anything then. if (!liveDragging && activeDivider) { n = numChildren; for (i = 0; i < n; i++) { var child:IUIComponent = getLayoutChildAt(i); if (!child.includeInLayout) continue; // Clear out measured min/max // so super.layout() doesn't use them. child.measuredMinWidth = 0; child.measuredMinHeight = 0; } return; } // Before we allow layout, let's clear out any measured min // values of our children so that they don't restrict us. // We only honour explicitly set mins/maxs. // We also try to remove any excess space, but tweaking // the % values on the flexible components. preLayoutAdjustment(); // Let Box lay out the children. super.updateDisplayList(unscaledWidth, unscaledHeight); postLayoutAdjustment(); // Lay out the dividers. if (!dividerLayer) return; var vm:EdgeMetrics = viewMetrics; dividerLayer.x = vm.left; dividerLayer.y = vm.top; var prevChild:IUIComponent = null; var dividerIndex:int = 0; n = numChildren; for (i = 0; i < n; i++) { child = UIComponent(getChildAt(i)); if (child.includeInLayout) { if (prevChild) { layoutDivider(dividerIndex, unscaledWidth, unscaledHeight, prevChild, child); dividerIndex++; } prevChild = child; } } } /** * @private */ override public function styleChanged(styleProp:String):void { super.styleChanged(styleProp); // Need to invalidate all our dividers if (dividerLayer) { var n:int = dividerLayer.numChildren; for (var i:int = 0; i < n; i++) { getDividerAt(i).styleChanged(styleProp); } } if (styleManager.isSizeInvalidatingStyle(styleProp)) { layoutStyleChanged = true; } } /** * @private */ override protected function scrollChildren():void { super.scrollChildren(); // Scroll divider layer. if (contentPane && dividerLayer) dividerLayer.scrollRect = contentPane.scrollRect; } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * Returns a reference to the specified BoxDivider object * in this DividedBox container. * * @param i Zero-based index of a divider, counting from * the left for a horizontal DividedBox, * or from the top for a vertical DividedBox. * * @return A BoxDivider object. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function getDividerAt(i:int):BoxDivider { return BoxDivider(dividerLayer.getChildAt(i)); } /** * Move a specific divider a given number of pixels. * * @param i Zero-based index of a divider, counting from * the left for a horizontal DividedBox, * or from the top for a vertical DividedBox. * * @param amt The number of pixels to move the divider. * A negative number can be specified in order to move * a divider up or left. The divider movement is * constrained in the same manner as if a user * had moved it. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function moveDivider(i:int, amt:Number):void { // Check whether this is a valid divider index. if (i < 0 || i >= numDividers) return; // Make sure the user is not currently dragging. if (activeDividerIndex >= 0) return; // We have to first hit the children if we haven't // yet done so since the first movement . // Mimic a divider moving. activeDividerIndex = i; // Store away child sizes, // then determine the limits on our movement. cacheChildSizes(); computeMinAndMaxDelta(); dragDelta = limitDelta(amt); // Now update the children sizes accordingly. adjustChildSizes(); invalidateSize(); invalidateDisplayList(); // Reset the divider tracking stuff. resetDividerTracking(); } /** * @private */ private function createDivider(i:int):BoxDivider { // Create separate layer for holding divider objects. if (!dividerLayer) { dividerLayer = UIComponent(rawChildren.addChild(new UIComponent())); } var divider:BoxDivider = BoxDivider(new dividerClass()); dividerLayer.addChild(divider); // if we are creating the active divider bring the divider layer // to the top most so that users can see the divider line over // the other children if (i == PROXY_DIVIDER_INDEX) { rawChildren.setChildIndex(dividerLayer, rawChildren.numChildren-1); } // Tell BoxDivider to use DividedBox's styles, // unless we are sliding the divider; in that case, // use the styles of the divider we are sliding. var basedOn:IFlexDisplayObject = (i == PROXY_DIVIDER_INDEX) ? getDividerAt(activeDividerIndex) : this; divider.styleName = basedOn; divider.owner = this; return divider; } /** * @private */ private function layoutDivider(i:int, unscaledWidth:Number, unscaledHeight:Number, prevChild:IUIComponent, nextChild:IUIComponent):void { // The mouse-over thickness of the divider is normally determined // by the dividerAffordance style, and the visible thickness is // normally determined by the dividerThickness style, assuming that // the relationship thickness <= affordance <= gap applies. But if // one of the other five orderings applies, here is a table of what // happens: // // divider divider horizontalGap/ dividerWidth/ visible width/ // Thickness Affordance verticalGap dividerHeight visible height // // 4 6 8 6 4 // 4 8 6 6 4 // 6 4 8 6 6 // 6 8 4 4 4 // 8 4 6 6 6 // 8 6 4 4 4 var divider:BoxDivider = BoxDivider(getDividerAt(i)); var vm:EdgeMetrics = viewMetrics; var verticalGap:Number = getStyle(""verticalGap""); var horizontalGap:Number = getStyle(""horizontalGap""); var thickness:Number = divider.getStyle(""dividerThickness""); var affordance:Number = divider.getStyle(""dividerAffordance""); if (isVertical()) { var dividerHeight:Number = affordance; // dividerHeight is the mouse-over height, // not necessarily the visible height. // The specified affordance should be greater than the thickness. // But if it isn't, use the thickness instead to determine the // divider height. if (dividerHeight < thickness) dividerHeight = thickness; // Don't let the divider overlap the children. if (dividerHeight > verticalGap) dividerHeight = verticalGap; divider.setActualSize(unscaledWidth - vm.left - vm.right, dividerHeight); divider.move(vm.left, Math.round((prevChild.y + prevChild.height + nextChild.y - dividerHeight) / 2)); } else { var dividerWidth:Number = affordance; // dividerWidth is the mouse-over width, // not necessarily the visible width. // The specified affordance should be greater than the thickness. // But if it isn't, use the thickness instead to determine the // divider width. if (dividerWidth < thickness) dividerWidth = thickness; // Don't let the divider overlap the children. if (dividerWidth > horizontalGap) dividerWidth = horizontalGap; divider.setActualSize(dividerWidth, unscaledHeight - vm.top - vm.bottom); divider.move(Math.round((prevChild.x + prevChild.width + nextChild.x - dividerWidth) / 2), vm.top); } divider.invalidateDisplayList(); } /** * @private */ mx_internal function changeCursor(divider:BoxDivider):void { if (cursorID == CursorManager.NO_CURSOR) { // If a cursor skin has been set for the specified BoxDivider, // use it. Otherwise, use the cursor skin for the DividedBox. var cursorClass:Class = isVertical() ? getStyle(""verticalDividerCursor"") as Class : getStyle(""horizontalDividerCursor"") as Class; cursorID = cursorManager.setCursor(cursorClass, CursorManagerPriority.HIGH, 0, 0); } } /** * @private */ mx_internal function restoreCursor():void { if (cursorID != CursorManager.NO_CURSOR) { cursorManager.removeCursor(cursorID); cursorID = CursorManager.NO_CURSOR; } } /** * @private */ mx_internal function getDividerIndex(divider:BoxDivider):int { var n:int = numChildren; for (var i:int = 0; i < n - 1; i++) { if (getDividerAt(i) == divider) return i; } return -1; } /** * @private */ private function getMousePosition(event:MouseEvent):Number { var point:Point = new Point(event.stageX, event.stageY); point = globalToLocal(point); return isVertical() ? point.y : point.x; } /** * @private */ mx_internal function startDividerDrag(divider:BoxDivider, trigger:MouseEvent):void { // Make sure the user is not currently dragging. if (activeDividerIndex >= 0) return; activeDividerIndex = getDividerIndex(divider); var event:DividerEvent = new DividerEvent(DividerEvent.DIVIDER_PRESS); event.dividerIndex = activeDividerIndex; dispatchEvent(event); if (liveDragging) activeDivider = divider; else { activeDivider = createDivider(PROXY_DIVIDER_INDEX); activeDivider.visible = false; activeDivider.state = DividerState.DOWN; activeDivider.setActualSize(divider.width, divider.height); activeDivider.move(divider.x, divider.y); activeDivider.visible = true; divider.state = DividerState.UP; } if (isVertical()) activeDividerStartPosition = activeDivider.y; else activeDividerStartPosition = activeDivider.x; dragStartPosition = getMousePosition(trigger); dragDelta = 0; cacheChildSizes(); adjustChildSizes(); computeMinAndMaxDelta(); systemManager.getSandboxRoot().addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler, true); systemManager.deployMouseShields(true); } /** * @private * Store away some important information about * each child for us to use while we move the divider. */ private function cacheSizes():void { oldChildSizes = []; // empty array var vertical:Boolean = isVertical(); var smallest:Number = Number.MAX_VALUE; // use a big number var n:int = numChildren; for (var i:int = 0; i < n; i++) { var child:IUIComponent = getLayoutChildAt(i); if (!child.includeInLayout) continue; var sz:Number = vertical ? child.height : child.width; var mx:Number = vertical ? child.maxHeight : child.maxWidth; var umn:Number = vertical ? child.explicitMinHeight : child.explicitMinWidth; // avoid measured values // A NaN min means 0. var mn:Number = (isNaN(umn)) ? 0 : umn; // Compute these for later use. var dMin:Number = Math.max(0, sz - mn); var dMax:Number = Math.max(0, mx - sz); if (sz > 0 && sz < smallest) smallest = sz; oldChildSizes.push(new ChildSizeInfo(sz, mn, mx, dMin, dMax)); } // Remember the smallest child size we saw. oldChildSizes.push(new ChildSizeInfo((smallest == Number.MAX_VALUE) ? 1 : smallest)); } /** * @private */ private function cacheChildSizes():void { oldChildSizes = []; // clear or store cacheSizes(); } /** * @private */ private function mouseMoveHandler(event:MouseEvent):void { dragDelta = limitDelta(getMousePosition(event) - dragStartPosition); var dividerEvent:DividerEvent = new DividerEvent(DividerEvent.DIVIDER_DRAG); dividerEvent.dividerIndex = activeDividerIndex; dividerEvent.delta = dragDelta; dispatchEvent(dividerEvent); if (liveDragging) { adjustChildSizes(); invalidateDisplayList(); updateDisplayList(unscaledWidth, unscaledHeight); } else { if (isVertical()) activeDivider.move(0, activeDividerStartPosition + dragDelta); else activeDivider.move(activeDividerStartPosition + dragDelta, 0); } } /** * @private * * @param trigger May be null if the event is not a MouseEvent but * a mouse event from another sandbox. */ mx_internal function stopDividerDrag(divider:BoxDivider, trigger:MouseEvent):void { if (trigger) dragDelta = limitDelta(getMousePosition(trigger) - dragStartPosition); var event:DividerEvent = new DividerEvent(DividerEvent.DIVIDER_RELEASE); event.dividerIndex = activeDividerIndex; event.delta = dragDelta; dispatchEvent(event); if (!liveDragging) { if (dragDelta == 0) getDividerAt(activeDividerIndex).state = DividerState.OVER; if (activeDivider) dividerLayer.removeChild(activeDivider); activeDivider = null; adjustChildSizes(); invalidateSize(); invalidateDisplayList(); } resetDividerTracking(); systemManager.getSandboxRoot().removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler, true); systemManager.deployMouseShields(false); } /** * @private */ private function resetDividerTracking():void { activeDivider = null; activeDividerIndex = -1; activeDividerStartPosition = NaN; dragStartPosition = NaN; dragDelta = NaN; oldChildSizes = null; minDelta = NaN; maxDelta = NaN; } /** * @private * Determine the maximum amount of movement that * a divider, i, can move both up and down. * * We base this calculation on the amount of * travel that each divider supports, assuming * that as one divider reaches its limits, the next * divider will move. In this way dividers will * cascade. */ private function computeAllowableMovement(at:int):void { // We break the computation into two loops, // so that we can calc min and max travel // independently as one would move the divider // either up or down. var deltaMinAbove:Number = 0; var deltaMaxAbove:Number = 0; var deltaMinBelow:Number = 0; var deltaMaxBelow:Number = 0; var n:int = numLayoutChildren; var i:int; var child:ChildSizeInfo; if (at < 0) return; for (i = at; i >= 0; i--) { child = ChildSizeInfo(oldChildSizes[i]); deltaMinAbove += (dontCoalesceDividers && deltaMinAbove) ? 0 : child.deltaMin; deltaMaxAbove += (dontCoalesceDividers && deltaMaxAbove) ? 0 : child.deltaMax; } for (i = at + 1; i < n; i++) { child = ChildSizeInfo(oldChildSizes[i]); deltaMinBelow += (dontCoalesceDividers && deltaMinBelow) ? 0 : child.deltaMin; deltaMaxBelow += (dontCoalesceDividers && deltaMaxBelow) ? 0 : child.deltaMax; } // Now the maximum movement we can have if // the divider is moved up is equal to the // smaller of how much we can shrink all // components above our divider or the // maximum of how much the components below // our divider can grow. Similarly for the // divider moving in the opposite direction. var deltaUp:Number = Math.min(deltaMinAbove, deltaMaxBelow); var deltaDn:Number = Math.min(deltaMinBelow, deltaMaxAbove); // deltaUp needs to be in -ve in order for our // update logic to work minDelta = -deltaUp; maxDelta = deltaDn; } /** * @private */ private function computeMinAndMaxDelta():void { computeAllowableMovement(activeDividerIndex); } /** * @private */ private function limitDelta(delta:Number):Number { if (delta < minDelta) delta = minDelta; else if (delta > maxDelta) delta = maxDelta; // Make sure it is not fractional, // otherwise we lose pixels. (Bug 87339) delta = Math.round(delta); return delta; } /** * @private * We distribute the delta space in the same * fashion that we calculated it. That is we * start at the divider and give out space * until we hit a limit on the component or * we run out of space to distribute. * We need to do this in both directions since * in one direction we are shrinking and * in the other we are growing. */ private function distributeDelta():void { // if there is no movement of divider we need not // do any child resizing. if (!dragDelta) return; var vertical:Boolean = isVertical(); var n:int = numLayoutChildren; var k:int = activeDividerIndex; var smallest:Number = oldChildSizes[n].size - Math.abs(dragDelta); // smallest possible child size if (smallest <= 0 || isNaN(smallest)) smallest = 1; var i:int; var size:ChildSizeInfo; var move:Number; var newSize:Number; var child:IUIComponent; var childSize:Number; // Find the index of the child before the active divider var activeDividerChildIndex:int = -1; var dividerIndex:int = -1; while (dividerIndex < activeDividerIndex) { if (UIComponent(getChildAt(++activeDividerChildIndex)).includeInLayout) ++dividerIndex; } // Distribute space starting from the center and // moving upwards. var curChildIndex:int = activeDividerChildIndex; var amt:Number = dragDelta; for (i = k; i >= 0; i--) { // If dragDelta -ve => shrink upper components // otherwise grow them. size = ChildSizeInfo(oldChildSizes[i]); move = (amt < 0) ? -Math.min(-amt, size.deltaMin) : Math.min(amt, size.deltaMax); // Adjust the component and reduce the remaining delta newSize = size.size + move; amt -= move; // Find the previous child included in the layout do { child = IUIComponent(getChildAt(curChildIndex--)); } while (!child.includeInLayout); // Adjust the child size. childSize = (newSize / smallest) * 100; if (vertical) child.percentHeight = childSize; else child.percentWidth = childSize; // Force a re-measure. if (child is IInvalidating) IInvalidating(child).invalidateSize(); } // assert(amt == 0) // Now do the same distribution but moving downwards. curChildIndex = activeDividerChildIndex + 1; amt = dragDelta; for (i = k + 1; i < n; i++) { // If dragDelta -ve => grow lower components // otherwise shrink them. size = ChildSizeInfo(oldChildSizes[i]); move = (amt < 0) ? Math.min(-amt, size.deltaMax) : -Math.min(amt, size.deltaMin); // Adjust the component and reduce the remaining delta. newSize = size.size + move; amt += move; // Find the next child included in the layout do { child = IUIComponent(getChildAt(curChildIndex++)); } while (!child.includeInLayout); childSize = (newSize / smallest) * 100; if (vertical) child.percentHeight = childSize; else child.percentWidth = childSize; // Force a re-measure. if (child is IInvalidating) IInvalidating(child).invalidateSize(); } } /** * @private * For 1.5 we normalize all children to the smallest one * So that we can remove n-1 children and still guarantee * one child can consume 100%. * Also we support the concept of fixed sized children, * which allows us to have one or more children be rigid * in the DividedBox in this case, the dividers above * and below the fixed component move in unison. */ private function adjustChildSizes():void { distributeDelta(); } /** * @private * Algorithm employed pre-layout to ensure that * we don't leave any dangling space and to ensure * that only explicit min/max values are honored. * * We first compute the sum of %'s across all * children to ensure that we have at least 100%. * If so, we are done. If not, then we attempt * to attach the remaining amount to the last * component, if not, then we distribute the * percentages evenly across all % components. * */ private function preLayoutAdjustment():void { // Calculate the total % var vertical:Boolean = isVertical(); var totalPerc:Number = 0; var percCount:Number = 0; var n:int = numChildren; var i:int; var child:IUIComponent; var perc:Number; for (i = 0; i < n; i++) { child = getLayoutChildAt(i); if (!child.includeInLayout) continue; // Clear out measured min/max // so super.layout() doesn't use them. child.measuredMinWidth = 0; child.measuredMinHeight = 0; perc = vertical ? child.percentHeight : child.percentWidth; if (!isNaN(perc)) { totalPerc += perc; percCount++; } } // during preLayoutAdjustment, we make some changes to the children's // widths and heights. We keep track of the original values in postLayoutChanges // so we can later go back and reset them so another layout pass is working // with the correct values rather than these modified values. postLayoutChanges = []; var changeObject:Object; // No flexible children, so we make the last one 100%. if (totalPerc == 0 && percCount == 0) { // Everyone is fixed and we can give 100% to the last // included in layout one without concern. for (i = n-1; i >= 0; i--) { child = UIComponent(getChildAt(i)); if (child.includeInLayout) { // create a changeObject to keep track of the original values // that this child had for width and height changeObject = {child: child}; if (vertical) { // we know there's no percentHeight originally if (child.explicitHeight) changeObject.explicitHeight = child.explicitHeight; else changeObject.percentHeight = NaN; child.percentHeight = 100; } else { // we know there's no percentWidth originally if (child.explicitWidth) changeObject.explicitWidth = child.explicitWidth; else if (child.percentWidth) changeObject.percentWidth = NaN; child.percentWidth = 100; } postLayoutChanges.push(changeObject); break; } } } else if (totalPerc < 100) { // We have some %s but they don't total to 100, so lets // distribute the delta across all of them and in the // meantime normalize all %s to unscaledHeight/Width. // The normalization takes care of the case where any one // of the components hits a min/max limit on their size, // which could result in the others filling less than 100%. var delta:Number = Math.ceil((100 - totalPerc) / percCount); for (i = 0; i < n; i++) { child = getLayoutChildAt(i); if (!child.includeInLayout) continue; changeObject = {child: child}; if (vertical) { perc = child.percentHeight; if (!isNaN(perc)) { changeObject.percentHeight = child.percentHeight; postLayoutChanges.push(changeObject); child.percentHeight = (perc + delta) * unscaledHeight; } } else { perc = child.percentWidth; if (!isNaN(perc)) { changeObject.percentWidth = child.percentWidth; postLayoutChanges.push(changeObject); child.percentWidth = (perc + delta) * unscaledWidth; } } } } // OK after all this magic we still can't guarantee that the space is // entirely filled. For example, all percent components hit their max // values. In this case, the layout will include empty space at the end, // and once the divider is touched, the non-percent based components // will be converted into percent based ones and fill the remaining // space. It seems to me that this scenario is highly unlikely. // Thus I've choosen the route of stretching the percent based // components and not touching the explicitly sized or default // sized ones. // // Another option would be to stretch the default sized components // either in addition to the percent based ones or instead of. // This seemed a little odd to me as the user never indicated // that these components are to be stretched initially, so in the end // I choose to tweak the components that the user has indicated // as being stretchable. } /** * @private * During preLayoutAdjustment, we make some changes to the children's * widths and heights. We keep track of the original values in postLayoutChanges * so we can later go back and reset them so another layout pass is working * with the correct values rather than these modified values. */ private var postLayoutChanges:Array; /** * @private * Post layout work. In preLayoutAdjustment() * sometimes we set a child's percentWidth/percentHeight. * postLayoutAdjustment() will reset the child's width or height * back to what it was. */ private function postLayoutAdjustment():void { // each object has a child property and may have a set of width/height // properties that it would like to be set var len:int = postLayoutChanges.length; for (var i:int = 0; i < len; i++) { var changeObject:Object = postLayoutChanges[i]; if (changeObject.percentWidth !== undefined) changeObject.child.percentWidth = changeObject.percentWidth; if (changeObject.percentHeight !== undefined) changeObject.child.percentHeight = changeObject.percentHeight; if (changeObject.explicitWidth !== undefined) changeObject.child.explicitWidth = changeObject.explicitWidth; if (changeObject.explicitHeight !== undefined) changeObject.child.explicitHeight = changeObject.explicitHeight; } postLayoutChanges = null; } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * @private */ private function childAddHandler(event:ChildExistenceChangedEvent):void { var child:DisplayObject = event.relatedObject; child.addEventListener(""includeInLayoutChanged"", child_includeInLayoutChangedHandler); if (!IUIComponent(child).includeInLayout) return; numLayoutChildren++; if (numLayoutChildren > 1) createDivider(numLayoutChildren - 2); // Clear the cached values so that we do another // measurement pass. dbMinWidth = NaN; dbMinHeight = NaN; dbPreferredWidth = NaN; dbPreferredHeight = NaN; } /** * @private */ private function childRemoveHandler(event:ChildExistenceChangedEvent):void { var child:DisplayObject = event.relatedObject; child.removeEventListener(""includeInLayoutChanged"", child_includeInLayoutChangedHandler); if (!IUIComponent(child).includeInLayout) return; numLayoutChildren--; if (numLayoutChildren > 0) dividerLayer.removeChild(getDividerAt(numLayoutChildren - 1)); // Clear the cached values so that we do another // measurement pass. dbMinWidth = NaN; dbMinHeight = NaN; dbPreferredWidth = NaN; dbPreferredHeight = NaN; invalidateSize(); } /** * @private * When a child's includeInLayout changes, we either remove or add a * divider. */ private function child_includeInLayoutChangedHandler(event:Event):void { var child:UIComponent = UIComponent(event.target); if (child.includeInLayout && ++numLayoutChildren > 1) createDivider(numLayoutChildren - 2); else if (!child.includeInLayout && --numLayoutChildren > 0) dividerLayer.removeChild(getDividerAt(numLayoutChildren - 1)); // Clear the cached values so that we do another // measurement pass. dbMinWidth = NaN; dbMinHeight = NaN; dbPreferredWidth = NaN; dbPreferredHeight = NaN; invalidateSize(); } } } //////////////////////////////////////////////////////////////////////////////// // // Helper class: ChildSizeInfo // //////////////////////////////////////////////////////////////////////////////// /** * @private */ class ChildSizeInfo { //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * @private */ public function ChildSizeInfo(size:Number, min:Number = 0, max:Number = 0, deltaMin:Number = 0, deltaMax:Number = 0) { super(); this.size = size; this.min = min; this.max = max; this.deltaMin = deltaMin; this.deltaMax = deltaMax; } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // deltaMin //---------------------------------- /** * @private */ public var deltaMin:Number; //---------------------------------- // deltaMax //---------------------------------- /** * @private */ public var deltaMax:Number; //---------------------------------- // min //---------------------------------- /** * @private */ public var min:Number; //---------------------------------- // max //---------------------------------- /** * @private */ public var max:Number; //---------------------------------- // size //---------------------------------- /** * @private */ public var size:Number; } ",12464,False,2099.029980108415,median "= TimeBook - User Guide :site-section: UserGuide :toc: :toc-title: :toc-placement: preamble :toclevels: 3 :sectnums: :imagesDir: images :stylesDir: stylesheets :xrefstyle: full :experimental: ifdef::env-github[] :tip-caption: :bulb: :note-caption: :information_source: :warning-caption: :warning: :important-caption: :exclamation: endif::[] :repoURL: https://github.com/AY1920S1-CS2103T-T10-4/main By: `Team TimeBook` Since: `Aug 2019` Licence: `MIT` Our team is still working on the User Guide. Keep a look out for more cool and exciting features coming soon! == Introduction Thank you for checking out TimeBook! // tag::ppp-introduction[] TimeBook is a desktop application that is morphed from AddressBook Level 3 (AB3). TimeBook is a scheduling application that aims to help busy NUS undergraduates keep track of the schedules of you and your friends. It also can find the common free time and venues among you and your friends. TimeBook will have the following features: . A graphical user interface (GUI) but most of the interactions with the application would happen using command line interface (CLI). . Allows users to add the schedules of his or her friends and organise them into groups. . Deconflict different schedules of different people and different groups to find the common free time among them. . Integration with NUSmods API to allow users to enter their NUSmods timetable link to add it to their schedule. . Integration with Google Maps API to allow the application to evaluate the best venue for the group to meet up during the free time in their schedules. // end::ppp-introduction[] == Understanding this guide === Basic Information This guide explains how you can use *TimeBook* to the fullest extent to assist you to plan for your group's meeting. You can find the steps needed to start scheduling group activities with your friends or loved ones in the <> and general *lifecycle* usage of our application. If you happen to stumble upon some difficulties, our <> (FAQ) is here to address that. If you are an experienced *Command Line Interface (CLI)* user, you can hop right into using the application by looking at our <>. Otherwise, take a look at the <> section to obtain more information on how to use our application. We have used the following symbols to help you better understand our application usage. (For now we have not picked our symbols yet.) [width=""80%"",cols=""^3, ^10"",options=""header""] |==== | Symbol | What it means | image:./icons/important.png[] | Important information that you may want to note. | image:./icons/lightbulb.png[] | Shortcuts or hacks that would improve your experience using this application. | image:./icons/warning.png[] | Warning! Be careful if you encounter this symbol. |==== == Quick Start ==== image:./icons/important.png[] Make sure that your screen resolution height is at least 720 pixels before you continue this section! ==== . Ensure you have Java `11` or above installed in your Computer. . Download the latest `timebook.jar` link:{repoURL}/releases[here]. . Copy the file to the folder you want to use as the home folder for your TimeBook. . Double-click the file to start the app. + The GUI should appear in a few seconds. image:Ui.png[width=""790""] + . Type the command in the command box and press kbd:[Enter] to execute it. + e.g. typing *`help`* and pressing kbd:[Enter] will open the help window. . Some example commands you can try: * *`list`* : lists all information in TimeBook. * *`addperson`* `n/John Doe p/98765432 em/johnd@example.com a/John street, block 123, #01-01` : adds a contact named `John Doe` to the TimeBook. * *`deleteperson`* `n/John Doe` : deletes the person named `John Doe` from the TimeBook. * *`addgroup`* `g/CS2103` : adds a new group called `CS2103` to the TimeBook. * *`addtogroup`* `n/John Doe` `g/CS2103` : Adds a person `John Doe` into the group `CS2103`. * *`exit`* : exits the app + [IMPORTANT] ==== include::UserGuide.adoc[tag=alice-full] ==== . Refer to <> for details of each command. == Inexperienced CLI user Unlike most applications, where you use your mouse to interact with the application such as scrolling and clicking, our application mostly use the *Command Line Interface*. Most of the time, you would be interacting with the application through typing commands in the command box of the application. You can play around with the commands in <> to get yourself warmed up. == GUI Components In this section, you will learn more about the different components of our application. Here is an overview of all of the components in our application: image::guiComponents.png[] === MenuBar You may use the menu bar to access file or exit the application. image::menuBar.png[] === Schedule Display The schedule display is the main component that you will be looking at to look schedules of yours or others! image::scheduleDisplay.png[] ==== How to read the schedule view Unsure of how to read the combined schedules of your friends in TimeBook? Here is a simple example to guide you! TimeBook ensures that the leftmost column will always start from today's date. Each unnumbered coloured block belongs to someone's schedule in the group. For example, the image below highlights all of Charlie's schedule. image::charlieBusyTimeslot.png[] Take note of the numbered green boxes you see below! [[FreeTimeSlot-Scheule]] image::freeTimeslot.png[] These are the common free time slot that you and your *entire* group members share! You can use these numbered green boxes to arrange your meetings or share it with your group members to pick. **** image:./icons/important.png[] Note that the labels for each of the coloured block will become hidden if each block becomes too small! To get more information about the coloured block, you can just hover your mouse over it! + **** === Tabs Tabs will contain your contacts and your groups. You can use it to see all your existing contacts and groups! image::tabs.png[] === Result Display Box This box shows you whether your command executed is successful or unsuccessful. If you encounter an error message here, look at our <> section to see what is the cause of error. image::resultDisplayBox.png[] === Command Box Type your commands here to execute them! image::commandBox.png[] === Suggestions Autocomplete TimeBook comes with a helpful feature that provides suggested commands or relevant values so you can spend less time typing commands and more time on your group meetings. When you type a command, TimeBook will show a dropdown with similarly matching commands. For example, you type in the command `add`. TimeBook will then suggest commands such as `addevent`, `addgroup`, `addperson` like so: image::command-suggestions/user-guide-example-step1.png[width=50%] If you meant to type the `addevent` command, you can immediately select it by pressing the kbd:[Tab] key. Otherwise, you can pick other options by using the kbd:[Up] or kbd:[Down] arrow keys and then hit the kbd:[Tab] key to confirm your selection. For now, try selecting the `addtogroup` command. TimeBook will complete the command like this: image::command-suggestions/user-guide-example-step2.png[width=50%] ***** image:./icons/lightbulb.png[] You can type an abbreviated version of the command as long as the letters are in order! For example, instead of typing `addtogroup`, try `atg`. ***** Remember how TimeBook can also suggest relevant values? Let's try that by specifying a person's name using the `n/` parameter like so: image::command-suggestions/user-guide-example-step3.png[width=50%] Again, TimeBook provides useful suggestions, in this case, the names of the people we've previously added. Now, try using the kbd:[Tab] key to immediately fill in ""Bobby"". image::command-suggestions/user-guide-example-step4.png[width=50%] Now, let's complete the `addtogroup` command. Let's add Bobby to the Friends group by typing `g/` and using the suggestions to help us pick the Friends group. [width=""100%"",cols=""^3,^1,^3"",frame=""none"",grid=""none"",valign=""middle""] |======= a|image::command-suggestions/user-guide-example-step5.png[] | –kbd:[Tab]–> a|image::command-suggestions/user-guide-example-step6.png[] |======= Let's say we change our mind and don't want to add Bobby to the Friends group. No problem, just remove Bobby's name and pick someone else using the familiar kbd:[Up], kbd:[Down] and kbd:[Tab] keys. TimeBook is smart enough to only fill in the name parameter and won't mess up the rest of your command. [width=""100%"",cols=""^3,^1,^3"",frame=""none"",grid=""none"",valign=""middle""] |======= a|image::command-suggestions/user-guide-example-step7.png[] | –kbd:[Tab]–> a|image::command-suggestions/user-guide-example-step8.png[] |======= Congratulations! You've now mastered the suggestions feature using just three simple keys, the kbd:[Up] and kbd:[Down] arrow keys to navigate between suggestions and the kbd:[Tab] key to select it. + The following sections will explain all the commands we have in TimeBook and what they do. [[Features]] == Commands ==== *Command Format* * Words in `UPPER_CASE` are the parameters to be supplied by you e.g. in `addperson n/NAME`, `NAME` is a parameter which can be used as `addperson n/John Doe`. * Items in square brackets are optional e.g `n/NAME [t/TAG]` can be used as `n/John Doe t/friend` or as `n/John Doe`. * Items with `…`​ after them can be used multiple times including zero times e.g. `[t/TAG]...` can be used as `{nbsp}` (i.e. 0 times), `t/friend`, `t/friend t/family` etc. * Parameters can be in any order e.g. if the command specifies `n/NAME p/PHONE_NUMBER`, `p/PHONE_NUMBER n/NAME` is also acceptable. ==== === Navigation ==== Home: `home` You can return back to the home page to see your upcoming schedule for today. Format: `home` ==== Switch tabs: `switch-tab` You can switch the tab of *Person* and *Group* using this command. Format: `switch-tab` ==== Viewing help: `help` Format: `help` ==== Exiting the program: `exit` Exits the program. + Format: `exit` ___ === Person Management [[edit-user-command]] ==== Editing your details: `edituser` [IMPORTANT] ==== When you first start using TimeBook, a default profile has been created for you! This default profile will have a default name: `User` To personalize TimeBook and make it yours, use the `edituser` command as described below. ==== ____ Lets start off by editing our profile by using the command `edituser`! ____ Format: `edituser [n/NAME] [p/PHONE] [em/EMAIL] [a/ADDRESS] [r/REMARK] [tag/TAG]...` **** * The `n/` prefix (optional) specifies your `name` ** Names must be alphanumeric * The `p/` prefix (optional) specifies your `phone number` ** Phone numbers must only contain numbers and must be at least 3 digits long * The `em/` prefix (optional) specifies your `email address` ** Emails should be of the format local-part@domain and adhere to the following constraints: 1. The local-part should only contain alphanumeric characters and these special characters, excluding the parentheses, (!#$%&'*+/=?`{|}~^.-) . 2. This is followed by a '@' and then a domain name. The domain name must: - be at least 2 characters long - start and end with alphanumeric characters - consist of alphanumeric characters, a period or a hyphen for the characters in between, if any. * The `a/` prefix (optional) specifies your `address` ** An address can take any values * The `r/` prefix (optional) specifies a `remark` ** A remark must be alphanumeric * The `tag/` prefix (optional) specifies your `tag` ** You can have multiple tags ** A tag must be alphanumeric and cannot contain spaces * At least one of the optional fields must be provided. * When editing tags, your existing tags will be removed (i.e. adding of tags is not cumulative). * You can remove all your tags by typing `tag/` without specifying any tags after it. **** Suppose our name is `Alice`, we can edit our profile like this! Example: * `edituser n/Alice p/91239123 a/Kent Ridge Drive em/alice@gmail.com r/Student` image::scheduler/edituser.png[width=100%] After editing our profile, this is what we should see! ==== Adding a person: `addperson` ____ The first thing to do in TimeBook is to add people that you know! It could be friends, family and even your colleagues! ____ To add a new person into TimeBook, simply use the command `addperson` and specify his or her name! You can also optionally specify his or her phone number, email address, home address, a remark and tags. Format: `addperson n/NAME [p/PHONE] [em/EMAIL] [a/ADDRESS] [r/REMARK] [tag/TAG]...` **** * The `n/` prefix specifies the `name` of the person to add * The `p/` prefix (optional) specifies a `phone number` * The `em/` prefix (optional) specifies an `email address` * The `a/` prefix (optional) specifies an `address` * The `r/` prefix (optional) specifies a `remark` * The `tag/` prefix (optional) specifies a `tag` ** A person can have multiple tags **** Suppose we met our new friend `Fred` and want to add him into TimeBook, simply use this command! Example: * `addperson n/Fred p/91234567 em/fred@example.com a/kent ridge drive r/friend tag/Friends tag/Colleague` image::scheduler/addperson.png[width=100%] After adding `Fred` into the TimeBook, his name will appear on the list of people on tabs in the side panel! ==== Editing a person: `editperson` ____ Accidentally added the wrong info of a person into TimeBook? No worries, you can simple edit an existing person with our `editperson` command! ____ To edit an existing person, simply use the `editperson` command and specify the name of the person you wish to edit with the `ed/` prefix! Then, simply edit each of the fields of a person with their corresponding prefixes! Format: `editperson ed/PERSON_NAME [n/NAME] [p/PHONE] [em/EMAIL] [a/ADDRESS] [r/REMARK] [tag/TAG]...` **** * The `ed/` tag specifies the person to be edited ** This person must exist in the TimeBook * At least one of the optional fields must be provided. * When editing tags, the existing tags of the person will be removed i.e adding of tags is not cumulative. * You can remove all the person's tags by typing `tag/` without specifying any tags after it. * Note: `TAG` cannot have white space in the argument. **** Suppose we added Fred's name wrongly, and he wants to be called `Freddie`. Additionally, he has also changed his phone number, and he wants to be your best friend! To update his particulars, simply execute this command! Example: * `editperson ed/Fred n/Freddie p/85868784 r/best friend tag/bestfriend` image::scheduler/editperson.png[width=100%] After editing a person, this is what you will see! Freddie's details has been updated accordingly! ==== Deleting a person: `deleteperson` ____ Want to delete a person from TimeBook? That's easy! Simply use our `deleteperson` command! ____ To delete a person from TimeBook, simply use the `deleteperson` command and specify the name of the person you wish to delete! Format: `deleteperson n/NAME` **** * the `n/` tag specifies the name of the person to be deleted * Only one person can be deleted at a time **** Suppose our business with Freddie is over, we can simply delete him from TimeBook! Examples: * `deleteperson n/Freddie` image::scheduler/deleteperson.png[width=100%] As you can see, after deleting Freddie, he is removed from our persons tab! // tag::showperson[] ==== Show person: `show` Want to arrange a private meeting with someone in TimeBook? You can see the schedule of this person up to 4 weeks in advance using the `show` command. + Format: `show n/NAME` **** * Shows the full name, address, email, phone number and schedule of this person. **** Example: . Type `show n/Bobby` in the command line as shown below: + + .Command box image::showpersoncommand.png[] . Hit the kbd:[Enter] key and you should see details of the person! You should see a window similar to the one below. + .Result after executing the `show` command for Bobby image::showpersonresult.png[] // tag::navigationforshow[] ***** image:./icons/lightbulb.png[] You can use the command `scroll` to help you scroll the schedule view without touching your mouse! image:./icons/lightbulb.png[] You can use the command `togglenext` see the schedule for next week! You may see this schedule up to 4 weeks in advance. After you've reached the fourth week's schedule, the next `togglenext` command will start back on the first week's schedule. image:./icons/important.png[] Unfortunately, TimeBook does not let you see a schedule that has already passed. ***** // end::navigationforshow[] // end::showperson[] === Schedule Management // tag::addmod[] // tag::addmod-short[] ==== Add Module to Schedule: `addmod` Want to add an NUS module to you or your friend's schedule on TimeBook? You can do so with the `addmod` command! If you already have your timetable on NUSMods, check out <>! Format: `addmod [n/NAME] m/MODULE_CODE cl/CLASS_1_TYPE:CLASS_1_NUMBER,...` **** * Currently supports academic year 2019/2020 and semester 1 only. * If the NAME is not provided, then the modules will be added to the default user, which is you! * image:./icons/warning.png[]: Just like adding a normal event via `addevent`, the module will only be added if the specified classes does not clash with any events in the person's schedule. **** Examples: * `addmod m/CS2103T cl/LEC:G01` + This adds CS2103T lecture G01 to your schedule. * `addmod n/John m/CS3230 cl/LEC:1,TUT:08` + This adds CS3230 lecture 1 and tutorial 08 to John's schedule. * `addmod n/John m/CS2100 cl/LEC:1,TUT:01,LAB:08` + This adds CS2100 lecture 1, tutorial 01 and lab 08 to John's schedule. // end::addmod-short[] *How do I add an NUS module to my schedule?* . Suppose you want to add CS3230 lecture 1 and tutorial 08 to your schedule. You can add the classes to your schedule easily by first typing `addmod m/CS3230 cl/LEC:1,TUT:08` into the command box, then pressing btn:[Enter] to execute it! + image::nusmods/addmod1.PNG[] . If you manage to successfully add the module and its classes into the person's schedule, you will see the person's schedule appearing with the newly added timeslots: + image::nusmods/addmod2.PNG[] // end::addmod[] // tag::addmods[] ==== Add Modules via NUSMods Link: `addmods` Already have your modules timetable on NUSMods? Great, you can easily add your modules timetable into TimeBook with the `addmods` command! Format: `addmods [n/NAME] link/NUSMODS_SHARE_LINK` **** * Reads the specified `NUSMODS_SHARE_LINK` to get the modules and classes, then adds the classes into the person's schedule. * If the NAME is not provided, then the modules will be added to the default user, which is you! * Currently supports academic year 2019/2020 and semester 1 only. * image:./icons/warning.png[]: Just like adding a normal event via `addevent`, the module will only be added if the specified classes does not clash with any events in the person's schedule. **** *Examples:* * `addmods link/https://nusmods.com/timetable/sem-1/share?CS2101=&CS2103T=LEC:G05&CS3230=LEC:1,TUT:08&CS3243=TUT:07,LEC:1&GEQ1000=TUT:D17` + This will add the modules in the NUSMods link to your schedule. * `addmods n/John link/https://nusmods.com/timetable/sem-1/share?CS2101=&CS2103T=LEC:G05&CS3230=LEC:1,TUT:08&CS3243=TUT:07,LEC:1&GEQ1000=TUT:D17` + This will add the modules in the NUSMods link to John's schedule. * `addmods n/Bob link/https://nusmods.com/timetable/sem-1/share?CS2101=&CS2103T=LEC:G05&CS3230=LEC:1,TUT:08&CS3243=TUT:07,LEC:1&GEQ1000=TUT:D17` + This will add the modules in the NUSMods link to Bob's schedule. *How do I add my team member John's NUSMods timetable to TimeBook?* . Well that is simple, add John's NUSMods timetable by first typing `addmods n/John link/` into the command box, then copy and paste his NUSMods link. Finally, press btn:[Enter] to execute it. + image::nusmods/addmods1.PNG[] . If the command succeeds, you will see John's schedule update with the newly added timeslots from his NUSMods timetable: + image::nusmods/addmods2.PNG[] // end::addmods[] ==== Add Event to Schedule: `addevent` ____ Have an event outside of your NUSmods timetable? Simply add them in using the `addevent` command! ____ To add an event into TimeBook, simply specify the name of that event, and the time slots of that event! Format: * `addevent [n/NAME] e/EVENT_NAME t/DATETIME...` **** * The `n/` (optional) prefix specifies the name of the person whom we want to add an event to. * If the `n/` prefix is not specified, TimeBook will add the event to your schedule! * The `e/` prefix specifies the name of the event to be added. ** An event name must be alphanumeric and must not be blank * The `t/` prefix specifies the time slot of that event. ** Format: `DATE-STARTTIME-ENDTIME-LOCATION` *** Date format: `ddMMyyyy` *** Start/End time format: `HHmm` *** Location: Can take in any values. ** An event can have multiple time slots. ** A time slot must be between `0800` to `2000` hrs. ** A time slot must not have a clash with an existing event. **** Suppose Bobby has to meet his project mates to work on his project, let's try adding that event into our TimeBook! Example: * `addevent n/Bobby e/Project Meeting t/10112019-1200-1400-COM1 t/13112019-1000-1200-AS6` image::scheduler/addevent.png[width=100%] After adding the event into our TimeBook, Bobby's schedule is automatically updated! ==== Delete an Event from a Schedule: `deleteevent` ____ What should I do if an event is cancelled? Simply delete it from TimeBook with our `deletevent` command! ____ To delete an event, simply execute the `deleteevent` command and specify the event to delete and the person to delete it from! Format: * `deleteevent [n/NAME] e/EVENT_NAME` **** * The `n/` (optional) prefix specifies the name of the person whom we want to delete an event from. * If the `n/` prefix is not specified, TimeBook will try to delete the event from your schedule! * image:./icons/lightbulb.png[] You can delete a module by specifying the module code! A module's event name is its module code! **** Suppose Bobby wants to drop CS2105 from his timetable as he finds it too hard to cope with so many modules. We can simply delete it! Example: * `deleteevent n/Bobby e/CS2105` image::scheduler/deleteevent.png[width=100%] After deleting that event from TimeBook, Bobby's schedule is automatically updated! //tag::schedule-command[] ==== Generate a Schedule: `schedule` ____ Want to see a schedule between you and your friends? Simple use the `schedule` command! ____ To generate a schedule for you and your friends, simply execute the `schedule` command and specify who to add to this schedule! Format: * `schedule n/NAME...` **** * The `n/` prefix specifies the name of the person whom we want to add to this schedule * You can add multiple people into a schedule **** Lets try and generate a schedule between you, Bobby and Charlie! Execute the following command! Example: * `schedule n/Bobby n/Charlie` image::scheduler/schedule.png[width=100%] When executing the command, TimeBook will calculate the free time slots among the schedule members! //end::schedule-command[] === Group Management ==== Adding a group: `addgroup` ____ In TimeBook, we allow you to organise your contacts too! This can be done through making groups! This can be done using our `addgroup` command! ____ To add a new group into TimeBook, simply execute the `addgroup` command and specify the name of the group you want to make! Format: * `addgroup g/GROUP_NAME [d/GROUP_DESCRIPTION] [role/USER_ROLE]` **** * image:./icons/important.png[] Whenever a new group is created, you are automatically added into that group! * The `g/` prefix specifies the name of the group you want to create. ** A group name must be alphanumeric * The `d/` prefix (optional) gives a description to the group ** A group description must be alphanumeric * The `role/` prefix (optional) specifies the role you play in that group ** A role must be alphanumeric **** Suppose you want to create a new group for your CS2103 project, and you are appointed as the leader for this group! Let's try to add a new group with the following command! Example: * `addgroup g/CS2103 d/A CS2103 project group role/Leader` image::scheduler/addgroup.png[width=100%] When a new group is added, it is automatically added into the list of groups! ==== Editing a group: `editgroup` ____ The details for your group has changed? Edit it with our `editgroup` command! ____ To edit an existing group, simply use the `editgroup` command and specify the name of the group you wish to edit with the `ed/` prefix! Format: `editgroup ed/GROUP [g/GROUP_NAME] [d/GROUP_DESCRIPTION] [role/USER_ROLE]` **** * The `ed/` tag specifies the group to be edited ** This group must exist in the TimeBook * At least one of the optional fields must be provided. **** Suppose we entered the details for our group wrongly, no worries we can edit them! Example: * `editgroup ed/CS2103 g/CS3203 d/A CS3203 project group role/Member` image::scheduler/editgroup.png[width=100%] When a group is edited, it is automatically updated as shown above! ==== Add Person to Group: `addtogroup` ____ After you have created your group, you can add people into the group with our `addtogroup` command! ____ To add a person into a group, simply execute the `addtogroup` command, and specify the person's name and the group's name! Format: `addtogroup n/PERSON_NAME g/GROUP_NAME [role/ROLE]` **** * The `n/` prefix specifies the name of the existing `person` in TimeBook * The `g/` prefix specifies the name of the existing `group` in TimeBook * The `role/` prefix (optional) specifies the role this person would play in the group **** Let's add a new person Denise into our CS3203 project group! Example: * `addtogroup n/Denise g/CS3203 role/Manager` image::scheduler/addtogroup.png[width=100%] When a new person is added into the group, it automatically updates the group's schedule as well! ==== Delete a Person from Group: `deletefromgroup` ____ What if I want to remove a person from my group? You can! With our `deletefromgroup` command! ____ To delete a person from a group, simply execute the `deletefromgroup` command, and specify the person's name and the group's name and the person will be removed from the group! Format: * `deletefromgroup n/NAME g/GROUP_NAME` **** * The `n/` prefix specifies the name of the `person` * The `g/` prefix specifies the name of the `group` * This person must be in the group * image:./icons/important.png[] deleting a person from group does not delete your contacts! Your contacts still exists in your persons tab! **** Let's remove Charlie from our group! We can simply execute the following command! Example: * `deletefromgroup n/Charlie g/CS3203` image::scheduler/deletefromgroup.png[width=100%] When a person is removed from the group, the group's schedule will automatically be updated as well! ==== Deleting a group: `deletegroup` ____ The project is over, and there is no need for this group anymore? Delete it! ____ To delete a group, simply execute the `deletegroup` command and specify the group's name! Format: * `deletegroup g/GROUP_NAME` **** * The `g/` prefix specifies the name of the `group` * image:./icons/important.png[] deleting a group does not delete your contacts! Your contacts still exists in your persons tab! **** Let's delete CS3203 group from our TimeBook! Simply use this command! Example: * `deletegroup g/CS3203` image::scheduler/deletegroup.png[width=100%] Deleteing a group will automatically update your groups tab! // tag::showgroup1[] ==== Show group: `show` Want to see your group's schedules to plan for your next group meeting? The `show` command is what you need to see the schedules of your group members! You can view a group's schedule up to 4 weeks in advance. + Format: `show g/GROUP_NAME` **** * Shows the description, members and aggregated schedules for this group. **** // end::showgroup1[] [IMPORTANT] ==== include::UserGuide.adoc[tag=alice-full] ==== // tag::showgroup2[] Examples: . Let's say you want to organise a group meeting for a group named CS2103. Simply enter `show g/CS2103` in the command line as shown below + + .Command box image::showgroupcommand.png[] . Hit the kbd:[Enter] key and you should see the details of this group in a similar window below. + [[showgroupresult]] .Result after executing `show g/CS2103` image::showgroupresult.png[sgr,900,600] include::UserGuide.adoc[tag=navigationforshow] ==== Look at some members: `lookat` Suppose that all of your group members are extremely busy and the common free time is too short to do any productive work, you may use the `lookat` command to see if you can meet with some of your group members. You *must* be viewing a group's schedule in order for this command to work. Format: * `lookat [n/Name]...` The `lookat` command takes in any number of `n/Name` arguments and highlights the group members according to name. Example: Let's use the same schedule exactly like the one shown <<#showgroupresult, above>>. * Type `lookat n/Bobby n/Denise` if you are interested to inspect both Bobby's and Denise's schedules! You should see that both of these schedules become highlighted. .Zoom in of Bobby and Denise's schedule image::lookatgroupresult.png[lagr,800,500] ***** image:./icons/important.png[] *Empty blocks* represent the free time slots for the group members that you are looking at. The green blocks still represent the common free time slots for the entire group! ***** // end::showgroup2[] === Advanced Features // tag::showmod[] ==== Show Module: `showmod` Want to know more information about an NUS module? Use `showmod` to quickly open up the NUSMods page for a specific module on your browser! Format: `showmod m/MODULE_CODE` **** * image:./icons/warning.png[]: This command requires internet connection. **** Examples: * `showmod m/CS2103T` + Opens up https://nusmods.com/modules/CS2103T on your default browser. * `showmod m/CS2101` + Opens up https://nusmods.com/modules/CS2101 on your default browser. // end::showmod[] ==== Export: `export` Want to share a schedule with your friends? This command exports a visualisation representation of the schedule (timetable) of a group or person to a PNG file! + **** image:./icons/warning.png[] Take note when exporting a person's schedule, *sensitive information* are omitted. Only the person's schedule is exported. image:./icons/warning.png[] Take note that if you are exporting a group's schedule, the *entire* group's schedule will be exported. If you have used the `lookat` command, this command disregards it. **** Format: * Simply enter the `export` command to export the currently shown schedule in TimeBook! + //tag::select-command[] ==== Select Time Slot: `select` ____ Want to get more information about a particular time slot? Want to know where the venue of that time slot is? No worries! Simply select the time slot and TimeBook will tell you all about it! ____ When viewing a schedule on TimeBook, you can select a time slot to get more information out of it! The `select` command works when you are viewing a group's schedule, person's schedule or home page! The format for this command's use are detailed below! Format (group schedule): `select n/NAME [week/WEEK_NUMBER] i/ID` * Selects a time slot specified by `ID` that belongs to a person specified by `NAME`, on week `WEEK_NUMBER` Format (person schedule): `select [week/WEEK_NUMBER] i/ID` * Selects a time slot specified by `ID` on week `WEEK_NUMBER` that belongs to the current person shown in the schedule * If a name is specified, TimeBook will ignore it! Because we know you want to view the current person that is shown! Format (home): `select i/ID` * Selects a time slot specified by `ID` on your home page. The home page will not show the ID of the time slot, the `ID` is ordered with the earliest time slot as `ID:1` * If a person name or week is specified, TimeBook will ignore it! Because we know you want to view the time slots on your home page! Prefixes: * `n/`: specifies the name of a person ** A name must be alphanumeric * `week/` specifies the week of the schedule (optional) ** A week must be an interger between 1 and 4 inclusive ** If no week number is specified, TimeBook will choose the default week 1 * `i/`: specifies the ID number of the time slot ** An ID must be a positive number. When you execute the `select` command, it generates a pop up window that shows you the details of the selected time slot! We have also integrated this service with GoogleMaps and shows you the location of this time slot on the map! The figure below shows how a pop up window will look like! image::scheduler/selectpopup.png[width=100%] After you have viewed the time slot details, simply press the `ESC` key on your keyboard, and it will close the pop up! You will never have to touch your mouse! | image:./icons/important.png[] | When the location of the time slot is not a valid location in NUS, the location will not be shown on the map! The following shows some example usage! image::scheduler/select1.png[width=100%] When a group's schedule is shown, each members time slots are colour coded as shown above. Each time slot is also labeled with an ID for easy reference! Let us try to select Bobby's time slot 1. To select it, simply execute the following command! Example: * `select n/Bobby i/1` After executing that command, a pop up will be shown just like the one above! image::scheduler/select2.png[width=100%] When a person's schedule is shown, each events are colour coded as shown above. Each time slot is also labeled with an ID for easy reference! The name of the event is also shown! Let us try to select time slot 1. To select it, simply execute the following command! Example: * `select i/1` After executing that command, a pop up will be shown just like the one above! image::scheduler/select3.png[width=100%] When the home page is shown, you can select each time slot on the list! Do note that the first time slot on the list will have `ID:1` and the following time slots will follow with the next number. We chose to omit the number so you have a more cleaner home page! Simply execute the `select` command and specify the time slot you want to view like so: Example: * `select i/1` After executing that command, a pop up will be shown similar to the one above! //end::select-command[] //tag::Closest-Common-Location[] [[Closest-Common-Location]] === Closest Common Location TimeBook will also help you to decide where to meet for your project meetings by suggesting to you an optimal location for everyone. The optimal location is the closest location for everyone to meet in NUS based on their schedule. In time book we define the optimal location for everyone as the _closest common location_. *Steps* . Set up your group by: .. Adding your group members to your TimeBook with `addperson` command .. Adding your group to TimeBook with `addgroup` command .. Add your group members to your group with `addtogroup` command . Get the relevant information for your group schedule with `show g/[GROUP_NAME]` .. Identify the `ID` and `Week` of the time slot you want to get the closest common location for. . With the free time slot `id` and `week` get the details for the closest common location with `selectfreetime` command . Press `esc` button to close the popup *Constraints* Due to the lack of internet connectivity, TimeBook will only support locations that are in NUSMods and identifiable by Google Maps. The full list of supported locations is <>. *Definitions* . We define closest common location as the location that requires the least average distance to travel to and from different sources by car. . Locations that are not supported are voided and are not used for the calculations of the closest common location and average travelling distance. . Refer to the `Developer Guide` on how we computed the closest common location. ==== Select Free Time `selectfreetime` Select a free time slot to launch a popup window with all the relevant information to help you make decide on the venue to conduct your project meetings at. The image below is an example of the popup. Below is an example of a popup. [#img-SuccessfulPopup] .An example of a popup when `selectfreetime` is executed image::gmaps/SuccessfulPopup.png[SuccessfulPopup] command: `selectfreetime [week/WEEK_NUMBER] i/FREETIMESLOTID` Examples: * `selectfreetime i/3` * `selectfreetime week/2 i/3` _Description_ When the command is executed, a popup will appear that shows all the information of the closest common location for a particular free time slot in a group. _Prerequisite_ . You must be have group on TimeBook with members in it. . You must execute `show g/[GROUP NAME]` before executing `selectfreetime` command. _Parameters_ . `[WEEK_NUMBER]` - Description: The week(1-4) of the group schedule you want to select the free time slot from. If parameter is not stated, it will default to the first week(the default schedule when you execute `show g/GROUP_NAME`). - Type: `Integer` - Enum: `1`, `2`, `3`, `4` . `FREETIMESLOTID` - Description: ID of the free time slot in the <>. You can get this from the number in the free time slot box. You can only enter the `id` that is shown on the screen. - Type: `Integer` _Success Response_ If you follow the steps above, a popup will appear as seen in the Figure above. There are two main information that you will see in the popup when you execute the command. . The summary of the results that will be `displayed` on the top of the popup. .. *Your best location to meet up is:* The first choice location to meet(closest for everyone). .. *Everyone's locations:* List of locations that the group members will be at before the free time slot. .. *Out of all these locations, the valid locations are:* List of TimeBook supported locations that the group members will be at before the free time slot that. ... Subset of the *Everyone's locations:* list .. *Locations that cannot be found in NUS:* List of locations that the group members will be at before the free time slot but not supported by TimeBook. ... Subset of the *Everyone's locations:* list ... If all the locations are valid, this attribute will be empty as seen in the Figure above . The full details of the first, second and third closest common location will be shown at the bottom of the popup. .. First choice represents the first closest and so on and so forth. .. The average distance(m) to reach the various locations will be displayed below the respective choices. .. The picture of the location of the venue on Google Maps will be displayed below each choice. ... For locations that are not supported on Google Maps, a picture of the center of NUS will be displayed. _Failure Response_ - `Error` when all the source locations are not recognised by TimeBook, a popup will not appear. Feedback box will show: ``` We could not find a common location because all places cannot be found in NUS. The locations are: ``` - `Error` when all the group members are not in school before the free time slot, a popup will not appear. Feedback box will show: ``` We could not find a common location because: Everyone has not started their schedule yet. Feel free to meet up any time. ``` - `Error` when invalid free time slot `ID` entered. Feedback box will show: ``` Invalid time slot ID: 0. Please enter a valid id as shown in the GUI. ``` - `Error` when invalid `GROUP_NAME` entered. Feedback box will show: ``` Cannot recognise GROUP_NAME. Make sure you entered the correct value. ``` ==== Close popup `esc` After you are done with viewing the information on the popup press `esc` button on your keyboard to close the popup and and return to the main screen. Format: kbd:[esc] button on keyboard. // end::Closest-Common-Location[] === Upcoming schedule list. Unsure of what is your next event for the day? TimeBook's home page has a list that keeps track of your upcoming events for the day and would automatically tick off events that have past! Format: `home` === Saving the data TimeBook data are saved in the hard disk automatically after any command that changes the data. + There is no need to save manually. == FAQ [qanda] [[alice-notice]] Who is Alice? / How do I store my details and schedule?:: // tag::alice-full[] // tag::alice-brief[] When you first start using TimeBook, it will create a hidden person called `Alice` to store your details and schedule. This profile will be a member of every group you create. Note that you, as a user, are not present in TimeBook's contacts list! // end::alice-brief[] + {nbsp} + To personalize TimeBook and make it yours, rename `Alice` by entering the command `edituser n/Your Name Here`. If you'd like to fill in more details, you can do so using the <> command. // end::alice-full[] + {nbsp} + How do I transfer my data to another Computer?:: Install the app in the other computer and overwrite the empty data file it creates with the file that contains the data of your previous TimeBook folder. + {nbsp} + Why can I enter irrelevant arguments?:: We understand that users occasionally make error while typing and it is frustrating for the application to fail because of it. Thus for all commands that do not require any arguments(ie `help`, `home` and `exit`), TimeBook allows you to enter any value after the command word. For example `help 1` will execute `help` command eventhough `1` is irrelevant to the command. We hope with this feature you will have a seamless and pleasant experience with TimeBook. + {nbsp} + Help! I encountered an error!:: We understand that you may encounter a weird error message and are unsure of what it means so we prepared this section that describes the uncommon errors that you may see. [cols=""25h, ~""] |=== |Error message |What it means: | Invalid timing arguments | Ensure that the time you provide as argument follow the format. Example: 11 Nov 2019, 0800 to 0900 is represented as 11112019-0800-0900 | Clash in events | There is already a pre-existing event that is happening at that time slot. | Duplicate Mapping | This person is already in the group. | Cannot find closest location | The closest common location cannot be determined because everyone is not in NUS. | XXX does not exist | This person or group does not exist in TimeBook. Some names are case-sensitive. | No schedule to XXX | This error occurs when you use `scroll` and `togglenext` command when there is no schedule shown. | No group schedule is shown | You'll see this error when you are invoking the `look at` command when a group schedule is not displayed. | Internal Error. Please try again later | You'll see this error when our remote database cannot handle your requests. |=== {nbsp} + == Command Summary *Navigation* * *Return to Home page* : `home` * *Switch tabs* : `switch-tab` * *Viewing help* : `help` * *Exiting the program* : `exit` *Person Management* * *Edit your details* : `edituser` * *Add Person* `addperson n/NAME [p/PHONE] [em/EMAIL] [a/ADDRESS] [r/REMARK] [tag/TAG]...` + e.g. `addperson n/James Ho p/22224444 em/jamesho@example.com a/123, Clementi Rd, 1234665 r/Always helpful tag/friend tag/colleague` * *Edit Person* : `editperson ed/PERSON_NAME [n/NAME] [p/PHONE] [em/EMAIL] [a/ADDRESS] [r/REMARK] [tag/TAG]...` + e.g. `editperson ed/James Lee em/jameslee@example.com` * *Delete Person* : `deleteperson n/NAME` + e.g. `deleteperson n/Benedict` * *Show Person* : `show n/NAME` + e.g. `show n/James Jake` *Schedule Management* * *Add Module to Person's Schedule* : `addmod n/NAME m/MODULE_CODE class/CLASS_NUMBERS(comma-separated) [ay/ACADEMIC_YEAR] [s/SEMESTER]` + e.g. `addmod n/John m/CS2103T class/G01,T5 ay/2019/2020 s/1` * *Add Modules to Person's Schedule via NUSMods Link* : `addmods n/NAME l/NUSMODS_SHARE_LINK` + e.g. `addmods n/John l/https://nusmods.com/timetable/sem-1/share?CS2101=&CS2103T=LEC:G05&CS3230=LEC:1,TUT:08&CS3243=TUT:07,LEC:1&GEQ1000=TUT:D17` * *Show Module Classes Schedule* : `showmod m/MODULE_CODE [ay/ACADEMIC_YEAR] [s/SEMESTER]` + e.g. `showmod m/CS3230 ay/2019/2020 s/2` * *Add Event to Person's Schedule* : `addevent n/NAME e/EVENT_NAME t/DATETIME...` + e.g. `addevent n/John e/Math Lecture t/26092019-1300-1400` * *Delete Event* : `deleteevent [n/NAME] e/EVENT_NAME` + e.g. `deleteevent n/Bobby e/CS2105` * *Generate Schedule* : `schedule n/NAME...` + e.g. `schedule n/Bobby n/Charlie` *Group Management* * *Add Group* `addgroup g/GROUP_NAME [d/GROUP_DESCRIPTION] [role/USER_ROLE]` + e.g. `addgroup g/CS2103 d/A CS2103 project group role/Leader` * *Add Person to Group* : `addtogroup n/PERSON_NAME g/GROUP_NAME [role/ROLE]` + e.g. `addtogroup n/Denise g/CS3203 role/Manager` * *Edit Group* `editgroup ed/GROUP [g/GROUP_NAME] [d/GROUP_DESCRIPTION] [role/USER_ROLE]` + e.g. `editgroup ed/CS2103 g/CS3203 d/A CS3203 project group role/Member` * *Delete Group* : `deletegroup g/GROUP_NAME` + e.g. `deletegroup g/CS2103` * *Show Group Details and Schedule* : `show g/GROUP_NAME` + e.g. `show g/CS2030` *Advanced Features* * *Export Visual Representation* : `export-vr [n/NAME]… [g/GROUP_NAME]… o/SAVE_LOCATION` + e.g. `export-vr g/TimeBook o/timetable.jpg` * *Select Time slot* : `select n/NAME [week/WEEK_NUMBER] i/ID` + e.g. `select n/Bobby i/1` * *Closest Location* : `closestlocation l/LOCATIONA LOCATIONB ...` + e.g. `closestlocation l/LT16 LT15 AS5` * *Select Free Time Slot* : `selectfreetime [week/WEEK_NUMBER] i/FREETIMESLOTID` + e.g. `selectfreetime i/1` [[Supported-Locations]] == Supported Locations !=== 10+|Valid Locations| |AS4-0116|AS3-0214|AS3-0213|AS3-0303|AS3-0212|AS3-0302|AS1-0303|AS1-0302|AS5-0309|LT9 AS1-0304|AS6-0214|AS5-0205|AS2-0413|AS3-0215|LT12|AS7-0119|AS4-0118|LT11|AS1-0209| AS4-0109|LT14|AS6-0212|AS1-0203|AS1-0208|AS4-0601|AS5-0202|AS4-0206|AS7-0102|AS8-0402| UTSRC-SR5|UTSRC-SR2|UT-AUD1|ERC-SR9CAM|ERC-SR8|ERC-GLR|AS3-0306|ERC-SR10|UTSRC-SR3|TP-SR1| UTSRC-GLR|UTSRC-SR6|UTSRC-SR7|TP-GLR|AS6-0333|AS1-0211|AS6-0338|AS4-0119|AS1-0205|AS7-0106| AS3-0309|AS4-0604|AS1-0301|AS1-0213|AS4-0335|TP-SR8|UTSRC-LT51|AS8-0401|AS6-0215B|AS1-0207| AS7-0101|LT10|AS1-0201|NAK-AUD|ERC-SR11|UTSRC-SR1|UTSRC-LT52|AS4-0603|ERC-ALR|UTSRC-SR9| UTSRC-SR4|LT8|S16-0435|S16-0437|LT7A|LT28|E3-06-02|E3-06-03|S16-0304|AS2-0510| UTSRC-SR8|AS2-0509|AS3-0304|AS4-0117|AS2-0312|AS7-0117|AS8-0405|AS2-0311|AS5-0203|LT13| AS3-0308|AS2-0316|AS2-0313|AS2-0203|AS2-0204|AS2-ELAB|AS2-0302|AS1-0524|AS3-0307|AS4-0602| AS8-0646|AS1-0204|AS3-0305|AS3-0523|TP-SR2|AS7-0201|AS4-0208|CHPC|AS7-0201A|AS4-B107| AS4-B109|AS4-B110|AS1-0212|AS4-0115|AS1-0210|AS8-0647|AS3-0209|AS4-0519|AS4-0318|BIZ1-0301| BIZ1-0303|BIZ1-0302|BIZ1-0307|BIZ1-0202|BIZ1-0204|BIZ1-CMRI|BIZ1-0305|BIZ1-0205|BIZ1-0201|BIZ1-0304| BIZ1-0203|BIZ2-0413A|HSSMLCR|BIZ2-0509|BIZ1-SR6-1|BIZ2-0510|BIZ2-0413C|BIZ1-0206|BIZ2-B104|BIZ2-0301| BIZ2-0118|BIZ2-0114|LT17|LT16|BIZ2-0202|BIZ2-0224|BIZ2-0404|BIZ2-0420|BIZ2-0228|BIZ2-0117| BIZ1-SR6-4|LT19|LT18|BIZ2-0226|BIZ2-0227|BIZ2-0302|BIZ2-0413B|BIZ2-0303|BIZ2-0201|BIZ2-0229| I3-AUD|COM1-VCRM|SR_LT19|COM1-0206|LT15|COM1-0204|COM1-0201|COM1-0210|COM1-B103|COM1-0114| COM1-0208|COM2-0108|I3-0336|I3-0338|I3-0344|COM1-B112|COM1-0113|I3-0339|COM1-B108|COM1-B111| COM1-B110|AS6-0421|LT7|COM1-0209|UT-AUD2|AS6-0211|COM1-0203|COM1-0207|COM1-0212|COM1-B113| COM1-B102|COM1-0216|COM1-0217|AS6-0210|AS6-0208|AS3-0611|AS3-0610|COM1-0120|AS3-0620|S16-0436| LT26|COM1-B109|RMI-SR1|I3-0337|SDE2-ER1|SDE-ER5|UTSRC-LT53|UTSRC-LT50|SDE1-ISD-1|LAW_SR3| NHM-1M-03|UT-AUD3|AKIMAUD|UT22-07-02|SDE4-GISL1|SDE-ER4|SDE2-MEZZ|AKI5B|SDE2-ES1|SDE2-ES2| AKIMLA4|TP-SR3|WT-Lab|GBT-Lab|SDE-EXR-2|SDE4-EXR1-2|SDE4-EXR-2|SDE4-EXR-1|E2-03-02|E1-06-02| E1-06-06|E1-06-13|E5-03-22|E3-06-04|E5-03-21|E3-06-11|E3-06-01|E4-04-04|ENG-AUD|E2A-03-01| E2A-02-02|E2A-02-01|E2A-03-02|E2A-04-02|E2A-04-03|E3-06-08|E1-06-10|E3-06-12|E3-06-10|E3-06-13| E5-03-23|E1-06-16|E3-06-14|E1-06-15|E1-06-11|E1-06-12|E4-04-02|E2-0308PC5|E2-0309PC6|LT2| E4-02-06|EA-06-04|EA-02-11|EA-06-02|EA-06-05|EA-06-03|LT6|E3-06-05|E1-06-08|E5-03-20| E1-06-01|LT4|E1-06-07|E1-06-04|E1-06-05|E1-06-09|EW2-04-02|E1-06-03|E5-03-19|E3-06-07| E2-0307PC4|LT3|E5-03-24|E2-0306PC3|E3-06-09|LT1|E4-03-07|E4A-06-03|E3-06-15|E4-02-01| E4-04-03|E3-05-21|E3-03-01|EA-06-06|E1-0410PC2|E3A-05-03|E3A-05-04|E3A-05-07|E5-02-32|EA-04-21| EA-06-07|EA-04-22|EA-04-07|EA-04-06|E3-04-02E|E3-04-02L|E1A-01-06|EA-02-21|EA-04-04|E1-06-0506| E5-0320-21|E3-06-06|EW1-03-02|EW1-02-03|EW1-04-02|EW1-01-01|EW2-03-14|EW1-1M-03|EW1-1M-02|LAW_SR5-3| LAW_SR5-4|LAW_SR4-1|LAW_SR5-2|FED-01-02|LAW_SR5-1|LAW_ESR|LAW_SR4-2|LAW_SR4-3|LAW_SR5-5|LAW_CR3-5| TB-08-01R|LAW_SR4-4|LAW_CR3-4|LAW_LT|LAW_CR4-2|LAW_CR5|LAW_CR3-6|LAW_CR4-1|LAW_CR2-1|LAW_CR3-3| LAW_CR2-2|LAW_CR3-7|LT33|MD10-01-01|LT34|S14-0619|S16-0430|S16-0307|LT29|MD7_LAB8| LT20|MD7-02-03|MD4-02-03E|MD4_LAB9|S14-0620|MD1-03-01B|MD1-07-01A|LT21|LT32|S1A-0217| MD9-01-02|CELS-04-01|LT28-01-01|YSTCM-TR|YSTCM-RS|YSTCM-SR2|YSTCM-SR8|YSTCM-WS|YSTCM-OH|YSTCM-ER3| YSTCM-HALL|YSTCM-MLAB|YSTCM-SR4|YSTCM-SR7|YSTCM-ER2|YSTCM-ER6|YSTCM-ER1|YSTCM-SR1|YSTCM-SR5|YSTCM-RECS| YSTCM-SR3|YSTCM-SR6|YSTCM-ER4|S16-03-0506|S16-0598|S16-0309|S2-0414|S2-0415|S2-04LAB5|S1A-03LAB1| S1A-04LAB3|S2-03LAB7|S13-M-08|S13-M-09|S1A-03LAB2|LT31|S1A-04LAB4|S16-0431|S8-0314|S5-01PHYS| S5-0224|S5-0410|S8-0402|S7-0401|S14-0503|S5-01GEN|S17-0406|S17-0405|S17-0512|S17-0511| S17-0404|S17-0611|S17-0304|S17-0302|MD1-06-03M|MD1-05-01A|MD1-06-01A|S4-02LAB|MD1-05-03K|S16-0440| S4-04LAB|S12-0403|S11-0204|S11-0301|S12-0402A|S12-0402B|S12-0402C|S12-0402D|S11-0302A|S12-0401| S11-0401A|S13-0313|S12-0402|E4-07-08|S11-0302|S16-06118|S16-05102|S16-05101|LKY_SR3-5|LKY_SR3-1| LKY_SR2-1|LKY_EA_M|LKY_SR2-2|LKY_SR2-3|LKY_SR3-4|LKY_TB10SR|LKY_EE_CSU|LKY_SR3-3|CELS-01-08|CQT/SR0315| USP-TR1|USP-SR1|USP-SR2|USP-SR3|USP-TR2|UTSRC-PR1|TC-TR2|TC-SR6|TC-SR3|TC-SR4| TC-SR5|CAPT-SR5|CAPT-SR1-2|CAPT-SR3|CAPT-SR6|RC4-SR1-2|RC4-SR3|RC4-SR5|RC4-SR4|RVR_MPR1| RVR_MPR2|RVR-SRM04|RVR-SRM03|RVR-SRM02|RVR-SRM01|MD1-08-01E|MD1-0801AB|MD1-0903EF|MD1-09-01A|MD1-09-01B| MD1-08-03E|MD1-08-01B|Y-CR21|Y-CR19|Y-CR9|Y-GLRm1|Y-PracRm6|Y-CR13|Y-CR18|Y-CR22| Y-CR17|Y-KChanrai|Y-CR6|Y-LT1|Y-TCTLT|Y-CR8|Y-CR20|Y-CR2|Y-CR12|Y-CR5| Y-CR14|Y-CR4|Y-CR15|Y-GLRm2|Y-CR3|Y-PgRm1|Y-CR7|Y-ArtsStud|Y-PgRm2|Y-CompLab| Y-CR11|Y-PerfHall|Y-AChemLab|Y-OChemLab|Y-CR1|Y-CR23|Y-CR16|E3-0605-06|E2-03-03|E4A-04-08| E1-06-14|CELC-SR1A|CELC-TR6|BIZ2-0115|BIZ2-0116|BIZ2-0112|CAPT-SR4|RC4-SR6|TH-SR1|KEVII-MR2| RH-CONF-RM|KRH-SR3|SH-SR1|AS3-0314|AS3-0312|AS3-0208|AS3-0316|ISS/3-12|ISS/2-9|ISS/4-6| ISS/3-3|ISS/2-1|ISS/AUD|ISS/3-1|ISS/3-5|ISS/4-4|TP-SR7|TP-SR4|TP-SR5|TP-SR6| !=== ",16134,True,2601.3204187216343,median "package away3d.core.math { public class PoissonLookup { private static var _distributions:Vector.>; public static function initDistributions():void { // precalculated for best control _distributions = new Vector.>(); _distributions[0] = new [0.3082841, 0.4320919]; _distributions[1] = new [0.3082841, 0.4320919, -0.2274942, -0.6640266]; _distributions[2] = new [0.8742689, 0.0009265686, -0.6864116, -0.5536607, -0.2325206, 0.7678371 ]; _distributions[3] = new [0.3913446, -0.7084417, -0.7511101, -0.5935929, -0.2323436, 0.5320091, 0.8435315, 0.5035911 ]; _distributions[4] = new [0.2122471, -0.5771395, -0.8543506, -0.1763534, 0.5189021, 0.8323698, -0.3616908, 0.5865368, 0.9523004, -0.04948437]; _distributions[5] = new [0.5791035, 0.3496495, 0.2959551, -0.6006749, -0.2419119, -0.06879545, -0.7403072, 0.6110353, -0.04555973, 0.8059174, -0.5275017, -0.737129]; _distributions[6] = new [0.06941478, 0.8519508, -0.7441907, 0.2426432, 0.6439992, -0.2405252, -0.1007523, -0.2327587, -0.6427067, -0.7248485, 0.8050759, 0.5492936, 0.3573822, -0.8824506]; _distributions[7] = new [0.8509863, 0.4452587, -0.09507271, 0.2073005, 0.1706571, -0.6434793, 0.8029777, -0.2718274, -0.4401725, 0.8196304, 0.2715359, 0.8598521, -0.8121575, -0.006447683, -0.6486837, -0.7237598]; _distributions[8] = new [0.6951686, -0.2680728, -0.04933243, 0.3710589, 0.6592212, 0.3661054, -0.01579228, -0.6909603, -0.3275101, -0.1756866, 0.3811549, 0.9218544, -0.216032, 0.9755028, -0.7065172, 0.3355389, -0.6579109, -0.6798355]; _distributions[9] = new [0.6181276, -0.09790418, -0.2537868, -0.5570995, -0.1964931, 0.3459414, 0.3474613, -0.8885581, 0.5135743, 0.5753114, -0.9549091, 0.1480672, -0.8711916, -0.4293123, -0.6928071, 0.6190156, -0.13369, 0.8892705, 0.0548224, -0.1246777]; _distributions[10] = new [0.4853027, -0.5080479, -0.1331675, -0.506597, 0.139575, 0.01316885, 0.803486, -0.07568797, 0.5240274, 0.4883182, -0.4334005, 0.1207938, -0.7794577, -0.3985141, 0.1576432, -0.9861221, -0.3712867, 0.6959021, 0.1517378, 0.9847429, -0.9762396, 0.1661073]; _distributions[11] = new [-0.2790166, -0.01252619, 0.3389016, 0.3921154, 0.2408341, -0.313211, -0.8151779, -0.3898362, -0.6347761, 0.3486495, 0.09471484, -0.7722448, -0.1385674, 0.6364574, 0.2456331, 0.9295807, -0.3864306, -0.8247881, 0.6111673, -0.7164014, 0.8287669, 0.05466961, 0.837706, 0.5415626]; _distributions[12] = new [0.056417, 0.3185693, -0.8245888, 0.1882799, 0.8575996, 0.1136829, 0.1070375, 0.875332, 0.4076743, -0.06000621, -0.4311306, 0.7239349, 0.2677574, -0.538472, -0.08486642, -0.2083647, -0.888989, -0.3906443, -0.4768958, -0.6664082, 0.09334993, -0.9861541, 0.808736, -0.455949, 0.5889823, 0.7660807]; _distributions[13] = new [-0.2681346, -0.3955857, -0.1315102, -0.8852947, -0.5143692, 0.09551838, 0.4344836, -0.546945, -0.8620899, -0.3813288, 0.1650431, 0.02034803, -0.1543657, 0.3842218, -0.828457, 0.5376903, -0.6145, -0.7818927, -0.2639062, 0.8784655, 0.1912684, 0.9720125, 0.3135219, 0.5224229, 0.7850655, 0.4592297, 0.7465045, -0.1368916]; _distributions[14] = new [0.4241029, 0.695281, 0.150511, -0.02304107, -0.2482675, 0.9120338, 0.8057325, 0.2622084, -0.2445909, 0.2765962, 0.8588713, -0.1772072, 0.3117845, -0.4385471, -0.3923851, -0.3298936, -0.1751254, -0.7405846, 0.6926506, -0.684163, -0.9304563, -0.3254691, -0.8533293, 0.1523024, 0.2510415, -0.917345, -0.6239773, -0.7105472, -0.6104624, 0.6041355]; _distributions[15] = new [0.5844554, 0.06651045, 0.1343258, 0.6756578, 0.3799674, -0.6301104, 0.5590436, 0.7940555, 0.09574714, 0.02262517, 0.8697868, 0.393301, 0.003945862, -0.421735, 0.9043913, -0.2432393, -0.4844007, 0.7190998, -0.3201078, 0.2972371, -0.3852352, -0.6341155, -0.5413069, -0.09223081, -0.8468984, -0.5126905, 0.004156174, -0.8633173, -0.9681889, -0.03305046, -0.846509, 0.4414353]; _distributions[16] = new [0.4506488, 0.657668, 0.4621297, 0.07441051, -0.2782125, 0.6201044, 0.9750003, 0.09110117, 0.1019436, 0.2986514, 0.03457398, 0.9631706, 0.542098, -0.5505635, 0.8675668, 0.4938077, -0.5414361, 0.2655292, -0.7941836, 0.6003053, -0.09847672, -0.1001604, -0.9316511, -0.08572888, 0.07286467, -0.611899, -0.5232627, -0.4082253, -0.5481608, -0.827938, -0.1551939, -0.9621193, 0.9220031, -0.3315949]; _distributions[17] = new [0.197908, -0.4697656, -0.4474689, -0.3428435, 0.8529873, -0.2228634, 0.6022478, -0.5469642, 0.2545276, -0.931133, -0.1507547, -0.7855865, -0.07606658, 0.1011628, 0.3046715, 0.2785755, 0.4698432, -0.1064076, 0.6831254, 0.4152522, 0.1374381, 0.8363233, -0.2166121, 0.6682042, 0.5511393, 0.7996449, -0.4278994, 0.28836, -0.8875198, 0.2181732, -0.8772842, -0.2818254, -0.7000262, 0.5762185, -0.6062385, -0.7439126]; _distributions[18] = new [0.6645703, -0.05678739, 0.5720971, 0.4533803, -0.07660709, 0.08802763, 0.5163431, -0.4426552, 0.1163455, -0.3404382, -0.4004807, -0.5046007, 0.2932099, -0.8201418, -0.5322125, 0.03834766, -0.1490209, -0.8817304, -0.8000439, -0.3509448, 0.5260983, 0.8421043, 0.1197811, 0.6963812, 0.9498612, 0.3122156, -0.9285746, 0.02120355, -0.6670724, 0.7217396, 0.9155889, -0.3510147, -0.271941, 0.4727852, 0.318879, 0.1634057, -0.2686755, 0.9253026]; _distributions[19] = new [0.5064292, 0.422527, 0.8935515, -0.06610427, 0.1199719, 0.175568, 0.403388, -0.2003276, 0.1657927, 0.8154403, 0.9301245, 0.2929218, -0.1644068, 0.6201534, 0.7113559, -0.6589743, -0.3364046, -0.1799502, 0.02109996, -0.392765, -0.382213, 0.3219992, -0.9201946, 0.1207967, -0.726185, 0.4291916, -0.7443482, -0.2480059, -0.5147594, 0.7418784, 0.1935272, -0.7406143, -0.3643523, -0.5559214, -0.7147766, -0.6326278, -0.2524151, -0.9096627, 0.5161405, 0.7908453]; _distributions[20] = new [0.7921003, -0.3032096, 0.5992879, -0.009052323, 0.2538549, -0.1872749, 0.7053444, 0.3677175, 0.5417761, -0.8170255, 0.9749611, 0.1210478, 0.1969143, -0.6117041, -0.1824499, -0.4634196, -0.1181338, -0.8668742, -0.3050112, -0.1352596, -0.4409327, -0.7082354, -0.03225285, 0.1171548, 0.3113096, 0.3250439, -0.8166144, -0.463995, -0.01014475, 0.4715334, -0.6868284, 0.05091889, -0.4011163, 0.2717285, -0.06756835, 0.8307694, -0.7938535, 0.4352129, -0.4663842, 0.7165329, 0.559729, 0.8093995]; _distributions[21] = new [0.07832243, 0.426151, -0.3856795, 0.5799953, 0.01970797, 0.06706189, 0.4822682, 0.3014512, -0.1532982, 0.87485, -0.4959527, 0.07888043, 0.260601, -0.2304784, 0.4996209, 0.7167382, 0.585986, -0.04265174, -0.7679967, 0.5509416, -0.9041753, 0.1802134, -0.8407655, -0.4442826, -0.2058258, -0.2636995, -0.4984115, -0.5928579, 0.2926032, -0.7886473, -0.06933882, -0.621177, 0.578115, -0.4813387, 0.8981777, -0.3291056, 0.1942733, 0.9255584, 0.8084362, 0.5066984, 0.9920095, 0.03103104, -0.2403206, -0.9389018]; _distributions[22] = new [-0.5691095, 0.1014316, -0.7788262, 0.384012, -0.8253665, -0.1645582, -0.1830993, 0.002997211, -0.2555013, -0.4177977, -0.6640869, -0.4794711, -0.2351242, 0.5850121, 0.02436554, 0.2825883, 0.006061143, -0.8200245, 0.1618791, -0.3063331, -0.3765897, -0.7249815, 0.6092919, -0.6769328, -0.5956934, 0.6957655, 0.5383642, 0.4522677, -0.1489165, 0.9125596, 0.4167473, 0.1335986, 0.1898309, 0.5874342, 0.2288171, 0.9624356, 0.7540846, -0.07672304, 0.8986252, 0.2788797, 0.3555991, -0.9262139, 0.8454325, -0.4027667, 0.4945236, -0.2935512]; _distributions[23] = new [-0.4481403, -0.3758374, -0.8877251, 0.08739938, 0.05015831, -0.1339983, -0.4070427, -0.8534173, 0.1019274, -0.5503222, -0.445998, 0.1997541, -0.8686263, -0.2788867, -0.7695944, -0.6033704, -0.05515742, -0.885711, -0.7714347, 0.5790485, 0.3466263, -0.8799297, 0.4487582, -0.5321087, -0.2461368, 0.6053771, -0.05568117, 0.2457351, -0.4668669, 0.8523816, 0.8103387, -0.4255538, 0.4054182, -0.175663, -0.2802011, -0.08920153, 0.2665959, 0.382935, 0.555679, 0.1621837, 0.105246, 0.8420411, 0.6921161, 0.6902903, 0.880946, 0.2483067, 0.9699264, -0.1021767]; _distributions[24] = new [-0.1703323, -0.3119385, 0.2916039, -0.2988263, -0.008472982, -0.9277695, -0.7730271, -0.3277904, 0.3440474, -0.6815342, -0.2910278, 0.03461745, -0.6764899, -0.657078, -0.3505501, -0.7311988, -0.03478927, 0.3258755, -0.6048835, 0.159423, 0.2035525, 0.02212214, 0.5116573, 0.2226856, 0.6664805, -0.2500189, 0.7147882, -0.6609634, 0.03030632, -0.5763278, -0.2516585, 0.6116219, -0.9434413, -0.0116792, 0.9061816, 0.2491155, 0.182867, 0.6076167, 0.286593, 0.9485695, -0.5992439, 0.6970096, -0.2082874, 0.9416641, 0.9880044, -0.1541709, -0.9122881, 0.331555, 0.7324886, 0.6725098]; _distributions[25] = new [0.3869598, -0.04974834, 0.7168844, -0.0693711, -0.07166742, 0.1725325, 0.4599592, 0.3232779, 0.5872094, -0.4198674, 0.2442266, -0.625667, 0.1254557, 0.4500048, -0.2290154, -0.1803567, 0.890583, 0.3373493, 0.1256081, 0.7853789, -0.2676466, 0.5305805, -0.7063224, 0.252168, -0.3989835, 0.1189921, 0.09617215, -0.2451447, 0.6302541, 0.6085876, 0.9380925, -0.3234899, 0.5086241, -0.8573482, 0.03576187, -0.9876697, -0.0876712, -0.6365195, -0.5276513, 0.823456, -0.6935764, -0.2240411, -0.5212318, -0.5383121, -0.2116208, 0.9639363, -0.9840096, 0.02743555, -0.3991577, -0.8994547, -0.7830126, 0.614068]; _distributions[26] = new [-0.8366601, 0.4464895, -0.5917366, -0.02073906, -0.9845258, 0.1635625, -0.3097973, 0.4379579, -0.5478154, 0.7173221, -0.1685888, 0.9261969, 0.01503595, 0.6046097, 0.4452421, 0.5449086, 0.0315687, 0.1944619, 0.3753404, 0.8688548, 0.4143643, 0.1396648, 0.8711032, 0.4304703, 0.7328773, 0.1461501, 0.6374492, -0.3521495, 0.145613, -0.1341466, 0.9040975, -0.135123, -0.7839059, -0.5450199, -0.516019, -0.3320859, -0.206158, -0.4431106, -0.9703014, -0.2368356, -0.2473119, -0.0864351, 0.2130725, -0.4604077, -0.003726701, -0.7122303, -0.4072131, -0.6833169, 0.1632999, -0.9776646, 0.4686888, -0.680495, -0.2293511, -0.9509777]; _distributions[27] = new [0.107311, -0.1311369, -0.4194764, -0.3148777, 0.6171439, -0.2745973, 0.2796618, 0.1937153, -0.09106886, 0.4180236, 0.6044006, 0.05577846, 0.02927299, -0.6738263, -0.2580845, 0.1179939, -0.09023564, -0.3830024, 0.3570953, -0.5000587, 0.81591, -0.5518309, 0.9300217, -0.1257987, 0.4904627, -0.8381903, -0.3163182, -0.8632009, 0.1137595, -0.9875998, 0.8390043, 0.3538185, 0.2149114, 0.4993694, 0.5191584, 0.3833552, 0.5002763, 0.7061465, -0.2567276, 0.9068756, -0.5197366, 0.3467845, 0.03668867, 0.9734009, -0.5347553, 0.66747, -0.9028882, 0.1023768, -0.8967977, 0.412834, -0.5821944, 0.0426479, -0.8032165, -0.2397038, -0.5597343, -0.6358021]; _distributions[28] = new [-0.6562496, -0.1781036, -0.9301494, 0.1185208, -0.3861143, -0.4153562, -0.1560799, -0.1099607, -0.5587025, 0.395218, -0.5322112, -0.699701, -0.5008639, 0.08726846, -0.970524, -0.1963461, -0.813577, -0.5185111, -0.1644458, 0.298, -0.3216791, 0.639982, 0.3315373, 0.3339162, 0.2383235, -0.00105722, 0.1137828, 0.5450742, -0.01899921, 0.8798413, 0.2849685, 0.8255596, 0.6974412, 0.2123175, 0.7588523, 0.5470437, 0.5102502, -0.1687844, 0.5853448, 0.8033476, 0.2590716, -0.5262504, 0.5607718, -0.6342825, 0.8666443, -0.1491841, 0.8341052, -0.4935003, -0.1568441, -0.6634066, 0.2512113, -0.8769391, -0.2559827, -0.9572457, -0.01928852, -0.3966542, -0.750667, 0.6409678]; _distributions[29] = new [0.3454786, -0.04837726, 0.2649553, 0.2406852, 0.5599093, -0.3839145, -0.1111814, -0.05502108, 0.7586042, -0.05818377, 0.2519488, -0.4665135, -0.1264972, 0.2602723, -0.08766216, -0.3671907, 0.6428129, 0.3999204, -0.6105871, -0.1246869, -0.4589451, -0.7646643, -0.03021116, -0.7899352, -0.6036922, -0.4293956, -0.2481938, 0.6534185, 0.102798, 0.6784465, -0.6392644, 0.4821358, -0.6789002, 0.1779133, -0.9140783, -0.1989647, -0.9262617, 0.3381507, 0.4794891, -0.8093274, 0.3959447, 0.668478, 0.9602883, 0.2272305, -0.123672, 0.9210883, 0.2375148, 0.9523395, -0.52898, 0.7973378, -0.382433, 0.1228794, 0.695015, 0.6948439, 0.7530277, -0.6458191, 0.8777987, -0.3272956, 0.2318525, -0.962768]; _distributions[30] = new [0.4518921, -0.1146195, 0.4720805, -0.4238748, 0.3655423, 0.1806341, 0.1589939, -0.23568, 0.7673324, -0.5149941, 0.01163658, 0.09045836, 0.7010971, 0.1245747, 0.7518286, -0.1855433, 0.4960719, 0.4601022, 0.2566979, -0.6308268, -0.0654714, -0.5126389, -0.1823319, -0.1343282, -0.1464312, 0.4883236, -0.3858738, 0.203523, 0.1484799, 0.4432284, -0.477109, -0.116241, 0.2719092, 0.7208626, 0.9104174, 0.3578536, -0.5956199, 0.7662588, -0.6996251, 0.3678654, -0.2514512, 0.9251933, 0.1275825, -0.9478135, -0.204608, -0.8611552, 0.4264838, -0.877443, 0.9854161, 0.05521112, 0.5912951, 0.7997434, 0.1140349, 0.982093, -0.9324368, -0.2094094, -0.42436, -0.6441524, -0.6722705, -0.3554261, -0.7844236, 0.08587621]; _distributions[31] = new [-0.4206714, -0.5613642, -0.8733016, -0.3373051, -0.1046226, -0.2902999, -0.1318562, -0.8434365, 0.1145093, -0.5962623, -0.4965627, -0.1873259, -0.5011808, -0.8546229, -0.7165636, -0.5743566, 0.1090901, 0.2017643, 0.3404809, -0.220455, -0.1989015, 0.2372122, -0.4538706, 0.0979171, 0.4514146, -0.572846, 0.2314168, -0.8514503, -0.4247236, 0.5650803, -0.943347, 0.04514639, -0.1309718, 0.5221877, -0.7004157, 0.4561877, 0.6306441, 0.04448673, 0.4301621, 0.5766876, 0.1078042, 0.7245752, 0.3875354, 0.2794483, 0.702876, -0.2924213, 0.7360667, -0.6210318, 0.7486517, 0.6531103, 0.4898235, 0.8591025, 0.6549174, 0.3854057, -0.2596106, 0.7916998, 0.9251194, -0.05296265, -0.5620695, 0.820877, -0.01228026, 0.9937211, 0.9612103, 0.2628758]; } public static function getDistribution(n:int):Vector. { if (!_distributions) initDistributions(); if (n < 2 || n > 32) return null; return _distributions[n - 1]; } } } ",12124,True,4230.7602790726905,median "//// 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. //// image::apache-tinkerpop-logo.png[width=500,link=""http://tinkerpop.apache.org""] *x.y.z* :toc-position: left Provider Documentation ====================== TinkerPop exposes a set of interfaces, protocols, and tests that make it possible for third-parties to build libraries and systems that plug-in to the TinkerPop stack. TinkerPop refers to those third-parties as ""providers"" and this documentation is designed to help providers understand what is involved in developing code on these lower levels of the TinkerPop API. This document attempts to address the needs of the different providers that have been identified: * Graph System Provider ** Graph Database Provider ** Graph Processor Provider * Graph Driver Provider * Graph Language Provider * Graph Plugin Provider [[graph-system-provider-requirements]] Graph System Provider Requirements ---------------------------------- image:tinkerpop-enabled.png[width=140,float=left] At the core of TinkerPop3 is a Java8 API. The implementation of this core API and its validation via the `gremlin-test` suite is all that is required of a graph system provider wishing to provide a TinkerPop3-enabled graph engine. Once a graph system has a valid implementation, then all the applications provided by TinkerPop (e.g. Gremlin Console, Gremlin Server, etc.) and 3rd-party developers (e.g. Gremlin-Scala, Gremlin-JS, etc.) will integrate properly. Finally, please feel free to use the logo on the left to promote your TinkerPop3 implementation. Implementing Gremlin-Core ~~~~~~~~~~~~~~~~~~~~~~~~~ The classes that a graph system provider should focus on implementing are itemized below. It is a good idea to study the link:http://tinkerpop.apache.org/docs/x.y.z/reference/#tinkergraph-gremlin[TinkerGraph] (in-memory OLTP and OLAP in `tinkergraph-gremlin`), link:http://tinkerpop.apache.org/docs/x.y.z/reference/#neo4j-gremlin[Neo4jGraph] (OLTP w/ transactions in `neo4j-gremlin`) and/or link:http://tinkerpop.apache.org/docs/x.y.z/reference/#hadoop-gremlin[HadoopGraph] (OLAP in `hadoop-gremlin`) implementations for ideas and patterns. . Online Transactional Processing Graph Systems (*OLTP*) .. Structure API: `Graph`, `Element`, `Vertex`, `Edge`, `Property` and `Transaction` (if transactions are supported). .. Process API: `TraversalStrategy` instances for optimizing Gremlin traversals to the provider's graph system (i.e. `TinkerGraphStepStrategy`). . Online Analytics Processing Graph Systems (*OLAP*) .. Everything required of OLTP is required of OLAP (but not vice versa). .. GraphComputer API: `GraphComputer`, `Messenger`, `Memory`. Please consider the following implementation notes: * Be sure your `Graph` implementation is named as `XXXGraph` (e.g. TinkerGraph, Neo4jGraph, HadoopGraph, etc.). * Use `StringHelper` to ensuring that the `toString()` representation of classes are consistent with other implementations. * Ensure that your implementation's `Features` (Graph, Vertex, etc.) are correct so that test cases handle particulars accordingly. * Use the numerous static method helper classes such as `ElementHelper`, `GraphComputerHelper`, `VertexProgramHelper`, etc. * There are a number of default methods on the provided interfaces that are semantically correct. However, if they are not efficient for the implementation, override them. * Implement the `structure/` package interfaces first and then, if desired, interfaces in the `process/` package interfaces. * `ComputerGraph` is a `Wrapper` system that ensure proper semantics during a GraphComputer computation. [[oltp-implementations]] OLTP Implementations ^^^^^^^^^^^^^^^^^^^^ image:pipes-character-1.png[width=110,float=right] The most important interfaces to implement are in the `structure/` package. These include interfaces like Graph, Vertex, Edge, Property, Transaction, etc. The `StructureStandardSuite` will ensure that the semantics of the methods implemented are correct. Moreover, there are numerous `Exceptions` classes with static exceptions that should be thrown by the graph system so that all the exceptions and their messages are consistent amongst all TinkerPop3 implementations. [[olap-implementations]] OLAP Implementations ^^^^^^^^^^^^^^^^^^^^ image:furnace-character-1.png[width=110,float=right] Implementing the OLAP interfaces may be a bit more complicated. Note that before OLAP interfaces are implemented, it is necessary for the OLTP interfaces to be, at minimal, implemented as specified in <>. A summary of each required interface implementation is presented below: . `GraphComputer`: A fluent builder for specifying an isolation level, a VertexProgram, and any number of MapReduce jobs to be submitted. . `Memory`: A global blackboard for ANDing, ORing, INCRing, and SETing values for specified keys. . `Messenger`: The system that collects and distributes messages being propagated by vertices executing the VertexProgram application. . `MapReduce.MapEmitter`: The system that collects key/value pairs being emitted by the MapReduce applications map-phase. . `MapReduce.ReduceEmitter`: The system that collects key/value pairs being emitted by the MapReduce applications combine- and reduce-phases. NOTE: The VertexProgram and MapReduce interfaces in the `process/computer/` package are not required by the graph system. Instead, these are interfaces to be implemented by application developers writing VertexPrograms and MapReduce jobs. IMPORTANT: TinkerPop3 provides three OLAP implementations: link:http://tinkerpop.apache.org/docs/x.y.z/reference/#tinkergraph-gremlin[TinkerGraphComputer] (TinkerGraph), link:http://tinkerpop.apache.org/docs/x.y.z/reference/#giraphgraphcomputer[GiraphGraphComputer] (HadoopGraph), and link:http://tinkerpop.apache.org/docs/x.y.z/reference/#sparkgraphcomputer[SparkGraphComputer] (Hadoop). Given the complexity of the OLAP system, it is good to study and copy many of the patterns used in these reference implementations. Implementing GraphComputer ++++++++++++++++++++++++++ image:furnace-character-3.png[width=150,float=right] The most complex method in GraphComputer is the `submit()`-method. The method must do the following: . Ensure the GraphComputer has not already been executed. . Ensure that at least there is a VertexProgram or 1 MapReduce job. . If there is a VertexProgram, validate that it can execute on the GraphComputer given the respectively defined features. . Create the Memory to be used for the computation. . Execute the VertexProgram.setup() method once and only once. . Execute the VertexProgram.execute() method for each vertex. . Execute the VertexProgram.terminate() method once and if true, repeat VertexProgram.execute(). . When VertexProgram.terminate() returns true, move to MapReduce job execution. . MapReduce jobs are not required to be executed in any specified order. . For each Vertex, execute MapReduce.map(). Then (if defined) execute MapReduce.combine() and MapReduce.reduce(). . Update Memory with runtime information. . Construct a new `ComputerResult` containing the compute Graph and Memory. Implementing Memory +++++++++++++++++++ image:gremlin-brain.png[width=175,float=left] The Memory object is initially defined by `VertexProgram.setup()`. The memory data is available in the first round of the `VertexProgram.execute()` method. Each Vertex, when executing the VertexProgram, can update the Memory in its round. However, the update is not seen by the other vertices until the next round. At the end of the first round, all the updates are aggregated and the new memory data is available on the second round. This process repeats until the VertexProgram terminates. Implementing Messenger ++++++++++++++++++++++ The Messenger object is similar to the Memory object in that a vertex can read and write to the Messenger. However, the data it reads are the messages sent to the vertex in the previous step and the data it writes are the messages that will be readable by the receiving vertices in the subsequent round. Implementing MapReduce Emitters +++++++++++++++++++++++++++++++ image:hadoop-logo-notext.png[width=150,float=left] The MapReduce framework in TinkerPop3 is similar to the model popularized by link:http://hadoop.apache.org[Hadoop]. The primary difference is that all Mappers process the vertices of the graph, not an arbitrary key/value pair. However, the vertices' edges can not be accessed -- only their properties. This greatly reduces the amount of data needed to be pushed through the MapReduce engine as any edge information required, can be computed in the VertexProgram.execute() method. Moreover, at this stage, vertices can not be mutated, only their token and property data read. A Gremlin OLAP system needs to provide implementations for to particular classes: `MapReduce.MapEmitter` and `MapReduce.ReduceEmitter`. TinkerGraph's implementation is provided below which demonstrates the simplicity of the algorithm (especially when the data is all within the same JVM). [source,java] ---- public class TinkerMapEmitter implements MapReduce.MapEmitter { public Map> reduceMap; public Queue> mapQueue; private final boolean doReduce; public TinkerMapEmitter(final boolean doReduce) { <1> this.doReduce = doReduce; if (this.doReduce) this.reduceMap = new ConcurrentHashMap<>(); else this.mapQueue = new ConcurrentLinkedQueue<>(); } @Override public void emit(K key, V value) { if (this.doReduce) this.reduceMap.computeIfAbsent(key, k -> new ConcurrentLinkedQueue<>()).add(value); <2> else this.mapQueue.add(new KeyValue<>(key, value)); <3> } protected void complete(final MapReduce mapReduce) { if (!this.doReduce && mapReduce.getMapKeySort().isPresent()) { <4> final Comparator comparator = mapReduce.getMapKeySort().get(); final List> list = new ArrayList<>(this.mapQueue); Collections.sort(list, Comparator.comparing(KeyValue::getKey, comparator)); this.mapQueue.clear(); this.mapQueue.addAll(list); } else if (mapReduce.getMapKeySort().isPresent()) { final Comparator comparator = mapReduce.getMapKeySort().get(); final List>> list = new ArrayList<>(); list.addAll(this.reduceMap.entrySet()); Collections.sort(list, Comparator.comparing(Map.Entry::getKey, comparator)); this.reduceMap = new LinkedHashMap<>(); list.forEach(entry -> this.reduceMap.put(entry.getKey(), entry.getValue())); } } } ---- <1> If the MapReduce job has a reduce, then use one data structure (`reduceMap`), else use another (`mapList`). The difference being that a reduction requires a grouping by key and therefore, the `Map>` definition. If no reduction/grouping is required, then a simple `Queue>` can be leveraged. <2> If reduce is to follow, then increment the Map with a new value for the key. `MapHelper` is a TinkerPop3 class with static methods for adding data to a Map. <3> If no reduce is to follow, then simply append a KeyValue to the queue. <4> When the map phase is complete, any map-result sorting required can be executed at this point. [source,java] ---- public class TinkerReduceEmitter implements MapReduce.ReduceEmitter { protected Queue> reduceQueue = new ConcurrentLinkedQueue<>(); @Override public void emit(final OK key, final OV value) { this.reduceQueue.add(new KeyValue<>(key, value)); } protected void complete(final MapReduce mapReduce) { if (mapReduce.getReduceKeySort().isPresent()) { final Comparator comparator = mapReduce.getReduceKeySort().get(); final List> list = new ArrayList<>(this.reduceQueue); Collections.sort(list, Comparator.comparing(KeyValue::getKey, comparator)); this.reduceQueue.clear(); this.reduceQueue.addAll(list); } } } ---- The method `MapReduce.reduce()` is defined as: [source,java] public void reduce(final OK key, final Iterator values, final ReduceEmitter emitter) { ... } In other words, for the TinkerGraph implementation, iterate through the entrySet of the `reduceMap` and call the `reduce()` method on each entry. The `reduce()` method can emit key/value pairs which are simply aggregated into a `Queue>` in an analogous fashion to `TinkerMapEmitter` when no reduce is to follow. These two emitters are tied together in `TinkerGraphComputer.submit()`. [source,java] ---- ... for (final MapReduce mapReduce : mapReducers) { if (mapReduce.doStage(MapReduce.Stage.MAP)) { final TinkerMapEmitter mapEmitter = new TinkerMapEmitter<>(mapReduce.doStage(MapReduce.Stage.REDUCE)); final SynchronizedIterator vertices = new SynchronizedIterator<>(this.graph.vertices()); workers.setMapReduce(mapReduce); workers.mapReduceWorkerStart(MapReduce.Stage.MAP); workers.executeMapReduce(workerMapReduce -> { while (true) { final Vertex vertex = vertices.next(); if (null == vertex) return; workerMapReduce.map(ComputerGraph.mapReduce(vertex), mapEmitter); } }); workers.mapReduceWorkerEnd(MapReduce.Stage.MAP); // sort results if a map output sort is defined mapEmitter.complete(mapReduce); // no need to run combiners as this is single machine if (mapReduce.doStage(MapReduce.Stage.REDUCE)) { final TinkerReduceEmitter reduceEmitter = new TinkerReduceEmitter<>(); final SynchronizedIterator>> keyValues = new SynchronizedIterator((Iterator) mapEmitter.reduceMap.entrySet().iterator()); workers.mapReduceWorkerStart(MapReduce.Stage.REDUCE); workers.executeMapReduce(workerMapReduce -> { while (true) { final Map.Entry> entry = keyValues.next(); if (null == entry) return; workerMapReduce.reduce(entry.getKey(), entry.getValue().iterator(), reduceEmitter); } }); workers.mapReduceWorkerEnd(MapReduce.Stage.REDUCE); reduceEmitter.complete(mapReduce); // sort results if a reduce output sort is defined mapReduce.addResultToMemory(this.memory, reduceEmitter.reduceQueue.iterator()); <1> } else { mapReduce.addResultToMemory(this.memory, mapEmitter.mapQueue.iterator()); <2> } } } ... ---- <1> Note that the final results of the reducer are provided to the Memory as specified by the application developer's `MapReduce.addResultToMemory()` implementation. <2> If there is no reduce stage, the map-stage results are inserted into Memory as specified by the application developer's `MapReduce.addResultToMemory()` implementation. Hadoop-Gremlin Usage ^^^^^^^^^^^^^^^^^^^^ Hadoop-Gremlin is centered around `InputFormats` and `OutputFormats`. If a 3rd-party graph system provider wishes to leverage Hadoop-Gremlin (and its respective `GraphComputer` engines), then they need to provide, at minimum, a Hadoop2 `InputFormat` for their graph system. If the provider wishes to persist computed results back to their graph system (and not just to HDFS via a `FileOutputFormat`), then a graph system specific `OutputFormat` must be developed as well. Conceptually, `HadoopGraph` is a wrapper around a `Configuration` object. There is no ""data"" in the `HadoopGraph` as the `InputFormat` specifies where and how to get the graph data at OLAP (and OLTP) runtime. Thus, `HadoopGraph` is a small object with little overhead. Graph system providers should realize `HadoopGraph` as the gateway to the OLAP features offered by Hadoop-Gremlin. For example, a graph system specific `Graph.compute(Class graphComputerClass)`-method may look as follows: [source,java] ---- public C compute(final Class graphComputerClass) throws IllegalArgumentException { try { if (AbstractHadoopGraphComputer.class.isAssignableFrom(graphComputerClass)) return graphComputerClass.getConstructor(HadoopGraph.class).newInstance(this); else throw Graph.Exceptions.graphDoesNotSupportProvidedGraphComputer(graphComputerClass); } catch (final Exception e) { throw new IllegalArgumentException(e.getMessage(),e); } } ---- Note that the configurations for Hadoop are assumed to be in the `Graph.configuration()` object. If this is not the case, then the `Configuration` provided to `HadoopGraph.open()` should be dynamically created within the `compute()`-method. It is in the provided configuration that `HadoopGraph` gets the various properties which determine how to read and write data to and from Hadoop. For instance, `gremlin.hadoop.graphReader` and `gremlin.hadoop.graphWriter`. GraphFilterAware Interface ++++++++++++++++++++++++++ <> by OLAP processors to only pull a subgraph of the full graph from the graph data source. For instance, the example below constructs a `GraphFilter` that will only pull the ""knows""-graph amongst people into the `GraphComputer` for processing. [source,java] ---- graph.compute().vertices(hasLabel(""person"")).edges(bothE(""knows"")) ---- If the provider has a custom `InputRDD`, they can implement `GraphFilterAware` and that graph filter will be provided to their `InputRDD` at load time. For providers that use an `InputFormat`, state but the graph filter can be accessed from the configuration as such: [source,java] ---- if (configuration.containsKey(Constants.GREMLIN_HADOOP_GRAPH_FILTER)) this.graphFilter = VertexProgramHelper.deserialize(configuration, Constants.GREMLIN_HADOOP_GRAPH_FILTER); ---- PersistResultGraphAware Interface +++++++++++++++++++++++++++++++++ A graph system provider's `OutputFormat` should implement the `PersistResultGraphAware` interface which determines which persistence options are available to the user. For the standard file-based `OutputFormats` provided by Hadoop-Gremlin (e.g. <>, <>, and <>) `ResultGraph.ORIGINAL` is not supported as the original graph data files are not random access and are, in essence, immutable. Thus, these file-based `OutputFormats` only support `ResultGraph.NEW` which creates a copy of the data specified by the `Persist` enum. [[io-implementations]] IO Implementations ^^^^^^^^^^^^^^^^^^ If a `Graph` requires custom serializers for IO to work properly, implement the `Graph.io` method. A typical example of where a `Graph` would require such a custom serializers is if their identifier system uses non-primitive values, such as OrientDB's `Rid` class. From basic serialization of a single `Vertex` all the way up the stack to Gremlin Server, the need to know how to handle these complex identifiers is an important requirement. The first step to implementing custom serializers is to first implement the `IoRegistry` interface and register the custom classes and serializers to it. Each `Io` implementation has different requirements for what it expects from the `IoRegistry`: * *GraphML* - No custom serializers expected/allowed. * *GraphSON* - Register a Jackson `SimpleModule`. The `SimpleModule` encapsulates specific classes to be serialized, so it does not need to be registered to a specific class in the `IoRegistry` (use `null`). * *Gryo* - Expects registration of one of three objects: ** Register just the custom class with a `null` Kryo `Serializer` implementation - this class will use default ""field-level"" Kryo serialization. ** Register the custom class with a specific Kryo `Serializer' implementation. ** Register the custom class with a `Function` for those cases where the Kryo `Serializer` requires the `Kryo` instance to get constructed. This implementation should provide a zero-arg constructor as the stack may require instantiation via reflection. Consider extending `AbstractIoRegistry` for convenience as follows: [source,java] ---- public class MyGraphIoRegistry extends AbstractIoRegistry { public MyGraphIoRegistry() { register(GraphSONIo.class, null, new MyGraphSimpleModule()); register(GryoIo.class, MyGraphIdClass.class, new MyGraphIdSerializer()); } } ---- In the `Graph.io` method, provide the `IoRegistry` object to the supplied `Builder` and call the `create` method to return that `Io` instance as follows: [source,java] ---- public I io(final Io.Builder builder) { return (I) builder.graph(this).registry(myGraphIoRegistry).create(); }} ---- In this way, `Graph` implementations can pre-configure custom serializers for IO interactions and users will not need to know about those details. Following this pattern will ensure proper execution of the test suite as well as simplified usage for end-users. IMPORTANT: Proper implementation of IO is critical to successful `Graph` operations in Gremlin Server. The Test Suite does have ""serialization"" tests that provide some assurance that an implementation is working properly, but those tests cannot make assertions against any specifics of a custom serializer. It is the responsibility of the implementer to test the specifics of their custom serializers. TIP: Consider separating serializer code into its own module, if possible, so that clients that use the `Graph` implementation remotely don't need a full dependency on the entire `Graph` - just the IO components and related classes being serialized. [[remoteconnection-implementations]] RemoteConnection Implementations ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A `RemoteConnection` is an interface that is important for usage on traversal sources configured using the link:http://tinkerpop.apache.org/docs/x.y.z/reference/#connecting-via-remotegraph[withRemote()] option. A `Traversal` that is generated from that source will apply a `RemoteStrategy` which will inject a `RemoteStep` to its end. That step will then send the `Bytecode` of the `Traversal` over the `RemoteConnection` to get the results that it will iterate. There is one method to implement on `RemoteConnection`: [source,java] public CompletableFuture> submitAsync(final Bytecode bytecode) throws RemoteConnectionException; Note that it returns a `RemoteTraversal`. This interface should also be implemented and in most cases implementers can simply extend the `AbstractRemoteTraversal`, which provides default implementations for all the `Traversal` methods except for the important one `getSideEffects()`. [source,java] public RemoteTraversalSideEffects getSideEffects(); This method has been overriden from `Traversal` to return `RemoteTraversalSideEffects` and this interface allows a user to do a retrieval of any side-effects produced by the `Traversal`. The assumption, of course, is that the `RemoteConnection` is communicating with a server that supports side-effect retreival (as Gremlin Server does). TinkerPop provides the `DriverRemoteConnection` as a useful and link:https://github.com/apache/tinkerpop/blob/x.y.z/gremlin-driver/src/main/java/org/apache/tinkerpop/gremlin/driver/remote[example implementation]. `DriverRemoteConnection` serializes the `Traversal` and then submits it for remote processing on Gremlin Server. Gremlin Server rebinds the `Traversal` to a configured `Graph` instance and then iterates the results back as it would normally do. Implementing `RemoteConnection` is not something routinely done for those implementing `gremlin-core`. It is only something required if there is a need to exploit `withRemote()` in some way. If a graph provider has a ""graph server"" similar to Gremlin Server that can accept a serialized `Traversal` instance, then that would be one example of a reason to implement this interface. [[validating-with-gremlin-test]] Validating with Gremlin-Test ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ image:gremlin-edumacated.png[width=225] [source,xml] ---- org.apache.tinkerpop gremlin-test x.y.z ---- The operational semantics of any OLTP or OLAP implementation are validated by `gremlin-test`. To implement these tests, provide test case implementations as shown below, where `XXX` below denotes the name of the graph implementation (e.g. TinkerGraph, Neo4jGraph, HadoopGraph, etc.). [source,java] ---- // Structure API tests @RunWith(StructureStandardSuite.class) @GraphProviderClass(provider = XXXGraphProvider.class, graph = XXXGraph.class) public class XXXStructureStandardTest {} // Process API tests @RunWith(ProcessComputerSuite.class) @GraphProviderClass(provider = XXXGraphProvider.class, graph = XXXGraph.class) public class XXXProcessComputerTest {} @RunWith(ProcessStandardSuite.class) @GraphProviderClass(provider = XXXGraphProvider.class, graph = XXXGraph.class) public class XXXProcessStandardTest {} ---- The above set of tests represent the minimum test suite set to implement. There are other ""integration"" and ""performance"" tests that should be considered optional. Implementing those tests requires the same pattern as shown above. IMPORTANT: It is as important to look at ""ignored"" tests as it is to look at ones that fail. The `gremlin-test` suite utilizes the `Feature` implementation exposed by the `Graph` to determine which tests to execute. If a test utilizes features that are not supported by the graph, it will ignore them. While that may be fine, implementers should validate that the ignored tests are appropriately bypassed and that there are no mistakes in their feature definitions. Moreover, implementers should consider filling gaps in their own test suites, especially when IO-related tests are being ignored. The only test-class that requires any code investment is the `GraphProvider` implementation class. This class is a used by the test suite to construct `Graph` configurations and instances and provides information about the implementation itself. In most cases, it is best to simply extend `AbstractGraphProvider` as it provides many default implementations of the `GraphProvider` interface. Finally, specify the test suites that will be supported by the `Graph` implementation using the `@Graph.OptIn` annotation. See the `TinkerGraph` implementation below as an example: [source,java] ---- @Graph.OptIn(Graph.OptIn.SUITE_STRUCTURE_STANDARD) @Graph.OptIn(Graph.OptIn.SUITE_PROCESS_STANDARD) @Graph.OptIn(Graph.OptIn.SUITE_PROCESS_COMPUTER) public class TinkerGraph implements Graph { ---- Only include annotations for the suites the implementation will support. Note that implementing the suite, but not specifying the appropriate annotation will prevent the suite from running (an obvious error message will appear in this case when running the mis-configured suite). There are times when there may be a specific test in the suite that the implementation cannot support (despite the features it implements) or should not otherwise be executed. It is possible for implementers to ""opt-out"" of a test by using the `@Graph.OptOut` annotation. The following is an example of this annotation usage as taken from `HadoopGraph`: [source, java] ---- @Graph.OptIn(Graph.OptIn.SUITE_PROCESS_STANDARD) @Graph.OptIn(Graph.OptIn.SUITE_PROCESS_COMPUTER) @Graph.OptOut( test = ""org.apache.tinkerpop.gremlin.process.graph.step.map.MatchTest$Traversals"", method = ""g_V_matchXa_hasXname_GarciaX__a_inXwrittenByX_b__a_inXsungByX_bX"", reason = ""Hadoop-Gremlin is OLAP-oriented and for OLTP operations, linear-scan joins are required. This particular tests takes many minutes to execute."") @Graph.OptOut( test = ""org.apache.tinkerpop.gremlin.process.graph.step.map.MatchTest$Traversals"", method = ""g_V_matchXa_inXsungByX_b__a_inXsungByX_c__b_outXwrittenByX_d__c_outXwrittenByX_e__d_hasXname_George_HarisonX__e_hasXname_Bob_MarleyXX"", reason = ""Hadoop-Gremlin is OLAP-oriented and for OLTP operations, linear-scan joins are required. This particular tests takes many minutes to execute."") @Graph.OptOut( test = ""org.apache.tinkerpop.gremlin.process.computer.GraphComputerTest"", method = ""shouldNotAllowBadMemoryKeys"", reason = ""Hadoop does a hard kill on failure and stops threads which stops test cases. Exception handling semantics are correct though."") @Graph.OptOut( test = ""org.apache.tinkerpop.gremlin.process.computer.GraphComputerTest"", method = ""shouldRequireRegisteringMemoryKeys"", reason = ""Hadoop does a hard kill on failure and stops threads which stops test cases. Exception handling semantics are correct though."") public class HadoopGraph implements Graph { ---- The above examples show how to ignore individual tests. It is also possible to: * Ignore an entire test case (i.e. all the methods within the test) by setting the `method` to ""*"". * Ignore a ""base"" test class such that test that extend from those classes will all be ignored. * Ignore a `GraphComputer` test based on the type of `GraphComputer` being used. Specify the ""computer"" attribute on the `OptOut` (which is an array specification) which should have a value of the `GraphComputer` implementation class that should ignore that test. This attribute should be left empty for ""standard"" execution and by default all `GraphComputer` implementations will be included in the `OptOut` so if there are multiple implementations, explicitly specify the ones that should be excluded. Also note that some of the tests in the Gremlin Test Suite are parameterized tests and require an additional level of specificity to be properly ignored. To ignore these types of tests, examine the name template of the parameterized tests. It is defined by a Java annotation that looks like this: [source, java] @Parameterized.Parameters(name = ""expect({0})"") The annotation above shows that the name of each parameterized test will be prefixed with ""expect"" and have parentheses wrapped around the first parameter (at index 0) value supplied to each test. This information can only be garnered by studying the test set up itself. Once the pattern is determined and the specific unique name of the parameterized test is identified, add it to the `specific` property on the `OptOut` annotation in addition to the other arguments. These annotations help provide users a level of transparency into test suite compliance (via the link:http://tinkerpop.apache.org/docs/x.y.z/reference/#describe-graph[describeGraph()] utility function). It also allows implementers to have a lot of flexibility in terms of how they wish to support TinkerPop. For example, maybe there is a single test case that prevents an implementer from claiming support of a `Feature`. The implementer could choose to either not support the `Feature` or to support it but ""opt-out"" of the test with a ""reason"" as to why so that users understand the limitation. IMPORTANT: Before using `OptOut` be sure that the reason for using it is sound and it is more of a last resort. It is possible that a test from the suite doesn't properly represent the expectations of a feature, is too broad or narrow for the semantics it is trying to enforce or simply contains a bug. Please consider raising issues in the developer mailing list with such concerns before assuming `OptOut` is the only answer. IMPORTANT: There are no tests that specifically validate complete compliance with Gremlin Server. Generally speaking, a `Graph` that passes the full Test Suite, should be compliant with Gremlin Server. The one area where problems can occur is in serialization. Always ensure that IO is properly implemented, that custom serializers are tested fully and ultimately integration test the `Graph` with an actual Gremlin Server instance. WARNING: Configuring tests to run in parallel might result in errors that are difficult to debug as there is some shared state in test execution around graph configuration. It is therefore recommended that parallelism be turned off for the test suite (the Maven SureFire Plugin is configured this way by default). It may also be important to include this setting, `false`, in the SureFire configuration if tests are failing in an unexplainable way. TIP: When running the `gremlin-test` suite against your implementation, you may need to set `build.dir` as an environment variable, depending on your project layout. Some tests require this to find a writable directory for creating temporary files. The value is typically set to the project build directory. For example using the Maven SureFire Plugin, this is done via the configuration argLine with `-Dbuild.dir=${project.build.directory}`. Accessibility via GremlinPlugin ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ image:gremlin-plugin.png[width=100,float=left] The applications distributed with TinkerPop3 do not distribute with any graph system implementations besides TinkerGraph. If your implementation is stored in a Maven repository (e.g. Maven Central Repository), then it is best to provide a <> implementation so the respective jars can be downloaded according and when required by the user. Neo4j's GremlinPlugin is provided below for reference. [source,java] ---- public class Neo4jGremlinPlugin implements GremlinPlugin { private static final String IMPORT = ""import ""; private static final String DOT_STAR = "".*""; private static final Set IMPORTS = new HashSet() {{ add(IMPORT + Neo4jGraph.class.getPackage().getName() + DOT_STAR); }}; @Override public String getName() { return ""neo4j""; } @Override public void pluginTo(final PluginAcceptor pluginAcceptor) { pluginAcceptor.addImports(IMPORTS); } } ---- With the above plugin implementations, users can now download respective binaries for Gremlin Console, Gremlin Server, etc. [source,groovy] gremlin> g = Neo4jGraph.open('/tmp/neo4j') No such property: Neo4jGraph for class: groovysh_evaluate Display stack trace? [yN] gremlin> :install org.apache.tinkerpop neo4j-gremlin x.y.z ==>loaded: [org.apache.tinkerpop, neo4j-gremlin, …] gremlin> :plugin use tinkerpop.neo4j ==>tinkerpop.neo4j activated gremlin> g = Neo4jGraph.open('/tmp/neo4j') ==>neo4jgraph[EmbeddedGraphDatabase [/tmp/neo4j]] In-Depth Implementations ~~~~~~~~~~~~~~~~~~~~~~~~ image:gremlin-painting.png[width=200,float=right] The graph system implementation details presented thus far are minimum requirements necessary to yield a valid TinkerPop3 implementation. However, there are other areas that a graph system provider can tweak to provide an implementation more optimized for their underlying graph engine. Typical areas of focus include: * Traversal Strategies: A link:http://tinkerpop.apache.org/docs/x.y.z/reference/#traversalstrategy[TraversalStrategy] can be used to alter a traversal prior to its execution. A typical example is converting a pattern of `g.V().has('name','marko')` into a global index lookup for all vertices with name ""marko"". In this way, a `O(|V|)` lookup becomes an `O(log(|V|))`. Please review `TinkerGraphStepStrategy` for ideas. * Step Implementations: Every link:http://tinkerpop.apache.org/docs/x.y.z/reference/#graph-traversal-steps[step] is ultimately referenced by the `GraphTraversal` interface. It is possible to extend `GraphTraversal` to use a graph system specific step implementation. Graph Driver Provider Requirements ---------------------------------- image::gremlin-server-protocol.png[width=325] One of the roles for link:http://tinkerpop.apache.org/docs/x.y.z/reference/#gremlin-server[Gremlin Server] is to provide a bridge from TinkerPop to non-JVM languages (e.g. Go, Python, etc.). Developers can build language bindings (or driver) that provide a way to submit Gremlin scripts to Gremlin Server and get back results. Given the extensible nature of Gremlin Server, it is difficult to provide an authoritative guide to developing a driver. It is however possible to describe the core communication protocol using the standard out-of-the-box configuration which should provide enough information to develop a driver for a specific language. image::gremlin-server-flow.png[width=300,float=right] Gremlin Server is distributed with a configuration that utilizes link:http://en.wikipedia.org/wiki/WebSocket[WebSocket] with a custom sub-protocol. Under this configuration, Gremlin Server accepts requests containing a Gremlin script, evaluates that script and then streams back the results. The notion of ""streaming"" is depicted in the diagram to the right. The diagram shows an incoming request to process the Gremlin script of `g.V()`. Gremlin Server evaluates that script, getting an `Iterator` of vertices as a result, and steps through each `Vertex` within it. The vertices are batched together given the `resultIterationBatchSize` configuration. In this case, that value must be `2` given that each ""response"" contains two vertices. Each response is serialized given the requested serializer type (JSON is likely best for non-JVM languages) and written back to the requesting client immediately. Gremlin Server does not wait for the entire result to be iterated, before sending back a response. It will send the responses as they are realized. This approach allows for the processing of large result sets without having to serialize the entire result into memory for the response. It places a bit of a burden on the developer of the driver however, because it becomes necessary to provide a way to reconstruct the entire result on the client side from all of the individual responses that Gremlin Server returns for a single request. Again, this description of Gremlin Server's ""flow"" is related to the out-of-the-box configuration. It is quite possible to construct other flows, that might be more amenable to a particular language or style of processing. To formulate a request to Gremlin Server, a `RequestMessage` needs to be constructed. The `RequestMessage` is a generalized representation of a request that carries a set of ""standard"" values in addition to optional ones that are dependent on the operation being performed. A `RequestMessage` has these fields: [width=""100%"",cols=""3,10"",options=""header""] |========================================================= |Key |Description |requestId |A link:http://en.wikipedia.org/wiki/Globally_unique_identifier[UUID] representing the unique identification for the request. |op |The name of the ""operation"" to execute based on the available `OpProcessor` configured in the Gremlin Server. To evaluate a script, use `eval`. |processor |The name of the `OpProcessor` to utilize. The default `OpProcessor` for evaluating scripts is unnamed and therefore script evaluation purposes, this value can be an empty string. |args |A `Map` of arbitrary parameters to pass to Gremlin Server. The requirements for the contents of this `Map` are dependent on the `op` selected. |========================================================= This message can be serialized in any fashion that is supported by Gremlin Server. New serialization methods can be plugged in by implementing a `ServiceLoader` enabled `MessageSerializer`, however Gremlin Server provides for JSON serialization by default which will be good enough for purposes of most developers building drivers. A `RequestMessage` to evaluate a script with variable bindings looks like this in JSON: [source,js] ---- { ""requestId"":""1d6d02bd-8e56-421d-9438-3bd6d0079ff1"", ""op"":""eval"", ""processor"":"""", ""args"":{""gremlin"":""g.traversal().V(x).out()"", ""bindings"":{""x"":1}, ""language"":""gremlin-groovy""}} ---- The above JSON represents the ""body"" of the request to send to Gremlin Server. When sending this ""body"" over WebSocket, Gremlin Server can accept a packet frame using a ""text"" (1) or a ""binary"" (2) opcode. Using ""text"" is a bit more limited in that Gremlin Server will always process the body of that request as JSON. Generally speaking ""text"" is just for testing purposes. The preferred method for sending requests to Gremlin Server is to use the ""binary"" opcode. In this case, a ""header"" will need be sent in addition to to the ""body"". The ""header"" basically consists of a ""mime type"" so that Gremlin Server knows how to deserialize the `RequestMessage`. So, the actual byte array sent to Gremlin Server would be formatted as follows: image::gremlin-server-request.png[] The first byte represents the length of the ""mime type"" string value that follows. Given the default configuration of Gremlin Server, this value should be set to `application/json`. The ""payload"" represents the JSON message above encoded as bytes. NOTE: Gremlin Server will only accept masked packets as it pertains to a WebSocket packet header construction. When Gremlin Server receives that request, it will decode it given the ""mime type"", pass it to the requested `OpProcessor` which will execute the `op` defined in the message. In this case, it will evaluate the script `g.traversal().V(x).out()` using the `bindings` supplied in the `args` and stream back the results in a series of `ResponseMessages`. A `ResponseMessage` looks like this: [width=""100%"",cols=""3,10"",options=""header""] |========================================================= |Key |Description |requestId |The identifier of the `RequestMessage` that generated this `ResponseMessage`. |status | The `status` contains a `Map` of three keys: `code` which refers to a `ResultCode` that is somewhat analogous to an link:http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html[HTTP status code], `attributes` that represent a `Map` of protocol-level information, and `message` which is just a human-readable `String` usually associated with errors. |result | The `result` contains a `Map` of two keys: `data` which refers to the actual data returned from the server (the type of data is determined by the operation requested) and `meta` which is a `Map` of meta-data related to the response. |========================================================= In this case the `ResponseMessage` returned to the client would look something like this: [source,js] ---- {""result"":{""data"":[{""id"": 2,""label"": ""person"",""type"": ""vertex"",""properties"": [ {""id"": 2, ""value"": ""vadas"", ""label"": ""name""}, {""id"": 3, ""value"": 27, ""label"": ""age""}]}, ], ""meta"":{}}, ""requestId"":""1d6d02bd-8e56-421d-9438-3bd6d0079ff1"", ""status"":{""code"":206,""attributes"":{},""message"":""""}} ---- Gremlin Server is capable of streaming results such that additional responses will arrive over the WebSocket connection until the iteration of the result on the server is complete. Each successful incremental message will have a `ResultCode` of `206`. Termination of the stream will be marked by a final `200` status code. Note that all messages without a `206` represent terminating conditions for a request. The following table details the various status codes that Gremlin Server will send: [width=""100%"",cols=""2,2,9"",options=""header""] |========================================================= |Code |Name |Description |200 |SUCCESS |The server successfully processed a request to completion - there are no messages remaining in this stream. |204 |NO CONTENT |The server processed the request but there is no result to return (e.g. an `Iterator` with no elements) - there are no messages remaining in this stream. |206 |PARTIAL CONTENT |The server successfully returned some content, but there is more in the stream to arrive - wait for a `SUCCESS` to signify the end of the stream. |401 |UNAUTHORIZED |The request attempted to access resources that the requesting user did not have access to. |407 |AUTHENTICATE |A challenge from the server for the client to authenticate its request. |498 |MALFORMED REQUEST | The request message was not properly formatted which means it could not be parsed at all or the ""op"" code was not recognized such that Gremlin Server could properly route it for processing. Check the message format and retry the request. |499 |INVALID REQUEST ARGUMENTS |The request message was parseable, but the arguments supplied in the message were in conflict or incomplete. Check the message format and retry the request. |500 |SERVER ERROR |A general server error occurred that prevented the request from being processed. |597 |SCRIPT EVALUATION ERROR |The script submitted for processing evaluated in the `ScriptEngine` with errors and could not be processed. Check the script submitted for syntax errors or other problems and then resubmit. |598 |SERVER TIMEOUT |The server exceeded one of the timeout settings for the request and could therefore only partially responded or did not respond at all. |599 |SERVER SERIALIZATION ERROR |The server was not capable of serializing an object that was returned from the script supplied on the request. Either transform the object into something Gremlin Server can process within the script or install mapper serialization classes to Gremlin Server. |========================================================= NOTE: Please refer to the link:http://tinkerpop.apache.org/docs/current/dev/io[IO Reference Documentation] for more examples of `RequestMessage` and `ResponseMessage` instances. OpProcessors Arguments ~~~~~~~~~~~~~~~~~~~~~~ The following sections define a non-exhaustive list of available operations and arguments for embedded `OpProcessors` (i.e. ones packaged with Gremlin Server). Common ^^^^^^ All `OpProcessor` instances support these arguments. [width=""100%"",cols=""2,2,9"",options=""header""] |========================================================= |Key |Type |Description |batchSize |Int |When the result is an iterator this value defines the number of iterations each `ResponseMessage` should contain - overrides the `resultIterationBatchSize` server setting. |========================================================= Standard OpProcessor ^^^^^^^^^^^^^^^^^^^^ The ""standard"" `OpProcessor` handles requests for the primary function of Gremlin Server - executing Gremlin. Requests made to this `OpProcessor` are ""sessionless"" in the sense that a request must encapsulate the entirety of a transaction. There is no state maintained between requests. A transaction is started when the script is first evaluated and is committed when the script completes (or rolled back if an error occurred). [width=""100%"",cols=""3,10a"",options=""header""] |========================================================= |Key |Description |processor |As this is the default `OpProcessor` this value can be set to an empty string. |op |[width=""100%"",cols=""3,10"",options=""header""] !========================================================= !Key !Description !`authentication` !A request that contains the response to a server challenge for authentication. !`eval` !Evaluate a Gremlin script provided as a `String`. !========================================================= |========================================================= '`authentication` operation arguments' [width=""100%"",cols=""2,2,9"",options=""header""] |========================================================= |Key |Type |Description |sasl |String | *Required* The response to the server authentication challenge. This value is dependent on the SASL authentication mechanism required by the server and is Base64 encoded. |saslMechanism |String | The SASL mechanism: `PLAIN` or `GSSAPI`. Note that it is up to the server implementation to use or disregard this setting (default implementation in Gremlin Server ignores it). |========================================================= '`eval` operation arguments' [width=""100%"",cols=""2,2,9"",options=""header""] |========================================================= |Key |Type |Description |gremlin |String | *Required* The Gremlin script to evaluate. |bindings |Map |A map of key/value pairs to apply as variables in the context of the Gremlin script. |language |String |The flavor of Gremlin used (e.g. `gremlin-groovy`). |aliases |Map |A map of key/value pairs that allow globally bound `Graph` and `TraversalSource` objects to be aliased to different variable names for purposes of the current request. The value represents the name of the global variable and its key represents the new binding name as it will be referenced in the Gremlin query. For example, if the Gremlin Server defines two `TraversalSource` instances named `g1` and `g2`, it would be possible to send an alias pair with key of ""g"" and value of ""g2"" and thus allow the script to refer to ""g2"" simply as ""g"". |scriptEvaluationTimeout |Long |An override for the server setting that determines the maximum time to wait for a script to execute on the server. |========================================================= Session OpProcessor ^^^^^^^^^^^^^^^^^^^ The ""session"" `OpProcessor` handles requests for the primary function of Gremlin Server - executing Gremlin. It is like the ""standard"" `OpProcessor`, but instead maintains state between sessions and allows the option to leave all transaction management up to the calling client. It is important that clients that open sessions, commit or roll them back, however Gremlin Server will try to clean up such things when a session is killed that has been abandoned. It is important to consider that a session can only be maintained with a single machine. In the event that multiple Gremlin Server are deployed, session state is not shared among them. [width=""100%"",cols=""3,10a"",options=""header""] |========================================================= |Key |Description |processor |This value should be set to `session` |op | [cols=""3,10"",options=""header""] !========================================================= !Key !Description !`authentication` !A request that contains the response to a server challenge for authentication. !`eval` !Evaluate a Gremlin script provided as a `String`. !`close` !Close the specified session. Will return a `NO CONTENT` message as confirmation of the close being completed. |========================================================= '`authentication` operation arguments' [width=""100%"",cols=""2,2,9"",options=""header""] |========================================================= |Key |Type |Description |saslMechanism |String | The SASL mechanism: `PLAIN` or `GSSAPI`. Note that it is up to the server implementation to use or disregard this setting (default implementation in Gremlin Server ignores it). |sasl |String | *Required* The response to the server authentication challenge. This value is dependent on the SASL authentication mechanism required by the server and is Base64 encoded. |========================================================= '`eval` operation arguments' [width=""100%"",options=""header""] |========================================================= |Key |Type |Description |gremlin |String | *Required* The Gremlin script to evaluate. |session |String | *Required* The session identifier for the current session - typically this value should be a UUID (the session will be created if it doesn't exist). |manageTransaction |Boolean |When set to `true` the transaction for the current request is auto-committed or rolled-back as are done with sessionless requests - defaulted to `false`. |bindings |Map |A map of key/value pairs to apply as variables in the context of the Gremlin script. |scriptEvaluationTimeout |Long |An override for the server setting that determines the maximum time to wait for a script to execute on the server. |language |String |The flavor of Gremlin used (e.g. `gremlin-groovy`) |aliases |Map |A map of key/value pairs that allow globally bound `Graph` and `TraversalSource` objects to be aliased to different variable names for purposes of the current request. The value represents the name the global variable and its key represents the new binding name as it will be referenced in the Gremlin query. For example, if the Gremlin Server defines two `TraversalSource` instances named `g1` and `g2`, it would be possible to send an alias pair with key of ""g"" and value of ""g2"" and thus allow the script to refer to ""g2"" simply as ""g"". |========================================================= '`close` operation arguments' [width=""100%"",cols=""2,2,9"",options=""header""] |========================================================= |Key |Type |Description |session |String | *Required* The session identifier for the session to close. |force |Boolean | Determines if the session should be force closed when the client is closed. Force closing will not attempt to close open transactions from existing running jobs and leave it to the underlying graph to decided how to proceed with those orphaned transactions. Setting this to `true` tends to lead to faster close operation and release of resources which can be desirable if Gremlin Server has a long session timeout and a long script evaluation timeout as attempts to close long run jobs can occur more rapidly. If not provided, this value is `false`. |========================================================= Traversal OpProcessor ^^^^^^^^^^^^^^^^^^^^^ Both the Standard and Session OpProcessors allow for Gremlin scripts to be submitted to the server. The `TraversalOpProcessor` however allows Gremlin `Bytecode` to be submitted to the server. Supporting this `OpProcessor` makes it possible for a link:http://tinkerpop.apache.org/docs/current/tutorials/gremlin-language-variants/[Gremlin Language Variant] to submit a `Traversal` directly to Gremlin Server in the native language of the GLV without having to use a script in a different language. Unlike Standard and Session OpProcessors, the Traversal OpProcessor does not simply return the results of the `Traversal`. It instead returns `Traverser` objects which allows the client to take advantage of link:http://tinkerpop.apache.org/docs/current/reference/#barrier-step[bulking]. To describe this interaction more directly, the returned `Traverser` will represent some value from the `Traversal` result and the number of times it is represented in the full stream of results. So, if a `Traversal` happens to return the same vertex twenty times it won't return twenty instances of the same object. It will return one in `Traverser` with the `bulk` value set to twenty. Under this model, the amount of processing and network overhead can be reduced considerably. To demonstrate consider this example: [gremlin-groovy] ---- cluster = Cluster.open() client = cluster.connect() aliased = client.alias(""g"") g = org.apache.tinkerpop.gremlin.structure.util.empty.EmptyGraph.INSTANCE.traversal() <1> rs = aliased.submit(g.V().both().barrier().both().barrier()).all().get() <2> aliased.submit(g.V().both().barrier().both().barrier().count()).all().get().get(0).getInt() <3> rs.collect{[value: it.getObject().get(), bulk: it.getObject().bulk()]} <4> ---- <1> All commands through this step are just designed to demonstrate bulking with Gremlin Server and don't represent a real-world way that this feature would be used. <2> Submit a `Traversal` that happens to ensure that the server uses bulking. Note that a `Traverser` is returned and that there are only six results. <3> In actuality, however, if this same `Traversal` is iterated there are thirty results. Without bulking, the previous request would have sent back thirty traversers. <4> Note that the sum of the bulk of each `Traverser` is thirty. The full iteration of aa `Traversal` is thus left to the client. It must interpret the bulk on the `Traverser` and unroll it to represent the actual number of times it exists when iterated. The unrolling is typically handled directly within TinkerPop's `RemoteGraph` implementations. One of the important aspects of the Traversal OpProcessor is that it enables the user to not only get the results of the `Traversal` but also the side-effects that it produces. When the `Traversal` is submitted with the ""bytecode"" operation, the results are iterated back as usual, but any side-effects are retained on the server in a cache keyed by the identifier of the request that originally submitted the `Traversal`. The client will want to retain that identifier if it intends to later get side-effects. The Traversal OpProcessor supplies the ""keys"" and ""gather"" operations to get the keys stored in the side-effect and to get the value of a specific side-effect respectively. Finally, a ""close"" operation is available to clear the cache of a specific side-effect. [width=""100%"",cols=""3,10a"",options=""header""] |========================================================= |Key |Description |processor |This value should be set to `traversal` |op | [cols=""3,10"",options=""header""] !========================================================= !Key !Description !`authentication` !A request that contains the response to a server challenge for authentication. !`bytecode` !A request that contains the `Bytecode` representation of a `Traversal`. !`close` !Releases side-effects held in cache for a particular `Traversal`. !`gather` !Gets a particular side-effect as produced by a previously executed `Traversal`. !`keys` !Gets all the keys of all side-effects as produced by a previously executed `Traversal`. |========================================================= '`authentication` operation arguments' [width=""100%"",cols=""2,2,9"",options=""header""] |========================================================= |Key |Type |Description |sasl |String | *Required* The response to the server authentication challenge. This value is dependent on the SASL authentication mechanism required by the server and is Base64 encoded. |========================================================= '`bytecode` operation arguments' [width=""100%"",cols=""2,2,9"",options=""header""] |========================================================= |Key |Type |Description |gremlin |String | *Required* The `Bytecode` representation of a `Traversal`. |aliases |Map | *Required* A map with a single key/value pair that refers to a globally bound `TraversalSource` object to be aliased to different variable names for purposes of the current request. The value represents the name of the global variable and its key represents the new binding name as it will be referenced in the Gremlin query. For example, if the Gremlin Server defines two `TraversalSource` instances named `g1`, it would be possible to send an alias pair with key of ""g"" and value of ""g1"" and thus allow the script to refer to ""g1"" simply as ""g"". Note that unlike users of `alias` in other contexts, in this case, the key can *only* be set to ""g"" and there can be only one key value pair present (since only one `Traversal` is being submitted, there is no sense to having more than a single alias). |========================================================= '`close` operation arguments' [width=""100%"",cols=""2,2,9"",options=""header""] |========================================================= |Key |Type |Description |sideEffect |UUID | *Required* The unique identifier for the request that original submitted the traversal (side-effects are keyed by that value) |========================================================= '`gather` operation arguments' [width=""100%"",cols=""2,2,9"",options=""header""] |========================================================= |Key |Type |Description |sideEffect |UUID | *Required* The unique identifier for the request that original submitted the traversal (side-effects are keyed by that value) |sideEffectKey |String | *Required* The key for a specific side-effect. |aliases |Map | *Required* A map with a single key/value pair that refers to a globally bound `TraversalSource` object to be aliased to different variable names for purposes of the current request. The value represents the name of the global variable and its key represents the new binding name as it will be referenced in the Gremlin query. For example, if the Gremlin Server defines two `TraversalSource` instances named `g1`, it would be possible to send an alias pair with key of ""g"" and value of ""g1"" and thus allow the script to refer to ""g1"" simply as ""g"". Note that unlike users of `alias` in other contexts, in this case, the key can *only* be set to ""g"" and there can be only one key value pair present (since only one `Traversal` is being submitted, there is no sense to having more than a single alias). |========================================================= When using ""gather"" it is important to note the metadata that is returned on the `ResponseMessage`. It returns both the ""sideEffectKey"" that was requested as well as a value keyed as ""aggregateTo"". The ""aggregateTo"" field describes how the streamed side-effect data should be treated on the client. It provides a hint as to whether or not the data should be rolled back up into a single object or simply left as-is. There are four values for ""aggregateTo"": `bulkset`, `list`, `map`, `set` and `none`. '`keys` operation arguments' [width=""100%"",cols=""2,2,9"",options=""header""] |========================================================= |Key |Type |Description |sideEffect |UUID | *Required* The unique identifier for the request that original submitted the traversal (side-effects are keyed by that value) |========================================================= Authentication ~~~~~~~~~~~~~~ Gremlin Server supports link:https://en.wikipedia.org/wiki/Simple_Authentication_and_Security_Layer[SASL-based] authentication. A SASL implementation provides a series of challenges and responses that a driver must comply with in order to authenticate. By default, Gremlin Server only supports the ""PLAIN"" SASL mechanism, which is a cleartext password system. When authentication is enabled, an incoming request is intercepted before it is evaluated by the `ScriptEngine`. The request is saved on the server and a `AUTHENTICATE` challenge response (status code `407`) is returned to the client. The client will detect the `AUTHENTICATE` and respond with an `authentication` for the `op` and an `arg` named `sasl` that contains the password. The password should be either, an encoded sequence of UTF-8 bytes, delimited by 0 (US-ASCII NUL), where the form is : `usernamepassword`, or a Base64 encoded string of the former (which in this instance would be `AHVzZXJuYW1lAHBhc3N3b3Jk`). Should Gremlin Server be able to authenticate with the provided credentials, the server will return the results of the original request as it normally does without authentication. If it cannot authenticate given the challenge response from the client, it will return `UNAUTHORIZED` (status code `401`). NOTE: Gremlin Server does not support the ""authorization identity"" as described in link:https://tools.ietf.org/html/rfc4616[RFC4616]. [[gremlin-plugins]] Gremlin Plugins --------------- image:gremlin-plugin.png[width=125] Plugins provide a way to expand the features of a `GremlinScriptEngine`, which stands at that core of both Gremlin Console and Gremlin Server. Providers may wish to create plugins for a variety of reasons, but some common examples include: * Initialize the `GremlinScriptEngine` application with important classes so that the user doesn't need to type their own imports. * Place specific objects in the bindings of the `GremlinScriptEngine` for the convenience of the user. * Bootstrap the `GremlinScriptEngine` with custom functions so that they are ready for usage at startup. The first step to developing a plugin is to implement the link:http://tinkerpop.apache.org/javadocs/x.y.z/full/org/apache/tinkerpop/gremlin/jsr223/GremlinPlugin.html[GremlinPlugin] interface: [source,java] ---- include::{basedir}/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/jsr223/GremlinPlugin.java[] ---- The most simple plugin and the one most commonly implemented will likely be one that just provides a list of classes for import. This type of plugin is the easiest way for implementers of the TinkerPop Structure and Process APIs to make their implementations available to users. The TinkerGraph implementation has just such a plugin: [source,java] ---- include::{basedir}/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/jsr223/TinkerGraphGremlinPlugin.java[] ---- This plugin extends from the abstract base class of link:http://tinkerpop.apache.org/javadocs/x.y.z/full/org/apache/tinkerpop/gremlin/jsr223/AbstractGremlinPlugin.html[AbstractGremlinPlugin] which provides some default implementations of the `GremlinPlugin` methods. It simply allows those who extend from it to be able to just supply the name of the module and a list of link:http://tinkerpop.apache.org/javadocs/x.y.z/full/org/apache/tinkerpop/gremlin/jsr223/Customizer.html[Customizer] instances to apply to the `GremlinScriptEngine`. In this case, the TinkerGraph plugin just needs an link:http://tinkerpop.apache.org/javadocs/x.y.z/full/org/apache/tinkerpop/gremlin/jsr223/ImportCustomizer.html[ImportCustomizer] which describes the list of classes to import when the plugin is activated and applied to the `GremlinScriptEngine`. The `ImportCustomizer` is just one of several provided `Customizer` implementations that can be used in conjunction with plugin development: * link:http://tinkerpop.apache.org/javadocs/x.y.z/full/org/apache/tinkerpop/gremlin/jsr223/BindingCustomizer.html[BindingCustomizer] - Inject a key/value pair into the global bindings of the `GremlinScriptEngine` instances * link:http://tinkerpop.apache.org/javadocs/x.y.z/full/org/apache/tinkerpop/gremlin/jsr223/ImportCustomizer.html[ImportCustomizer] - Add imports to a `GremlinScriptEngine` * link:http://tinkerpop.apache.org/javadocs/x.y.z/full/org/apache/tinkerpop/gremlin/jsr223/ScriptCustomizer.html[ScriptCustomizer] - Execute a script on a `GremlinScriptEngine` at startup Individual `GremlinScriptEngine` instances may have their own `Customizer` instances that can be used only with that engine - e.g. `gremlin-groovy` has some that are specific to controlling the Groovy compiler configuration. Developing a new `Customizer` implementation is not really possible without changes to TinkerPop, as the framework is not designed to respond to external ones. The base `Customizer` implementations listed above should cover most needs. A `GremlinPlugin` must support one of two instantiation models so that it can be instantiated from configuration files for use in various situations - e.g. Gremlin Server. The first option is to use a static initializer given a method with the following signature: [source,java] ---- public static GremlinPlugin instance() ---- The limitation with this approach is that it does not provide a way to supply any configuration to the plugin so it tends to only be useful for fairly simplistic plugins. The more advanced approach is to provide a ""builder"" given a method with the following signature: [source,java] ---- public static Builder build() ---- It doesn't really matter what kind of class is returned from `build` so long as it follows a ""Builder"" pattern, where methods on that object return an instance of itself, so that builder methods can be chained together prior to calling a final `create` method as follows: [source,java] ---- public GremlinPlugin create() ---- Please see the link:http://tinkerpop.apache.org/javadocs/x.y.z/full/org/apache/tinkerpop/gremlin/jsr223/ImportGremlinPlugin.html for an example of what implementing a `Builder` might look like in this context. Note that the plugin provides a unique name for the plugin which follows a namespaced pattern as _namespace_._plugin-name_ (e.g. ""tinkerpop.hadoop"" - ""tinkerpop"" is the reserved namespace for TinkerPop maintained plugins). For plugins that will work with Gremlin Console, there is one other step to follow to ensure that the `GremlinPlugin` will work there. The console loads `GremlinPlugin` instances via link:http://docs.oracle.com/javase/8/docs/api/java/util/ServiceLoader.html[ServiceLoader] and therefore need a resource file added to the jar file where the plugin exists. Add a file called `org.apache.tinkerpop.gremlin.jsr223.GremlinPlugin` to `META-INF/services`. In the case of the TinkerGraph plugin above, that file will have this line in it: [source,java] ---- include::{basedir}/tinkergraph-gremlin/src/main/resources/META-INF/services/org.apache.tinkerpop.gremlin.jsr223.GremlinPlugin[] ---- Once the plugin is packaged, there are two ways to test it out: . Copy the jar and its dependencies to the Gremlin Console path and start it. It is preferrable that the plugin is copied to the `/ext/_plugin_name_` directory. . Start Gremlin Console and try the `:install` command: `:install com.company my-plugin 1.0.0`. In either case, once one of these two approaches is taken, the jars and their dependencies are available to the Console. The next step is to ""activate"" the plugin by doing `:plugin use my-plugin`, where ""my-plugin"" refers to the name of the plugin to activate. NOTE: When `:install` is used logging dependencies related to link:http://www.slf4j.org/[SLF4J] are filtered out so as not to introduce multiple logger bindings (which generates warning messages to the logs). A plugin can do much more than just import classes. One can expand the Gremlin language with new functions or steps, provide useful commands to make repetitive or complex tasks easier to execute, or do helpful integrations with other systems. The secret to doing so lies in the `PluginAcceptor`. As mentioned earlier, the `PluginAcceptor` provides access to the host of the plugin. It provides several important methods for doing so: . `addBinding` - These two function allow the plugin to inject whatever context it wants to the host. For example, doing `addBinding('x',1)` would place a variable of `x` with a value of 1 into the console at the time of the plugin load. . `eval` - Evaluates a script in the context of the host at the time of plugin startup. For example, doing `eval(""sum={x,y->x+y}"")` would create a `sum` function that would be available to the user of the Console after the load of the plugin. . `environment` - Provides context from the host environment. For the console, the environment will return a `Map` containing a reference to the `IO` stream and the `Groovysh` instance. These classes represent very low-level access to the underpinnings of the console. Access to `Groovysh` allows for advanced features such as registering new commands (e.g. like the `:plugin` or `:remote` commands). Plugins can also tie into the `:remote` and `:submit` commands. Recall that a `:remote` represents a different context within which Gremlin is executed, when issued with `:submit`. It is encouraged to use this integration point when possible, as opposed to registering new commands that can otherwise follow the `:remote` and `:submit` pattern. To expose this integration point as part of a plugin, implement the `RemoteAcceptor` interface: TIP: Be good to the users of plugins and prevent dependency conflicts. Maintaining a conflict free plugin is most easily done by using the link:http://maven.apache.org/enforcer/maven-enforcer-plugin/[Maven Enforcer Plugin]. TIP: Consider binding the plugin's minor version to the TinkerPop minor version so that it's easy for users to figure out plugin compatibility. Otherwise, clearly document a compatibility matrix for the plugin somewhere that users can find it. [source,java] ---- include::{basedir}/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/jsr223/console/RemoteAcceptor.java[] ---- The `RemoteAcceptor` can be bound to a `GremlinPlugin` by adding a `ConsoleCustomizer` implementation to the list of `Customizer` instances that are returned from the `GremlinPlugin`. The `ConsoleCustomizer` will only be executed when in use with the Gremlin Console plugin host. Simply instantiate and return a `RemoteAcceptor` in the `ConsoleCustomizer.getRemoteAcceptor(GremlinShellEnvironment)` method. Generally speaking, each call to `getRemoteAcceptor(GremlinShellEnvironment)` should produce a new instance of a `RemoteAcceptor`. ",16337,True,2520.8149665333945,median "package Ankama_Taxi.ui { import com.ankamagames.berilia.api.UiApi; import com.ankamagames.berilia.components.Grid; import com.ankamagames.berilia.components.Input; import com.ankamagames.berilia.components.Label; import com.ankamagames.berilia.components.Texture; import com.ankamagames.berilia.enums.SelectMethodEnum; import com.ankamagames.berilia.enums.StatesEnum; import com.ankamagames.berilia.types.LocationEnum; import com.ankamagames.berilia.types.graphic.ButtonContainer; import com.ankamagames.berilia.types.graphic.GraphicContainer; import com.ankamagames.berilia.utils.BeriliaHookList; import com.ankamagames.berilia.utils.ComponentHookList; import com.ankamagames.dofus.datacenter.world.MapPosition; import com.ankamagames.dofus.datacenter.world.Waypoint; import com.ankamagames.dofus.internalDatacenter.taxi.TeleportDestinationWrapper; import com.ankamagames.dofus.kernel.sound.enum.SoundTypeEnum; import com.ankamagames.dofus.kernel.sound.enum.UISoundEnum; import com.ankamagames.dofus.logic.game.roleplay.actions.LeaveDialogRequestAction; import com.ankamagames.dofus.logic.game.roleplay.actions.TeleportRequestAction; import com.ankamagames.dofus.logic.game.roleplay.actions.ZaapRespawnSaveRequestAction; import com.ankamagames.dofus.misc.lists.ChatHookList; import com.ankamagames.dofus.misc.lists.HookList; import com.ankamagames.dofus.misc.lists.RoleplayHookList; import com.ankamagames.dofus.network.enums.TeleporterTypeEnum; import com.ankamagames.dofus.uiApi.DataApi; import com.ankamagames.dofus.uiApi.PlayedCharacterApi; import com.ankamagames.dofus.uiApi.RoleplayApi; import com.ankamagames.dofus.uiApi.SoundApi; import com.ankamagames.dofus.uiApi.SystemApi; import com.ankamagames.dofus.uiApi.TimeApi; import com.ankamagames.dofus.uiApi.UiTutoApi; import com.ankamagames.dofus.uiApi.UtilApi; import com.ankamagames.jerakine.types.Uri; import com.ankamagames.jerakine.types.enums.DataStoreEnum; import flash.display.DisplayObject; import flash.utils.Dictionary; public class ZaapSelection { protected static const SORT_SPAWN:String = ""spawn""; protected static const SORT_AREA_NAME:String = ""areaName""; protected static const SORT_SUB_AREA_NAME:String = ""subAreaName""; protected static const SORT_COORD:String = ""coord""; protected static const SORT_COST:String = ""cost""; [Api(name=""SystemApi"")] public var sysApi:SystemApi; [Api(name=""UiApi"")] public var uiApi:UiApi; [Api(name=""PlayedCharacterApi"")] public var playerApi:PlayedCharacterApi; [Api(name=""RoleplayApi"")] public var rpApi:RoleplayApi; [Api(name=""DataApi"")] public var dataApi:DataApi; [Api(name=""SoundApi"")] public var soundApi:SoundApi; [Api(name=""UtilApi"")] public var utilApi:UtilApi; [Api(name=""UiTutoApi"")] public var hintsApi:UiTutoApi; [Api(name=""TimeApi"")] public var timeApi:TimeApi; private var INPUT_SEARCH_DEFAULT_TEXT:String; private var _params:Array; private var _teleportType:uint; private var _bDescendingSort:Boolean = false; protected var _componentsList:Dictionary; protected var _favoriteZaap:Array; protected var _fullZaapList:Array; protected var _tab1List:Array; protected var _tab2List:Array; protected var _tab3List:Array; protected var _currentdataProvider:Array; protected var _currentSortCriteria:String = ""areaName""; protected var _cacheSortCriteriaName:String; protected var _cacheDescendingSortName:String; protected var _currentZaap:TeleportDestinationWrapper; protected var _currentSpawnZaap:TeleportDestinationWrapper; protected var _uriEmptyStar:Uri; protected var _uriYellowStar:Uri; protected var _uriAnomaly:Uri; private var _currentTabName:String; private var _lastFavZaap:TeleportDestinationWrapper; private var _lastKnownZaap:TeleportDestinationWrapper; protected var _usingZaapi:Boolean = false; public var lbl_title:Label; public var lbl_availableKamasNb:Label; public var tx_availableKamas:Texture; public var lbl_noDestination:Label; public var tx_currentRespawn:Texture; public var gd_zaap:Grid; public var btn_validate:ButtonContainer; public var btn_close:ButtonContainer; public var btn_tabSpawn:ButtonContainer; public var btn_tabSubAreaName:ButtonContainer; public var btn_tabAreaName:ButtonContainer; public var btn_tabCoord:ButtonContainer; public var btn_tabCost:ButtonContainer; public var btn_resetSearch:ButtonContainer; public var tx_sortSubAreaDown:Texture; public var tx_sortSubAreaUp:Texture; public var tx_sortAreaUp:Texture; public var tx_sortAreaDown:Texture; public var tx_sortCoordUp:Texture; public var tx_sortCoordDown:Texture; public var tx_sortCostUp:Texture; public var tx_sortCostDown:Texture; public var btn_tab1:ButtonContainer; public var btn_tab2:ButtonContainer; public var btn_tab3:ButtonContainer; public var btn_help:ButtonContainer; public var tx_fav:Texture; public var btn_showUnknowZaap:ButtonContainer; public var btn_label_btn_showUnknowZaap:Label; public var lbl_btn_tab1:Label; public var lbl_btn_tab2:Label; public var lbl_btn_tab3:Label; public var lbl_tabSubAreaName:Label; public var lbl_tabAreaName:Label; public var lbl_tabCoord:Label; public var lbl_tabCost:Label; public var ctr_saveZaap:GraphicContainer; public var lbl_currentZaapSaved:Label; public var lbl_changeSavedZaap:Label; public var btn_save:ButtonContainer; public var inp_search:Input; public function ZaapSelection() { this._componentsList = new Dictionary(false); super(); } private static function sortArrayByCoord(a:TeleportDestinationWrapper, b:TeleportDestinationWrapper) : Number { var aCoordY:int = 0; var bCoordY:int = 0; var aCoordArray:Array = a.coord.split("",""); var bCoordArray:Array = b.coord.split("",""); var aCoordX:int = parseInt(aCoordArray[0]); var bCoordX:int = parseInt(bCoordArray[0]); if(aCoordX > bCoordX) { return 1; } if(aCoordX < bCoordX) { return -1; } aCoordY = parseInt(aCoordArray[1]); bCoordY = parseInt(bCoordArray[1]); if(aCoordY > bCoordY) { return 1; } if(aCoordY < bCoordY) { return -1; } return 0; } public function get currentTabName() : String { return this._currentTabName; } public function set currentTabName(value:String) : void { this._currentTabName = value; } public function main(params:Array) : void { this._params = params; this.soundApi.playSound(SoundTypeEnum.OPEN_WINDOW); this.btn_validate.soundId = UISoundEnum.OK_BUTTON; this.btn_close.soundId = UISoundEnum.CANCEL_BUTTON; this.btn_tab1.soundId = UISoundEnum.TAB; this.btn_tab2.soundId = UISoundEnum.TAB; this.btn_tab3.soundId = UISoundEnum.TAB; this.sysApi.addHook(BeriliaHookList.UiLoaded,this.onUiLoaded); this.sysApi.addHook(RoleplayHookList.TeleportDestinationList,this.onTeleportDestinationList); this.sysApi.addHook(HookList.LeaveDialog,this.onLeaveDialog); this.sysApi.addHook(BeriliaHookList.KeyUp,this.onKeyUp); this.sysApi.addHook(HookList.SaveCurrentZaap,this.onSaveCurrentZaap); this.uiApi.addShortcutHook(""closeUi"",this.onShortcut); this.uiApi.addShortcutHook(""validUi"",this.onShortcut); this.uiApi.addComponentHook(this.gd_zaap,ComponentHookList.ON_SELECT_ITEM); this.uiApi.addComponentHook(this.tx_fav,ComponentHookList.ON_RELEASE); this.uiApi.addComponentHook(this.tx_fav,ComponentHookList.ON_ROLL_OVER); this.uiApi.addComponentHook(this.tx_fav,ComponentHookList.ON_ROLL_OUT); this.uiApi.addComponentHook(this.btn_save,ComponentHookList.ON_ROLL_OVER); this.uiApi.addComponentHook(this.btn_save,ComponentHookList.ON_ROLL_OUT); this.uiApi.addComponentHook(this.tx_currentRespawn,ComponentHookList.ON_ROLL_OVER); this.uiApi.addComponentHook(this.tx_currentRespawn,ComponentHookList.ON_ROLL_OUT); this.uiApi.addComponentHook(this.inp_search,ComponentHookList.ON_RELEASE); this.uiApi.addComponentHook(this.btn_help,ComponentHookList.ON_RELEASE); this._cacheSortCriteriaName = this.uiApi.me().name + ""_sortCriteria""; this._cacheDescendingSortName = this.uiApi.me().name + ""_descendingSort""; this._currentSortCriteria = this.sysApi.getSetData(this._cacheSortCriteriaName,SORT_AREA_NAME,DataStoreEnum.BIND_ACCOUNT); this._bDescendingSort = this.sysApi.getSetData(this._cacheDescendingSortName,false,DataStoreEnum.BIND_ACCOUNT); this._teleportType = params[1]; if(this._teleportType != TeleporterTypeEnum.TELEPORTER_SUBWAY) { this.lbl_btn_tab1.text = this.uiApi.getText(""ui.zaap.zaap""); this.lbl_btn_tab2.text = this.uiApi.getText(""ui.zaap.prism""); this.lbl_btn_tab3.text = this.uiApi.getText(""ui.zaap.anomaly""); if(this.btn_tab1.selected) { this.currentTabName = ""zaap""; } else if(this.btn_tab2.selected) { this.currentTabName = ""prism""; } else { this.currentTabName = ""anomaly""; } } this.btn_showUnknowZaap.visible = true; this.tx_fav.handCursor = true; this.btn_showUnknowZaap.selected = this.sysApi.getData(""showUnknowZaap""); this.lbl_availableKamasNb.text = this.utilApi.kamasToString(this.playerApi.characteristics().kamas,""""); this.INPUT_SEARCH_DEFAULT_TEXT = this.uiApi.getText(""ui.zaap.searchDestination""); this.inp_search.placeholderText = this.INPUT_SEARCH_DEFAULT_TEXT; this.inp_search.focus(); this._uriEmptyStar = this.uiApi.createUri(this.uiApi.me().getConstant(""texture"") + ""zaap/"" + ""icon_star_normal.png""); this._uriYellowStar = this.uiApi.createUri(this.uiApi.me().getConstant(""texture"") + ""zaap/"" + ""icon_star_selected.png""); this._uriAnomaly = this.uiApi.createUri(this.uiApi.me().getConstant(""texture"") + ""zaap/"" + ""icon_anomaly_grey.png""); this._favoriteZaap = this.sysApi.getData(""favoriteZap""); } public function unload() : void { this.soundApi.playSound(SoundTypeEnum.CLOSE_WINDOW); } public function updateZaapLine(data:*, componentsRef:*, selected:Boolean) : void { if(data) { if(!this._componentsList[componentsRef.btn_zaapCoord.name]) { this.uiApi.addComponentHook(componentsRef.btn_zaapCoord,ComponentHookList.ON_RELEASE); this.uiApi.addComponentHook(componentsRef.lbl_zaapCoord,ComponentHookList.ON_ROLL_OVER); this.uiApi.addComponentHook(componentsRef.lbl_zaapCoord,ComponentHookList.ON_ROLL_OUT); } this._componentsList[componentsRef.btn_zaapCoord.name] = data; componentsRef.lbl_zaapSubArea.text = !!this._usingZaapi ? data.areaName : data.subAreaName; componentsRef.lbl_zaapArea.text = !!this._usingZaapi ? data.subAreaName : data.areaName; componentsRef.lbl_zaapCoord.text = ""("" + data.coord + "")""; componentsRef.btn_savedZaap.visible = false; componentsRef.tx_lineSeparator.visible = false; if(this.btn_tab3.selected && this._teleportType != TeleporterTypeEnum.TELEPORTER_SUBWAY) { componentsRef.lbl_zaapCost.text = data.level; this.updateAnomalyZaapLine(componentsRef,data.mapId); } else { componentsRef.lbl_zaapCost.text = this.utilApi.kamasToString(data.cost,""""); this.updateZaapZaapLine(componentsRef,data); } componentsRef.btn_zaapSubArea.disabled = false; componentsRef.btn_zaapCoord.disabled = false; componentsRef.btn_zaapSubArea.selected = selected; componentsRef.btn_zaapCoord.selected = selected; componentsRef.btn_favoritZap.selected = selected; componentsRef.btn_zaapSubArea.state = !!selected ? StatesEnum.STATE_SELECTED : StatesEnum.STATE_NORMAL; componentsRef.tx_favoritZap.visible = true; } else { componentsRef.lbl_zaapSubArea.text = """"; componentsRef.lbl_zaapArea.text = """"; componentsRef.lbl_zaapCost.text = """"; componentsRef.lbl_zaapCoord.text = """"; componentsRef.btn_zaapSubArea.selected = false; componentsRef.btn_zaapSubArea.disabled = true; componentsRef.btn_zaapCoord.disabled = true; componentsRef.btn_favoritZap.disabled = true; componentsRef.tx_favoritZap.visible = false; componentsRef.tx_zaapCost.visible = false; componentsRef.btn_savedZaap.visible = false; componentsRef.tx_lineSeparator.visible = false; componentsRef.btn_savedZaap.visible = false; } } private function updateZaapZaapLine(componentsRef:*, data:*) : void { if(!this._componentsList[componentsRef.btn_favoritZap.name]) { this.uiApi.addComponentHook(componentsRef.btn_favoritZap,ComponentHookList.ON_RELEASE); this.uiApi.addComponentHook(componentsRef.btn_favoritZap,ComponentHookList.ON_ROLL_OVER); this.uiApi.addComponentHook(componentsRef.btn_favoritZap,ComponentHookList.ON_ROLL_OUT); } this._componentsList[componentsRef.btn_favoritZap.name] = data; if(!this._componentsList[componentsRef.btn_savedZaap.name]) { this.uiApi.addComponentHook(componentsRef.btn_savedZaap,ComponentHookList.ON_ROLL_OVER); this.uiApi.addComponentHook(componentsRef.btn_savedZaap,ComponentHookList.ON_ROLL_OUT); } this._componentsList[componentsRef.btn_savedZaap.name] = data; if(this._favoriteZaap && this._favoriteZaap.indexOf(data.mapId) != -1) { componentsRef.tx_favoritZap.uri = this._uriYellowStar; } else { componentsRef.tx_favoritZap.uri = this._uriEmptyStar; } componentsRef.tx_favoritZap.alpha = 1; componentsRef.tx_zaapCost.visible = data.known && data.mapId != this.playerApi.currentMap().mapId; componentsRef.btn_favoritZap.visible = data.known; componentsRef.btn_favoritZap.disabled = !data.known; if(data.known) { if(data == this._lastFavZaap || data == this._lastKnownZaap && this.btn_showUnknowZaap.selected) { componentsRef.tx_lineSeparator.visible = true; } if(data.spawn) { componentsRef.lbl_zaapSubArea.cssClass = ""green""; componentsRef.lbl_zaapArea.cssClass = ""italic""; if(this.playerApi.characteristics().kamas < data.cost) { componentsRef.lbl_zaapCost.cssClass = ""redright""; } else { componentsRef.lbl_zaapCost.cssClass = ""right""; } if(data.mapId == this.playerApi.currentMap().mapId) { componentsRef.lbl_zaapCost.text = """"; } componentsRef.btn_savedZaap.visible = true; componentsRef.btn_savedZaap.x = componentsRef.lbl_zaapSubArea.x + Math.min(this.uiApi.me().getConstant(""lbl_subArea_width""),componentsRef.lbl_zaapSubArea.textWidth) + 10; componentsRef.btn_savedZaap.y = 10; } else if(data.mapId == this.playerApi.currentMap().mapId) { componentsRef.lbl_zaapSubArea.cssClass = ""orangeleft""; componentsRef.lbl_zaapArea.cssClass = ""italic""; componentsRef.lbl_zaapCoord.cssClass = ""greencenter""; componentsRef.lbl_zaapCost.cssClass = ""right""; componentsRef.lbl_zaapCost.text = """"; } else if(this.playerApi.characteristics().kamas < data.cost) { componentsRef.lbl_zaapSubArea.cssClass = ""disabled""; componentsRef.lbl_zaapArea.cssClass = ""disabled""; componentsRef.lbl_zaapCoord.cssClass = ""disabledcenter""; componentsRef.lbl_zaapCost.cssClass = ""redright""; } else { componentsRef.lbl_zaapSubArea.cssClass = ""bold""; componentsRef.lbl_zaapArea.cssClass = ""italic""; componentsRef.lbl_zaapCoord.cssClass = ""greencenter""; componentsRef.lbl_zaapCost.cssClass = ""right""; } } else { componentsRef.lbl_zaapSubArea.cssClass = ""disabled""; componentsRef.lbl_zaapArea.cssClass = ""disabled""; componentsRef.lbl_zaapCoord.cssClass = ""disabledcenter""; componentsRef.lbl_zaapCost.cssClass = ""disabledright""; componentsRef.lbl_zaapCost.text = ""--""; } } private function updateAnomalyZaapLine(componentsRef:*, mapId:Number) : void { if(this._componentsList[componentsRef.btn_favoritZap.name]) { this.uiApi.removeComponentHook(componentsRef.btn_favoritZap,ComponentHookList.ON_RELEASE); this.uiApi.removeComponentHook(componentsRef.btn_favoritZap,ComponentHookList.ON_ROLL_OVER); this.uiApi.removeComponentHook(componentsRef.btn_favoritZap,ComponentHookList.ON_ROLL_OUT); } this._componentsList[componentsRef.btn_favoritZap.name] = null; componentsRef.tx_favoritZap.uri = this._uriAnomaly; componentsRef.tx_zaapCost.visible = false; componentsRef.btn_favoritZap.visible = true; componentsRef.btn_favoritZap.disabled = false; if(mapId == this.playerApi.currentMap().mapId) { componentsRef.lbl_zaapSubArea.cssClass = ""p""; componentsRef.lbl_zaapArea.cssClass = ""p""; componentsRef.lbl_zaapCoord.cssClass = ""greencenter""; componentsRef.lbl_zaapCost.cssClass = ""right""; componentsRef.tx_favoritZap.alpha = 1; } else { componentsRef.lbl_zaapSubArea.cssClass = ""disabled""; componentsRef.lbl_zaapArea.cssClass = ""disabled""; componentsRef.lbl_zaapCoord.cssClass = ""disabledcenter""; componentsRef.lbl_zaapCost.cssClass = ""disabledright""; componentsRef.tx_favoritZap.alpha = 0.5; } } private function validateZaapChoice() : void { var selectedZaap:TeleportDestinationWrapper = this.gd_zaap.selectedItem; if(!selectedZaap) { return; } if(selectedZaap.destinationType == TeleporterTypeEnum.TELEPORTER_ANOMALY) { if(selectedZaap.mapId == this.playerApi.currentMap().mapId) { this.sysApi.sendAction(new TeleportRequestAction([this._teleportType,selectedZaap.destinationType,selectedZaap.subArea.id,selectedZaap.cost])); } else { this.sysApi.dispatchHook(ChatHookList.TextInformation,this.uiApi.getText(""ui.error.inaccessibleAnomaly""),666,this.timeApi.getTimestamp()); } } else { this.sysApi.sendAction(new TeleportRequestAction([this._teleportType,selectedZaap.destinationType,selectedZaap.mapId,selectedZaap.cost])); } } private function displaySortArrows() : void { if(this._usingZaapi) { this.tx_sortSubAreaDown.visible = this._currentSortCriteria == SORT_AREA_NAME && !this._bDescendingSort; this.tx_sortSubAreaUp.visible = this._currentSortCriteria == SORT_AREA_NAME && this._bDescendingSort; this.tx_sortAreaDown.visible = this._currentSortCriteria == SORT_SUB_AREA_NAME && !this._bDescendingSort; this.tx_sortAreaUp.visible = this._currentSortCriteria == SORT_SUB_AREA_NAME && this._bDescendingSort; } else { this.tx_sortSubAreaDown.visible = this._currentSortCriteria == SORT_SUB_AREA_NAME && !this._bDescendingSort; this.tx_sortSubAreaUp.visible = this._currentSortCriteria == SORT_SUB_AREA_NAME && this._bDescendingSort; this.tx_sortAreaDown.visible = this._currentSortCriteria == SORT_AREA_NAME && !this._bDescendingSort; this.tx_sortAreaUp.visible = this._currentSortCriteria == SORT_AREA_NAME && this._bDescendingSort; } this.tx_sortSubAreaDown.x = this.tx_sortSubAreaUp.x = this.lbl_tabSubAreaName.anchorX + this.uiApi.getTextSize(this.lbl_tabSubAreaName.text,this.lbl_tabSubAreaName.css,this.lbl_tabSubAreaName.cssClass).width + 10; this.tx_sortAreaDown.x = this.tx_sortAreaUp.x = this.lbl_tabAreaName.anchorX + this.uiApi.getTextSize(this.lbl_tabAreaName.text,this.lbl_tabAreaName.css,this.lbl_tabAreaName.cssClass).width + 10; this.tx_sortCoordDown.visible = this._currentSortCriteria == SORT_COORD && !this._bDescendingSort; this.tx_sortCoordUp.visible = this._currentSortCriteria == SORT_COORD && this._bDescendingSort; this.tx_sortCoordDown.x = this.tx_sortCoordUp.x = this.lbl_tabCoord.anchorX + this.uiApi.getTextSize(this.lbl_tabCoord.text,this.lbl_tabCoord.css,this.lbl_tabCoord.cssClass).width + 10; this.tx_sortCostDown.visible = this._currentSortCriteria == SORT_COST && !this._bDescendingSort; this.tx_sortCostUp.visible = this._currentSortCriteria == SORT_COST && this._bDescendingSort; this.tx_sortCostDown.x = this.tx_sortCostUp.x = this.lbl_tabCost.anchorX + this.uiApi.getTextSize(this.lbl_tabCost.text,this.lbl_tabCost.css,this.lbl_tabCost.cssClass).width + 10; } private function sortZaapiByAreaNameWithoutAccent(a:TeleportDestinationWrapper, b:TeleportDestinationWrapper) : Number { var aName:String = this.utilApi.noAccent(a.areaName); var bName:String = this.utilApi.noAccent(b.areaName); if(aName > bName) { return 1; } if(aName < bName) { return -1; } return this.sortZaapiBySubAreaNameWithoutAccent(a,b); } private function sortZaapiBySubAreaNameWithoutAccent(a:TeleportDestinationWrapper, b:TeleportDestinationWrapper) : Number { var aName:String = this.utilApi.noAccent(a.subAreaName); var bName:String = this.utilApi.noAccent(b.subAreaName); if(aName > bName) { return 1; } if(aName < bName) { return -1; } return this.sortZaapiByAreaNameWithoutAccent(a,b); } protected function sortZaap(zaapList:*, sortField:String) : Array { var zaap:TeleportDestinationWrapper = null; this._currentSortCriteria = sortField; this.sysApi.setData(this._cacheSortCriteriaName,this._currentSortCriteria,DataStoreEnum.BIND_ACCOUNT); if(!this._favoriteZaap) { this._favoriteZaap = []; } var favArray:Array = []; var noFavArray:Array = []; var unknowZaapArray:Array = []; for each(zaap in zaapList) { if(zaap.known && (zaapList != this._tab3List || this._teleportType != TeleporterTypeEnum.TELEPORTER_ZAAP) || zaapList == this._tab3List && this._teleportType == TeleporterTypeEnum.TELEPORTER_ZAAP && zaap.mapId == this.playerApi.currentMap().mapId) { if(this._favoriteZaap.indexOf(zaap.mapId) != -1 && zaap.known) { favArray.push(zaap); } else { noFavArray.push(zaap); } } else { unknowZaapArray.push(zaap); } } if(sortField == SORT_SUB_AREA_NAME) { if(this._bDescendingSort) { favArray.sort(this.sortZaapiBySubAreaNameWithoutAccent,Array.DESCENDING); noFavArray.sort(this.sortZaapiBySubAreaNameWithoutAccent,Array.DESCENDING); if(this.btn_showUnknowZaap.selected) { unknowZaapArray.sort(this.sortZaapiBySubAreaNameWithoutAccent,Array.DESCENDING); } } else { favArray.sort(this.sortZaapiBySubAreaNameWithoutAccent); noFavArray.sort(this.sortZaapiBySubAreaNameWithoutAccent); if(this.btn_showUnknowZaap.selected) { unknowZaapArray.sort(this.sortZaapiBySubAreaNameWithoutAccent); } } } else if(sortField == SORT_AREA_NAME) { if(this._bDescendingSort) { favArray.sort(this.sortZaapiByAreaNameWithoutAccent,Array.DESCENDING); noFavArray.sort(this.sortZaapiByAreaNameWithoutAccent,Array.DESCENDING); if(this.btn_showUnknowZaap.selected) { unknowZaapArray.sort(this.sortZaapiByAreaNameWithoutAccent,Array.DESCENDING); } } else { favArray.sort(this.sortZaapiByAreaNameWithoutAccent); noFavArray.sort(this.sortZaapiByAreaNameWithoutAccent); if(this.btn_showUnknowZaap.selected) { unknowZaapArray.sort(this.sortZaapiByAreaNameWithoutAccent); } } } else if(sortField == SORT_COORD) { if(this._bDescendingSort) { favArray.sort(sortArrayByCoord,Array.DESCENDING); noFavArray.sort(sortArrayByCoord,Array.DESCENDING); if(this.btn_showUnknowZaap.selected) { unknowZaapArray.sort(sortArrayByCoord,Array.DESCENDING); } } else { favArray.sort(sortArrayByCoord); noFavArray.sort(sortArrayByCoord); if(this.btn_showUnknowZaap.selected) { unknowZaapArray.sort(sortArrayByCoord); } } } else if(this._bDescendingSort) { favArray.sortOn(sortField,Array.NUMERIC | Array.DESCENDING); noFavArray.sortOn(sortField,Array.NUMERIC | Array.DESCENDING); if(this.btn_showUnknowZaap.selected) { unknowZaapArray.sortOn(sortField,Array.NUMERIC | Array.DESCENDING); } } else { favArray.sortOn(sortField,Array.NUMERIC); noFavArray.sortOn(sortField,Array.NUMERIC); if(this.btn_showUnknowZaap.selected) { unknowZaapArray.sortOn(sortField,Array.NUMERIC); } } this._lastFavZaap = favArray[favArray.length - 1]; this._lastKnownZaap = noFavArray[noFavArray.length - 1]; if(this.btn_showUnknowZaap.selected) { noFavArray = noFavArray.concat(unknowZaapArray); } return favArray.concat(noFavArray); } public function onRelease(target:GraphicContainer) : void { var p:MapPosition = null; var flagText:String = null; var currentZaap:* = undefined; if(target.name.indexOf(""btn_zaapCoord"") != -1) { p = this.dataApi.getMapInfo(this._componentsList[target.name].mapId); if(this._teleportType == TeleporterTypeEnum.TELEPORTER_ZAAP) { flagText = this.uiApi.getText(""ui.zaap.zaap""); } else if(this._teleportType == TeleporterTypeEnum.TELEPORTER_PRISM) { flagText = this.uiApi.getText(""ui.zaap.prism""); } else if(this._teleportType == TeleporterTypeEnum.TELEPORTER_SUBWAY) { flagText = this.uiApi.getText(""ui.zaap.zaapi""); } flagText += "" - "" + this._componentsList[target.name].areaName + ""("" + this._componentsList[target.name].subAreaName + "")"" + "" ("" + this._componentsList[target.name].coord + "")""; this.sysApi.dispatchHook(HookList.AddMapFlag,""flag_teleportPoint_"" + p.posX + ""_"" + p.posY,flagText,p.worldMap,p.posX,p.posY,8969710,true); } else if(target.name.indexOf(""btn_favoritZap"") != -1) { this.addRemoveFavoritZaap(this._componentsList[target.name]); } else { switch(target) { case this.btn_tab1: case this.btn_tab2: case this.btn_tab3: this.changeZaapTab(target as ButtonContainer); break; case this.tx_fav: for each(currentZaap in this._fullZaapList) { if(currentZaap.mapId == this._currentZaap.mapId) { this.addRemoveFavoritZaap(currentZaap); break; } } break; case this.btn_save: this.sysApi.sendAction(new ZaapRespawnSaveRequestAction([])); break; case this.btn_validate: this.validateZaapChoice(); break; case this.btn_close: this.sysApi.sendAction(new LeaveDialogRequestAction([])); break; case this.btn_tabSpawn: if(this._currentSortCriteria == SORT_SPAWN) { this._bDescendingSort = !this._bDescendingSort; this.sysApi.setData(this._cacheDescendingSortName,this._bDescendingSort,DataStoreEnum.BIND_ACCOUNT); } this.gd_zaap.dataProvider = this.sortZaap(this.gd_zaap.dataProvider,SORT_SPAWN); break; case this.btn_tabSubAreaName: if(this._usingZaapi) { if(this._currentSortCriteria == SORT_AREA_NAME) { this._bDescendingSort = !this._bDescendingSort; this.sysApi.setData(this._cacheDescendingSortName,this._bDescendingSort,DataStoreEnum.BIND_ACCOUNT); } this.gd_zaap.dataProvider = this.sortZaap(this.gd_zaap.dataProvider,SORT_AREA_NAME); } else { if(this._currentSortCriteria == SORT_SUB_AREA_NAME) { this._bDescendingSort = !this._bDescendingSort; this.sysApi.setData(this._cacheDescendingSortName,this._bDescendingSort,DataStoreEnum.BIND_ACCOUNT); } this.gd_zaap.dataProvider = this.sortZaap(this.gd_zaap.dataProvider,SORT_SUB_AREA_NAME); } this.displaySortArrows(); break; case this.btn_tabAreaName: if(this._usingZaapi) { if(this._currentSortCriteria == SORT_SUB_AREA_NAME) { this._bDescendingSort = !this._bDescendingSort; this.sysApi.setData(this._cacheDescendingSortName,this._bDescendingSort,DataStoreEnum.BIND_ACCOUNT); } this.gd_zaap.dataProvider = this.sortZaap(this.gd_zaap.dataProvider,SORT_SUB_AREA_NAME); } else { if(this._currentSortCriteria == SORT_AREA_NAME) { this._bDescendingSort = !this._bDescendingSort; this.sysApi.setData(this._cacheDescendingSortName,this._bDescendingSort,DataStoreEnum.BIND_ACCOUNT); } this.gd_zaap.dataProvider = this.sortZaap(this.gd_zaap.dataProvider,SORT_AREA_NAME); } this.displaySortArrows(); break; case this.btn_tabCoord: if(this._currentSortCriteria == SORT_COORD) { this._bDescendingSort = !this._bDescendingSort; this.sysApi.setData(this._cacheDescendingSortName,this._bDescendingSort,DataStoreEnum.BIND_ACCOUNT); } this.gd_zaap.dataProvider = this.sortZaap(this.gd_zaap.dataProvider,SORT_COORD); this.displaySortArrows(); break; case this.btn_tabCost: if(this._currentSortCriteria == SORT_COST) { this._bDescendingSort = !this._bDescendingSort; this.sysApi.setData(this._cacheDescendingSortName,this._bDescendingSort,DataStoreEnum.BIND_ACCOUNT); } this.gd_zaap.dataProvider = this.sortZaap(this.gd_zaap.dataProvider,SORT_COST); this.displaySortArrows(); break; case this.btn_showUnknowZaap: this.sysApi.setData(""showUnknowZaap"",this.btn_showUnknowZaap.selected); this.gd_zaap.dataProvider = this.sortZaap(this._currentdataProvider,this._currentSortCriteria); break; case this.btn_resetSearch: if(this.inp_search.text != this.INPUT_SEARCH_DEFAULT_TEXT) { this.inp_search.placeholderText = this.INPUT_SEARCH_DEFAULT_TEXT; this.gd_zaap.dataProvider = this.sortZaap(this._currentdataProvider,this._currentSortCriteria); } break; case this.btn_help: this.hintsApi.showSubHints(this.currentTabName); } } } protected function changeZaapTab(target:ButtonContainer) : void { var tabList:Array = null; if(target == this.btn_tab3) { this.currentTabName = ""anomaly""; tabList = this._tab3List; this.lbl_tabSubAreaName.text = this.uiApi.getText(""ui.common.subarea""); this.lbl_tabAreaName.text = this.uiApi.getText(""ui.common.area""); this.lbl_tabCoord.text = this.uiApi.getText(""ui.zaap.associatedZaap""); this.lbl_tabCost.text = this.uiApi.getText(""ui.common.level""); this.btn_label_btn_showUnknowZaap.text = this.uiApi.getText(""ui.zaap.showAllAnomaly""); } else { if(target == this.btn_tab1) { this.currentTabName = ""zaap""; tabList = this._tab1List; } else if(target == this.btn_tab2) { this.currentTabName = ""prism""; tabList = this._tab2List; } this.lbl_tabSubAreaName.text = this.uiApi.getText(""ui.common.subarea""); this.lbl_tabAreaName.text = this.uiApi.getText(""ui.common.area""); this.lbl_tabCoord.text = this.uiApi.getText(""ui.common.coordinatesSmall""); this.lbl_tabCost.text = this.uiApi.getText(""ui.common.cost""); this.btn_label_btn_showUnknowZaap.text = this.uiApi.getText(""ui.zaap.showUnknowZaap""); } if(this._currentSpawnZaap) { this.btn_save.visible = false; this.ctr_saveZaap.visible = target == this.btn_tab1 && this._teleportType == TeleporterTypeEnum.TELEPORTER_ZAAP; } else { this.ctr_saveZaap.visible = false; this.btn_save.visible = target == this.btn_tab1 && this._teleportType == TeleporterTypeEnum.TELEPORTER_ZAAP; } this.tx_currentRespawn.visible = target == this.btn_tab1 && this._teleportType == TeleporterTypeEnum.TELEPORTER_ZAAP; this.lbl_availableKamasNb.visible = target != this.btn_tab3; this.tx_availableKamas.visible = target != this.btn_tab3; this.hintsApi.uiTutoTabLaunch(); this.gd_zaap.dataProvider = this.sortZaap(tabList,this._currentSortCriteria); this._currentdataProvider = tabList; } protected function addRemoveFavoritZaap(favZaap:Object) : void { var zaap:* = undefined; if(!this._favoriteZaap) { this._favoriteZaap = []; } if(this._favoriteZaap.indexOf(favZaap.mapId) == -1) { for each(zaap in this._fullZaapList) { if(zaap.coord == favZaap.coord && this._favoriteZaap.indexOf(zaap.mapId) == -1) { this._favoriteZaap.push(zaap.mapId); } } } else { for each(zaap in this._fullZaapList) { if(zaap.coord == favZaap.coord) { this._favoriteZaap.splice(this._favoriteZaap.indexOf(zaap.mapId),1); } } } this.sysApi.setData(""favoriteZap"",this._favoriteZaap.concat()); if(this._currentZaap && this._favoriteZaap.indexOf(this._currentZaap.mapId) != -1) { this.tx_fav.uri = this._uriYellowStar; } else { this.tx_fav.uri = this._uriEmptyStar; } this.gd_zaap.dataProvider = this.sortZaap(this.gd_zaap.dataProvider,this._currentSortCriteria); } public function onUiLoaded(pUiName:String) : void { if(pUiName == this.uiApi.me().name) { this.onZaapList(this._params[0]); this.displaySortArrows(); } } public function onRollOver(target:GraphicContainer) : void { var text:String = null; var point:int = 7; var relativePoint:int = 1; var offset:int = 3; if(target.name.indexOf(""lbl_zaapCoord"") != -1) { text = this.uiApi.getText(""ui.tooltip.questMarker""); } else if(target.name.indexOf(""btn_favoritZap"") != -1) { if(this._favoriteZaap && this._favoriteZaap.indexOf(this._componentsList[target.name].mapId) != -1) { text = this.uiApi.getText(""ui.zaap.deleteFavoritTooltip""); } else { text = this.uiApi.getText(""ui.zaap.addFavoritTooltip""); } } else if(target == this.tx_fav) { if(this._favoriteZaap && this._currentZaap && this._favoriteZaap.indexOf(this._currentZaap.mapId) != -1) { text = this.uiApi.getText(""ui.zaap.deleteFavoritTooltip""); } else { text = this.uiApi.getText(""ui.zaap.addFavoritTooltip""); } } else if(target == this.tx_currentRespawn || target.name.indexOf(""btn_savedZaap"") != -1) { text = this.uiApi.getText(""ui.zaap.respawn""); } else if(target == this.btn_save) { if(this._teleportType == TeleporterTypeEnum.TELEPORTER_HAVENBAG || this.playerApi.isInHavenbag()) { text = this.uiApi.getText(""ui.zaap.saveInHavenbag""); } else { text = this.uiApi.getText(""ui.zaap.saveAsRespawn""); } } else if(target == this.lbl_availableKamasNb) { text = this.uiApi.getText(""ui.storage.ownedKamas""); point = LocationEnum.POINT_BOTTOMRIGHT; relativePoint = LocationEnum.POINT_TOPRIGHT; offset = 0; } if(text) { this.uiApi.showTooltip(this.uiApi.textTooltipInfo(text),target,false,""standard"",point,relativePoint,offset,null,null,null,""TextInfo""); } } public function onRollOut(target:GraphicContainer) : void { this.uiApi.hideTooltip(); } public function onKeyUp(target:DisplayObject, keyCode:uint) : void { var filteredDataProvider:Array = null; var searchCriteria:String = null; var tdv:TeleportDestinationWrapper = null; if(this.inp_search.haveFocus && this.inp_search.text != this.INPUT_SEARCH_DEFAULT_TEXT) { filteredDataProvider = []; searchCriteria = this.utilApi.noAccent(this.inp_search.text).toLowerCase(); for each(tdv in this._currentdataProvider) { if(this.utilApi.noAccent(tdv.subAreaName).toLowerCase().indexOf(searchCriteria) != -1 || this.utilApi.noAccent(tdv.areaName).toLowerCase().indexOf(searchCriteria) != -1) { filteredDataProvider.push(tdv); } } this.gd_zaap.dataProvider = this.sortZaap(filteredDataProvider,this._currentSortCriteria); } } public function onShortcut(s:String) : Boolean { switch(s) { case ""validUi"": this.validateZaapChoice(); return true; case ""closeUi"": this.sysApi.sendAction(new LeaveDialogRequestAction([])); return true; default: return false; } } public function onSelectItem(target:GraphicContainer, selectMethod:uint, isNewSelection:Boolean) : void { if(selectMethod == SelectMethodEnum.DOUBLE_CLICK) { this.validateZaapChoice(); } } public function onTeleportDestinationList(teleportList:Object, tpType:uint) : void { var i:* = null; var tdp:TeleportDestinationWrapper = null; var onCurrentMap:* = false; this._tab1List = []; this._tab2List = []; this._tab3List = []; this.tx_currentRespawn.visible = false; this.btn_save.softDisabled = false; if(teleportList.length != 0) { for(i in teleportList) { if(teleportList[i].destinationType == TeleporterTypeEnum.TELEPORTER_ZAAP) { this._tab1List.push(teleportList[i]); } else if(teleportList[i].destinationType == TeleporterTypeEnum.TELEPORTER_PRISM) { this._tab2List.push(teleportList[i]); } else if(teleportList[i].destinationType == TeleporterTypeEnum.TELEPORTER_ANOMALY) { this._tab3List.push(teleportList[i]); } if(teleportList[i].mapId == this.playerApi.currentMap().mapId) { this._teleportType = teleportList[i].destinationType; } if(teleportList[i].spawn) { this._currentSpawnZaap = teleportList[i]; } } if(this._currentSpawnZaap) { this.btn_save.visible = false; this.ctr_saveZaap.visible = true; this.lbl_currentZaapSaved.text = this._currentSpawnZaap.subAreaName; if(this._currentZaap) { this.lbl_changeSavedZaap.text = "" ("" + this.uiApi.getText(""ui.zaap.changeBy"") + "" "" + this._currentZaap.subAreaName + "")""; this.lbl_changeSavedZaap.x = this.lbl_currentZaapSaved.x + this.uiApi.getTextSize(this.lbl_currentZaapSaved.text,this.lbl_currentZaapSaved.css,this.lbl_currentZaapSaved.cssClass).width + 3; this.lbl_changeSavedZaap.width = 380 - this.lbl_changeSavedZaap.x; } onCurrentMap = this._currentSpawnZaap.mapId != this.playerApi.currentMap().mapId; if(onCurrentMap) { this.lbl_currentZaapSaved.width = this.uiApi.me().getConstant(""lbl_currentZaapSaved_minWidth""); } else { this.lbl_currentZaapSaved.width = this.uiApi.me().getConstant(""lbl_currentZaapSaved_maxWidth""); } this.lbl_changeSavedZaap.visible = onCurrentMap; } else { this.btn_save.visible = true; this.ctr_saveZaap.visible = false; } for each(tdp in this.dataApi.getUnknowZaaps(this._tab1List)) { if(tdp.mapId != this.playerApi.currentMap().mapId) { this._tab1List.push(tdp); } } if(this.btn_tab1.selected) { this.tx_currentRespawn.visible = this._teleportType == TeleporterTypeEnum.TELEPORTER_ZAAP; this.gd_zaap.dataProvider = this.sortZaap(this._tab1List,this._currentSortCriteria); this._currentdataProvider = this._tab1List; } else if(this.btn_tab2.selected) { this.gd_zaap.dataProvider = this.sortZaap(this._tab2List,this._currentSortCriteria); this._currentdataProvider = this._tab2List; } else if(this.btn_tab3.selected) { this.gd_zaap.dataProvider = this.sortZaap(this._tab3List,this._currentSortCriteria); this._currentdataProvider = this._tab3List; } this.gd_zaap.visible = true; this.lbl_noDestination.visible = false; } else { this.gd_zaap.visible = false; this.lbl_noDestination.visible = true; if(this.btn_tab1.selected) { this.tx_currentRespawn.visible = this._teleportType == TeleporterTypeEnum.TELEPORTER_ZAAP; this.btn_save.softDisabled = this.rpApi.getSpawnMap() == this.playerApi.currentMap().mapId; } } if(this._teleportType == TeleporterTypeEnum.TELEPORTER_HAVENBAG || this.playerApi.isInHavenbag()) { this.btn_save.softDisabled = true; this.tx_fav.visible = false; } } public function onZaapList(zaapList:Object) : void { var i:* = null; var isVestige:Boolean = false; var waypoint:Waypoint = null; var tdp:TeleportDestinationWrapper = null; this._tab1List = []; this._tab2List = []; this._tab3List = []; this._fullZaapList = []; this._currentSortCriteria = this.sysApi.getSetData(this._cacheSortCriteriaName,SORT_AREA_NAME,DataStoreEnum.BIND_ACCOUNT); this.tx_currentRespawn.visible = false; this.btn_save.softDisabled = false; this.btn_save.visible = false; if(zaapList.length != 0) { for(i in zaapList) { this._fullZaapList.push(zaapList[i]); if(zaapList[i].destinationType == TeleporterTypeEnum.TELEPORTER_ZAAP) { this._tab1List.push(zaapList[i]); } else if(zaapList[i].destinationType == TeleporterTypeEnum.TELEPORTER_PRISM) { this._tab2List.push(zaapList[i]); } else if(zaapList[i].destinationType == TeleporterTypeEnum.TELEPORTER_ANOMALY) { this._tab3List.push(zaapList[i]); } if(zaapList[i].mapId == this.playerApi.currentMap().mapId && zaapList[i].destinationType != TeleporterTypeEnum.TELEPORTER_ANOMALY) { this._teleportType = zaapList[i].destinationType; this._currentZaap = zaapList[i]; } if(zaapList[i].spawn) { this._currentSpawnZaap = zaapList[i]; } } if(this._currentSpawnZaap) { this.btn_save.visible = false; this.ctr_saveZaap.visible = true; this.lbl_currentZaapSaved.text = this._currentSpawnZaap.subAreaName; if(this._currentZaap) { this.lbl_changeSavedZaap.text = "" ("" + this.uiApi.getText(""ui.zaap.changeBy"") + "" "" + this._currentZaap.subAreaName + "")""; this.lbl_changeSavedZaap.x = this.lbl_currentZaapSaved.x + this.uiApi.getTextSize(this.lbl_currentZaapSaved.text,this.lbl_currentZaapSaved.css,this.lbl_currentZaapSaved.cssClass).width + 3; this.lbl_changeSavedZaap.width = 380 - this.lbl_changeSavedZaap.x; } this.lbl_changeSavedZaap.visible = this._currentSpawnZaap.mapId != this.playerApi.currentMap().mapId; } else { this.btn_save.visible = true; this.ctr_saveZaap.visible = false; } isVestige = false; for each(waypoint in this.dataApi.getAllWaypoints()) { if(waypoint.activated == false && this.playerApi.currentMap().mapId == waypoint.mapId) { this.lbl_title.text = this.uiApi.getText(""ui.zaap.zaap"") + "" - "" + this.playerApi.currentSubArea().name; this.tx_fav.visible = false; this.btn_tab1.visible = false; this.btn_tab2.visible = false; this.btn_tab3.disabled = false; this.btn_tab3.x = this.btn_tab1.x; this.uiApi.me().render(); isVestige = true; break; } } if(!isVestige) { if(this._favoriteZaap && this._currentZaap && this._favoriteZaap.indexOf(this._currentZaap.mapId) != -1) { this.tx_fav.uri = this._uriYellowStar; } else { this.tx_fav.uri = this._uriEmptyStar; } for each(tdp in this.dataApi.getUnknowZaaps(this._tab1List)) { if(tdp.mapId != this.playerApi.currentMap().mapId) { this._tab1List.push(tdp); } } this.btn_tab1.disabled = false; this.btn_tab2.disabled = this._tab2List.length == 0; this.btn_tab3.disabled = this._tab3List.length == 0; if(this._teleportType == TeleporterTypeEnum.TELEPORTER_ZAAP) { this.lbl_title.text = this.uiApi.getText(""ui.zaap.zaap"") + "" - "" + this.playerApi.currentSubArea().name; this.ctr_saveZaap.visible = this._currentSpawnZaap != null; this.btn_save.visible = this._currentSpawnZaap == null; } else if(this._teleportType == TeleporterTypeEnum.TELEPORTER_PRISM) { this.lbl_title.text = this.uiApi.getText(""ui.zaap.prism"") + "" - "" + this.playerApi.currentSubArea().name; this.ctr_saveZaap.visible = this._currentSpawnZaap != null; this.btn_save.visible = this._currentSpawnZaap == null; } } if(!this.btn_tab1.disabled && this.btn_tab1.visible && (this._teleportType != TeleporterTypeEnum.TELEPORTER_PRISM || this.btn_tab2.disabled)) { this.uiApi.setRadioGroupSelectedItem(""tabHGroup"",this.btn_tab1,this.uiApi.me()); this.btn_tab1.selected = true; this.changeZaapTab(this.btn_tab1); } else if(!this.btn_tab2.disabled && this.btn_tab2.visible) { this.uiApi.setRadioGroupSelectedItem(""tabHGroup"",this.btn_tab2,this.uiApi.me()); this.btn_tab2.selected = true; this.changeZaapTab(this.btn_tab2); } else if(!this.btn_tab3.disabled && this.btn_tab3.visible) { this.uiApi.setRadioGroupSelectedItem(""tabHGroup"",this.btn_tab3,this.uiApi.me()); this.btn_tab3.selected = true; this.changeZaapTab(this.btn_tab3); } this.gd_zaap.visible = true; this.lbl_noDestination.visible = false; } else { this.gd_zaap.visible = false; this.lbl_noDestination.visible = true; if(this.btn_tab1.selected) { this.tx_currentRespawn.visible = this._teleportType == TeleporterTypeEnum.TELEPORTER_ZAAP; this.btn_save.softDisabled = this.rpApi.getSpawnMap() == this.playerApi.currentMap().mapId; } } if(this._teleportType == TeleporterTypeEnum.TELEPORTER_HAVENBAG || this.playerApi.isInHavenbag()) { this.btn_save.softDisabled = true; this.ctr_saveZaap.visible = false; this.tx_fav.visible = false; this.btn_tab3.visible = false; } } public function onSaveCurrentZaap() : void { this.sysApi.sendAction(new ZaapRespawnSaveRequestAction([])); } public function onLeaveDialog() : void { this.uiApi.unloadUi(this.uiApi.me().name); } } } ",12483,False,2492.432005661045,median "package tofflist { import com.pickgliss.loader.BaseLoader; import com.pickgliss.loader.LoaderManager; import consortion.data.ConsortiaApplyInfo; import ddt.data.ConsortiaInfo; import ddt.data.player.PlayerInfo; import ddt.manager.PathManager; import ddt.manager.PlayerManager; import flash.events.EventDispatcher; import flash.net.URLVariables; import tofflist.analyze.RankInfoAnalyz; import tofflist.data.RankInfo; import tofflist.data.TofflistListData; import tofflist.view.TofflistStairMenu; import tofflist.view.TofflistThirdClassMenu; import tofflist.view.TofflistTwoGradeMenu; public class TofflistModel { private static var _tofflistType:int; public static var childType:int; private static var _currentPlayerInfo:PlayerInfo; public static var currentText:String; public static var currentIndex:int; private static var _firstMenuType:String = TofflistStairMenu.PERSONAL; private static var _secondMenuType:String = TofflistTwoGradeMenu.BATTLE; private static var _thirdMenuType:String = TofflistThirdClassMenu.TOTAL; private static var _dispatcher:EventDispatcher = new EventDispatcher(); private static var _currentConsortiaInfo:ConsortiaInfo; private static var _instance:TofflistModel; private var _personalBattleAccumulate:TofflistListData; private var _individualGradeDay:TofflistListData; private var _individualGradeWeek:TofflistListData; private var _individualGradeAccumulate:TofflistListData; private var _individualExploitDay:TofflistListData; private var _individualExploitWeek:TofflistListData; private var _individualExploitAccumulate:TofflistListData; private var _personalAchievementPointDay:TofflistListData; private var _personalAchievementPointWeek:TofflistListData; private var _personalAchievementPoint:TofflistListData; private var _PersonalCharmvalueDay:TofflistListData; private var _PersonalCharmvalueWeek:TofflistListData; private var _PersonalCharmvalue:TofflistListData; private var _personalMatchesWeek:TofflistListData; private var _consortiaBattleAccumulate:TofflistListData; private var _consortiaGradeAccumulate:TofflistListData; private var _consortiaAssetDay:TofflistListData; private var _consortiaAssetWeek:TofflistListData; private var _consortiaAssetAccumulate:TofflistListData; private var _consortiaExploitDay:TofflistListData; private var _consortiaExploitWeek:TofflistListData; private var _consortiaExploitAccumulate:TofflistListData; private var _ConsortiaCharmvalueDay:TofflistListData; private var _ConsortiaCharmvalueWeek:TofflistListData; private var _ConsortiaCharmvalue:TofflistListData; private var _crossServerPersonalBattleAccumulate:TofflistListData; private var _crossServerIndividualGradeDay:TofflistListData; private var _crossServerIndividualGradeWeek:TofflistListData; private var _crossServerIndividualGradeAccumulate:TofflistListData; private var _crossServerIndividualExploitDay:TofflistListData; private var _crossServerIndividualExploitWeek:TofflistListData; private var _crossServerIndividualExploitAccumulate:TofflistListData; private var _crossServerPersonalAchievementPointDay:TofflistListData; private var _crossServerPersonalAchievementPointWeek:TofflistListData; private var _crossServerPersonalAchievementPoint:TofflistListData; private var _crossServerPersonalCharmvalueDay:TofflistListData; private var _crossServerPersonalCharmvalueWeek:TofflistListData; private var _crossServerPersonalCharmvalue:TofflistListData; private var _crossServerConsortiaBattleAccumulate:TofflistListData; private var _crossServerConsortiaGradeAccumulate:TofflistListData; private var _crossServerConsortiaAssetDay:TofflistListData; private var _crossServerConsortiaAssetWeek:TofflistListData; private var _crossServerConsortiaAssetAccumulate:TofflistListData; private var _crossServerConsortiaExploitDay:TofflistListData; private var _crossServerConsortiaExploitWeek:TofflistListData; private var _crossServerConsortiaExploitAccumulate:TofflistListData; private var _crossServerConsortiaCharmvalueDay:TofflistListData; private var _crossServerConsortiaCharmvalueWeek:TofflistListData; private var _crossServerConsortiaCharmvalue:TofflistListData; private var _myConsortiaAuditingApplyData:Vector.; public var rankInfo:RankInfo; public function TofflistModel() { super(); } public static function addEventListener(param1:String, param2:Function, param3:Boolean = false) : void { _dispatcher.addEventListener(param1,param2,param3); } public static function removeEventListener(param1:String, param2:Function, param3:Boolean = false) : void { _dispatcher.removeEventListener(param1,param2,param3); } public static function set firstMenuType(param1:String) : void { _firstMenuType = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_TYPE_CHANGE,param1)); } public static function get firstMenuType() : String { return _firstMenuType; } public static function set secondMenuType(param1:String) : void { _secondMenuType = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_TYPE_CHANGE,param1)); } public static function get secondMenuType() : String { return _secondMenuType; } public static function set thirdMenuType(param1:String) : void { _thirdMenuType = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_TYPE_CHANGE,param1)); } public static function get thirdMenuType() : String { return _thirdMenuType; } public static function set currentPlayerInfo(param1:PlayerInfo) : void { _currentPlayerInfo = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_CURRENT_PLAYER,param1)); } public static function get currentPlayerInfo() : PlayerInfo { return _currentPlayerInfo; } public static function set currentConsortiaInfo(param1:ConsortiaInfo) : void { _currentConsortiaInfo = param1; } public static function get currentConsortiaInfo() : ConsortiaInfo { return _currentConsortiaInfo; } public static function get Instance() : TofflistModel { if(_instance == null) { _instance = new TofflistModel(); } return _instance; } public function set personalBattleAccumulate(param1:TofflistListData) : void { this._personalBattleAccumulate = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_PERSONAL_BATTLE_ACCUMULATE,this._personalBattleAccumulate))); } public function get personalBattleAccumulate() : TofflistListData { return this._personalBattleAccumulate; } public function set individualGradeDay(param1:TofflistListData) : void { this._individualGradeDay = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_INDIVIDUAL_GRADE_DAY,this._individualGradeDay))); } public function get individualGradeDay() : TofflistListData { return this._individualGradeDay; } public function set individualGradeWeek(param1:TofflistListData) : void { this._individualGradeWeek = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_INDIVIDUAL_GRADE_WEEK,this._individualGradeWeek))); } public function get individualGradeWeek() : TofflistListData { return this._individualGradeWeek; } public function set individualGradeAccumulate(param1:TofflistListData) : void { this._individualGradeAccumulate = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_INDIVIDUAL_GRADE_ACCUMULATE,this._individualGradeAccumulate))); } public function get individualGradeAccumulate() : TofflistListData { return this._individualGradeAccumulate; } public function set individualExploitDay(param1:TofflistListData) : void { this._individualExploitDay = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_INDIVIDUAL_EXPLOIT_DAY,this._individualExploitDay))); } public function get individualExploitDay() : TofflistListData { return this._individualExploitDay; } public function set individualExploitWeek(param1:TofflistListData) : void { this._individualExploitWeek = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_INDIVIDUAL_EXPLOIT_WEEK,this._individualExploitWeek))); } public function get individualExploitWeek() : TofflistListData { return this._individualExploitWeek; } public function set individualExploitAccumulate(param1:TofflistListData) : void { this._individualExploitAccumulate = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_INDIVIDUAL_EXPLOIT_ACCUMULATE,this._individualExploitAccumulate))); } public function get individualExploitAccumulate() : TofflistListData { return this._individualExploitAccumulate; } public function set PersonalAchievementPointDay(param1:TofflistListData) : void { this._personalAchievementPointDay = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_INDIVIDUAL_ACHIEVEMENTPOINT_DAY,this._personalAchievementPointDay))); } public function get PersonalAchievementPointDay() : TofflistListData { return this._personalAchievementPointDay; } public function set PersonalAchievementPointWeek(param1:TofflistListData) : void { this._personalAchievementPointWeek = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_INDIVIDUAL_ACHIEVEMENTPOINT_WEEK,this._personalAchievementPointWeek))); } public function get PersonalAchievementPointWeek() : TofflistListData { return this._personalAchievementPointWeek; } public function set PersonalAchievementPoint(param1:TofflistListData) : void { this._personalAchievementPoint = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_INDIVIDUAL_ACHIEVEMENTPOINT_ACCUMULATE,this._personalAchievementPoint))); } public function get PersonalAchievementPoint() : TofflistListData { return this._personalAchievementPoint; } public function set PersonalCharmvalueDay(param1:TofflistListData) : void { this._PersonalCharmvalueDay = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_INDIVIDUAL_CHARMVALUE_DAY,this._PersonalCharmvalueDay))); } public function get PersonalCharmvalueDay() : TofflistListData { return this._PersonalCharmvalueDay; } public function set PersonalCharmvalueWeek(param1:TofflistListData) : void { this._PersonalCharmvalueWeek = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_INDIVIDUAL_CHARMVALUE_WEEK,this._PersonalCharmvalueWeek))); } public function get PersonalCharmvalueWeek() : TofflistListData { return this._PersonalCharmvalueWeek; } public function set PersonalCharmvalue(param1:TofflistListData) : void { this._PersonalCharmvalue = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_INDIVIDUAL_CHARMVALUE_ACCUMULATE,this._PersonalCharmvalue))); } public function get PersonalCharmvalue() : TofflistListData { return this._PersonalCharmvalue; } public function get personalMatchesWeek() : TofflistListData { return this._personalMatchesWeek; } public function set personalMatchesWeek(param1:TofflistListData) : void { this._personalMatchesWeek = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_INDIVIDUAL_MATCHES_WEEK,this._personalMatchesWeek))); } public function set consortiaBattleAccumulate(param1:TofflistListData) : void { this._consortiaBattleAccumulate = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_BATTLE_ACCUMULATE,this._consortiaBattleAccumulate))); } public function get consortiaBattleAccumulate() : TofflistListData { return this._consortiaBattleAccumulate; } public function set consortiaGradeAccumulate(param1:TofflistListData) : void { this._consortiaGradeAccumulate = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_GRADE_ACCUMULATE,this._consortiaGradeAccumulate))); } public function get consortiaGradeAccumulate() : TofflistListData { return this._consortiaGradeAccumulate; } public function set consortiaAssetDay(param1:TofflistListData) : void { this._consortiaAssetDay = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_ASSET_DAY,this._consortiaAssetDay))); } public function get consortiaAssetDay() : TofflistListData { return this._consortiaAssetDay; } public function set consortiaAssetWeek(param1:TofflistListData) : void { this._consortiaAssetWeek = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_ASSET_WEEK,this._consortiaAssetWeek))); } public function get consortiaAssetWeek() : TofflistListData { return this._consortiaAssetWeek; } public function set consortiaAssetAccumulate(param1:TofflistListData) : void { this._consortiaAssetAccumulate = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_ASSET_ACCUMULATE,this._consortiaAssetAccumulate))); } public function get consortiaAssetAccumulate() : TofflistListData { return this._consortiaAssetAccumulate; } public function set consortiaExploitDay(param1:TofflistListData) : void { this._consortiaExploitDay = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_EXPLOIT_DAY,this._consortiaExploitDay))); } public function get consortiaExploitDay() : TofflistListData { return this._consortiaExploitDay; } public function set consortiaExploitWeek(param1:TofflistListData) : void { this._consortiaExploitWeek = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_EXPLOIT_WEEK,this._consortiaExploitWeek))); } public function get consortiaExploitWeek() : TofflistListData { return this._consortiaExploitWeek; } public function set consortiaExploitAccumulate(param1:TofflistListData) : void { this._consortiaExploitAccumulate = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_EXPLOIT_ACCUMULATE,this._consortiaExploitAccumulate))); } public function get consortiaExploitAccumulate() : TofflistListData { return this._consortiaExploitAccumulate; } public function set ConsortiaCharmvalueDay(param1:TofflistListData) : void { this._ConsortiaCharmvalueDay = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_CHARMVALUE_DAY,this._ConsortiaCharmvalueDay))); } public function get ConsortiaCharmvalueDay() : TofflistListData { return this._ConsortiaCharmvalueDay; } public function set ConsortiaCharmvalueWeek(param1:TofflistListData) : void { this._ConsortiaCharmvalueWeek = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_CHARMVALUE_WEEK,this._ConsortiaCharmvalueWeek))); } public function get ConsortiaCharmvalueWeek() : TofflistListData { return this._ConsortiaCharmvalueWeek; } public function set ConsortiaCharmvalue(param1:TofflistListData) : void { this._ConsortiaCharmvalue = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.TOFFLIST_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_CHARMVALUE_ACCUMULATE,this._ConsortiaCharmvalue))); } public function get ConsortiaCharmvalue() : TofflistListData { return this._ConsortiaCharmvalue; } public function set crossServerPersonalBattleAccumulate(param1:TofflistListData) : void { this._crossServerPersonalBattleAccumulate = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.CROSS_SEREVR_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_PERSONAL_BATTLE_ACCUMULATE,this._crossServerPersonalBattleAccumulate))); } public function get crossServerPersonalBattleAccumulate() : TofflistListData { return this._crossServerPersonalBattleAccumulate; } public function set crossServerIndividualGradeDay(param1:TofflistListData) : void { this._crossServerIndividualGradeDay = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.CROSS_SEREVR_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_INDIVIDUAL_GRADE_DAY,this._crossServerIndividualGradeDay))); } public function get crossServerIndividualGradeDay() : TofflistListData { return this._crossServerIndividualGradeDay; } public function set crossServerIndividualGradeWeek(param1:TofflistListData) : void { this._crossServerIndividualGradeWeek = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.CROSS_SEREVR_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_INDIVIDUAL_GRADE_WEEK,this._crossServerIndividualGradeWeek))); } public function get crossServerIndividualGradeWeek() : TofflistListData { return this._crossServerIndividualGradeWeek; } public function set crossServerIndividualGradeAccumulate(param1:TofflistListData) : void { this._crossServerIndividualGradeAccumulate = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.CROSS_SEREVR_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_INDIVIDUAL_GRADE_ACCUMULATE,this._crossServerIndividualGradeAccumulate))); } public function get crossServerIndividualGradeAccumulate() : TofflistListData { return this._crossServerIndividualGradeAccumulate; } public function set crossServerIndividualExploitDay(param1:TofflistListData) : void { this._crossServerIndividualExploitDay = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.CROSS_SEREVR_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_INDIVIDUAL_EXPLOIT_DAY,this._crossServerIndividualExploitDay))); } public function get crossServerIndividualExploitDay() : TofflistListData { return this._crossServerIndividualExploitDay; } public function set crossServerIndividualExploitWeek(param1:TofflistListData) : void { this._crossServerIndividualExploitWeek = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.CROSS_SEREVR_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_INDIVIDUAL_EXPLOIT_WEEK,this._crossServerIndividualExploitWeek))); } public function get crossServerIndividualExploitWeek() : TofflistListData { return this._crossServerIndividualExploitWeek; } public function set crossServerIndividualExploitAccumulate(param1:TofflistListData) : void { this._crossServerIndividualExploitAccumulate = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.CROSS_SEREVR_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_INDIVIDUAL_EXPLOIT_ACCUMULATE,this._crossServerIndividualExploitAccumulate))); } public function get crossServerIndividualExploitAccumulate() : TofflistListData { return this._crossServerIndividualExploitAccumulate; } public function set crossServerPersonalAchievementPointDay(param1:TofflistListData) : void { this._crossServerPersonalAchievementPointDay = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.CROSS_SEREVR_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_ACHIEVEMENTPOINT_DAY,this._crossServerPersonalAchievementPointDay))); } public function get crossServerPersonalAchievementPointDay() : TofflistListData { return this._crossServerPersonalAchievementPointDay; } public function set crossServerPersonalAchievementPointWeek(param1:TofflistListData) : void { this._crossServerPersonalAchievementPointWeek = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.CROSS_SEREVR_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_ACHIEVEMENTPOINT_WEEK,this._crossServerPersonalAchievementPointWeek))); } public function get crossServerPersonalAchievementPointWeek() : TofflistListData { return this._crossServerPersonalAchievementPointWeek; } public function set crossServerPersonalAchievementPoint(param1:TofflistListData) : void { this._crossServerPersonalAchievementPoint = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.CROSS_SEREVR_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_ACHIEVEMENTPOINT_ACCUMULATE,this._crossServerPersonalAchievementPoint))); } public function get crossServerPersonalAchievementPoint() : TofflistListData { return this._crossServerPersonalAchievementPoint; } public function set crossServerPersonalCharmvalueDay(param1:TofflistListData) : void { this._crossServerPersonalCharmvalueDay = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.CROSS_SEREVR_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_INDIVIDUAL_CHARMVALUE_DAY,this._crossServerPersonalCharmvalueDay))); } public function get crossServerPersonalCharmvalueDay() : TofflistListData { return this._crossServerPersonalCharmvalueDay; } public function set crossServerPersonalCharmvalueWeek(param1:TofflistListData) : void { this._crossServerPersonalCharmvalueWeek = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.CROSS_SEREVR_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_INDIVIDUAL_CHARMVALUE_WEEK,this._crossServerPersonalCharmvalueWeek))); } public function get crossServerPersonalCharmvalueWeek() : TofflistListData { return this._crossServerPersonalCharmvalueWeek; } public function set crossServerPersonalCharmvalue(param1:TofflistListData) : void { this._crossServerPersonalCharmvalue = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.CROSS_SEREVR_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_INDIVIDUAL_CHARMVALUE_ACCUMULATE,this._crossServerPersonalCharmvalue))); } public function get crossServerPersonalCharmvalue() : TofflistListData { return this._crossServerPersonalCharmvalue; } public function set crossServerConsortiaBattleAccumulate(param1:TofflistListData) : void { this._crossServerConsortiaBattleAccumulate = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.CROSS_SEREVR_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_BATTLE_ACCUMULATE,this._crossServerConsortiaBattleAccumulate))); } public function get crossServerConsortiaBattleAccumulate() : TofflistListData { return this._crossServerConsortiaBattleAccumulate; } public function set crossServerConsortiaGradeAccumulate(param1:TofflistListData) : void { this._crossServerConsortiaGradeAccumulate = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.CROSS_SEREVR_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_GRADE_ACCUMULATE,this._crossServerConsortiaGradeAccumulate))); } public function get crossServerConsortiaGradeAccumulate() : TofflistListData { return this._crossServerConsortiaGradeAccumulate; } public function set crossServerConsortiaAssetDay(param1:TofflistListData) : void { this._crossServerConsortiaAssetDay = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.CROSS_SEREVR_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_ASSET_DAY,this._crossServerConsortiaAssetDay))); } public function get crossServerConsortiaAssetDay() : TofflistListData { return this._crossServerConsortiaAssetDay; } public function set crossServerConsortiaAssetWeek(param1:TofflistListData) : void { this._crossServerConsortiaAssetWeek = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.CROSS_SEREVR_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_ASSET_WEEK,this._crossServerConsortiaAssetWeek))); } public function get crossServerConsortiaAssetWeek() : TofflistListData { return this._crossServerConsortiaAssetWeek; } public function set crossServerConsortiaAssetAccumulate(param1:TofflistListData) : void { this._crossServerConsortiaAssetAccumulate = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.CROSS_SEREVR_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_ASSET_ACCUMULATE,this._crossServerConsortiaAssetAccumulate))); } public function get crossServerConsortiaAssetAccumulate() : TofflistListData { return this._crossServerConsortiaAssetAccumulate; } public function set crossServerConsortiaExploitDay(param1:TofflistListData) : void { this._crossServerConsortiaExploitDay = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.CROSS_SEREVR_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_EXPLOIT_DAY,this._crossServerConsortiaExploitDay))); } public function get crossServerConsortiaExploitDay() : TofflistListData { return this._crossServerConsortiaExploitDay; } public function set crossServerConsortiaExploitWeek(param1:TofflistListData) : void { this._crossServerConsortiaExploitWeek = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.CROSS_SEREVR_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_EXPLOIT_WEEK,this._crossServerConsortiaExploitWeek))); } public function get crossServerConsortiaExploitWeek() : TofflistListData { return this._crossServerConsortiaExploitWeek; } public function set crossServerConsortiaExploitAccumulate(param1:TofflistListData) : void { this._crossServerConsortiaExploitAccumulate = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.CROSS_SEREVR_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_EXPLOIT_ACCUMULATE,this._crossServerConsortiaExploitAccumulate))); } public function get crossServerConsortiaExploitAccumulate() : TofflistListData { return this._crossServerConsortiaExploitAccumulate; } public function set crossServerConsortiaCharmvalueDay(param1:TofflistListData) : void { this._crossServerConsortiaCharmvalueDay = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.CROSS_SEREVR_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_CHARMVALUE_DAY,this._crossServerConsortiaCharmvalueDay))); } public function get crossServerConsortiaCharmvalueDay() : TofflistListData { return this._crossServerConsortiaCharmvalueDay; } public function set crossServerConsortiaCharmvalueWeek(param1:TofflistListData) : void { this._crossServerConsortiaCharmvalueWeek = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.CROSS_SEREVR_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_CHARMVALUE_WEEK,this._crossServerConsortiaCharmvalueWeek))); } public function get crossServerConsortiaCharmvalueWeek() : TofflistListData { return this._crossServerConsortiaCharmvalueWeek; } public function set crossServerConsortiaCharmvalue(param1:TofflistListData) : void { this._crossServerConsortiaCharmvalue = param1; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.CROSS_SEREVR_DATA_CHANGER,this.getTofflistEventParams(TofflistEvent.TOFFLIST_CONSORTIA_CHARMVALUE_ACCUMULATE,this._crossServerConsortiaCharmvalue))); } public function get crossServerConsortiaCharmvalue() : TofflistListData { return this._crossServerConsortiaCharmvalue; } private function getTofflistEventParams(param1:String, param2:TofflistListData) : Object { var _loc3_:Object = new Object(); _loc3_.flag = param1; _loc3_.data = param2; return _loc3_; } public function set myConsortiaAuditingApplyData(param1:Vector.) : void { this._myConsortiaAuditingApplyData = param1; } public function get myConsortiaAuditingApplyData() : Vector. { return this._myConsortiaAuditingApplyData; } public function loadRankInfo() : void { var _loc1_:URLVariables = new URLVariables(); _loc1_[""userID""] = PlayerManager.Instance.Self.ID; _loc1_[""ConsortiaID""] = PlayerManager.Instance.Self.ConsortiaID; var _loc2_:BaseLoader = LoaderManager.Instance.creatLoader(PathManager.solveRequestPath(""UserRankDate.ashx""),BaseLoader.REQUEST_LOADER,_loc1_); _loc2_.loadErrorMessage = """"; _loc2_.analyzer = new RankInfoAnalyz(this._loadRankCom); LoaderManager.Instance.startLoad(_loc2_); } private function _loadRankCom(param1:RankInfoAnalyz) : void { this.rankInfo = param1.info; _dispatcher.dispatchEvent(new TofflistEvent(TofflistEvent.RANKINFO_READY)); } } } ",8398,True,2646.117971067109,median "/** * BigInteger * * An ActionScript 3 implementation of BigInteger (light version) * Copyright (c) 2007 Henri Torgemane * * Derived from: * The jsbn library, Copyright (c) 2003-2005 Tom Wu * * See LICENSE.txt for full license information. */ /*[IF-FLASH]*/package com.hurlant.math { import com.hurlant.crypto.prng.Random; import com.hurlant.util.Hex; import com.hurlant.util.Memory; import flash.utils.ByteArray; use namespace bi_internal; public class BigInteger { public static const DB:int = 30; // number of significant bits per chunk public static const DV:int = (1< 0) { if (p>p)>0) { m = true; r = d.toString(36); } while (i >= 0) { if (p>(p+=DB-k); } else { d = (a[i]>>(p-=k))&km; if (p<=0) { p += DB; --i; } } if (d>0) { m = true; } if (m) { r += d.toString(36); } } } return m?r:""0""; } public function toArray(array:ByteArray):uint { const k:int = 8; const km:int = (1<<8)-1; var d:int = 0; var i:int = t; var p:int = DB-(i*DB)%k; var m:Boolean = false; var c:int = 0; if (i-- > 0) { if (p>p)>0) { m = true; array.writeByte(d); c++; } while (i >= 0) { if (p>(p+=DB-k); } else { d = (a[i]>>(p-=k))&km; if (p<=0) { p += DB; --i; } } if (d>0) { m = true; } if (m) { array.writeByte(d); c++; } } } return c; } /** * best-effort attempt to fit into a Number. * precision can be lost if it just can't fit. */ public function valueOf():Number { if (s==-1) { return -negate().valueOf(); } var coef:Number = 1; var value:Number = 0; for (var i:uint=0;i v, - if this < v, 0 if equal */ public function compareTo(v:BigInteger):int { var r:int = s - v.s; if (r!=0) { return r; } var i:int = t; r = i-v.t; if (r!=0) { return r; } while (--i >=0) { r=a[i]-v.a[i]; if (r != 0) return r; } return 0; } /** * returns bit length of the integer x */ bi_internal function nbits(x:int):int { var r:int = 1; var t:int; if ((t=x>>>16) != 0) { x = t; r += 16; } if ((t=x>>8) != 0) { x = t; r += 8; } if ((t=x>>4) != 0) { x = t; r += 4; } if ((t=x>>2) != 0) { x = t; r += 2; } if ((t=x>>1) != 0) { x = t; r += 1; } return r; } /** * returns the number of bits in this */ public function bitLength():int { if (t<=0) return 0; return DB*(t-1)+nbits(a[t-1]^(s&DM)); } /** * * @param v * @return this % v * */ public function mod(v:BigInteger):BigInteger { var r:BigInteger = nbi(); abs().divRemTo(v,null,r); if (s<0 && r.compareTo(ZERO)>0) { v.subTo(r,r); } return r; } /** * this^e % m, 0 <= e < 2^32 */ public function modPowInt(e:int, m:BigInteger):BigInteger { var z:IReduction; if (e<256 || m.isEven()) { z = new ClassicReduction(m); } else { z = new MontgomeryReduction(m); } return exp(e, z); } /** * copy this to r */ bi_internal function copyTo(r:BigInteger):void { for (var i:int = t-1; i>=0; --i) { r.a[i] = a[i]; } r.t = t; r.s = s; } /** * set from integer value ""value"", -DV <= value < DV */ bi_internal function fromInt(value:int):void { t = 1; s = (value<0)?-1:0; if (value>0) { a[0] = value; } else if (value<-1) { a[0] = value+DV; } else { t = 0; } } /** * set from ByteArray and length, * starting a current position * If length goes beyond the array, pad with zeroes. */ bi_internal function fromArray(value:ByteArray, length:int, unsigned:Boolean = false):void { var p:int = value.position; var i:int = p+length; var sh:int = 0; const k:int = 8; t = 0; s = 0; while (--i >= p) { var x:int = i DB) { a[t-1] |= (x&((1<<(DB-sh))-1))<>(DB-sh); } else { a[t-1] |= x<= DB) sh -= DB; } if (!unsigned && (value[0]&0x80)==0x80) { s = -1; if (sh > 0) { a[t-1] |= ((1<<(DB-sh))-1)<0 && a[t-1]==c) { --t; } } /** * r = this << n*DB */ bi_internal function dlShiftTo(n:int, r:BigInteger):void { var i:int; for (i=t-1; i>=0; --i) { r.a[i+n] = a[i]; } for (i=n-1; i>=0; --i) { r.a[i] = 0; } r.t = t+n; r.s = s; } /** * r = this >> n*DB */ bi_internal function drShiftTo(n:int, r:BigInteger):void { var i:int; for (i=n; i=0; --i) { r.a[i+ds+1] = (a[i]>>cbs)|c; c = (a[i]&bm)<=0; --i) { r.a[i] = 0; } r.a[ds] = c; r.t = t+ds+1; r.s = s; r.clamp(); } /** * r = this >> n */ bi_internal function rShiftTo(n:int, r:BigInteger):void { r.s = s; var ds:int = n/DB; if (ds >= t) { r.t = 0; return; } var bs:int = n%DB; var cbs:int = DB-bs; var bm:int = (1<>bs; var i:int; for (i=ds+1; i>bs; } if (bs>0) { r.a[t-ds-1] |= (s&bm)<>= DB; } if (v.t < t) { c -= v.s; while (i< t) { c+= a[i]; r.a[i++] = c&DM; c >>= DB; } c += s; } else { c += s; while (i < v.t) { c -= v.a[i]; r.a[i++] = c&DM; c >>= DB; } c -= v.s; } r.s = (c<0)?-1:0; if (c<-1) { r.a[i++] = DV+c; } else if (c>0) { r.a[i++] = c; } r.t = i; r.clamp(); } /** * am: Compute w_j += (x*this_i), propagates carries, * c is initial carry, returns final carry. * c < 3*dvalue, x < 2*dvalue, this_i < dvalue */ bi_internal function am(i:int,x:int,w:BigInteger,j:int,c:int,n:int):int { var xl:int = x&0x7fff; var xh:int = x>>15; while(--n >= 0) { var l:int = a[i]&0x7fff; var h:int = a[i++]>>15; var m:int = xh*l + h*xl; l = xl*l + ((m&0x7fff)<<15)+w.a[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w.a[j++] = l&0x3fffffff; } return c; } /** * r = this * v, r != this,a (HAC 14.12) * ""this"" should be the larger one if appropriate */ bi_internal function multiplyTo(v:BigInteger, r:BigInteger):void { var x:BigInteger = abs(); var y:BigInteger = v.abs(); var i:int = x.t; r.t = i+y.t; while (--i >= 0) { r.a[i] = 0; } for (i=0; i=0) r.a[i] = 0; for (i=0; i= DV) { r.a[i+x.t] -= DV; r.a[i+x.t+1] = 1; } } if (r.t>0) { r.a[r.t-1] += x.am(i, x.a[i], r, 2*i, 0, 1); } r.s = 0; r.clamp(); } /** * divide this by m, quotient and remainder to q, r (HAC 14.20) * r != q, this != m. q or r may be null. */ bi_internal function divRemTo(m:BigInteger, q:BigInteger = null, r:BigInteger = null):void { var pm:BigInteger = m.abs(); if (pm.t <= 0) return; var pt:BigInteger = abs(); if (pt.t < pm.t) { if (q!=null) q.fromInt(0); if (r!=null) copyTo(r); return; } if (r==null) r = nbi(); var y:BigInteger = nbi(); var ts:int = s; var ms:int = m.s; var nsh:int = DB-nbits(pm.a[pm.t-1]); // normalize modulus if (nsh>0) { pm.lShiftTo(nsh, y); pt.lShiftTo(nsh, r); } else { pm.copyTo(y); pt.copyTo(r); } var ys:int = y.t; var y0:int = y.a[ys-1]; if (y0==0) return; var yt:Number = y0*(1<1)?y.a[ys-2]>>F2:0); var d1:Number = FV/yt; var d2:Number = (1<=0) { r.a[r.t++] = 1; r.subTo(t,r); } ONE.dlShiftTo(ys,t); t.subTo(y,y); // ""negative"" y so we can replace sub with am later. while(y.t= 0) { // Estimate quotient digit var qd:int = (r.a[--i]==y0)?DM:Number(r.a[i])*d1+(Number(r.a[i-1])+e)*d2; if ((r.a[i]+= y.am(0, qd, r, j, 0, ys))0) { r.rShiftTo(nsh, r); // Denormalize remainder } if (ts<0) { ZERO.subTo(r,r); } } /** * return ""-1/this % 2^DB""; useful for Mont. reduction * justification: * xy == 1 (mod n) * xy = 1+km * xy(2-xy) = (1+km)(1-km) * x[y(2-xy)] = 1-k^2.m^2 * x[y(2-xy)] == 1 (mod m^2) * if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 * should reduce x and y(2-xy) by m^2 at each step to keep size bounded * [XXX unit test the living shit out of this.] */ bi_internal function invDigit():int { if (t<1) return 0; var x:int = a[0]; if ((x&1)==0) return 0; var y:int = x&3; // y == 1/x mod 2^2 y = (y*(2-(x&0xf )*y)) &0xf; // y == 1/x mod 2^4 y = (y*(2-(x&0xff)*y)) &0xff; // y == 1/x mod 2^8 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints // XXX 48 bit ints? Whaaaa? is there an implicit float conversion in here? y = (y*(2-x*y%DV))%DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y>0)?DV-y:-y; } /** * true iff this is even */ bi_internal function isEven():Boolean { return ((t>0)?(a[0]&1):s) == 0; } /** * this^e, e < 2^32, doing sqr and mul with ""r"" (HAC 14.79) */ bi_internal function exp(e:int, z:IReduction):BigInteger { if (e > 0xffffffff || e < 1) return ONE; var r:BigInteger = nbi(); var r2:BigInteger = nbi(); var g:BigInteger = z.convert(this); var i:int = nbits(e)-1; g.copyTo(r); while(--i>=0) { z.sqrTo(r, r2); if ((e&(1<0) { z.mulTo(r2,g,r); } else { var t:BigInteger = r; r = r2; r2 = t; } } return z.revert(r); } bi_internal function intAt(str:String, index:int):int { return parseInt(str.charAt(index), 36); } protected function nbi():* { return new BigInteger; } /** * return bigint initialized to value */ public static function nbv(value:int):BigInteger { var bn:BigInteger = new BigInteger; bn.fromInt(value); return bn; } // Functions above are sufficient for RSA encryption. // The stuff below is useful for decryption and key generation public static const lowprimes:Array = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; public static const lplim:int = (1<<26)/lowprimes[lowprimes.length-1]; public function clone():BigInteger { var r:BigInteger = new BigInteger; this.copyTo(r); return r; } /** * * @return value as integer * */ public function intValue():int { if (s<0) { if (t==1) { return a[0]-DV; } else if (t==0) { return -1; } } else if (t==1) { return a[0]; } else if (t==0) { return 0; } // assumes 16 < DB < 32 return ((a[1]&((1<<(32-DB))-1))<>24; } /** * * @return value as short (assumes DB>=16) * */ public function shortValue():int { return (t==0)?s:(a[0]<<16)>>16; } /** * * @param r * @return x s.t. r^x < DV * */ protected function chunkSize(r:Number):int { return Math.floor(Math.LN2*DB/Math.log(r)); } /** * * @return 0 if this ==0, 1 if this >0 * */ public function sigNum():int { if (s<0) { return -1; } else if (t<=0 || (t==1 && a[0]<=0)) { return 0; } else{ return 1; } } /** * * @param b: radix to use * @return a string representing the integer converted to the radix. * */ protected function toRadix(b:uint=10):String { if (sigNum()==0 || b<2 || b>32) return ""0""; var cs:int = chunkSize(b); var a:Number = Math.pow(b, cs); var d:BigInteger = nbv(a); var y:BigInteger = nbi(); var z:BigInteger = nbi(); var r:String = """"; divRemTo(d, y, z); while (y.sigNum()>0) { r = (a+z.intValue()).toString(b).substr(1) + r; y.divRemTo(d,y,z); } return z.intValue().toString(b) + r; } /** * * @param s a string to convert from using radix. * @param b a radix * */ protected function fromRadix(s:String, b:int = 10):void { fromInt(0); var cs:int = chunkSize(b); var d:Number = Math.pow(b, cs); var mi:Boolean = false; var j:int = 0; var w:int = 0; for (var i:int=0;i= cs) { dMultiply(d); dAddOffset(w,0); j=0; w=0; } } if (j>0) { dMultiply(Math.pow(b,j)); dAddOffset(w,0); } if (mi) { BigInteger.ZERO.subTo(this, this); } } // XXX function fromNumber not written yet. /** * * @return a byte array. * */ public function toByteArray():ByteArray { var i:int = t; var r:ByteArray = new ByteArray; r[0] = s; var p:int = DB-(i*DB)%8; var d:int; var k:int=0; if (i-- > 0) { if (p>p)!=(s&DM)>>p) { r[k++] = d|(s<<(DB-p)); } while (i>=0) { if(p<8) { d = (a[i]&((1<>(p+=DB-8); } else { d = (a[i]>>(p-=8))&0xff; if (p<=0) { p += DB; --i; } } if ((d&0x80)!=0) d|=-256; if (k==0 && (s&0x80)!=(d&0x80)) ++k; if (k>0 || d!=s) r[k++] = d; } } return r; } public function equals(a:BigInteger):Boolean { return compareTo(a)==0; } public function min(a:BigInteger):BigInteger { return (compareTo(a)<0)?this:a; } public function max(a:BigInteger):BigInteger { return (compareTo(a)>0)?this:a; } /** * * @param a a BigInteger to perform the operation with * @param op a Function implementing the operation * @param r a BigInteger to store the result of the operation * */ protected function bitwiseTo(a:BigInteger, op:Function, r:BigInteger):void { var i:int; var f:int; var m:int = Math.min(a.t, t); for (i=0; i>= 16; r += 16; } if ((x&0xff) == 0) { x>>= 8; r += 8; } if ((x&0xf) == 0) { x>>= 4; r += 4; } if ((x&0x3) == 0) { x>>= 2; r += 2; } if ((x&0x1) == 0) ++r; return r; } /** * * @return index of lowest 1-bit (or -1 if none) * */ public function getLowestSetBit():int { for (var i:int=0;i=t) { return s!=0; } return ((a[j]&(1<<(n%DB)))!=0); } /** * * @param n * @param op * @return this op (1<>=DB; } if (a.t < t) { c += a.s; while (i>= DB; } c += s; } else { c += s; while (i>= DB; } c += a.s; } r.s = (c<0)?-1:0; if (c>0) { r.a[i++] = c; } else if (c<-1) { r.a[i++] = DV+c; } r.t = i; r.clamp(); } /** * * @param a * @return this + a * */ public function add(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; addTo(a,r); return r; } /** * * @param a * @return this - a * */ public function subtract(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; subTo(a,r); return r; } /** * * @param a * @return this * a * */ public function multiply(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; multiplyTo(a,r); return r; } /** * * @param a * @return this / a * */ public function divide(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; divRemTo(a, r, null); return r; } public function remainder(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; divRemTo(a, null, r); return r; } /** * * @param a * @return [this/a, this%a] * */ public function divideAndRemainder(a:BigInteger):Array { var q:BigInteger = new BigInteger; var r:BigInteger = new BigInteger; divRemTo(a, q, r); return [q,r]; } /** * * this *= n, this >=0, 1 < n < DV * * @param n * */ bi_internal function dMultiply(n:int):void { a[t] = am(0, n-1, this, 0, 0, t); ++t; clamp(); } /** * * this += n << w words, this >= 0 * * @param n * @param w * */ bi_internal function dAddOffset(n:int, w:int):void { while (t<=w) { a[t++] = 0; } a[w] += n; while (a[w] >= DV) { a[w] -= DV; if (++w >= t) { a[t++] = 0; } ++a[w]; } } /** * * @param e * @return this^e * */ public function pow(e:int):BigInteger { return exp(e, new NullReduction); } /** * * @param a * @param n * @param r = lower n words of ""this * a"", a.t <= n * */ bi_internal function multiplyLowerTo(a:BigInteger, n:int, r:BigInteger):void { var i:int = Math.min(t+a.t, n); r.s = 0; // assumes a, this >= 0 r.t = i; while (i>0) { r.a[--i]=0; } var j:int; for (j=r.t-t;i 0 * */ bi_internal function multiplyUpperTo(a:BigInteger, n:int, r:BigInteger):void { --n; var i:int = r.t = t+a.t-n; r.s = 0; // assumes a,this >= 0 while (--i>=0) { r.a[i] = 0; } for (i=Math.max(n-t,0);i 1) { var g2:BigInteger = new BigInteger; z.sqrTo(g[1], g2); while (n<=km) { g[n] = new BigInteger; z.mulTo(g2, g[n-2], g[n]); n += 2; } } var j:int = e.t-1; var w:int; var is1:Boolean = true; var r2:BigInteger = new BigInteger; var t:BigInteger; i = nbits(e.a[j])-1; while (j>=0) { if (i>=k1) { w = (e.a[j]>>(i-k1))&km; } else { w = (e.a[j]&((1<<(i+1))-1))<<(k1-i); if (j>0) { w |= e.a[j-1]>>(DB+i-k1); } } n = k; while ((w&1)==0) { w >>= 1; --n; } if ((i -= n) <0) { i += DB; --j; } if (is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while (n>1) { z.sqrTo(r, r2); z.sqrTo(r2, r); n -= 2; } if (n>0) { z.sqrTo(r, r2); } else { t = r; r = r2; r2 = t; } z.mulTo(r2, g[w], r); } while (j>=0 && (e.a[j]&(1<0) { x.rShiftTo(g, x); y.rShiftTo(g, y); } while (x.sigNum()>0) { if ((i = x.getLowestSetBit()) >0) { x.rShiftTo(i, x); } if ((i = y.getLowestSetBit()) >0) { y.rShiftTo(i, y); } if (x.compareTo(y) >= 0) { x.subTo(y, x); x.rShiftTo(1, x); } else { y.subTo(x, y); y.rShiftTo(1, y); } } if (g>0) { y.lShiftTo(g, y); } return y; } /** * * @param n * @return this % n, n < 2^DB * */ protected function modInt(n:int):int { if (n<=0) return 0; var d:int = DV%n; var r:int = (s<0)?n-1:0; if (t>0) { if (d==0) { r = a[0]%n; } else { for (var i:int=t-1;i>=0;--i) { r = (d*r+a[i])%n; } } } return r; } /** * * @param m * @return 1/this %m (HAC 14.61) * */ public function modInverse(m:BigInteger):BigInteger { var ac:Boolean = m.isEven(); if ((isEven()&&ac) || m.sigNum()==0) { return BigInteger.ZERO; } var u:BigInteger = m.clone(); var v:BigInteger = clone(); var a:BigInteger = nbv(1); var b:BigInteger = nbv(0); var c:BigInteger = nbv(0); var d:BigInteger = nbv(1); while (u.sigNum()!=0) { while (u.isEven()) { u.rShiftTo(1,u); if (ac) { if (!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if (!b.isEven()) { b.subTo(m,b); } b.rShiftTo(1,b); } while (v.isEven()) { v.rShiftTo(1,v); if (ac) { if (!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if (!d.isEven()) { d.subTo(m,d); } d.rShiftTo(1,d); } if (u.compareTo(v)>=0) { u.subTo(v,u); if (ac) { a.subTo(c,a); } b.subTo(d,b); } else { v.subTo(u,v); if (ac) { c.subTo(a,c); } d.subTo(b,d); } } if (v.compareTo(BigInteger.ONE) != 0) { return BigInteger.ZERO; } if (d.compareTo(m) >= 0) { return d.subtract(m); } if (d.sigNum()<0) { d.addTo(m,d); } else { return d; } if (d.sigNum()<0) { return d.add(m); } else { return d; } } /** * * @param t * @return primality with certainty >= 1-.5^t * */ public function isProbablePrime(t:int):Boolean { var i:int; var x:BigInteger = abs(); if (x.t == 1 && x.a[0]<=lowprimes[lowprimes.length-1]) { for (i=0;i>1; if (t>lowprimes.length) { t = lowprimes.length; } var a:BigInteger = new BigInteger; for (var i:int=0;ibits) subTo(BigInteger.ONE.shiftLeft(bits-1),this); } } } } ",12301,True,2667.5717865398024,median "= v1.ImageStream {product-author} {product-version} :data-uri: :icons: :toc: macro :toc-title: :toclevels: 2 toc::[] == Description [%hardbreaks] ImageStream stores a mapping of tags to images, metadata overrides that are applied when images are tagged in a stream, and an optional reference to a Docker image repository on a registry. == Object Schema Expand or mouse-over a field for more information about it. ++++
apiVersion:
kind:
metadata:
annotations:
[string]:
clusterName:
creationTimestamp:
deletionGracePeriodSeconds:
deletionTimestamp:
finalizers:
- [string]:
generateName:
generation:
:
pending:
- name:
result:
apiVersion:
code:
details:
causes:
- field:
message:
reason:
group:
kind:
name:
retryAfterSeconds:
uid:
kind:
message:
metadata:
continue:
resourceVersion:
selfLink:
reason:
status:
labels:
[string]:
name:
namespace:
ownerReferences:
- apiVersion:
blockOwnerDeletion:
controller:
kind:
name:
uid:
resourceVersion:
selfLink:
uid:
spec:
dockerImageRepository:
lookupPolicy:
local:
tags:
- annotations:
- [string]:
from:
apiVersion:
fieldPath:
kind:
name:
namespace:
resourceVersion:
uid:
generation:
importPolicy:
insecure:
scheduled:
name:
reference:
referencePolicy:
type:
status:
dockerImageRepository:
publicDockerImageRepository:
tags:
- conditions:
- - generation:
lastTransitionTime:
message:
reason:
status:
type:
items:
- created:
dockerImageReference:
generation:
image:
tag:
++++ == Operations [[Post-apis-image.openshift.io-v1-imagestreams]] === Create a ImageStream Create an ImageStream ==== HTTP request ---- POST /apis/image.openshift.io/v1/imagestreams HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""ImageStream"", ""apiVersion"": ""image.openshift.io/v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X POST \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/imagestreams <<'EOF' { ""kind"": ""ImageStream"", ""apiVersion"": ""image.openshift.io/v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.ImageStream |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStream |201 Created|v1.ImageStream |202 Accepted|v1.ImageStream |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Post-apis-image.openshift.io-v1-namespaces-namespace-imagestreams]] === Create a ImageStream in a namespace Create an ImageStream ==== HTTP request ---- POST /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""ImageStream"", ""apiVersion"": ""image.openshift.io/v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X POST \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams <<'EOF' { ""kind"": ""ImageStream"", ""apiVersion"": ""image.openshift.io/v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.ImageStream |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStream |201 Created|v1.ImageStream |202 Accepted|v1.ImageStream |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name]] === Get a ImageStream in a namespace Read the specified ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStream |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |exact|Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. |export|Should this value be exported. Export strips fields that a user can not specify. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStream |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-image.openshift.io-v1-imagestreams]] === Get all ImageStreams List or watch objects of kind ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/imagestreams HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/imagestreams ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStreamList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-image.openshift.io-v1-namespaces-namespace-imagestreams]] === Get all ImageStreams in a namespace List or watch objects of kind ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStreamList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-image.openshift.io-v1-watch-namespaces-namespace-imagestreams-name]] === Watch a ImageStream in a namespace Watch changes to an object of kind ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/watch/namespaces/$NAMESPACE/imagestreams/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/watch/namespaces/$NAMESPACE/imagestreams/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStream |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-image.openshift.io-v1-watch-imagestreams]] === Watch all ImageStreams Watch individual changes to a list of ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/watch/imagestreams HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/watch/imagestreams ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-image.openshift.io-v1-watch-namespaces-namespace-imagestreams]] === Watch all ImageStreams in a namespace Watch individual changes to a list of ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/watch/namespaces/$NAMESPACE/imagestreams HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/watch/namespaces/$NAMESPACE/imagestreams ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Put-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name]] === Update a ImageStream in a namespace Replace the specified ImageStream ==== HTTP request ---- PUT /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""ImageStream"", ""apiVersion"": ""image.openshift.io/v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X PUT \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME <<'EOF' { ""kind"": ""ImageStream"", ""apiVersion"": ""image.openshift.io/v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.ImageStream |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStream |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStream |201 Created|v1.ImageStream |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Patch-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name]] === Patch a ImageStream in a namespace Partially update the specified ImageStream ==== HTTP request ---- PATCH /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json-patch+json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X PATCH \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json-patch+json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.Patch |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStream |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStream |401 Unauthorized| |=== ==== Consumes * application/json-patch+json * application/merge-patch+json * application/strategic-merge-patch+json ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Delete-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name]] === Delete a ImageStream in a namespace Delete an ImageStream ==== HTTP request ---- DELETE /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.DeleteOptions |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStream |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |gracePeriodSeconds|The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. |orphanDependents|Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the ""orphan"" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. |propagationPolicy|Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Status |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Delete-apis-image.openshift.io-v1-namespaces-namespace-imagestreams]] === Delete all ImageStreams in a namespace Delete collection of ImageStream ==== HTTP request ---- DELETE /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Status |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name-secrets]] === Get secrets of a ImageStream in a namespace Read secrets of the specified ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/secrets HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/secrets ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the SecretList |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.SecretList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name-status]] === Get status of a ImageStream in a namespace Read status of the specified ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/status HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/status ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStream |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStream |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Put-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name-status]] === Update status of a ImageStream in a namespace Replace status of the specified ImageStream ==== HTTP request ---- PUT /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/status HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""ImageStream"", ""apiVersion"": ""image.openshift.io/v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X PUT \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/status <<'EOF' { ""kind"": ""ImageStream"", ""apiVersion"": ""image.openshift.io/v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.ImageStream |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStream |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStream |201 Created|v1.ImageStream |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Patch-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name-status]] === Patch status of a ImageStream in a namespace Partially update status of the specified ImageStream ==== HTTP request ---- PATCH /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/status HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json-patch+json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X PATCH \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json-patch+json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/status <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.Patch |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStream |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStream |401 Unauthorized| |=== ==== Consumes * application/json-patch+json * application/merge-patch+json * application/strategic-merge-patch+json ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf ",16305,True,3046.227217751276,median "//////////////////////////////////////////////////////////////////////////////// // // ADOBE SYSTEMS INCORPORATED // Copyright 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.controls.dataGridClasses { import flash.display.DisplayObject; import flash.display.GradientType; import flash.display.Graphics; import flash.display.Shape; import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; import mx.controls.DataGrid; import mx.controls.listClasses.IDropInListItemRenderer; import mx.controls.listClasses.IListItemRenderer; import mx.core.EdgeMetrics; import mx.core.FlexSprite; import mx.core.IFlexDisplayObject; import mx.core.IUIComponent; import mx.core.LayoutDirection; import mx.core.UIComponent; import mx.core.UIComponentGlobals; import mx.core.mx_internal; import mx.effects.easing.Back; import mx.events.DataGridEvent; import mx.events.SandboxMouseEvent; import mx.managers.CursorManager; import mx.managers.CursorManagerPriority; import mx.skins.halo.DataGridColumnDropIndicator; import mx.styles.ISimpleStyleClient; import mx.styles.StyleManager; use namespace mx_internal; /** * The DataGridHeader class defines the default header * renderer for a DataGrid control. * By default, the header renderer * draws the text associated with each header in the list, and an optional * sort arrow (if sorted by that column). * * @see mx.controls.DataGrid * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class DataGridHeader extends DataGridHeaderBase { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function DataGridHeader() { super(); addEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler); addEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler); addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); } /** * @private * Additional affordance given to header separators. */ private var separatorAffordance:Number = 3; /** * a function to clear selections * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ override mx_internal function clearSelectionLayer():void { while (selectionLayer.numChildren > 0) { selectionLayer.removeChildAt(0); } } /** * The DataGrid control associated with this renderer. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected var dataGrid:DataGrid; /** * An Array of header renderer instances. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected var headerItems:Array = []; /** * The cached header height, in pixels. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected var cachedHeaderHeight:Number = 0; /** * The cached padding for the bottom of the renderer, in pixels. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected var cachedPaddingBottom:Number = 0; /** * The cached padding for the top of the renderer, in pixels. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected var cachedPaddingTop:Number = 0; /** * Whether we need the separator on the far right * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var needRightSeparator:Boolean = false; /** * Whether we need the separator events on the far right * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var needRightSeparatorEvents:Boolean = false; /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ override protected function createChildren():void { dataGrid = parent as DataGrid; // this is the layer where we draw selection indicators selectionLayer = new UIComponent(); addChild(selectionLayer); } /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ override protected function measure():void { super.measure(); var calculatedHeight:Number = dataGrid.calculateHeaderHeight(); cachedHeaderHeight = dataGrid._explicitHeaderHeight ? dataGrid.headerHeight : calculatedHeight; cachedPaddingBottom = getStyle(""paddingBottom""); cachedPaddingTop = getStyle(""paddingTop""); measuredHeight = cachedHeaderHeight; var ww:Number = 0; var n:int = visibleColumns ? visibleColumns.length : 0; for (var i:int = 0; i < n; i++) ww += visibleColumns[i].preferredWidth; measuredWidth = ww; } /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ override protected function updateDisplayList(w:Number, h:Number):void { allowItemSizeChangeNotification = false; // make new ones var cols:Array = visibleColumns; if (headerItemsChanged && (cols && cols.length > 0 || dataGrid.headerVisible)) { headerItemsChanged = false; var xx:Number = 0; var yy:Number = 0; var hh:Number = 0; var ww:Number = 0; var rh:Number; var colNum:int = 0; // visible columns compensate for firstCol offset var rowData:DataGridListData; var item:IListItemRenderer; var extraItem:IListItemRenderer; var data:Object; var uid:String; var c:DataGridColumn; var maxHeaderHeight:Number = 0; // copy current list of renderers var oldHeaderItems:Array = headerItems.slice(); while (cols && colNum < cols.length) { c = cols[colNum]; item = c.cachedHeaderRenderer; if (!item) { item = dataGrid.createColumnItemRenderer(c, true, c); item.styleName = c; c.cachedHeaderRenderer = item; } rowData = new DataGridListData((c.headerText != null) ? c.headerText : c.dataField, c.dataField, colNum, uid, dataGrid, 0); if (item is IDropInListItemRenderer) IDropInListItemRenderer(item).listData = rowData; item.data = c; item.visible = true; // if it isn't parented by us, add it (could be in lockedColumns header) if (item.parent != this) addChild(DisplayObject(item)); headerItems[colNum] = item; // set prefW so we can compute prefH item.explicitWidth = ww = c.width; UIComponentGlobals.layoutManager.validateClient(item, true); // but size it regardless of what prefW is rh = item.getExplicitOrMeasuredHeight(); item.setActualSize(ww, dataGrid._explicitHeaderHeight ? cachedHeaderHeight - cachedPaddingTop - cachedPaddingBottom : rh); item.move(xx, yy + cachedPaddingTop); xx += ww; colNum++; hh = Math.ceil(Math.max(hh, dataGrid._explicitHeaderHeight ? cachedHeaderHeight : rh + cachedPaddingBottom + cachedPaddingTop)); maxHeaderHeight = Math.max(maxHeaderHeight, dataGrid._explicitHeaderHeight ? cachedHeaderHeight - cachedPaddingTop - cachedPaddingBottom : rh); } // expand all headers to be of maximum height for (var i:int = 0; i < headerItems.length; i++) headerItems[i].setActualSize(headerItems[i].width, maxHeaderHeight); for (i = 0; i < oldHeaderItems.length; i++) { item = oldHeaderItems[i]; if (item && headerItems.indexOf(item) == -1) { // if it is parented by us, remove it (could be in lockedColumns header) if (item.parent == this) removeChild(DisplayObject(item)); } } while (headerItems.length > colNum) { // remove extra columns extraItem = headerItems.pop(); // if it is parented by us, remove it (could be in lockedColumns header) if (extraItem.parent == this) { // make sure it isn't already in there elsewhere if (headerItems.indexOf(extraItem) == -1) removeChild(DisplayObject(extraItem)); } } } var headerBG:UIComponent = UIComponent(getChildByName(""headerBG"")); if (headerBGSkinChanged) { headerBGSkinChanged = false; if (headerBG) removeChild(headerBG); headerBG = null; } if (!headerBG) { headerBG = new UIComponent(); headerBG.name = ""headerBG""; addChildAt(DisplayObject(headerBG), 0); var headerBGSkinClass:Class = getStyle(""headerBackgroundSkin""); var headerBGSkin:IFlexDisplayObject = new headerBGSkinClass(); if (headerBGSkin is ISimpleStyleClient) ISimpleStyleClient(headerBGSkin).styleName = this; headerBG.addChild(DisplayObject(headerBGSkin)); } if (dataGrid.headerVisible) { headerBG.visible = true; drawHeaderBackgroundSkin(IFlexDisplayObject(headerBG.getChildAt(0))); dataGrid._drawSeparators(); } else { headerBG.visible = false; dataGrid._clearSeparators(); } dataGrid._placeSortArrow(); allowItemSizeChangeNotification = true; } mx_internal function _drawHeaderBackground(headerBG:UIComponent):void { drawHeaderBackground(headerBG); } /** * Draws the background of the headers into the given * UIComponent. The graphics drawn may be scaled horizontally * if the component's width changes or this method will be * called again to redraw at a different width and/or height * * @param headerBG A UIComponent that will contain the header * background graphics. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function drawHeaderBackground(headerBG:UIComponent):void { var tot:Number = width; var hh:Number = cachedHeaderHeight; var g:Graphics = headerBG.graphics; g.clear(); var colors:Array = getStyle(""headerColors""); styleManager.getColorNames(colors); var matrix:Matrix = new Matrix(); matrix.createGradientBox(tot, hh + 1, Math.PI/2, 0, 0); colors = [ colors[0], colors[0], colors[1] ]; var ratios:Array = [ 0, 60, 255 ]; var alphas:Array = [ 1.0, 1.0, 1.0 ]; g.beginGradientFill(GradientType.LINEAR, colors, alphas, ratios, matrix); g.lineStyle(0, 0x000000, 0); g.moveTo(0, 0); g.lineTo(tot, 0); g.lineTo(tot, hh - 0.5); g.lineStyle(0, getStyle(""borderColor""), 100); g.lineTo(0, hh - 0.5); g.lineStyle(0, 0x000000, 0); g.endFill(); } private function drawHeaderBackgroundSkin(headerBGSkin:IFlexDisplayObject):void { headerBGSkin.setActualSize(unscaledWidth, Math.ceil(cachedHeaderHeight)); } mx_internal function _clearSeparators():void { clearSeparators(); } /** * Removes column header separators that the user normally uses * to resize columns. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function clearSeparators():void { if (!separators) return; var lines:Sprite = Sprite(getChildByName(""lines"")); while (lines.numChildren) { lines.removeChildAt(lines.numChildren - 1); separators.pop(); } } mx_internal function _drawSeparators():void { drawSeparators(); } /** * Creates and displays the column header separators that the user * normally uses to resize columns. This implementation uses * the same Sprite as the lines and column backgrounds and adds * instances of the headerSeparatorSkin and attaches mouse * listeners to them in order to know when the user wants * to resize a column. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function drawSeparators():void { if (!separators) separators = []; var lines:UIComponent = UIComponent(getChildByName(""lines"")); if (!lines) { lines = new UIComponent(); lines.name = ""lines""; addChild(lines); } else setChildIndex(lines, numChildren - 1); // required to deal with some 2.x clipping behavior lines.scrollRect = new Rectangle(0, 0, unscaledWidth, unscaledHeight + 1); if (headerSepSkinChanged) { headerSepSkinChanged = false; clearSeparators(); } var n:int = visibleColumns ? visibleColumns.length : 0; if (!needRightSeparator && n > 0) n--; for (var i:int = 0; i < n; i++) { var sep:UIComponent; var sepSkin:IFlexDisplayObject; if (i < lines.numChildren) { sep = UIComponent(lines.getChildAt(i)); sepSkin = IFlexDisplayObject(sep.getChildAt(0)); } else { var headerSeparatorClass:Class = getStyle(""headerSeparatorSkin""); sepSkin = new headerSeparatorClass(); if (sepSkin is ISimpleStyleClient) ISimpleStyleClient(sepSkin).styleName = this; sep = new UIComponent(); sep.addChild(DisplayObject(sepSkin)); lines.addChild(sep); UIComponentGlobals.layoutManager.validateClient(sep, true); separators.push(sep); } // if not separator if ( !(i == visibleColumns.length-1 && !needRightSeparatorEvents) ) { DisplayObject(sep).addEventListener( MouseEvent.MOUSE_OVER, columnResizeMouseOverHandler); DisplayObject(sep).addEventListener( MouseEvent.MOUSE_OUT, columnResizeMouseOutHandler); DisplayObject(sep).addEventListener( MouseEvent.MOUSE_DOWN, columnResizeMouseDownHandler); } else { // if not separator if ( (i == visibleColumns.length-1 && !needRightSeparatorEvents) ) { DisplayObject(sep).removeEventListener( MouseEvent.MOUSE_OVER, columnResizeMouseOverHandler); DisplayObject(sep).removeEventListener( MouseEvent.MOUSE_OUT, columnResizeMouseOutHandler); DisplayObject(sep).removeEventListener( MouseEvent.MOUSE_DOWN, columnResizeMouseDownHandler); } } var cols:Array = visibleColumns; if (!(cols && cols.length > 0 || dataGrid.headerVisible)) { sep.visible = false; continue; } // Spark skins don't measure if the width is specified. var skinWidth:Number; if (sepSkin is IUIComponent) skinWidth = IUIComponent(sepSkin).getExplicitOrMeasuredWidth(); else skinWidth = sepSkin.measuredWidth; sep.visible = true; sep.x = headerItems[i].x + visibleColumns[i].width - Math.round(skinWidth / 2); if (i > 0) { sep.x = Math.max(sep.x, separators[i - 1].x + Math.round(skinWidth / 2)); } sep.y = 0; sepSkin.setActualSize(skinWidth, Math.ceil(cachedHeaderHeight)); // Draw invisible background for separator affordance sep.graphics.clear(); sep.graphics.beginFill(0xFFFFFF, 0); sep.graphics.drawRect(-separatorAffordance, 0, sepSkin.measuredWidth + separatorAffordance, cachedHeaderHeight); sep.graphics.endFill(); sep.mouseEnabled = true; } while (lines.numChildren > n) { lines.removeChildAt(lines.numChildren - 1); separators.pop(); } UIComponentGlobals.layoutManager.validateClient(lines, true); } /** * Draws the highlight indicator into the given Sprite * at the position, width and height specified using the * color specified. * * @param indicator A Sprite that should contain the graphics * that make a renderer look highlighted. * * @param x The suggested x position for the indicator. * * @param y The suggested y position for the indicator. * * @param width The suggested width for the indicator. * * @param height The suggested height for the indicator. * * @param color The suggested color for the indicator. * * @param itemRenderer The item renderer that is being highlighted. * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function drawHeaderIndicator(indicator:Sprite, x:Number, y:Number, width:Number, height:Number, color:uint, itemRenderer:IListItemRenderer):void { var g:Graphics = indicator.graphics; g.clear(); g.beginFill(color); g.drawRect(0, 0, width, height); g.endFill(); indicator.x = x; indicator.y = y; } /** * Draws the selection indicator into the given Sprite * at the position, width and height specified using the * color specified. * * @param indicator A Sprite that should contain the graphics * that make a renderer look selected. * * @param x The suggested x position for the indicator. * * @param y The suggested y position for the indicator. * * @param width The suggested width for the indicator. * * @param height The suggested height for the indicator. * * @param color The suggested color for the indicator. * * @param itemRenderer The item renderer that is being selected. * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function drawSelectionIndicator(indicator:Sprite, x:Number, y:Number, width:Number, height:Number, color:uint, itemRenderer:IListItemRenderer):void { var g:Graphics = indicator.graphics; g.clear(); g.beginFill(color); g.drawRect(0, 0, width, height); g.endFill(); indicator.x = x; indicator.y = y; } /** * Draws the overlay on the dragged column into the given Sprite * at the position, width and height specified using the * color specified. * * @param indicator A Sprite that should contain the graphics * that indicate that a column is being dragged. * * @param x The suggested x position for the indicator. * * @param y The suggested y position for the indicator. * * @param width The suggested width for the indicator. * * @param height The suggested height for the indicator. * * @param color The suggested color for the indicator. * * @param itemRenderer The item renderer that is being dragged. * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function drawColumnDragOverlay(indicator:Sprite, x:Number, y:Number, width:Number, height:Number, color:uint, itemRenderer:IListItemRenderer):void { var g:Graphics = indicator.graphics; g.clear(); g.beginFill(color); g.drawRect(0, 0, width, height); g.endFill(); indicator.x = x; indicator.y = y; } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * @private */ private function columnResizeMouseOverHandler(event:MouseEvent):void { if (!enabled || !dataGrid.resizableColumns) return; var target:DisplayObject = DisplayObject(event.target); var index:int = target.parent.getChildIndex(target); if (!visibleColumns[index].resizable) return; // hide the mouse, attach and show the cursor var stretchCursorClass:Class = getStyle(""stretchCursor""); resizeCursorID = cursorManager.setCursor(stretchCursorClass, CursorManagerPriority.HIGH, 0, 0); } /** * @private */ private function columnResizeMouseOutHandler(event:MouseEvent):void { if (!enabled || !dataGrid.resizableColumns) return; var target:DisplayObject = DisplayObject(event.target); var index:int = target.parent.getChildIndex(target); if (!visibleColumns[index].resizable) return; cursorManager.removeCursor(resizeCursorID); } /** * @private * Indicates where the right side of a resized column appears. */ private function columnResizeMouseDownHandler(event:MouseEvent):void { if (!enabled || !dataGrid.resizableColumns) return; var target:DisplayObject = DisplayObject(event.target); var index:int = target.parent.getChildIndex(target); if (!visibleColumns[index].resizable) return; startX = DisplayObject(event.target).x + x; lastPt = new Point(event.stageX, event.stageY); lastPt = dataGrid.globalToLocal(lastPt); var n:int = separators.length; var colIndex:int = 0; for (var i:int = 0; i < n; i++) { if (separators[i] == event.target) { resizingColumn = visibleColumns[i]; colIndex = i; } else separators[i].mouseEnabled = false; } if (!resizingColumn) return; minX = headerItems[colIndex].x + x + resizingColumn.minWidth; var sbRoot:DisplayObject = systemManager.getSandboxRoot(); sbRoot.addEventListener(MouseEvent.MOUSE_MOVE, columnResizingHandler, true); sbRoot.addEventListener(MouseEvent.MOUSE_UP, columnResizeMouseUpHandler, true); sbRoot.addEventListener(SandboxMouseEvent.MOUSE_UP_SOMEWHERE, columnResizeMouseUpHandler); systemManager.deployMouseShields(true); var resizeSkinClass:Class = getStyle(""columnResizeSkin""); resizeGraphic = new resizeSkinClass(); if (resizeGraphic is Sprite) Sprite(resizeGraphic).mouseEnabled = false; dataGrid.addChild(DisplayObject(resizeGraphic)); resizeGraphic.move(DisplayObject(event.target).x + x, 0); resizeGraphic.setActualSize(resizeGraphic.measuredWidth, dataGrid.height / dataGrid.scaleY); } /** * @private */ private function columnResizingHandler(event:MouseEvent):void { if (!MouseEvent(event).buttonDown) { columnResizeMouseUpHandler(event); return; } var vsw:int = dataGrid.vScrollBar ? dataGrid.vScrollBar.width : 0; var pt:Point = new Point(event.stageX, event.stageY); pt = dataGrid.globalToLocal(pt); lastPt = pt; resizeGraphic.move(Math.min(Math.max(minX, pt.x), (dataGrid.width / dataGrid.scaleX) - separators[0].width - vsw), 0); } /** * @private * Determines how much to resize the column. */ private function columnResizeMouseUpHandler(event:Event):void { if (!enabled || !dataGrid.resizableColumns) return; // Set this to null so sort doesn't happen. lastItemDown = null; var sbRoot:DisplayObject = systemManager.getSandboxRoot(); sbRoot.removeEventListener(MouseEvent.MOUSE_MOVE, columnResizingHandler, true); sbRoot.removeEventListener(MouseEvent.MOUSE_UP, columnResizeMouseUpHandler, true); sbRoot.removeEventListener(SandboxMouseEvent.MOUSE_UP_SOMEWHERE, columnResizeMouseUpHandler); systemManager.deployMouseShields(false); dataGrid.removeChild(DisplayObject(resizeGraphic)); resizeGraphic = null; cursorManager.removeCursor(resizeCursorID); var c:DataGridColumn = resizingColumn; resizingColumn = null; var vsw:int = dataGrid.vScrollBar ? dataGrid.vScrollBar.width : 0; var mouseEvent:MouseEvent = event as MouseEvent; var pt:Point; if (mouseEvent) { pt = new Point(mouseEvent.stageX, mouseEvent.stageY); pt = dataGrid.globalToLocal(pt); } else pt = lastPt; // resize the column var widthChange:Number = Math.min(Math.max(minX, pt.x), (dataGrid.width / dataGrid.scaleX) - separators[0].width - vsw) - startX; dataGrid.resizeColumn(c.colNum, Math.floor(c.width + widthChange)); invalidateDisplayList(); // force redraw of columns // event var dataGridEvent:DataGridEvent = new DataGridEvent(DataGridEvent.COLUMN_STRETCH); dataGridEvent.columnIndex = c.colNum; dataGridEvent.dataField = c.dataField; dataGridEvent.localX = pt.x; dataGrid.dispatchEvent(dataGridEvent); } /** * @private */ private function columnDraggingMouseMoveHandler(event:MouseEvent):void { if (!event.buttonDown) { columnDraggingMouseUpHandler(event); return; } var item:IListItemRenderer; var c:DataGridColumn = dataGrid.movingColumn; var s:Sprite; var i:int = 0; var n:int = headerItems.length; var dgSelectionLayer:Sprite; if (isNaN(startX)) { // If startX is not a number, dragging has just started. // Initialise and return without actually moving anything. startX = event.stageX; // Set this to null so sort doesn't happen. lastItemDown = null; var vm:EdgeMetrics = dataGrid.viewMetrics; // Create, position and draw selection layer over both headers. dgSelectionLayer = new UIComponent(); dgSelectionLayer.name = ""columnDragSelectionLayer""; dgSelectionLayer.alpha = 0.6; dataGrid.addChild(dgSelectionLayer); dgSelectionLayer.x = vm.left; dgSelectionLayer.y = vm.top; // Create and position proxy. var proxy:IListItemRenderer = dataGrid.createColumnItemRenderer(c, true, c); proxy.name = ""headerDragProxy""; var rowData:DataGridListData = new DataGridListData((c.headerText != null) ? c.headerText : c.dataField, c.dataField, c.colNum, uid, dataGrid, 0); if (proxy is IDropInListItemRenderer) IDropInListItemRenderer(proxy).listData = rowData; dgSelectionLayer.addChild(DisplayObject(proxy)); proxy.data = c; proxy.styleName = getStyle(""headerDragProxyStyleName""); UIComponentGlobals.layoutManager.validateClient(proxy, true); proxy.setActualSize(c.width, dataGrid._explicitHeaderHeight ? dataGrid.headerHeight : proxy.getExplicitOrMeasuredHeight()); for (i = 0; i < n; i++) { item = headerItems[i]; if (item.data == dataGrid.movingColumn) break; } proxy.move(item.x + x, item.y); // Create, position and draw column overlay. s = new FlexSprite(); s.name = ""columnDragOverlay""; s.alpha = 0.6; dataGrid.addChild(s); if (c.width > 0) { drawColumnDragOverlay(s, item.x + x, 0, c.width, dataGrid.height / dataGrid.scaleY - vm.bottom - s.y, getStyle(""disabledColor""), item); } s = Sprite(selectionLayer.getChildByName(""headerSelection"")); if (s) { s.width = dataGrid.movingColumn.width; dgSelectionLayer.addChild(s); s.x += x; } // Clip the contents so the header drag proxy doesn't show // outside the list. dgSelectionLayer.scrollRect = new Rectangle(0, 0, dataGrid.width / dataGrid.scaleX, unscaledHeight); return; } // Global coordinates. var deltaX:Number = event.stageX - startX; dgSelectionLayer = Sprite(dataGrid.getChildByName(""columnDragSelectionLayer"")); // If the mouse pointer over the right (layoutDirection=”ltr”) or // left (layoutDirection=”rtl”) half of the column, the drop indicator // should be shown before the next column. var deltaXInLocalCoordinates:Number = (layoutDirection == LayoutDirection.LTR ? +deltaX : -deltaX); // Move header selection. s = Sprite(dgSelectionLayer.getChildByName(""headerSelection"")); if (s) s.x += deltaXInLocalCoordinates; // Move header proxy. item = IListItemRenderer(dgSelectionLayer.getChildByName(""headerDragProxy"")); if (item) item.move(item.x + deltaXInLocalCoordinates, item.y); // Global coordinates. startX += deltaX; var allVisibleColumns:Array = dataGrid.getAllVisibleColumns(); var pt:Point = new Point(event.stageX, event.stageY); pt = dataGrid.globalToLocal(pt); lastPt = pt; n = allVisibleColumns.length; var xx:Number = dataGrid.viewMetrics.left; var ww:Number; for (i = 0; i < n; i++) { ww = allVisibleColumns[i].width; if (pt.x < xx + ww) { // If the mouse pointer over the right (ltr) or left (rtl) half // of the column, the drop indicator should be shown before // the next column. if (pt.x > xx + ww / 2) { i++; xx += ww; } if (dropColumnIndex != i) { dropColumnIndex = i; if (!columnDropIndicator) { var dropIndicatorClass:Class = getStyle(""columnDropIndicatorSkin""); if (!dropIndicatorClass) dropIndicatorClass = DataGridColumnDropIndicator; columnDropIndicator = IFlexDisplayObject( new dropIndicatorClass()); if (columnDropIndicator is ISimpleStyleClient) ISimpleStyleClient(columnDropIndicator).styleName = this; dataGrid.addChild( DisplayObject(columnDropIndicator)); var m:Shape = new Shape(); m.graphics.beginFill(0xffffff); m.graphics.drawRect(0, 0, 10, 10); m.graphics.endFill(); dataGrid.addChild(m); columnDropIndicator.mask = m; } dataGrid.setChildIndex( DisplayObject(columnDropIndicator), dataGrid.numChildren - 1); columnDropIndicator.visible = true; m = columnDropIndicator.mask as Shape; m.x = dataGrid.viewMetrics.left; m.y = dataGrid.viewMetrics.top; m.width = dataGrid.width / dataGrid.scaleX - m.x - dataGrid.viewMetrics.right; m.height = dataGrid.height / dataGrid.scaleY - m.x - dataGrid.viewMetrics.bottom; columnDropIndicator.setActualSize(3, dataGrid.height / dataGrid.scaleY); columnDropIndicator.x = xx - columnDropIndicator.width + (layoutDirection == LayoutDirection.LTR ? 0 : 1); columnDropIndicator.y = 0; } break; } xx += ww; } } /** * @private * * @param event MouseEvent or SandboxMouseEvent. */ private function columnDraggingMouseUpHandler(event:Event):void { if (!dataGrid.movingColumn) return; var origIndex:int = dataGrid.movingColumn.colNum; var allVisibleColumns:Array = dataGrid.getAllVisibleColumns(); if (dropColumnIndex >= 0) { if (dropColumnIndex >= allVisibleColumns.length) { dropColumnIndex = allVisibleColumns.length - 1; } else { if (origIndex < allVisibleColumns[dropColumnIndex].colNum) dropColumnIndex--; } // dropColumnIndex is actually the index into the headerItems // array. Get the corresponding index into the _columns array. dropColumnIndex = allVisibleColumns[dropColumnIndex].colNum; } // Shift columns. dataGrid.shiftColumns(origIndex, dropColumnIndex, event as MouseEvent); var sbRoot:DisplayObject = systemManager.getSandboxRoot(); sbRoot.removeEventListener(MouseEvent.MOUSE_MOVE, columnDraggingMouseMoveHandler, true); sbRoot.removeEventListener(MouseEvent.MOUSE_UP, columnDraggingMouseUpHandler, true); sbRoot.removeEventListener(SandboxMouseEvent.MOUSE_UP_SOMEWHERE, columnDraggingMouseUpHandler); systemManager.deployMouseShields(false); var dgSelectionLayer:Sprite = Sprite(dataGrid.getChildByName(""columnDragSelectionLayer"")); if (!dgSelectionLayer) { startX = NaN; dataGrid.movingColumn = null; dropColumnIndex = -1; return; } var proxy:IListItemRenderer = IListItemRenderer(getChildByName(""headerDragProxy"")); if (proxy) dgSelectionLayer.removeChild(DisplayObject(proxy)); var s:Sprite = Sprite(dgSelectionLayer.getChildByName(""headerSelection"")); if (s) dgSelectionLayer.removeChild(s); if (columnDropIndicator) columnDropIndicator.visible = false; s = Sprite(dataGrid.getChildByName(""columnDragOverlay"")); if (s) dataGrid.removeChild(s); dataGrid.removeChild(dgSelectionLayer); startX = NaN; dataGrid.movingColumn = null; dropColumnIndex = -1; invalidateDisplayList(); // force redraw } /** * @private */ protected function mouseOverHandler(event:MouseEvent):void { var r:IListItemRenderer; var i:int; if (resizingColumn || dataGrid.movingColumn) return; if (dataGrid.enabled && dataGrid.sortableColumns && dataGrid.headerVisible) { // find out if we hit the sort arrow s = Sprite(getChildByName(""sortArrowHitArea"")); if (event.target == s) { var n:int = visibleColumns.length; for (i = 0; i < n; i++) { if (visibleColumns[i].colNum == dataGrid.sortIndex) { r = headerItems[i]; break; } } } else { for (i = 0; i < separators.length; i++) { if (event.target == separators[i] && visibleColumns[i].resizable) return; } var pt:Point = new Point(event.stageX, event.stageY); pt = globalToLocal(pt); for (i = 0; i < headerItems.length; i++) { if (headerItems[i].x + headerItems[i].width >= pt.x) { r = headerItems[i]; break; } } if (i >= headerItems.length) return; } s = Sprite(getChildByName(""sortArrowHitArea"")); if (visibleColumns[i].sortable) { var s:Sprite = Sprite( selectionLayer.getChildByName(""headerSelection"")); if (!s) { s = new FlexSprite(); s.name = ""headerSelection""; s.mouseEnabled = false; selectionLayer.addChild(s); } drawHeaderIndicator(s, r.x, 0, visibleColumns[i].width, cachedHeaderHeight - 0.5, getStyle(""rollOverColor""), r); } } if (event.buttonDown) lastItemDown = r; else lastItemDown = null; } /** * @private */ protected function mouseOutHandler(event:MouseEvent):void { var r:IListItemRenderer; var i:int; if (resizeGraphic || dataGrid.movingColumn) return; if (dataGrid.enabled && dataGrid.sortableColumns && dataGrid.headerVisible) { // find out if we hit the sort arrow s = Sprite(getChildByName(""sortArrowHitArea"")); if (event.target == s) { var n:int = visibleColumns.length; for (i = 0; i < n; i++) { if (visibleColumns[i].colNum == dataGrid.sortIndex) { r = headerItems[i]; break; } } if (i >= visibleColumns.length) return; } else { for (i = 0; i < separators.length; i++) { if (event.target == separators[i] && visibleColumns[i].resizable) return; } var pt:Point = new Point(event.stageX, event.stageY); pt = globalToLocal(pt); for (i = 0; i < headerItems.length; i++) { if (headerItems[i].x + headerItems[i].width >= pt.x) { r = headerItems[i]; break; } } if (i >= headerItems.length) i = headerItems.length - 1; } if (visibleColumns.length > 0 && visibleColumns[i].sortable) { var s:Sprite = Sprite( selectionLayer.getChildByName(""headerSelection"")); if (s) selectionLayer.removeChild(s); } } if (event.buttonDown) lastItemDown = r; else lastItemDown = null; } /** * @private */ protected function mouseDownHandler(event:MouseEvent):void { // trace("">>mouseDownHandler""); var r:IListItemRenderer; var s:Sprite; var i:int; systemManager.getSandboxRoot().addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler, true, 0, true); systemManager.getSandboxRoot().addEventListener(SandboxMouseEvent.MOUSE_UP_SOMEWHERE, mouseLeaveHandler, false, 0, true); // find out if we hit the sort arrow s = Sprite(getChildByName(""sortArrowHitArea"")); if (event.target == s) { var n:int = visibleColumns.length; for (i = 0; i < n; i++) { if (visibleColumns[i].colNum == dataGrid.sortIndex) { r = headerItems[i]; break; } } } else { for (i = 0; i < separators.length; i++) { if (event.target == separators[i] && visibleColumns[i].resizable) return; } var pt:Point = new Point(event.stageX, event.stageY); pt = globalToLocal(pt); for (i = 0; i < headerItems.length; i++) { if (headerItems[i].x + headerItems[i].width >= pt.x) { r = headerItems[i]; break; } } if (i >= headerItems.length) return; } // if headers are visible and clickable for sorting if (dataGrid.enabled && (dataGrid.sortableColumns || dataGrid.draggableColumns) && dataGrid.headerVisible) { if (dataGrid.sortableColumns && visibleColumns[i].sortable) { lastItemDown = r; s = Sprite(selectionLayer.getChildByName(""headerSelection"")); if (!s) { s = new FlexSprite(); s.name = ""headerSelection""; selectionLayer.addChild(s); } drawSelectionIndicator(s, r.x, 0, visibleColumns[i].width, cachedHeaderHeight - 0.5, getStyle(""selectionColor""), r); } // begin column dragging if (dataGrid.draggableColumns && visibleColumns[i].draggable) { startX = NaN; var sbRoot:DisplayObject = systemManager.getSandboxRoot(); sbRoot.addEventListener(MouseEvent.MOUSE_MOVE, columnDraggingMouseMoveHandler, true); sbRoot.addEventListener(MouseEvent.MOUSE_UP, columnDraggingMouseUpHandler, true); sbRoot.addEventListener(SandboxMouseEvent.MOUSE_UP_SOMEWHERE, columnDraggingMouseUpHandler); systemManager.deployMouseShields(true); dataGrid.movingColumn = visibleColumns[i]; } } } /** * @private */ protected function mouseUpHandler(event:MouseEvent):void { var dataGridEvent:DataGridEvent; var r:IListItemRenderer; var s:Sprite; var n:int; var i:int; systemManager.getSandboxRoot().removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler, true); systemManager.getSandboxRoot().removeEventListener(SandboxMouseEvent.MOUSE_UP_SOMEWHERE, mouseLeaveHandler); // find out if we hit the sort arrow s = Sprite(getChildByName(""sortArrowHitArea"")); if (event.target == s) { n = visibleColumns.length; for (i = 0; i < n; i++) { if (visibleColumns[i].colNum == dataGrid.sortIndex) { r = headerItems[i]; break; } } } else { for (i = 0; i < separators.length; i++) { if (event.target == separators[i] && visibleColumns[i].resizable) return; } var pt:Point = new Point(event.stageX, event.stageY); pt = globalToLocal(pt); for (i = 0; i < headerItems.length; i++) { if (headerItems[i].x + headerItems[i].width >= pt.x) { r = headerItems[i]; break; } } if (i >= headerItems.length) return; } if (dataGrid.enabled && (dataGrid.sortableColumns || dataGrid.draggableColumns) && dataGrid.dataProvider && dataGrid.headerVisible) { if (r == lastItemDown) { if (dataGrid.sortableColumns && visibleColumns[i].sortable) { lastItemDown = null; dataGridEvent = new DataGridEvent(DataGridEvent.HEADER_RELEASE, false, true); // HEADER_RELEASE event is cancelable dataGridEvent.columnIndex = visibleColumns[i].colNum; dataGridEvent.dataField = visibleColumns[i].dataField; dataGridEvent.itemRenderer = r; dataGrid.dispatchEvent(dataGridEvent); } } } } private function mouseLeaveHandler(event:Event):void { systemManager.getSandboxRoot().removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler, true); systemManager.getSandboxRoot().removeEventListener(SandboxMouseEvent.MOUSE_UP_SOMEWHERE, mouseLeaveHandler); } mx_internal function _placeSortArrow():void { placeSortArrow(); } /** * Draws the sort arrow graphic on the column that is the current sort key. * This implementation creates or reuses an instance of the skin specified * by sortArrowSkin style property and places * it in the appropriate column header. It * also shrinks the size of the column header if the text in the header * would be obscured by the sort arrow. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function placeSortArrow():void { var sortArrowHitArea:Sprite = Sprite(getChildByName(""sortArrowHitArea"")); if (dataGrid.sortIndex == -1 && dataGrid.lastSortIndex == -1) { if (sortArrow) sortArrow.visible = false; if (sortArrowHitArea) sortArrowHitArea.visible = false; return; } if (!dataGrid.headerVisible) { if (sortArrow) sortArrow.visible = false; if (sortArrowHitArea) sortArrowHitArea.visible = false; return; } if (!sortArrow) { var sortArrowClass:Class = getStyle(""sortArrowSkin""); sortArrow = new sortArrowClass(); DisplayObject(sortArrow).name = enabled ? ""sortArrow"" : ""sortArrowDisabled""; if (sortArrow is ISimpleStyleClient) ISimpleStyleClient(sortArrow).styleName = this; addChild(DisplayObject(sortArrow)); } var xx:Number; var n:int; var i:int; var found:Boolean = false; if (headerItems && headerItems.length) { n = headerItems.length; for (i = 0; i < n; i++) { if (visibleColumns[i].colNum == dataGrid.sortIndex) { xx = headerItems[i].x + visibleColumns[i].width; headerItems[i].setActualSize(visibleColumns[i].width - sortArrow.measuredWidth - 8, headerItems[i].height); if (!isNaN(headerItems[i].explicitWidth)) headerItems[i].explicitWidth = headerItems[i].width; UIComponentGlobals.layoutManager.validateClient(headerItems[i], true); // Create hit area to capture mouse clicks behind arrow. if (!sortArrowHitArea) { sortArrowHitArea = new FlexSprite(); sortArrowHitArea.name = ""sortArrowHitArea""; addChild(sortArrowHitArea); } else sortArrowHitArea.visible = true; sortArrowHitArea.x = headerItems[i].x + headerItems[i].width; sortArrowHitArea.y = headerItems[i].y; var g:Graphics = sortArrowHitArea.graphics; g.clear(); g.beginFill(0, 0); g.drawRect(0, 0, sortArrow.measuredWidth + 8, headerItems[i].height); g.endFill(); found = true; break; } } } if (isNaN(xx)) sortArrow.visible = false; else sortArrow.visible = true; if (visibleColumns.length && dataGrid.lastSortIndex >= 0 && dataGrid.lastSortIndex != dataGrid.sortIndex) if (visibleColumns[0].colNum <= dataGrid.lastSortIndex && dataGrid.lastSortIndex <= visibleColumns[visibleColumns.length - 1].colNum) { n = headerItems.length; for (var j:int = 0; j < n; j++) { if (visibleColumns[j].colNum == dataGrid.lastSortIndex) { headerItems[j].setActualSize(visibleColumns[j].width, headerItems[j].height); UIComponentGlobals.layoutManager.validateClient(headerItems[j], true); break; } } } var d:Boolean = (dataGrid.sortDirection == ""ASC""); sortArrow.width = sortArrow.measuredWidth; sortArrow.height = sortArrow.measuredHeight; DisplayObject(sortArrow).scaleY = (d) ? -1.0 : 1.0; sortArrow.x = xx - sortArrow.measuredWidth - 8; var hh:Number = cachedHeaderHeight; sortArrow.y = (hh - sortArrow.measuredHeight) / 2 + ((d) ? sortArrow.measuredHeight: 0); if (found && sortArrow.x < headerItems[i].x) sortArrow.visible = false; if (!sortArrow.visible && sortArrowHitArea) sortArrowHitArea.visible = false; } //-------------------------------------------------------------------------- // // Overridden methods: UIComponent // //-------------------------------------------------------------------------- /** * @private */ override public function invalidateSize():void { if (allowItemSizeChangeNotification) super.invalidateSize(); } /** * @copy mx.core.IUIComponent#enabled * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ override public function set enabled(value:Boolean):void { super.enabled = value; if (sortArrow) { removeChild(DisplayObject(sortArrow)); sortArrow = null; placeSortArrow(); } } /** * @private */ override public function styleChanged(styleProp:String):void { super.styleChanged(styleProp); if (styleProp == ""headerBackgroundSkin"") { headerBGSkinChanged = true; } else if (styleProp == ""headerSeparatorSkin"") { headerSepSkinChanged = true; } } /** * @private */ private var resizeCursorID:int = CursorManager.NO_CURSOR; /** * @private * A tmp var to store the stretching col's X coord. */ private var startX:Number; /** * @private * A tmp var to store the stretching col's min X coord for column's minWidth. */ private var minX:Number; /** * @private * A tmp var to store the last point (in dataGrid coords) received while dragging. */ private var lastPt:Point; /** * @private * List of header separators for column resizing. */ private var separators:Array; /** * @private */ mx_internal function getSeparators():Array { return separators; } /** * @private * The column that is being resized. */ private function get resizingColumn():DataGridColumn { return dataGrid.resizingColumn; } /** * @private * The column that is being resized. */ private function set resizingColumn(value:DataGridColumn):void { dataGrid.resizingColumn = value; } /** * Specifies a graphic that shows the proposed column width as the user stretches it. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ private var resizeGraphic:IFlexDisplayObject; // /** * @private */ private var lastItemDown:IListItemRenderer; /** * @private * Index of column before which to drop */ private var dropColumnIndex:int = -1; /** * @private */ mx_internal var columnDropIndicator:IFlexDisplayObject; /** * The small arrow graphic used to show sortable columns and direction. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal var sortArrow:IFlexDisplayObject; /** * diagnostics * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal function get rendererArray():Array { return headerItems; } /** * The offset, in pixels, from the left side of the content of the renderer. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var leftOffset:Number = 0; /** * The offset, in pixels, from the top of the content of the renderer. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var topOffset:Number = 0; /** * The offset, in pixels, from the right side of the content of the renderer. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var rightOffset:Number = 0; /** * The offset, in pixels, from the bottom of the content of the renderer. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var bottomOffset:Number = 0; /** * @private */ private var allowItemSizeChangeNotification:Boolean = true; private var headerBGSkinChanged:Boolean = false; private var headerSepSkinChanged:Boolean = false; } } ",12357,True,2623.9719368613623,median "//// 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. //// image::apache-tinkerpop-logo.png[width=500,link=""http://tinkerpop.apache.org""] *x.y.z* :toc-position: left Provider Documentation ====================== TinkerPop exposes a set of interfaces, protocols, and tests that make it possible for third-parties to build libraries and systems that plug-in to the TinkerPop stack. TinkerPop refers to those third-parties as ""providers"" and this documentation is designed to help providers understand what is involved in developing code on these lower levels of the TinkerPop API. This document attempts to address the needs of the different providers that have been identified: * Graph System Provider ** Graph Database Provider ** Graph Processor Provider * Graph Driver Provider * Graph Language Provider * Graph Plugin Provider [[graph-system-provider-requirements]] Graph System Provider Requirements ---------------------------------- image:tinkerpop-enabled.png[width=140,float=left] At the core of TinkerPop3 is a Java8 API. The implementation of this core API and its validation via the `gremlin-test` suite is all that is required of a graph system provider wishing to provide a TinkerPop3-enabled graph engine. Once a graph system has a valid implementation, then all the applications provided by TinkerPop (e.g. Gremlin Console, Gremlin Server, etc.) and 3rd-party developers (e.g. Gremlin-Scala, Gremlin-JS, etc.) will integrate properly. Finally, please feel free to use the logo on the left to promote your TinkerPop3 implementation. Implementing Gremlin-Core ~~~~~~~~~~~~~~~~~~~~~~~~~ The classes that a graph system provider should focus on implementing are itemized below. It is a good idea to study the link:http://tinkerpop.apache.org/docs/x.y.z/reference/#tinkergraph-gremlin[TinkerGraph] (in-memory OLTP and OLAP in `tinkergraph-gremlin`), link:http://tinkerpop.apache.org/docs/x.y.z/reference/#neo4j-gremlin[Neo4jGraph] (OLTP w/ transactions in `neo4j-gremlin`) and/or link:http://tinkerpop.apache.org/docs/x.y.z/reference/#hadoop-gremlin[HadoopGraph] (OLAP in `hadoop-gremlin`) implementations for ideas and patterns. . Online Transactional Processing Graph Systems (*OLTP*) .. Structure API: `Graph`, `Element`, `Vertex`, `Edge`, `Property` and `Transaction` (if transactions are supported). .. Process API: `TraversalStrategy` instances for optimizing Gremlin traversals to the provider's graph system (i.e. `TinkerGraphStepStrategy`). . Online Analytics Processing Graph Systems (*OLAP*) .. Everything required of OLTP is required of OLAP (but not vice versa). .. GraphComputer API: `GraphComputer`, `Messenger`, `Memory`. Please consider the following implementation notes: * Be sure your `Graph` implementation is named as `XXXGraph` (e.g. TinkerGraph, Neo4jGraph, HadoopGraph, etc.). * Use `StringHelper` to ensuring that the `toString()` representation of classes are consistent with other implementations. * Ensure that your implementation's `Features` (Graph, Vertex, etc.) are correct so that test cases handle particulars accordingly. * Use the numerous static method helper classes such as `ElementHelper`, `GraphComputerHelper`, `VertexProgramHelper`, etc. * There are a number of default methods on the provided interfaces that are semantically correct. However, if they are not efficient for the implementation, override them. * Implement the `structure/` package interfaces first and then, if desired, interfaces in the `process/` package interfaces. * `ComputerGraph` is a `Wrapper` system that ensure proper semantics during a GraphComputer computation. [[oltp-implementations]] OLTP Implementations ^^^^^^^^^^^^^^^^^^^^ image:pipes-character-1.png[width=110,float=right] The most important interfaces to implement are in the `structure/` package. These include interfaces like Graph, Vertex, Edge, Property, Transaction, etc. The `StructureStandardSuite` will ensure that the semantics of the methods implemented are correct. Moreover, there are numerous `Exceptions` classes with static exceptions that should be thrown by the graph system so that all the exceptions and their messages are consistent amongst all TinkerPop3 implementations. [[olap-implementations]] OLAP Implementations ^^^^^^^^^^^^^^^^^^^^ image:furnace-character-1.png[width=110,float=right] Implementing the OLAP interfaces may be a bit more complicated. Note that before OLAP interfaces are implemented, it is necessary for the OLTP interfaces to be, at minimal, implemented as specified in <>. A summary of each required interface implementation is presented below: . `GraphComputer`: A fluent builder for specifying an isolation level, a VertexProgram, and any number of MapReduce jobs to be submitted. . `Memory`: A global blackboard for ANDing, ORing, INCRing, and SETing values for specified keys. . `Messenger`: The system that collects and distributes messages being propagated by vertices executing the VertexProgram application. . `MapReduce.MapEmitter`: The system that collects key/value pairs being emitted by the MapReduce applications map-phase. . `MapReduce.ReduceEmitter`: The system that collects key/value pairs being emitted by the MapReduce applications combine- and reduce-phases. NOTE: The VertexProgram and MapReduce interfaces in the `process/computer/` package are not required by the graph system. Instead, these are interfaces to be implemented by application developers writing VertexPrograms and MapReduce jobs. IMPORTANT: TinkerPop3 provides three OLAP implementations: link:http://tinkerpop.apache.org/docs/x.y.z/reference/#tinkergraph-gremlin[TinkerGraphComputer] (TinkerGraph), link:http://tinkerpop.apache.org/docs/x.y.z/reference/#giraphgraphcomputer[GiraphGraphComputer] (HadoopGraph), and link:http://tinkerpop.apache.org/docs/x.y.z/reference/#sparkgraphcomputer[SparkGraphComputer] (Hadoop). Given the complexity of the OLAP system, it is good to study and copy many of the patterns used in these reference implementations. Implementing GraphComputer ++++++++++++++++++++++++++ image:furnace-character-3.png[width=150,float=right] The most complex method in GraphComputer is the `submit()`-method. The method must do the following: . Ensure the GraphComputer has not already been executed. . Ensure that at least there is a VertexProgram or 1 MapReduce job. . If there is a VertexProgram, validate that it can execute on the GraphComputer given the respectively defined features. . Create the Memory to be used for the computation. . Execute the VertexProgram.setup() method once and only once. . Execute the VertexProgram.execute() method for each vertex. . Execute the VertexProgram.terminate() method once and if true, repeat VertexProgram.execute(). . When VertexProgram.terminate() returns true, move to MapReduce job execution. . MapReduce jobs are not required to be executed in any specified order. . For each Vertex, execute MapReduce.map(). Then (if defined) execute MapReduce.combine() and MapReduce.reduce(). . Update Memory with runtime information. . Construct a new `ComputerResult` containing the compute Graph and Memory. Implementing Memory +++++++++++++++++++ image:gremlin-brain.png[width=175,float=left] The Memory object is initially defined by `VertexProgram.setup()`. The memory data is available in the first round of the `VertexProgram.execute()` method. Each Vertex, when executing the VertexProgram, can update the Memory in its round. However, the update is not seen by the other vertices until the next round. At the end of the first round, all the updates are aggregated and the new memory data is available on the second round. This process repeats until the VertexProgram terminates. Implementing Messenger ++++++++++++++++++++++ The Messenger object is similar to the Memory object in that a vertex can read and write to the Messenger. However, the data it reads are the messages sent to the vertex in the previous step and the data it writes are the messages that will be readable by the receiving vertices in the subsequent round. Implementing MapReduce Emitters +++++++++++++++++++++++++++++++ image:hadoop-logo-notext.png[width=150,float=left] The MapReduce framework in TinkerPop3 is similar to the model popularized by link:http://hadoop.apache.org[Hadoop]. The primary difference is that all Mappers process the vertices of the graph, not an arbitrary key/value pair. However, the vertices' edges can not be accessed -- only their properties. This greatly reduces the amount of data needed to be pushed through the MapReduce engine as any edge information required, can be computed in the VertexProgram.execute() method. Moreover, at this stage, vertices can not be mutated, only their token and property data read. A Gremlin OLAP system needs to provide implementations for to particular classes: `MapReduce.MapEmitter` and `MapReduce.ReduceEmitter`. TinkerGraph's implementation is provided below which demonstrates the simplicity of the algorithm (especially when the data is all within the same JVM). [source,java] ---- public class TinkerMapEmitter implements MapReduce.MapEmitter { public Map> reduceMap; public Queue> mapQueue; private final boolean doReduce; public TinkerMapEmitter(final boolean doReduce) { <1> this.doReduce = doReduce; if (this.doReduce) this.reduceMap = new ConcurrentHashMap<>(); else this.mapQueue = new ConcurrentLinkedQueue<>(); } @Override public void emit(K key, V value) { if (this.doReduce) this.reduceMap.computeIfAbsent(key, k -> new ConcurrentLinkedQueue<>()).add(value); <2> else this.mapQueue.add(new KeyValue<>(key, value)); <3> } protected void complete(final MapReduce mapReduce) { if (!this.doReduce && mapReduce.getMapKeySort().isPresent()) { <4> final Comparator comparator = mapReduce.getMapKeySort().get(); final List> list = new ArrayList<>(this.mapQueue); Collections.sort(list, Comparator.comparing(KeyValue::getKey, comparator)); this.mapQueue.clear(); this.mapQueue.addAll(list); } else if (mapReduce.getMapKeySort().isPresent()) { final Comparator comparator = mapReduce.getMapKeySort().get(); final List>> list = new ArrayList<>(); list.addAll(this.reduceMap.entrySet()); Collections.sort(list, Comparator.comparing(Map.Entry::getKey, comparator)); this.reduceMap = new LinkedHashMap<>(); list.forEach(entry -> this.reduceMap.put(entry.getKey(), entry.getValue())); } } } ---- <1> If the MapReduce job has a reduce, then use one data structure (`reduceMap`), else use another (`mapList`). The difference being that a reduction requires a grouping by key and therefore, the `Map>` definition. If no reduction/grouping is required, then a simple `Queue>` can be leveraged. <2> If reduce is to follow, then increment the Map with a new value for the key. `MapHelper` is a TinkerPop3 class with static methods for adding data to a Map. <3> If no reduce is to follow, then simply append a KeyValue to the queue. <4> When the map phase is complete, any map-result sorting required can be executed at this point. [source,java] ---- public class TinkerReduceEmitter implements MapReduce.ReduceEmitter { protected Queue> reduceQueue = new ConcurrentLinkedQueue<>(); @Override public void emit(final OK key, final OV value) { this.reduceQueue.add(new KeyValue<>(key, value)); } protected void complete(final MapReduce mapReduce) { if (mapReduce.getReduceKeySort().isPresent()) { final Comparator comparator = mapReduce.getReduceKeySort().get(); final List> list = new ArrayList<>(this.reduceQueue); Collections.sort(list, Comparator.comparing(KeyValue::getKey, comparator)); this.reduceQueue.clear(); this.reduceQueue.addAll(list); } } } ---- The method `MapReduce.reduce()` is defined as: [source,java] public void reduce(final OK key, final Iterator values, final ReduceEmitter emitter) { ... } In other words, for the TinkerGraph implementation, iterate through the entrySet of the `reduceMap` and call the `reduce()` method on each entry. The `reduce()` method can emit key/value pairs which are simply aggregated into a `Queue>` in an analogous fashion to `TinkerMapEmitter` when no reduce is to follow. These two emitters are tied together in `TinkerGraphComputer.submit()`. [source,java] ---- ... for (final MapReduce mapReduce : mapReducers) { if (mapReduce.doStage(MapReduce.Stage.MAP)) { final TinkerMapEmitter mapEmitter = new TinkerMapEmitter<>(mapReduce.doStage(MapReduce.Stage.REDUCE)); final SynchronizedIterator vertices = new SynchronizedIterator<>(this.graph.vertices()); workers.setMapReduce(mapReduce); workers.mapReduceWorkerStart(MapReduce.Stage.MAP); workers.executeMapReduce(workerMapReduce -> { while (true) { final Vertex vertex = vertices.next(); if (null == vertex) return; workerMapReduce.map(ComputerGraph.mapReduce(vertex), mapEmitter); } }); workers.mapReduceWorkerEnd(MapReduce.Stage.MAP); // sort results if a map output sort is defined mapEmitter.complete(mapReduce); // no need to run combiners as this is single machine if (mapReduce.doStage(MapReduce.Stage.REDUCE)) { final TinkerReduceEmitter reduceEmitter = new TinkerReduceEmitter<>(); final SynchronizedIterator>> keyValues = new SynchronizedIterator((Iterator) mapEmitter.reduceMap.entrySet().iterator()); workers.mapReduceWorkerStart(MapReduce.Stage.REDUCE); workers.executeMapReduce(workerMapReduce -> { while (true) { final Map.Entry> entry = keyValues.next(); if (null == entry) return; workerMapReduce.reduce(entry.getKey(), entry.getValue().iterator(), reduceEmitter); } }); workers.mapReduceWorkerEnd(MapReduce.Stage.REDUCE); reduceEmitter.complete(mapReduce); // sort results if a reduce output sort is defined mapReduce.addResultToMemory(this.memory, reduceEmitter.reduceQueue.iterator()); <1> } else { mapReduce.addResultToMemory(this.memory, mapEmitter.mapQueue.iterator()); <2> } } } ... ---- <1> Note that the final results of the reducer are provided to the Memory as specified by the application developer's `MapReduce.addResultToMemory()` implementation. <2> If there is no reduce stage, the map-stage results are inserted into Memory as specified by the application developer's `MapReduce.addResultToMemory()` implementation. Hadoop-Gremlin Usage ^^^^^^^^^^^^^^^^^^^^ Hadoop-Gremlin is centered around `InputFormats` and `OutputFormats`. If a 3rd-party graph system provider wishes to leverage Hadoop-Gremlin (and its respective `GraphComputer` engines), then they need to provide, at minimum, a Hadoop2 `InputFormat` for their graph system. If the provider wishes to persist computed results back to their graph system (and not just to HDFS via a `FileOutputFormat`), then a graph system specific `OutputFormat` must be developed as well. Conceptually, `HadoopGraph` is a wrapper around a `Configuration` object. There is no ""data"" in the `HadoopGraph` as the `InputFormat` specifies where and how to get the graph data at OLAP (and OLTP) runtime. Thus, `HadoopGraph` is a small object with little overhead. Graph system providers should realize `HadoopGraph` as the gateway to the OLAP features offered by Hadoop-Gremlin. For example, a graph system specific `Graph.compute(Class graphComputerClass)`-method may look as follows: [source,java] ---- public C compute(final Class graphComputerClass) throws IllegalArgumentException { try { if (AbstractHadoopGraphComputer.class.isAssignableFrom(graphComputerClass)) return graphComputerClass.getConstructor(HadoopGraph.class).newInstance(this); else throw Graph.Exceptions.graphDoesNotSupportProvidedGraphComputer(graphComputerClass); } catch (final Exception e) { throw new IllegalArgumentException(e.getMessage(),e); } } ---- Note that the configurations for Hadoop are assumed to be in the `Graph.configuration()` object. If this is not the case, then the `Configuration` provided to `HadoopGraph.open()` should be dynamically created within the `compute()`-method. It is in the provided configuration that `HadoopGraph` gets the various properties which determine how to read and write data to and from Hadoop. For instance, `gremlin.hadoop.graphReader` and `gremlin.hadoop.graphWriter`. GraphFilterAware Interface ++++++++++++++++++++++++++ <> by OLAP processors to only pull a subgraph of the full graph from the graph data source. For instance, the example below constructs a `GraphFilter` that will only pull the ""knows""-graph amongst people into the `GraphComputer` for processing. [source,java] ---- graph.compute().vertices(hasLabel(""person"")).edges(bothE(""knows"")) ---- If the provider has a custom `InputRDD`, they can implement `GraphFilterAware` and that graph filter will be provided to their `InputRDD` at load time. For providers that use an `InputFormat`, state but the graph filter can be accessed from the configuration as such: [source,java] ---- if (configuration.containsKey(Constants.GREMLIN_HADOOP_GRAPH_FILTER)) this.graphFilter = VertexProgramHelper.deserialize(configuration, Constants.GREMLIN_HADOOP_GRAPH_FILTER); ---- PersistResultGraphAware Interface +++++++++++++++++++++++++++++++++ A graph system provider's `OutputFormat` should implement the `PersistResultGraphAware` interface which determines which persistence options are available to the user. For the standard file-based `OutputFormats` provided by Hadoop-Gremlin (e.g. <>, <>, and <>) `ResultGraph.ORIGINAL` is not supported as the original graph data files are not random access and are, in essence, immutable. Thus, these file-based `OutputFormats` only support `ResultGraph.NEW` which creates a copy of the data specified by the `Persist` enum. [[io-implementations]] IO Implementations ^^^^^^^^^^^^^^^^^^ If a `Graph` requires custom serializers for IO to work properly, implement the `Graph.io` method. A typical example of where a `Graph` would require such a custom serializers is if their identifier system uses non-primitive values, such as OrientDB's `Rid` class. From basic serialization of a single `Vertex` all the way up the stack to Gremlin Server, the need to know how to handle these complex identifiers is an important requirement. The first step to implementing custom serializers is to first implement the `IoRegistry` interface and register the custom classes and serializers to it. Each `Io` implementation has different requirements for what it expects from the `IoRegistry`: * *GraphML* - No custom serializers expected/allowed. * *GraphSON* - Register a Jackson `SimpleModule`. The `SimpleModule` encapsulates specific classes to be serialized, so it does not need to be registered to a specific class in the `IoRegistry` (use `null`). * *Gryo* - Expects registration of one of three objects: ** Register just the custom class with a `null` Kryo `Serializer` implementation - this class will use default ""field-level"" Kryo serialization. ** Register the custom class with a specific Kryo `Serializer' implementation. ** Register the custom class with a `Function` for those cases where the Kryo `Serializer` requires the `Kryo` instance to get constructed. This implementation should provide a zero-arg constructor as the stack may require instantiation via reflection. Consider extending `AbstractIoRegistry` for convenience as follows: [source,java] ---- public class MyGraphIoRegistry extends AbstractIoRegistry { public MyGraphIoRegistry() { register(GraphSONIo.class, null, new MyGraphSimpleModule()); register(GryoIo.class, MyGraphIdClass.class, new MyGraphIdSerializer()); } } ---- In the `Graph.io` method, provide the `IoRegistry` object to the supplied `Builder` and call the `create` method to return that `Io` instance as follows: [source,java] ---- public I io(final Io.Builder builder) { return (I) builder.graph(this).registry(myGraphIoRegistry).create(); }} ---- In this way, `Graph` implementations can pre-configure custom serializers for IO interactions and users will not need to know about those details. Following this pattern will ensure proper execution of the test suite as well as simplified usage for end-users. IMPORTANT: Proper implementation of IO is critical to successful `Graph` operations in Gremlin Server. The Test Suite does have ""serialization"" tests that provide some assurance that an implementation is working properly, but those tests cannot make assertions against any specifics of a custom serializer. It is the responsibility of the implementer to test the specifics of their custom serializers. TIP: Consider separating serializer code into its own module, if possible, so that clients that use the `Graph` implementation remotely don't need a full dependency on the entire `Graph` - just the IO components and related classes being serialized. [[remoteconnection-implementations]] RemoteConnection Implementations ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A `RemoteConnection` is an interface that is important for usage on traversal sources configured using the link:http://tinkerpop.apache.org/docs/x.y.z/reference/#connecting-via-remotegraph[withRemote()] option. A `Traversal` that is generated from that source will apply a `RemoteStrategy` which will inject a `RemoteStep` to its end. That step will then send the `Bytecode` of the `Traversal` over the `RemoteConnection` to get the results that it will iterate. There is one method to implement on `RemoteConnection`: [source,java] public CompletableFuture> submitAsync(final Bytecode bytecode) throws RemoteConnectionException; Note that it returns a `RemoteTraversal`. This interface should also be implemented and in most cases implementers can simply extend the `AbstractRemoteTraversal`, which provides default implementations for all the `Traversal` methods except for the important one `getSideEffects()`. [source,java] public RemoteTraversalSideEffects getSideEffects(); This method has been overriden from `Traversal` to return `RemoteTraversalSideEffects` and this interface allows a user to do a retrieval of any side-effects produced by the `Traversal`. The assumption, of course, is that the `RemoteConnection` is communicating with a server that supports side-effect retreival (as Gremlin Server does). TinkerPop provides the `DriverRemoteConnection` as a useful and link:https://github.com/apache/tinkerpop/blob/x.y.z/gremlin-driver/src/main/java/org/apache/tinkerpop/gremlin/driver/remote[example implementation]. `DriverRemoteConnection` serializes the `Traversal` and then submits it for remote processing on Gremlin Server. Gremlin Server rebinds the `Traversal` to a configured `Graph` instance and then iterates the results back as it would normally do. Implementing `RemoteConnection` is not something routinely done for those implementing `gremlin-core`. It is only something required if there is a need to exploit `withRemote()` in some way. If a graph provider has a ""graph server"" similar to Gremlin Server that can accept a serialized `Traversal` instance, then that would be one example of a reason to implement this interface. [[validating-with-gremlin-test]] Validating with Gremlin-Test ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ image:gremlin-edumacated.png[width=225] [source,xml] ---- org.apache.tinkerpop gremlin-test x.y.z ---- The operational semantics of any OLTP or OLAP implementation are validated by `gremlin-test`. To implement these tests, provide test case implementations as shown below, where `XXX` below denotes the name of the graph implementation (e.g. TinkerGraph, Neo4jGraph, HadoopGraph, etc.). [source,java] ---- // Structure API tests @RunWith(StructureStandardSuite.class) @GraphProviderClass(provider = XXXGraphProvider.class, graph = XXXGraph.class) public class XXXStructureStandardTest {} // Process API tests @RunWith(ProcessComputerSuite.class) @GraphProviderClass(provider = XXXGraphProvider.class, graph = XXXGraph.class) public class XXXProcessComputerTest {} @RunWith(ProcessStandardSuite.class) @GraphProviderClass(provider = XXXGraphProvider.class, graph = XXXGraph.class) public class XXXProcessStandardTest {} ---- The above set of tests represent the minimum test suite set to implement. There are other ""integration"" and ""performance"" tests that should be considered optional. Implementing those tests requires the same pattern as shown above. IMPORTANT: It is as important to look at ""ignored"" tests as it is to look at ones that fail. The `gremlin-test` suite utilizes the `Feature` implementation exposed by the `Graph` to determine which tests to execute. If a test utilizes features that are not supported by the graph, it will ignore them. While that may be fine, implementers should validate that the ignored tests are appropriately bypassed and that there are no mistakes in their feature definitions. Moreover, implementers should consider filling gaps in their own test suites, especially when IO-related tests are being ignored. The only test-class that requires any code investment is the `GraphProvider` implementation class. This class is a used by the test suite to construct `Graph` configurations and instances and provides information about the implementation itself. In most cases, it is best to simply extend `AbstractGraphProvider` as it provides many default implementations of the `GraphProvider` interface. Finally, specify the test suites that will be supported by the `Graph` implementation using the `@Graph.OptIn` annotation. See the `TinkerGraph` implementation below as an example: [source,java] ---- @Graph.OptIn(Graph.OptIn.SUITE_STRUCTURE_STANDARD) @Graph.OptIn(Graph.OptIn.SUITE_PROCESS_STANDARD) @Graph.OptIn(Graph.OptIn.SUITE_PROCESS_COMPUTER) public class TinkerGraph implements Graph { ---- Only include annotations for the suites the implementation will support. Note that implementing the suite, but not specifying the appropriate annotation will prevent the suite from running (an obvious error message will appear in this case when running the mis-configured suite). There are times when there may be a specific test in the suite that the implementation cannot support (despite the features it implements) or should not otherwise be executed. It is possible for implementers to ""opt-out"" of a test by using the `@Graph.OptOut` annotation. The following is an example of this annotation usage as taken from `HadoopGraph`: [source, java] ---- @Graph.OptIn(Graph.OptIn.SUITE_PROCESS_STANDARD) @Graph.OptIn(Graph.OptIn.SUITE_PROCESS_COMPUTER) @Graph.OptOut( test = ""org.apache.tinkerpop.gremlin.process.graph.step.map.MatchTest$Traversals"", method = ""g_V_matchXa_hasXname_GarciaX__a_inXwrittenByX_b__a_inXsungByX_bX"", reason = ""Hadoop-Gremlin is OLAP-oriented and for OLTP operations, linear-scan joins are required. This particular tests takes many minutes to execute."") @Graph.OptOut( test = ""org.apache.tinkerpop.gremlin.process.graph.step.map.MatchTest$Traversals"", method = ""g_V_matchXa_inXsungByX_b__a_inXsungByX_c__b_outXwrittenByX_d__c_outXwrittenByX_e__d_hasXname_George_HarisonX__e_hasXname_Bob_MarleyXX"", reason = ""Hadoop-Gremlin is OLAP-oriented and for OLTP operations, linear-scan joins are required. This particular tests takes many minutes to execute."") @Graph.OptOut( test = ""org.apache.tinkerpop.gremlin.process.computer.GraphComputerTest"", method = ""shouldNotAllowBadMemoryKeys"", reason = ""Hadoop does a hard kill on failure and stops threads which stops test cases. Exception handling semantics are correct though."") @Graph.OptOut( test = ""org.apache.tinkerpop.gremlin.process.computer.GraphComputerTest"", method = ""shouldRequireRegisteringMemoryKeys"", reason = ""Hadoop does a hard kill on failure and stops threads which stops test cases. Exception handling semantics are correct though."") public class HadoopGraph implements Graph { ---- The above examples show how to ignore individual tests. It is also possible to: * Ignore an entire test case (i.e. all the methods within the test) by setting the `method` to ""*"". * Ignore a ""base"" test class such that test that extend from those classes will all be ignored. * Ignore a `GraphComputer` test based on the type of `GraphComputer` being used. Specify the ""computer"" attribute on the `OptOut` (which is an array specification) which should have a value of the `GraphComputer` implementation class that should ignore that test. This attribute should be left empty for ""standard"" execution and by default all `GraphComputer` implementations will be included in the `OptOut` so if there are multiple implementations, explicitly specify the ones that should be excluded. Also note that some of the tests in the Gremlin Test Suite are parameterized tests and require an additional level of specificity to be properly ignored. To ignore these types of tests, examine the name template of the parameterized tests. It is defined by a Java annotation that looks like this: [source, java] @Parameterized.Parameters(name = ""expect({0})"") The annotation above shows that the name of each parameterized test will be prefixed with ""expect"" and have parentheses wrapped around the first parameter (at index 0) value supplied to each test. This information can only be garnered by studying the test set up itself. Once the pattern is determined and the specific unique name of the parameterized test is identified, add it to the `specific` property on the `OptOut` annotation in addition to the other arguments. These annotations help provide users a level of transparency into test suite compliance (via the link:http://tinkerpop.apache.org/docs/x.y.z/reference/#describe-graph[describeGraph()] utility function). It also allows implementers to have a lot of flexibility in terms of how they wish to support TinkerPop. For example, maybe there is a single test case that prevents an implementer from claiming support of a `Feature`. The implementer could choose to either not support the `Feature` or to support it but ""opt-out"" of the test with a ""reason"" as to why so that users understand the limitation. IMPORTANT: Before using `OptOut` be sure that the reason for using it is sound and it is more of a last resort. It is possible that a test from the suite doesn't properly represent the expectations of a feature, is too broad or narrow for the semantics it is trying to enforce or simply contains a bug. Please consider raising issues in the developer mailing list with such concerns before assuming `OptOut` is the only answer. IMPORTANT: There are no tests that specifically validate complete compliance with Gremlin Server. Generally speaking, a `Graph` that passes the full Test Suite, should be compliant with Gremlin Server. The one area where problems can occur is in serialization. Always ensure that IO is properly implemented, that custom serializers are tested fully and ultimately integration test the `Graph` with an actual Gremlin Server instance. WARNING: Configuring tests to run in parallel might result in errors that are difficult to debug as there is some shared state in test execution around graph configuration. It is therefore recommended that parallelism be turned off for the test suite (the Maven SureFire Plugin is configured this way by default). It may also be important to include this setting, `false`, in the SureFire configuration if tests are failing in an unexplainable way. TIP: When running the `gremlin-test` suite against your implementation, you may need to set `build.dir` as an environment variable, depending on your project layout. Some tests require this to find a writable directory for creating temporary files. The value is typically set to the project build directory. For example using the Maven SureFire Plugin, this is done via the configuration argLine with `-Dbuild.dir=${project.build.directory}`. Accessibility via GremlinPlugin ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ image:gremlin-plugin.png[width=100,float=left] The applications distributed with TinkerPop3 do not distribute with any graph system implementations besides TinkerGraph. If your implementation is stored in a Maven repository (e.g. Maven Central Repository), then it is best to provide a <> implementation so the respective jars can be downloaded according and when required by the user. Neo4j's GremlinPlugin is provided below for reference. [source,java] ---- public class Neo4jGremlinPlugin implements GremlinPlugin { private static final String IMPORT = ""import ""; private static final String DOT_STAR = "".*""; private static final Set IMPORTS = new HashSet() {{ add(IMPORT + Neo4jGraph.class.getPackage().getName() + DOT_STAR); }}; @Override public String getName() { return ""neo4j""; } @Override public void pluginTo(final PluginAcceptor pluginAcceptor) { pluginAcceptor.addImports(IMPORTS); } } ---- With the above plugin implementations, users can now download respective binaries for Gremlin Console, Gremlin Server, etc. [source,groovy] gremlin> g = Neo4jGraph.open('/tmp/neo4j') No such property: Neo4jGraph for class: groovysh_evaluate Display stack trace? [yN] gremlin> :install org.apache.tinkerpop neo4j-gremlin x.y.z ==>loaded: [org.apache.tinkerpop, neo4j-gremlin, …] gremlin> :plugin use tinkerpop.neo4j ==>tinkerpop.neo4j activated gremlin> g = Neo4jGraph.open('/tmp/neo4j') ==>neo4jgraph[EmbeddedGraphDatabase [/tmp/neo4j]] In-Depth Implementations ~~~~~~~~~~~~~~~~~~~~~~~~ image:gremlin-painting.png[width=200,float=right] The graph system implementation details presented thus far are minimum requirements necessary to yield a valid TinkerPop3 implementation. However, there are other areas that a graph system provider can tweak to provide an implementation more optimized for their underlying graph engine. Typical areas of focus include: * Traversal Strategies: A link:http://tinkerpop.apache.org/docs/x.y.z/reference/#traversalstrategy[TraversalStrategy] can be used to alter a traversal prior to its execution. A typical example is converting a pattern of `g.V().has('name','marko')` into a global index lookup for all vertices with name ""marko"". In this way, a `O(|V|)` lookup becomes an `O(log(|V|))`. Please review `TinkerGraphStepStrategy` for ideas. * Step Implementations: Every link:http://tinkerpop.apache.org/docs/x.y.z/reference/#graph-traversal-steps[step] is ultimately referenced by the `GraphTraversal` interface. It is possible to extend `GraphTraversal` to use a graph system specific step implementation. Graph Driver Provider Requirements ---------------------------------- image::gremlin-server-protocol.png[width=325] One of the roles for link:http://tinkerpop.apache.org/docs/x.y.z/reference/#gremlin-server[Gremlin Server] is to provide a bridge from TinkerPop to non-JVM languages (e.g. Go, Python, etc.). Developers can build language bindings (or driver) that provide a way to submit Gremlin scripts to Gremlin Server and get back results. Given the extensible nature of Gremlin Server, it is difficult to provide an authoritative guide to developing a driver. It is however possible to describe the core communication protocol using the standard out-of-the-box configuration which should provide enough information to develop a driver for a specific language. image::gremlin-server-flow.png[width=300,float=right] Gremlin Server is distributed with a configuration that utilizes link:http://en.wikipedia.org/wiki/WebSocket[WebSocket] with a custom sub-protocol. Under this configuration, Gremlin Server accepts requests containing a Gremlin script, evaluates that script and then streams back the results. The notion of ""streaming"" is depicted in the diagram to the right. The diagram shows an incoming request to process the Gremlin script of `g.V()`. Gremlin Server evaluates that script, getting an `Iterator` of vertices as a result, and steps through each `Vertex` within it. The vertices are batched together given the `resultIterationBatchSize` configuration. In this case, that value must be `2` given that each ""response"" contains two vertices. Each response is serialized given the requested serializer type (JSON is likely best for non-JVM languages) and written back to the requesting client immediately. Gremlin Server does not wait for the entire result to be iterated, before sending back a response. It will send the responses as they are realized. This approach allows for the processing of large result sets without having to serialize the entire result into memory for the response. It places a bit of a burden on the developer of the driver however, because it becomes necessary to provide a way to reconstruct the entire result on the client side from all of the individual responses that Gremlin Server returns for a single request. Again, this description of Gremlin Server's ""flow"" is related to the out-of-the-box configuration. It is quite possible to construct other flows, that might be more amenable to a particular language or style of processing. To formulate a request to Gremlin Server, a `RequestMessage` needs to be constructed. The `RequestMessage` is a generalized representation of a request that carries a set of ""standard"" values in addition to optional ones that are dependent on the operation being performed. A `RequestMessage` has these fields: [width=""100%"",cols=""3,10"",options=""header""] |========================================================= |Key |Description |requestId |A link:http://en.wikipedia.org/wiki/Globally_unique_identifier[UUID] representing the unique identification for the request. |op |The name of the ""operation"" to execute based on the available `OpProcessor` configured in the Gremlin Server. To evaluate a script, use `eval`. |processor |The name of the `OpProcessor` to utilize. The default `OpProcessor` for evaluating scripts is unnamed and therefore script evaluation purposes, this value can be an empty string. |args |A `Map` of arbitrary parameters to pass to Gremlin Server. The requirements for the contents of this `Map` are dependent on the `op` selected. |========================================================= This message can be serialized in any fashion that is supported by Gremlin Server. New serialization methods can be plugged in by implementing a `ServiceLoader` enabled `MessageSerializer`, however Gremlin Server provides for JSON serialization by default which will be good enough for purposes of most developers building drivers. A `RequestMessage` to evaluate a script with variable bindings looks like this in JSON: [source,js] ---- { ""requestId"":""1d6d02bd-8e56-421d-9438-3bd6d0079ff1"", ""op"":""eval"", ""processor"":"""", ""args"":{""gremlin"":""g.traversal().V(x).out()"", ""bindings"":{""x"":1}, ""language"":""gremlin-groovy""}} ---- The above JSON represents the ""body"" of the request to send to Gremlin Server. When sending this ""body"" over WebSocket, Gremlin Server can accept a packet frame using a ""text"" (1) or a ""binary"" (2) opcode. Using ""text"" is a bit more limited in that Gremlin Server will always process the body of that request as JSON. Generally speaking ""text"" is just for testing purposes. The preferred method for sending requests to Gremlin Server is to use the ""binary"" opcode. In this case, a ""header"" will need be sent in addition to to the ""body"". The ""header"" basically consists of a ""mime type"" so that Gremlin Server knows how to deserialize the `RequestMessage`. So, the actual byte array sent to Gremlin Server would be formatted as follows: image::gremlin-server-request.png[] The first byte represents the length of the ""mime type"" string value that follows. Given the default configuration of Gremlin Server, this value should be set to `application/json`. The ""payload"" represents the JSON message above encoded as bytes. NOTE: Gremlin Server will only accept masked packets as it pertains to a WebSocket packet header construction. When Gremlin Server receives that request, it will decode it given the ""mime type"", pass it to the requested `OpProcessor` which will execute the `op` defined in the message. In this case, it will evaluate the script `g.traversal().V(x).out()` using the `bindings` supplied in the `args` and stream back the results in a series of `ResponseMessages`. A `ResponseMessage` looks like this: [width=""100%"",cols=""3,10"",options=""header""] |========================================================= |Key |Description |requestId |The identifier of the `RequestMessage` that generated this `ResponseMessage`. |status | The `status` contains a `Map` of three keys: `code` which refers to a `ResultCode` that is somewhat analogous to an link:http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html[HTTP status code], `attributes` that represent a `Map` of protocol-level information, and `message` which is just a human-readable `String` usually associated with errors. |result | The `result` contains a `Map` of two keys: `data` which refers to the actual data returned from the server (the type of data is determined by the operation requested) and `meta` which is a `Map` of meta-data related to the response. |========================================================= In this case the `ResponseMessage` returned to the client would look something like this: [source,js] ---- {""result"":{""data"":[{""id"": 2,""label"": ""person"",""type"": ""vertex"",""properties"": [ {""id"": 2, ""value"": ""vadas"", ""label"": ""name""}, {""id"": 3, ""value"": 27, ""label"": ""age""}]}, ], ""meta"":{}}, ""requestId"":""1d6d02bd-8e56-421d-9438-3bd6d0079ff1"", ""status"":{""code"":206,""attributes"":{},""message"":""""}} ---- Gremlin Server is capable of streaming results such that additional responses will arrive over the WebSocket connection until the iteration of the result on the server is complete. Each successful incremental message will have a `ResultCode` of `206`. Termination of the stream will be marked by a final `200` status code. Note that all messages without a `206` represent terminating conditions for a request. The following table details the various status codes that Gremlin Server will send: [width=""100%"",cols=""2,2,9"",options=""header""] |========================================================= |Code |Name |Description |200 |SUCCESS |The server successfully processed a request to completion - there are no messages remaining in this stream. |204 |NO CONTENT |The server processed the request but there is no result to return (e.g. an `Iterator` with no elements) - there are no messages remaining in this stream. |206 |PARTIAL CONTENT |The server successfully returned some content, but there is more in the stream to arrive - wait for a `SUCCESS` to signify the end of the stream. |401 |UNAUTHORIZED |The request attempted to access resources that the requesting user did not have access to. |407 |AUTHENTICATE |A challenge from the server for the client to authenticate its request. |498 |MALFORMED REQUEST | The request message was not properly formatted which means it could not be parsed at all or the ""op"" code was not recognized such that Gremlin Server could properly route it for processing. Check the message format and retry the request. |499 |INVALID REQUEST ARGUMENTS |The request message was parseable, but the arguments supplied in the message were in conflict or incomplete. Check the message format and retry the request. |500 |SERVER ERROR |A general server error occurred that prevented the request from being processed. |597 |SCRIPT EVALUATION ERROR |The script submitted for processing evaluated in the `ScriptEngine` with errors and could not be processed. Check the script submitted for syntax errors or other problems and then resubmit. |598 |SERVER TIMEOUT |The server exceeded one of the timeout settings for the request and could therefore only partially responded or did not respond at all. |599 |SERVER SERIALIZATION ERROR |The server was not capable of serializing an object that was returned from the script supplied on the request. Either transform the object into something Gremlin Server can process within the script or install mapper serialization classes to Gremlin Server. |========================================================= NOTE: Please refer to the link:http://tinkerpop.apache.org/docs/current/dev/io[IO Reference Documentation] for more examples of `RequestMessage` and `ResponseMessage` instances. OpProcessors Arguments ~~~~~~~~~~~~~~~~~~~~~~ The following sections define a non-exhaustive list of available operations and arguments for embedded `OpProcessors` (i.e. ones packaged with Gremlin Server). Common ^^^^^^ All `OpProcessor` instances support these arguments. [width=""100%"",cols=""2,2,9"",options=""header""] |========================================================= |Key |Type |Description |batchSize |Int |When the result is an iterator this value defines the number of iterations each `ResponseMessage` should contain - overrides the `resultIterationBatchSize` server setting. |========================================================= Standard OpProcessor ^^^^^^^^^^^^^^^^^^^^ The ""standard"" `OpProcessor` handles requests for the primary function of Gremlin Server - executing Gremlin. Requests made to this `OpProcessor` are ""sessionless"" in the sense that a request must encapsulate the entirety of a transaction. There is no state maintained between requests. A transaction is started when the script is first evaluated and is committed when the script completes (or rolled back if an error occurred). [width=""100%"",cols=""3,10a"",options=""header""] |========================================================= |Key |Description |processor |As this is the default `OpProcessor` this value can be set to an empty string. |op |[width=""100%"",cols=""3,10"",options=""header""] !========================================================= !Key !Description !`authentication` !A request that contains the response to a server challenge for authentication. !`eval` !Evaluate a Gremlin script provided as a `String`. !========================================================= |========================================================= '`authentication` operation arguments' [width=""100%"",cols=""2,2,9"",options=""header""] |========================================================= |Key |Type |Description |sasl |byte[] | *Required* The response to the server authentication challenge. This value is dependent on the SASL authentication mechanism required by the server. |saslMechanism |String | The SASL mechanism: `PLAIN` or `GSSAPI`. Note that it is up to the server implementation to use or disregard this setting (default implementation in Gremlin Server ignores it). |========================================================= '`eval` operation arguments' [width=""100%"",cols=""2,2,9"",options=""header""] |========================================================= |Key |Type |Description |gremlin |String | *Required* The Gremlin script to evaluate. |bindings |Map |A map of key/value pairs to apply as variables in the context of the Gremlin script. |language |String |The flavor of Gremlin used (e.g. `gremlin-groovy`). |aliases |Map |A map of key/value pairs that allow globally bound `Graph` and `TraversalSource` objects to be aliased to different variable names for purposes of the current request. The value represents the name of the global variable and its key represents the new binding name as it will be referenced in the Gremlin query. For example, if the Gremlin Server defines two `TraversalSource` instances named `g1` and `g2`, it would be possible to send an alias pair with key of ""g"" and value of ""g2"" and thus allow the script to refer to ""g2"" simply as ""g"". |scriptEvaluationTimeout |Long |An override for the server setting that determines the maximum time to wait for a script to execute on the server. |========================================================= Session OpProcessor ^^^^^^^^^^^^^^^^^^^ The ""session"" `OpProcessor` handles requests for the primary function of Gremlin Server - executing Gremlin. It is like the ""standard"" `OpProcessor`, but instead maintains state between sessions and allows the option to leave all transaction management up to the calling client. It is important that clients that open sessions, commit or roll them back, however Gremlin Server will try to clean up such things when a session is killed that has been abandoned. It is important to consider that a session can only be maintained with a single machine. In the event that multiple Gremlin Server are deployed, session state is not shared among them. [width=""100%"",cols=""3,10a"",options=""header""] |========================================================= |Key |Description |processor |This value should be set to `session` |op | [cols=""3,10"",options=""header""] !========================================================= !Key !Description !`authentication` !A request that contains the response to a server challenge for authentication. !`eval` !Evaluate a Gremlin script provided as a `String`. !`close` !Close the specified session. Will return a `NO CONTENT` message as confirmation of the close being completed. |========================================================= '`authentication` operation arguments' [width=""100%"",cols=""2,2,9"",options=""header""] |========================================================= |Key |Type |Description |saslMechanism |String | The SASL mechanism: `PLAIN` or `GSSAPI`. Note that it is up to the server implementation to use or disregard this setting (default implementation in Gremlin Server ignores it). |sasl |byte[] | *Required* The response to the server authentication challenge. This value is dependent on the SASL authentication mechanism required by the server. |========================================================= '`eval` operation arguments' [width=""100%"",options=""header""] |========================================================= |Key |Type |Description |gremlin |String | *Required* The Gremlin script to evaluate. |session |String | *Required* The session identifier for the current session - typically this value should be a UUID (the session will be created if it doesn't exist). |manageTransaction |Boolean |When set to `true` the transaction for the current request is auto-committed or rolled-back as are done with sessionless requests - defaulted to `false`. |bindings |Map |A map of key/value pairs to apply as variables in the context of the Gremlin script. |scriptEvaluationTimeout |Long |An override for the server setting that determines the maximum time to wait for a script to execute on the server. |language |String |The flavor of Gremlin used (e.g. `gremlin-groovy`) |aliases |Map |A map of key/value pairs that allow globally bound `Graph` and `TraversalSource` objects to be aliased to different variable names for purposes of the current request. The value represents the name the global variable and its key represents the new binding name as it will be referenced in the Gremlin query. For example, if the Gremlin Server defines two `TraversalSource` instances named `g1` and `g2`, it would be possible to send an alias pair with key of ""g"" and value of ""g2"" and thus allow the script to refer to ""g2"" simply as ""g"". |========================================================= '`close` operation arguments' [width=""100%"",cols=""2,2,9"",options=""header""] |========================================================= |Key |Type |Description |session |String | *Required* The session identifier for the session to close. |force |Boolean | Determines if the session should be force closed when the client is closed. Force closing will not attempt to close open transactions from existing running jobs and leave it to the underlying graph to decided how to proceed with those orphaned transactions. Setting this to `true` tends to lead to faster close operation and release of resources which can be desirable if Gremlin Server has a long session timeout and a long script evaluation timeout as attempts to close long run jobs can occur more rapidly. If not provided, this value is `false`. |========================================================= Traversal OpProcessor ^^^^^^^^^^^^^^^^^^^^^ Both the Standard and Session OpProcessors allow for Gremlin scripts to be submitted to the server. The `TraversalOpProcessor` however allows Gremlin `Bytecode` to be submitted to the server. Supporting this `OpProcessor` makes it possible for a link:http://tinkerpop.apache.org/docs/current/tutorials/gremlin-language-variants/[Gremlin Language Variant] to submit a `Traversal` directly to Gremlin Server in the native language of the GLV without having to use a script in a different language. Unlike Standard and Session OpProcessors, the Traversal OpProcessor does not simply return the results of the `Traversal`. It instead returns `Traverser` objects which allows the client to take advantage of link:http://tinkerpop.apache.org/docs/current/reference/#barrier-step[bulking]. To describe this interaction more directly, the returned `Traverser` will represent some value from the `Traversal` result and the number of times it is represented in the full stream of results. So, if a `Traversal` happens to return the same vertex twenty times it won't return twenty instances of the same object. It will return one in `Traverser` with the `bulk` value set to twenty. Under this model, the amount of processing and network overhead can be reduced considerably. To demonstrate consider this example: [gremlin-groovy] ---- cluster = Cluster.open() client = cluster.connect() aliased = client.alias(""g"") g = org.apache.tinkerpop.gremlin.structure.util.empty.EmptyGraph.INSTANCE.traversal() <1> rs = aliased.submit(g.V().both().barrier().both().barrier()).all().get() <2> aliased.submit(g.V().both().barrier().both().barrier().count()).all().get().get(0).getInt() <3> rs.collect{[value: it.getObject().get(), bulk: it.getObject().bulk()]} <4> ---- <1> All commands through this step are just designed to demonstrate bulking with Gremlin Server and don't represent a real-world way that this feature would be used. <2> Submit a `Traversal` that happens to ensure that the server uses bulking. Note that a `Traverser` is returned and that there are only six results. <3> In actuality, however, if this same `Traversal` is iterated there are thirty results. Without bulking, the previous request would have sent back thirty traversers. <4> Note that the sum of the bulk of each `Traverser` is thirty. The full iteration of aa `Traversal` is thus left to the client. It must interpret the bulk on the `Traverser` and unroll it to represent the actual number of times it exists when iterated. The unrolling is typically handled directly within TinkerPop's `RemoteGraph` implementations. One of the important aspects of the Traversal OpProcessor is that it enables the user to not only get the results of the `Traversal` but also the side-effects that it produces. When the `Traversal` is submitted with the ""bytecode"" operation, the results are iterated back as usual, but any side-effects are retained on the server in a cache keyed by the identifier of the request that originally submitted the `Traversal`. The client will want to retain that identifier if it intends to later get side-effects. The Traversal OpProcessor supplies the ""keys"" and ""gather"" operations to get the keys stored in the side-effect and to get the value of a specific side-effect respectively. Finally, a ""close"" operation is available to clear the cache of a specific side-effect. [width=""100%"",cols=""3,10a"",options=""header""] |========================================================= |Key |Description |processor |This value should be set to `traversal` |op | [cols=""3,10"",options=""header""] !========================================================= !Key !Description !`authentication` !A request that contains the response to a server challenge for authentication. !`bytecode` !A request that contains the `Bytecode` representation of a `Traversal`. !`close` !Releases side-effects held in cache for a particular `Traversal`. !`gather` !Gets a particular side-effect as produced by a previously executed `Traversal`. !`keys` !Gets all the keys of all side-effects as produced by a previously executed `Traversal`. |========================================================= '`authentication` operation arguments' [width=""100%"",cols=""2,2,9"",options=""header""] |========================================================= |Key |Type |Description |sasl |byte[] | *Required* The response to the server authentication challenge. This value is dependent on the SASL authentication mechanism required by the server. |========================================================= '`bytecode` operation arguments' [width=""100%"",cols=""2,2,9"",options=""header""] |========================================================= |Key |Type |Description |gremlin |String | *Required* The `Bytecode` representation of a `Traversal`. |aliases |Map | *Required* A map with a single key/value pair that refers to a globally bound `TraversalSource` object to be aliased to different variable names for purposes of the current request. The value represents the name of the global variable and its key represents the new binding name as it will be referenced in the Gremlin query. For example, if the Gremlin Server defines two `TraversalSource` instances named `g1`, it would be possible to send an alias pair with key of ""g"" and value of ""g1"" and thus allow the script to refer to ""g1"" simply as ""g"". Note that unlike users of `alias` in other contexts, in this case, the key can *only* be set to ""g"" and there can be only one key value pair present (since only one `Traversal` is being submitted, there is no sense to having more than a single alias). |========================================================= '`close` operation arguments' [width=""100%"",cols=""2,2,9"",options=""header""] |========================================================= |Key |Type |Description |sideEffect |UUID | *Required* The unique identifier for the request that original submitted the traversal (side-effects are keyed by that value) |========================================================= '`gather` operation arguments' [width=""100%"",cols=""2,2,9"",options=""header""] |========================================================= |Key |Type |Description |sideEffect |UUID | *Required* The unique identifier for the request that original submitted the traversal (side-effects are keyed by that value) |sideEffectKey |String | *Required* The key for a specific side-effect. |aliases |Map | *Required* A map with a single key/value pair that refers to a globally bound `TraversalSource` object to be aliased to different variable names for purposes of the current request. The value represents the name of the global variable and its key represents the new binding name as it will be referenced in the Gremlin query. For example, if the Gremlin Server defines two `TraversalSource` instances named `g1`, it would be possible to send an alias pair with key of ""g"" and value of ""g1"" and thus allow the script to refer to ""g1"" simply as ""g"". Note that unlike users of `alias` in other contexts, in this case, the key can *only* be set to ""g"" and there can be only one key value pair present (since only one `Traversal` is being submitted, there is no sense to having more than a single alias). |========================================================= When using ""gather"" it is important to note the metadata that is returned on the `ResponseMessage`. It returns both the ""sideEffectKey"" that was requested as well as a value keyed as ""aggregateTo"". The ""aggregateTo"" field describes how the streamed side-effect data should be treated on the client. It provides a hint as to whether or not the data should be rolled back up into a single object or simply left as-is. There are four values for ""aggregateTo"": `bulkset`, `list`, `map`, `set` and `none`. '`keys` operation arguments' [width=""100%"",cols=""2,2,9"",options=""header""] |========================================================= |Key |Type |Description |sideEffect |UUID | *Required* The unique identifier for the request that original submitted the traversal (side-effects are keyed by that value) |========================================================= Authentication ~~~~~~~~~~~~~~ Gremlin Server supports link:https://en.wikipedia.org/wiki/Simple_Authentication_and_Security_Layer[SASL-based] authentication. A SASL implementation provides a series of challenges and responses that a driver must comply with in order to authenticate. By default, Gremlin Server only supports the ""PLAIN"" SASL mechanism, which is a cleartext password system. When authentication is enabled, an incoming request is intercepted before it is evaluated by the `ScriptEngine`. The request is saved on the server and a `AUTHENTICATE` challenge response (status code `407`) is returned to the client. The client will detect the `AUTHENTICATE` and respond with an `authentication` for the `op` and an `arg` named `sasl` that contains the password. The password should be either, an encoded sequence of UTF-8 bytes, delimited by 0 (US-ASCII NUL), where the form is : `usernamepassword`, or a Base64 encoded string of the former (which in this instance would be `AHVzZXJuYW1lAHBhc3N3b3Jk`). Should Gremlin Server be able to authenticate with the provided credentials, the server will return the results of the original request as it normally does without authentication. If it cannot authenticate given the challenge response from the client, it will return `UNAUTHORIZED` (status code `401`). NOTE: Gremlin Server does not support the ""authorization identity"" as described in link:https://tools.ietf.org/html/rfc4616[RFC4616]. [[gremlin-plugins]] Gremlin Plugins --------------- image:gremlin-plugin.png[width=125] Plugins provide a way to expand the features of a `GremlinScriptEngine`, which stands at that core of both Gremlin Console and Gremlin Server. Providers may wish to create plugins for a variety of reasons, but some common examples include: * Initialize the `GremlinScriptEngine` application with important classes so that the user doesn't need to type their own imports. * Place specific objects in the bindings of the `GremlinScriptEngine` for the convenience of the user. * Bootstrap the `GremlinScriptEngine` with custom functions so that they are ready for usage at startup. The first step to developing a plugin is to implement the link:http://tinkerpop.apache.org/javadocs/x.y.z/full/org/apache/tinkerpop/gremlin/jsr223/GremlinPlugin.html[GremlinPlugin] interface: [source,java] ---- include::{basedir}/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/jsr223/GremlinPlugin.java[] ---- The most simple plugin and the one most commonly implemented will likely be one that just provides a list of classes for import. This type of plugin is the easiest way for implementers of the TinkerPop Structure and Process APIs to make their implementations available to users. The TinkerGraph implementation has just such a plugin: [source,java] ---- include::{basedir}/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/jsr223/TinkerGraphGremlinPlugin.java[] ---- This plugin extends from the abstract base class of link:http://tinkerpop.apache.org/javadocs/x.y.z/full/org/apache/tinkerpop/gremlin/jsr223/AbstractGremlinPlugin.html[AbstractGremlinPlugin] which provides some default implementations of the `GremlinPlugin` methods. It simply allows those who extend from it to be able to just supply the name of the module and a list of link:http://tinkerpop.apache.org/javadocs/x.y.z/full/org/apache/tinkerpop/gremlin/jsr223/Customizer.html[Customizer] instances to apply to the `GremlinScriptEngine`. In this case, the TinkerGraph plugin just needs an link:http://tinkerpop.apache.org/javadocs/x.y.z/full/org/apache/tinkerpop/gremlin/jsr223/ImportCustomizer.html[ImportCustomizer] which describes the list of classes to import when the plugin is activated and applied to the `GremlinScriptEngine`. The `ImportCustomizer` is just one of several provided `Customizer` implementations that can be used in conjunction with plugin development: * link:http://tinkerpop.apache.org/javadocs/x.y.z/full/org/apache/tinkerpop/gremlin/jsr223/BindingCustomizer.html[BindingCustomizer] - Inject a key/value pair into the global bindings of the `GremlinScriptEngine` instances * link:http://tinkerpop.apache.org/javadocs/x.y.z/full/org/apache/tinkerpop/gremlin/jsr223/ImportCustomizer.html[ImportCustomizer] - Add imports to a `GremlinScriptEngine` * link:http://tinkerpop.apache.org/javadocs/x.y.z/full/org/apache/tinkerpop/gremlin/jsr223/ScriptCustomizer.html[ScriptCustomizer] - Execute a script on a `GremlinScriptEngine` at startup Individual `GremlinScriptEngine` instances may have their own `Customizer` instances that can be used only with that engine - e.g. `gremlin-groovy` has some that are specific to controlling the Groovy compiler configuration. Developing a new `Customizer` implementation is not really possible without changes to TinkerPop, as the framework is not designed to respond to external ones. The base `Customizer` implementations listed above should cover most needs. A `GremlinPlugin` must support one of two instantiation models so that it can be instantiated from configuration files for use in various situations - e.g. Gremlin Server. The first option is to use a static initializer given a method with the following signature: [source,java] ---- public static GremlinPlugin instance() ---- The limitation with this approach is that it does not provide a way to supply any configuration to the plugin so it tends to only be useful for fairly simplistic plugins. The more advanced approach is to provide a ""builder"" given a method with the following signature: [source,java] ---- public static Builder build() ---- It doesn't really matter what kind of class is returned from `build` so long as it follows a ""Builder"" pattern, where methods on that object return an instance of itself, so that builder methods can be chained together prior to calling a final `create` method as follows: [source,java] ---- public GremlinPlugin create() ---- Please see the link:http://tinkerpop.apache.org/javadocs/x.y.z/full/org/apache/tinkerpop/gremlin/jsr223/ImportGremlinPlugin.html for an example of what implementing a `Builder` might look like in this context. Note that the plugin provides a unique name for the plugin which follows a namespaced pattern as _namespace_._plugin-name_ (e.g. ""tinkerpop.hadoop"" - ""tinkerpop"" is the reserved namespace for TinkerPop maintained plugins). For plugins that will work with Gremlin Console, there is one other step to follow to ensure that the `GremlinPlugin` will work there. The console loads `GremlinPlugin` instances via link:http://docs.oracle.com/javase/8/docs/api/java/util/ServiceLoader.html[ServiceLoader] and therefore need a resource file added to the jar file where the plugin exists. Add a file called `org.apache.tinkerpop.gremlin.jsr223.GremlinPlugin` to `META-INF/services`. In the case of the TinkerGraph plugin above, that file will have this line in it: [source,java] ---- include::{basedir}/tinkergraph-gremlin/src/main/resources/META-INF/services/org.apache.tinkerpop.gremlin.jsr223.GremlinPlugin[] ---- Once the plugin is packaged, there are two ways to test it out: . Copy the jar and its dependencies to the Gremlin Console path and start it. It is preferrable that the plugin is copied to the `/ext/_plugin_name_` directory. . Start Gremlin Console and try the `:install` command: `:install com.company my-plugin 1.0.0`. In either case, once one of these two approaches is taken, the jars and their dependencies are available to the Console. The next step is to ""activate"" the plugin by doing `:plugin use my-plugin`, where ""my-plugin"" refers to the name of the plugin to activate. NOTE: When `:install` is used logging dependencies related to link:http://www.slf4j.org/[SLF4J] are filtered out so as not to introduce multiple logger bindings (which generates warning messages to the logs). A plugin can do much more than just import classes. One can expand the Gremlin language with new functions or steps, provide useful commands to make repetitive or complex tasks easier to execute, or do helpful integrations with other systems. The secret to doing so lies in the `PluginAcceptor`. As mentioned earlier, the `PluginAcceptor` provides access to the host of the plugin. It provides several important methods for doing so: . `addBinding` - These two function allow the plugin to inject whatever context it wants to the host. For example, doing `addBinding('x',1)` would place a variable of `x` with a value of 1 into the console at the time of the plugin load. . `eval` - Evaluates a script in the context of the host at the time of plugin startup. For example, doing `eval(""sum={x,y->x+y}"")` would create a `sum` function that would be available to the user of the Console after the load of the plugin. . `environment` - Provides context from the host environment. For the console, the environment will return a `Map` containing a reference to the `IO` stream and the `Groovysh` instance. These classes represent very low-level access to the underpinnings of the console. Access to `Groovysh` allows for advanced features such as registering new commands (e.g. like the `:plugin` or `:remote` commands). Plugins can also tie into the `:remote` and `:submit` commands. Recall that a `:remote` represents a different context within which Gremlin is executed, when issued with `:submit`. It is encouraged to use this integration point when possible, as opposed to registering new commands that can otherwise follow the `:remote` and `:submit` pattern. To expose this integration point as part of a plugin, implement the `RemoteAcceptor` interface: TIP: Be good to the users of plugins and prevent dependency conflicts. Maintaining a conflict free plugin is most easily done by using the link:http://maven.apache.org/enforcer/maven-enforcer-plugin/[Maven Enforcer Plugin]. TIP: Consider binding the plugin's minor version to the TinkerPop minor version so that it's easy for users to figure out plugin compatibility. Otherwise, clearly document a compatibility matrix for the plugin somewhere that users can find it. [source,java] ---- include::{basedir}/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/jsr223/console/RemoteAcceptor.java[] ---- The `RemoteAcceptor` can be bound to a `GremlinPlugin` by adding a `ConsoleCustomizer` implementation to the list of `Customizer` instances that are returned from the `GremlinPlugin`. The `ConsoleCustomizer` will only be executed when in use with the Gremlin Console plugin host. Simply instantiate and return a `RemoteAcceptor` in the `ConsoleCustomizer.getRemoteAcceptor(GremlinShellEnvironment)` method. Generally speaking, each call to `getRemoteAcceptor(GremlinShellEnvironment)` should produce a new instance of a `RemoteAcceptor`. ",16322,True,2529.940111595002,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package flashx.textLayout.elements { import flash.display.Shape; import flash.text.engine.ContentElement; import flash.text.engine.EastAsianJustifier; import flash.text.engine.GroupElement; import flash.text.engine.LineJustification; import flash.text.engine.SpaceJustifier; import flash.text.engine.TabAlignment; import flash.text.engine.TabStop; import flash.text.engine.TextBaseline; import flash.text.engine.TextBlock; import flash.text.engine.TextLine; import flash.text.engine.TextLineValidity; import flash.text.engine.TextRotation; import flash.utils.Dictionary; import flash.utils.getQualifiedClassName; import flashx.textLayout.compose.TextFlowLine; import flashx.textLayout.container.ContainerController; import flashx.textLayout.debug.Debugging; import flashx.textLayout.debug.assert; import flashx.textLayout.formats.BlockProgression; import flashx.textLayout.formats.Direction; import flashx.textLayout.formats.FormatValue; import flashx.textLayout.formats.ITextLayoutFormat; import flashx.textLayout.formats.JustificationRule; import flashx.textLayout.formats.LeadingModel; import flashx.textLayout.formats.LineBreak; import flashx.textLayout.formats.TabStopFormat; import flashx.textLayout.formats.TextAlign; import flashx.textLayout.formats.TextJustify; import flashx.textLayout.formats.TextLayoutFormat; import flashx.textLayout.property.Property; import flashx.textLayout.tlf_internal; import flashx.textLayout.utils.CharacterUtil; import flashx.textLayout.utils.LocaleUtil; use namespace tlf_internal; /** * The ParagraphElement class represents a paragraph in the text flow hierarchy. Its parent * is a ParagraphFormattedElement, and its children can include spans (SpanElement), images * (inLineGraphicElement), links (LinkElement) and TCY (Tatechuuyoko - ta-tae-chu-yo-ko) elements (TCYElement). The * paragraph text is stored in one or more SpanElement objects, which define ranges of text that share the same attributes. * A TCYElement object defines a small run of Japanese text that runs perpendicular to the line, as in a horizontal run of text in a * vertical line. A TCYElement can also contain multiple spans. * * @includeExample examples\\ParagraphElementExample.as -noswf * @includeExample examples\\ParagraphElementExample2.as -noswf * * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 * * @see InlineGraphicElement * @see LinkElement * @see SpanElement * @see TCYElement * @see TextFlow */ public final class ParagraphElement extends ParagraphFormattedElement { //private var _textBlock:TextBlock; private var _textBlockChildren:Dictionary; private var _terminatorSpan:SpanElement; private var _interactiveChildrenCount:int; /** Constructor - represents a paragraph in a text flow. * * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 */ public function ParagraphElement() { super(); _terminatorSpan = null; _interactiveChildrenCount = 0 ; _textBlockChildren = new Dictionary(); } tlf_internal function get interactiveChildrenCount():int { return _interactiveChildrenCount; } /** @private */ tlf_internal function createTextBlock():void { CONFIG::debug { assert(_textBlock == null,""createTextBlock called when there is already a textblock""); } computedFormat; // recreate the format BEFORE the _textBlock is created var tbs:Vector. = getTextBlocks(); //tbs.length = 0; var tableCount:int = 0; if(tbs.length == 0 && !(getChildAt(0) is TableElement) ) tbs.push(new TextBlock()); //getTextBlocks()[0] = new TextBlock(); CONFIG::debug { Debugging.traceFTECall(_textBlock,null,""new TextBlock()""); } for (var i:int = 0; i < numChildren; i++) { var child:FlowElement = getChildAt(i); if(child is TableElement) tableCount++; // tbs.push(new TextBlock()); else { //child.releaseContentElement(); //child.createContentElement(); } } while(tableCount >= tbs.length) tbs.push(new TextBlock()); for (i = 0; i < numChildren; i++) { child = getChildAt(i); child.createContentElement(); } tbs.length = tableCount + 1; var tb:TextBlock; for each(tb in tbs){ updateTextBlock(tb); } } private function updateTextBlockDict():void { var tbs:Vector. = getTextBlocks(); if(tbs.length == 0) return;//nothing to do var tbIdx:int = 0; var tb:TextBlock = tbs[tbIdx]; var items:Array = []; var child:FlowElement; for (var i:int = 0; i < numChildren; i++) { child = getChildAt(i); if(child is TableElement) { _textBlockChildren[tb] = items; tb = tbs[++tbIdx]; items = []; continue; } items.push(child); } _textBlockChildren[tb] = items; } private function removeTextBlock(tb:TextBlock):void { var tbs:Vector. = getTextBlocks(); if(tbs) { var idx:int = getTextBlocks().indexOf(tb); if(idx > -1) { tbs.splice(idx,1); delete _textBlockChildren[tb]; } } } private function releaseTextBlockInternal(tb:TextBlock):void { if (!tb) return; if (tb.firstLine) // A TextBlock may have no firstLine if it has previously been released. { for (var textLineTest:TextLine = tb.firstLine; textLineTest != null; textLineTest = textLineTest.nextLine) { if(textLineTest.numChildren != 0) { //if the number of adornments added does not match the number of children on the textLine //then a third party has added adornments. Don't recycle the line or the adornment will be //lost. var tfl:TextFlowLine = textLineTest.userData as TextFlowLine; if(tfl.adornCount != textLineTest.numChildren) return; } } CONFIG::debug { Debugging.traceFTECall(null,tb,""releaseLines"",tb.firstLine, tb.lastLine); } tb.releaseLines(tb.firstLine, tb.lastLine); } var items:Array = _textBlockChildren[tb]; var len:int = items.length; for (var i:int = 0; i < len; i++) { var child:FlowElement = items[i]; child.releaseContentElement(); } items.length = 0; tb.content = null; removeTextBlock(tb); } /** @private */ tlf_internal function releaseTextBlock(tb:TextBlock=null):void { updateTextBlockDict(); if(tb) { releaseTextBlockInternal(tb); return; } var tbs:Vector. = getTextBlocks(); for each(var textBlock:TextBlock in tbs) { releaseTextBlockInternal(textBlock); } //_textBlock = null; if (_computedFormat) _computedFormat = null; } private var _textBlocks:Vector.; tlf_internal function getTextBlocks():Vector. { if(_textBlocks == null) _textBlocks = new Vector.(); return _textBlocks; } /** TextBlock where the text of the paragraph is kept. @private */ tlf_internal function getTextBlock():TextBlock { if (!getTextBlocks().length) createTextBlock(); return getTextBlocks()[0]; } /** Last TextBlock where the text of the paragraph is kept. @private */ tlf_internal function getLastTextBlock():TextBlock { var tbs:Vector. = getTextBlocks(); if(!tbs.length) createTextBlock(); return tbs[tbs.length-1]; } /** Get TextBlock at specified position. @private */ tlf_internal function getTextBlockAtPosition(pos:int):TextBlock { var curPos:int = 0; var posShift:int = 0; var tables:Vector. = getTables(); if(!tables.length) return getTextBlock(); for each(var table:TableElement in tables) { if(table.getElementRelativeStart(this) < pos) posShift++; } var tbs:Vector. = getTextBlocks(); for each(var tb:TextBlock in tbs) { if(tb.content == null) return tb; curPos += tb.content.rawText.length; if(curPos + posShift > pos) { if(getTextBlockStart(tb) > pos) return null; return tb; } } return null; } tlf_internal function getTextBlockAbsoluteStart(tb:TextBlock):int { var start:int = getTextBlockStart(tb); if(start < 0) start = 0; return getAbsoluteStart() + start; } tlf_internal function getTextBlockStart(tb:TextBlock):int { var i:int; var curPos:int = 0; var tbs:Vector. = getTextBlocks(); if(tbs.length == 0) return -1; var tables:Vector. = getTables(); for each(var curTB:TextBlock in tbs) { for each(var table:TableElement in tables) { if(table.getElementRelativeStart(this) <= curPos) { curPos++; tables.splice(tables.indexOf(table),1); } } if(tb == curTB) return curPos; if(tb.content) curPos += curTB.content.rawText.length; } return -1; } private function getTables():Vector. { var tables:Vector. = new Vector.(); for (var i:int = 0; i < numChildren; i++) { var child:FlowElement = getChildAt(i); if(child is TableElement) tables.push(child as TableElement); } return tables; } /** TextBlock where the text of the paragraph is kept, or null if we currently don't have one. @private */ tlf_internal function peekTextBlock():TextBlock { return getTextBlocks().length == 0 ? null : getTextBlocks()[0]; } /** @private */ tlf_internal function releaseLineCreationData():void { CONFIG::debug { assert(Configuration.playerEnablesArgoFeatures,""bad call to releaseLineCreationData""); } var tbs:Vector. = getTextBlocks(); for each(var tb:TextBlock in tbs) { tb[""releaseLineCreationData""](); } } /** @private */ tlf_internal override function createContentAsGroup(pos:int=0):GroupElement { var tb:TextBlock = getTextBlockAtPosition(pos); if(!tb) tb = getTextBlockAtPosition(pos-1); var group:GroupElement = tb.content as GroupElement; if (!group) { var originalContent:ContentElement = tb.content; group = new GroupElement(); CONFIG::debug { Debugging.traceFTECall(group,null,""new GroupElement()""); } tb.content = group; CONFIG::debug { Debugging.traceFTEAssign(tb,""content"",group); } if (originalContent) { var gc:Vector. = new Vector.(); CONFIG::debug { Debugging.traceFTECall(gc,null,""new Vector.()"") } gc.push(originalContent); CONFIG::debug { Debugging.traceFTECall(null,gc,""push"",originalContent); } group.replaceElements(0,0,gc); CONFIG::debug { Debugging.traceFTECall(null,group,""replaceElements"",0,0,gc); } } // Now we've got to force damage the entire paragraph, because we restructured it in FTE. if (tb.firstLine && textLength) { var textFlow:TextFlow = getTextFlow(); if (textFlow) textFlow.damage(getAbsoluteStart(), textLength, TextLineValidity.INVALID, false); } } return group; } /** @private */ tlf_internal override function removeBlockElement(child:FlowElement, block:ContentElement):void { var tb:TextBlock = getTextBlockAtPosition(child.getElementRelativeStart(this)); if(!tb) tb = getTextBlock(); if(tb.content == null) return; var relativeStart:int = child.getElementRelativeStart(this); if (getChildrenInTextBlock(relativeStart).length < 2) { if (block is GroupElement) { // see insertBlockElement CONFIG::debug { assert(_textBlock.content != block,""removeBlockElement: bad call to removeBlockElement""); } CONFIG::debug { assert(_textBlock.content is GroupElement,""removeBlockElement: bad content""); } CONFIG::debug { assert(GroupElement(_textBlock.content).elementCount == 1,""removeBlockElement: bad element count""); } CONFIG::debug { assert(GroupElement(_textBlock.content).getElementAt(0) == block,""removeBlockElement: bad group content""); } GroupElement(tb.content).replaceElements(0,1,null); CONFIG::debug { Debugging.traceFTECall(null,_textBlock.content,""replaceElements"",0,1,null); } } tb.content = null; CONFIG::debug { Debugging.traceFTEAssign(_textBlock,""content"",null); } } else if(block.groupElement) { var idx:int = getChildIndexInBlock(child); var group:GroupElement = GroupElement(tb.content); CONFIG::debug { assert(group.elementCount == numChildren,""Mismatched group and elementCount""); } group.replaceElements(idx,idx+1,null); if(group.elementCount == 0) return; CONFIG::debug { Debugging.traceFTECall(null,group,""replaceElements"",idx,idx+1,null); } if (numChildren == 2) // its going to be one so ungroup { // ungroup - need to take it out first as inlinelements can only have one parent var elem:ContentElement = group.getElementAt(0); CONFIG::debug { Debugging.traceFTECall(elem,group,""getElementAt"",0); } if (!(elem is GroupElement)) { group.replaceElements(0,1,null); CONFIG::debug { Debugging.traceFTECall(null,group,""replaceElements"",0,1,null); } tb.content = elem; CONFIG::debug { Debugging.traceFTEAssign(tb,""content"",elem); } } } } else { //trace(""1""); //tb.content = null; } } /** @private */ tlf_internal override function hasBlockElement():Boolean { return getTextBlocks().length > 0; } /** @private */ override tlf_internal function createContentElement():void { createTextBlock(); } /** @private */ private function getChildrenInTextBlock(pos:int):Array { var retVal:Array = []; if(numChildren == 0) return retVal; if(numChildren == 1) { retVal.push(getChildAt(0)); return retVal } var chldrn:Array = mxmlChildren.slice(); for(var i:int = 0; i= pos) break; } retVal.push(chldrn[i]); } return retVal; } /** @private */ tlf_internal override function insertBlockElement(child:FlowElement, block:ContentElement):void { var relativeStart:int = child.getElementRelativeStart(this); var tb:TextBlock = getTextBlockAtPosition(relativeStart); if(!tb) tb = getTextBlockAtPosition(relativeStart-1); if(!tb) { child.releaseContentElement(); return; } if (getTextBlocks().length == 0) { child.releaseContentElement(); createTextBlock(); // does the whole tree return; } var gc:Vector.; // scratch var var group:GroupElement; // scratch if (getChildrenInTextBlock(relativeStart).length < 2) { if (block is GroupElement) { // this case forces the Group to be in a Group so that following FlowLeafElements aren't in a SubParagraphGroupElementBase's group gc = new Vector.(); CONFIG::debug { Debugging.traceFTECall(gc,null,""new Vector.()"") } gc.push(block); CONFIG::debug { Debugging.traceFTECall(null,gc,""push"",block); } group = new GroupElement(gc); CONFIG::debug { Debugging.traceFTECall(group,null,""new GroupElement"",gc); } tb.content = group; CONFIG::debug { Debugging.traceFTEAssign(_textBlock,""content"",group); } } else { if(block.groupElement) { block.groupElement.elementCount; } tb.content = block; CONFIG::debug { Debugging.traceFTEAssign(_textBlock,""content"",block); } } } else { group = createContentAsGroup(relativeStart); var idx:int = getChildIndexInBlock(child); gc = new Vector.(); CONFIG::debug { Debugging.traceFTECall(gc,null,""new Vector."") } gc.push(block); CONFIG::debug { Debugging.traceFTECall(null,gc,""push"",block); } // If elements in the middle (i.e. ones in the process of being added) were missed, the idx can be too high. // The missed ones will be inserted later. if(idx > group.elementCount) idx = group.elementCount; group.replaceElements(idx,idx,gc); CONFIG::debug { Debugging.traceFTECall(null,group,""replaceElements"",idx,idx,gc); } } } private function getChildIndexInBlock(elem:FlowElement):int { var relIdx:int = 0; for (var i:int = 0; i < numChildren; i++) { var child:FlowElement = getChildAt(i); if(child == elem) return relIdx; relIdx++; if(child is TableElement) relIdx = 0; } return -1; } /** @private */ override protected function get abstract():Boolean { return false; } /** @private */ tlf_internal override function get defaultTypeName():String { return ""p""; } tlf_internal function removeEmptyTerminator():void { if(numChildren == 1 && _terminatorSpan && _terminatorSpan.textLength == 1) { _terminatorSpan.removeParaTerminator(); super.replaceChildren(0, 1); this._terminatorSpan = null; } } /** @private */ public override function replaceChildren(beginChildIndex:int,endChildIndex:int,...rest):void { var applyParams:Array; do{ if(_terminatorSpan) { var termIdx:int = getChildIndex(_terminatorSpan); if(termIdx > 0 && termIdx < beginChildIndex && _terminatorSpan.textLength == 1) { super.replaceChildren(termIdx, termIdx+1); _terminatorSpan = null; if(beginChildIndex >= termIdx) { beginChildIndex--; if(rest.length == 0) // delete of terminator was already done. break; } if(endChildIndex >= termIdx && beginChildIndex != endChildIndex) endChildIndex--; } } // makes a measurable difference - rest.length zero and one are the common cases if (rest.length == 1) applyParams = [beginChildIndex, endChildIndex, rest[0]]; else { applyParams = [beginChildIndex, endChildIndex]; if (rest.length != 0) applyParams = applyParams.concat.apply(applyParams, rest); } super.replaceChildren.apply(this, applyParams); }while(false); ensureTerminatorAfterReplace(); // ensure correct text blocks createTextBlock(); } public override function splitAtPosition(relativePosition:int):FlowElement { // need to handle multiple TextBlocks // maybe not. It might be handled in replaceChildren(). return super.splitAtPosition(relativePosition); } /** @private */ tlf_internal function ensureTerminatorAfterReplace():void { //lose reference to terminator if it was removed or not a direct child. if(_terminatorSpan && _terminatorSpan.parent != this) { _terminatorSpan.removeParaTerminator(); _terminatorSpan = null; } var newLastLeaf:FlowLeafElement = getLastLeaf(); if (_terminatorSpan != newLastLeaf) { if(_terminatorSpan) _terminatorSpan.removeParaTerminator(); if (newLastLeaf && _terminatorSpan) { if(_terminatorSpan.textLength == 0) { var termIdx:int = getChildIndex(_terminatorSpan); super.replaceChildren(termIdx, termIdx+1); } this._terminatorSpan = null; } if(newLastLeaf) { if (newLastLeaf is SpanElement) { (newLastLeaf as SpanElement).addParaTerminator(); this._terminatorSpan = newLastLeaf as SpanElement; } else { var s:SpanElement = new SpanElement(); super.replaceChildren(numChildren,numChildren,s); s.format = newLastLeaf ? newLastLeaf.format : _terminatorSpan.format; s.addParaTerminator(); this._terminatorSpan = s; } } else _terminatorSpan = null; } //merge terminator span to previous if possible if(_terminatorSpan && _terminatorSpan.textLength == 1) { var prev:FlowLeafElement = _terminatorSpan.getPreviousLeaf(this); if(prev && prev.parent == this && prev is SpanElement) { _terminatorSpan.mergeToPreviousIfPossible(); } } } /** @private */ tlf_internal function updateTerminatorSpan(splitSpan:SpanElement,followingSpan:SpanElement):void { if (_terminatorSpan == splitSpan) _terminatorSpan = followingSpan; } [RichTextContent] /** @private NOTE: all FlowElement implementers and overrides of mxmlChildren must specify [RichTextContent] metadata */ public override function set mxmlChildren(array:Array):void { // remove all existing children replaceChildren(0,numChildren); for each (var child:Object in array) { if (child is FlowElement) { if ((child is SpanElement) || (child is SubParagraphGroupElementBase)) child.bindableElement = true; // Note: calling super.replaceChildren because we don't want to transfer para terminator each time super.replaceChildren(numChildren, numChildren, child as FlowElement); } else if (child is String) { var s:SpanElement = new SpanElement(); s.text = String(child); s.bindableElement = true; // Note: calling super.replaceChildren because we don't want to transfer para terminator each time super.replaceChildren(numChildren, numChildren, s); } else if (child != null) throw new TypeError(GlobalSettings.resourceStringFunction(""badMXMLChildrenArgument"",[ getQualifiedClassName(child) ])); } // Now ensure para terminator ensureTerminatorAfterReplace(); // recreate text blocks to handle possible TableElement changes createTextBlock(); } /** @private */ public override function getText(relativeStart:int=0, relativeEnd:int=-1, paragraphSeparator:String=""\\n""):String { // Optimization for getting text of the entire paragraph if (relativeStart == 0 && (relativeEnd == -1 || relativeEnd >= textLength-1) && getTextBlocks().length) { var tb:TextBlock; var tbs:Vector. = getTextBlocks(); var text:String = """"; for each(tb in tbs) { text = text + getTextInBlock(tb); } if(tb.content && tb.content.rawText) return text.substring(0, text.length - 1); return text; } return super.getText(relativeStart, relativeEnd, paragraphSeparator); } private function getTextInBlock(tb:TextBlock):String{ if(!tb.content || !tb.content.rawText) return """"; return tb.content.rawText; } /** Returns the paragraph that follows this one, or null if there are no more paragraphs. * * @return the next paragraph or null if there are no more paragraphs. * * @includeExample examples\\ParagraphElement_getNextParagraph.as -noswf * * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 * * @see #getPreviousParagraph() */ public function getNextParagraph():ParagraphElement { var nextLeaf:FlowLeafElement = getLastLeaf().getNextLeaf(); return nextLeaf ? nextLeaf.getParagraph() : null; } /** Returns the paragraph that precedes this one, or null, if this paragraph is the first one * in the TextFlow. * * @includeExample examples\\ParagraphElement_getPreviousParagraph.as -noswf * * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 * * @see #getNextParagraph() */ public function getPreviousParagraph():ParagraphElement { var previousLeaf:FlowLeafElement = getFirstLeaf().getPreviousLeaf(); return previousLeaf ? previousLeaf.getParagraph() : null; } /** * Scans backward from the supplied position to find the location * in the text of the previous atom and returns the index. The term atom refers to * both graphic elements and characters (including groups of combining characters), the * indivisible entities that make up a text line. * * @param relativePosition position in the text to start from, counting from 0 * @return index in the text of the previous cluster * * @includeExample examples\\ParagraphElement_findPreviousAtomBoundary.as -noswf * * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 * * @see flash.text.engine.TextLine */ public function findPreviousAtomBoundary(relativePosition:int):int { var tb:TextBlock = getTextBlockAtPosition(relativePosition); var tbStart:int = getTextBlockStart(tb); var textBlockPos:int = relativePosition - tbStart; var tl:TextLine = tb.getTextLineAtCharIndex(textBlockPos); if (ContainerController.tlf_internal::usesDiscretionaryHyphens && tl != null) { var currentAtomIndex:int = tl.getAtomIndexAtCharIndex(textBlockPos); //trace(""relpos"", relativePosition, ""atomIndex"", currentAtomIndex); var isRTL:Boolean = tl.getAtomBidiLevel(currentAtomIndex) == 1; if (isRTL) { var foo:int = tb.findPreviousAtomBoundary(textBlockPos); if (currentAtomIndex == 0) { // when cursor is left of all characters (end of line) // atomIndex is 0, so compensate if (tl.atomCount > 0) { while (--textBlockPos) { --relativePosition; if (tl.getAtomIndexAtCharIndex(textBlockPos) != currentAtomIndex) break; } } } else { while (--relativePosition && --textBlockPos) { if (tl.getAtomIndexAtCharIndex(textBlockPos) != currentAtomIndex) break; } } if (CharacterUtil.isLowSurrogate(getText(relativePosition, relativePosition + 1).charCodeAt(0))) { relativePosition--; textBlockPos--; } //trace(""previous"", relativePosition, foo); } else { if (currentAtomIndex == 0) { tl = tl.previousLine; if (!tl) return -1; // need this when 0x2028 line separator in use if (tl.textBlockBeginIndex + tl.rawTextLength == textBlockPos) return tl.textBlockBeginIndex + tl.rawTextLength - 1 + tbStart; return tl.textBlockBeginIndex + tl.rawTextLength + tbStart; } while (--relativePosition && --textBlockPos) { if (tl.getAtomIndexAtCharIndex(textBlockPos) < currentAtomIndex) break; } if (CharacterUtil.isLowSurrogate(getText(relativePosition, relativePosition + 1).charCodeAt(0))) { relativePosition--; textBlockPos--; } } return relativePosition; } var pos:int = tb.findPreviousAtomBoundary(textBlockPos); if(pos >= 0) pos += tbStart; //trace(""previous"", relativePosition, pos); return pos; } /** * Scans ahead from the supplied position to find the location * in the text of the next atom and returns the index. The term atom refers to * both graphic elements and characters (including groups of combining characters), the * indivisible entities that make up a text line. * * @param relativePosition position in the text to start from, counting from 0 * @return index in the text of the following atom * * @includeExample examples\\ParagraphElement_findNextAtomBoundary.as -noswf * * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 * * @see flash.text.engine.TextLine */ public function findNextAtomBoundary(relativePosition:int):int { var tb:TextBlock = getTextBlockAtPosition(relativePosition); var tbStart:int = getTextBlockStart(tb); var textBlockPos:int = relativePosition - tbStart; var tl:TextLine = tb.getTextLineAtCharIndex(textBlockPos); if (ContainerController.tlf_internal::usesDiscretionaryHyphens && tl != null) { var currentAtomIndex:int = tl.getAtomIndexAtCharIndex(textBlockPos); //trace(""relpos"", relativePosition, ""atomIndex"", currentAtomIndex); var isRTL:Boolean = tl.getAtomBidiLevel(currentAtomIndex) == 1; if (isRTL) { var foo:int = tb.findNextAtomBoundary(textBlockPos); if (currentAtomIndex == 0) { while (++textBlockPos) { ++relativePosition; if (tl.getAtomIndexAtCharIndex(textBlockPos) != currentAtomIndex) break; } } else { while (++textBlockPos) { ++relativePosition; if (tl.getAtomIndexAtCharIndex(textBlockPos) != currentAtomIndex) break; } } if (CharacterUtil.isHighSurrogate(getText(relativePosition, relativePosition + 1).charCodeAt(0))) { relativePosition++; textBlockPos++; } //trace(""next"", relativePosition, foo); } else { if (currentAtomIndex == tl.atomCount - 1) { tl = tl.nextLine; if (!tl) return -1; return tl.textBlockBeginIndex + tbStart; } while (++textBlockPos) { ++relativePosition; if (tl.getAtomIndexAtCharIndex(textBlockPos) > currentAtomIndex) break; } if (CharacterUtil.isHighSurrogate(getText(relativePosition, relativePosition + 1).charCodeAt(0))) { relativePosition++; textBlockPos++; } } return relativePosition; } var pos:int = tb.findNextAtomBoundary(textBlockPos); if(pos >= 0) pos += tbStart; //trace(""next"", relativePosition, pos); return pos; } /** @private */ public override function getCharAtPosition(relativePosition:int):String { var foundTB:TextBlock = getTextBlockAtPosition(relativePosition); if(!foundTB) return ""\\u0016""; var tables:Vector. = getTables(); var pos:int = relativePosition; for each(var table:TableElement in tables) { if(table.getElementRelativeStart(this) < pos) relativePosition--; } var tbs:Vector. = getTextBlocks(); for each(var tb:TextBlock in tbs) { if(foundTB == tb) break; if(tb) relativePosition -= tb.content.rawText.length; else relativePosition -= 1;this.getText() } return foundTB.content.rawText.charAt(relativePosition); } /** * Returns the index of the previous word boundary in the text. * *

Scans backward from the supplied position to find the previous position * in the text that starts or ends a word.

* * @param relativePosition position in the text to start from, counting from 0 * @return index in the text of the previous word boundary * * @includeExample examples\\ParagraphElement_findPreviousWordBoundary.as -noswf * * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 */ public function findPreviousWordBoundary(relativePosition:int):int { if (relativePosition == 0) return 0; var prevCharCode:int = getCharCodeAtPosition(relativePosition - 1); if (CharacterUtil.isWhitespace(prevCharCode)) { while (CharacterUtil.isWhitespace(prevCharCode) && ((relativePosition - 1) > 0)) { relativePosition--; prevCharCode = getCharCodeAtPosition(relativePosition - 1); } return relativePosition; } var block:TextBlock = getTextBlockAtPosition(relativePosition); if(block == null) block = getTextBlockAtPosition(--relativePosition); var pos:int = getTextBlockStart(block); if(pos < 0) pos = 0; return relativePosition == pos ? pos : pos + block.findPreviousWordBoundary(relativePosition - pos); } /** * Returns the index of the next word boundary in the text. * *

Scans ahead from the supplied position to find the next position * in the text that starts or ends a word.

* * @param relativePosition position in the text to start from, counting from 0 * @return index in the text of the next word boundary * * @includeExample examples\\ParagraphElement_findNextWordBoundary.as -noswf * * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 */ public function findNextWordBoundary(relativePosition:int):int { if (relativePosition == textLength) return textLength; var curCharCode:int = getCharCodeAtPosition(relativePosition); if (CharacterUtil.isWhitespace(curCharCode)) { while (CharacterUtil.isWhitespace(curCharCode) && relativePosition < (textLength - 1)) { relativePosition++; curCharCode = getCharCodeAtPosition(relativePosition); } return relativePosition; } var block:TextBlock = getTextBlockAtPosition(relativePosition); if(block == null) block = getTextBlockAtPosition(--relativePosition); var pos:int = getTextBlockStart(block); if(pos < 0) pos = 0; return pos + block.findNextWordBoundary(relativePosition - pos); } static private var _defaultTabStops:Vector.; static private const defaultTabWidth:int = 48; // matches default tabs setting in Argo static private const defaultTabCount:int = 20; static private function initializeDefaultTabStops():void { _defaultTabStops = new Vector.(defaultTabCount, true); for (var i:int = 0; i < defaultTabCount; ++i) _defaultTabStops[i] = new TabStop(TextAlign.START, defaultTabWidth * i); } private function updateTextBlock(textBlock:TextBlock=null):void { if(!textBlock) textBlock = getTextBlock(); // find the ancestor with a container and use its format for various settings var containerElement:ContainerFormattedElement = getAncestorWithContainer(); if (!containerElement) return; var containerElementFormat:ITextLayoutFormat = containerElement ? containerElement.computedFormat : TextLayoutFormat.defaultFormat; var lineJust:String; if (computedFormat.textAlign == TextAlign.JUSTIFY) { lineJust = (_computedFormat.textAlignLast == TextAlign.JUSTIFY) ? LineJustification.ALL_INCLUDING_LAST : LineJustification.ALL_BUT_LAST; // We don't allow explicit line breaks and justification together because it results in very strange (invisible) lines if (containerElementFormat.lineBreak == LineBreak.EXPLICIT) lineJust = LineJustification.UNJUSTIFIED; } else lineJust = LineJustification.UNJUSTIFIED; var makeJustRuleStyle:String = this.getEffectiveJustificationStyle(); var justRule:String = this.getEffectiveJustificationRule(); // set the justifier in the TextBlock if (justRule == JustificationRule.SPACE) { var spaceJustifier:SpaceJustifier = new SpaceJustifier(_computedFormat.locale,lineJust,false); spaceJustifier.letterSpacing = _computedFormat.textJustify == TextJustify.DISTRIBUTE ? true : false; if (Configuration.playerEnablesArgoFeatures) { // These three properties have to be set in the correct order so that consistency checks done // in the Player on set are never violated var newMinimumSpacing:Number = Property.toNumberIfPercent(_computedFormat.wordSpacing.minimumSpacing)/100; var newMaximumSpacing:Number = Property.toNumberIfPercent(_computedFormat.wordSpacing.maximumSpacing)/100; var newOptimumSpacing:Number = Property.toNumberIfPercent(_computedFormat.wordSpacing.optimumSpacing)/100; spaceJustifier[""minimumSpacing""] = Math.min(newMinimumSpacing, spaceJustifier[""minimumSpacing""]); spaceJustifier[""maximumSpacing""] = Math.max(newMaximumSpacing, spaceJustifier[""maximumSpacing""]); spaceJustifier[""optimumSpacing""] = newOptimumSpacing; spaceJustifier[""minimumSpacing""] = newMinimumSpacing; spaceJustifier[""maximumSpacing""] = newMaximumSpacing; } CONFIG::debug { Debugging.traceFTECall(spaceJustifier,null,""new SpaceJustifier"",_computedFormat.locale,lineJust,spaceJustifier.letterSpacing); } textBlock.textJustifier = spaceJustifier; CONFIG::debug { Debugging.traceFTEAssign(textBlock,""textJustifier"",spaceJustifier); } textBlock.baselineZero = getLeadingBasis(this.getEffectiveLeadingModel()); CONFIG::debug { Debugging.traceFTEAssign(textBlock,""baselineZero"",textBlock.baselineZero); } } else { var eastAsianJustifier:Object = new EastAsianJustifier(_computedFormat.locale,lineJust, makeJustRuleStyle); if( Configuration.versionIsAtLeast(10,3) && eastAsianJustifier.hasOwnProperty(""composeTrailingIdeographicSpaces"")){ eastAsianJustifier.composeTrailingIdeographicSpaces = true; } CONFIG::debug { Debugging.traceFTECall(eastAsianJustifier,null,""new EastAsianJustifier"",_computedFormat.locale,lineJust,makeJustRuleStyle); } textBlock.textJustifier = eastAsianJustifier as EastAsianJustifier; CONFIG::debug { Debugging.traceFTEAssign(textBlock,""textJustifier"",eastAsianJustifier); } textBlock.baselineZero = getLeadingBasis(this.getEffectiveLeadingModel()); CONFIG::debug { Debugging.traceFTEAssign(textBlock,""baselineZero"",textBlock.baselineZero); } } textBlock.bidiLevel = _computedFormat.direction == Direction.LTR ? 0 : 1; CONFIG::debug { Debugging.traceFTEAssign(textBlock,""bidiLevel"",textBlock.bidiLevel); } textBlock.lineRotation = containerElementFormat.blockProgression == BlockProgression.RL ? TextRotation.ROTATE_90 : TextRotation.ROTATE_0; CONFIG::debug { Debugging.traceFTEAssign(textBlock,""lineRotation"",textBlock.lineRotation); } if (_computedFormat.tabStops && _computedFormat.tabStops.length != 0) { //create a vector of TabStops and assign it to tabStops in textBlock var tabStops:Vector. = new Vector.(); CONFIG::debug { Debugging.traceFTECall(tabStops,null,""new Vector.()""); } for each(var tsa:TabStopFormat in _computedFormat.tabStops) { var token:String = tsa.decimalAlignmentToken==null ? """" : tsa.decimalAlignmentToken; var alignment:String = tsa.alignment==null ? TabAlignment.START : tsa.alignment; var tabStop:TabStop = new TabStop(alignment,Number(tsa.position),token); // this next line when uncommented works around bug 1912782 if (tsa.decimalAlignmentToken != null) var garbage:String = ""x"" + tabStop.decimalAlignmentToken; CONFIG::debug { Debugging.traceFTECall(tabStop,null,""new TabStop"",tabStop.alignment,tabStop.position,tabStop.decimalAlignmentToken); } tabStops.push(tabStop); CONFIG::debug { Debugging.traceFTECall(null,tabStops,""push"",tabStop); } } textBlock.tabStops = tabStops; CONFIG::debug { Debugging.traceFTEAssign(textBlock,""tabStops"",tabStops); } } else if (GlobalSettings.enableDefaultTabStops && !Configuration.playerEnablesArgoFeatures) { // Player versions prior to 10.1 do not set up any default tabStops. As a workaround, if enableDefaultTabs // is true, TLF will set up default tabStops in the case where there are no tabs defined. if (_defaultTabStops == null) initializeDefaultTabStops(); textBlock.tabStops = _defaultTabStops; CONFIG::debug { Debugging.traceFTEAssign(textBlock,""tabStops"",_defaultTabStops); } } else { textBlock.tabStops = null; CONFIG::debug { Debugging.traceFTEAssign(textBlock,""tabStops"",null); } } } /** @private */ public override function get computedFormat():ITextLayoutFormat { if (!_computedFormat) { super.computedFormat; var tbs:Vector. = getTextBlocks(); for each(var tb:TextBlock in tbs) updateTextBlock(tb); } return _computedFormat; } /** @private */ tlf_internal override function canOwnFlowElement(elem:FlowElement):Boolean { return elem is FlowLeafElement || elem is SubParagraphGroupElementBase || elem is TableElement; } /** @private */ tlf_internal override function normalizeRange(normalizeStart:uint,normalizeEnd:uint):void { var idx:int = findChildIndexAtPosition(normalizeStart); if (idx != -1 && idx < numChildren) { var child:FlowElement = getChildAt(idx); normalizeStart = normalizeStart-child.parentRelativeStart; CONFIG::debug { assert(normalizeStart >= 0, ""bad normalizeStart in normalizeRange""); } for (;;) { // watch out for changes in the length of the child var origChildEnd:int = child.parentRelativeStart+child.textLength; child.normalizeRange(normalizeStart,normalizeEnd-child.parentRelativeStart); var newChildEnd:int = child.parentRelativeStart+child.textLength; normalizeEnd += newChildEnd-origChildEnd; // adjust // no zero length children if (child.textLength == 0 && !child.bindableElement) replaceChildren(idx,idx+1); else if (child.mergeToPreviousIfPossible()) { var prevElement:FlowElement = this.getChildAt(idx-1); // possibly optimize the start to the length of prevelement before the merge prevElement.normalizeRange(0,prevElement.textLength); } else idx++; if (idx == numChildren) { // check if last child is an empty SubPargraphBlock and remove it if (idx != 0) { var lastChild:FlowElement = this.getChildAt(idx-1); if (lastChild is SubParagraphGroupElementBase && lastChild.textLength == 1 && !lastChild.bindableElement) replaceChildren(idx-1,idx); } break; } // next child child = getChildAt(idx); if (child.parentRelativeStart > normalizeEnd) break; normalizeStart = 0; // for the next child } } // empty paragraphs not allowed after normalize if (numChildren == 0 || textLength == 0) { var s:SpanElement = new SpanElement(); replaceChildren(0,0,s); s.normalizeRange(0,s.textLength); } } /** @private */ tlf_internal function getEffectiveLeadingModel():String { return computedFormat.leadingModel == LeadingModel.AUTO ? LocaleUtil.leadingModel(computedFormat.locale) : computedFormat.leadingModel; } /** @private */ tlf_internal function getEffectiveDominantBaseline():String { return computedFormat.dominantBaseline == FormatValue.AUTO ? LocaleUtil.dominantBaseline(computedFormat.locale) : computedFormat.dominantBaseline; } /** @private */ tlf_internal function getEffectiveJustificationRule():String { return computedFormat.justificationRule == FormatValue.AUTO ? LocaleUtil.justificationRule(computedFormat.locale) : computedFormat.justificationRule; } /** @private */ tlf_internal function getEffectiveJustificationStyle():String { return computedFormat.justificationStyle == FormatValue.AUTO ? LocaleUtil.justificationStyle(computedFormat.locale) : computedFormat.justificationStyle; } /** @private */ CONFIG::debug public override function debugCheckFlowElement(depth:int = 0, extraData:String = """"):int { var tb:TextBlock = getTextBlock(); var rslt:int = super.debugCheckFlowElement(depth,"" fte:""+getDebugIdentity(tb)+"" ""+extraData); // now check the character count and then the last character if (tb) { var contentLength:int = tb.content && tb.content.rawText ? tb.content.rawText.length : 0; rslt += assert(contentLength == textLength,""Bad paragraph length mode:""+textLength.toString()+"" _textBlock:"" + contentLength.toString()); var groupElement:GroupElement = tb.content as GroupElement; if (groupElement) assert(groupElement.elementCount == numChildren,""Mismatched group and elementCount""); else if (tb.content) assert(1 == numChildren,""Mismatched group and elementCount""); else assert(0 == numChildren,""Mismatched group and elementCount""); } rslt += assert(numChildren == 0 || textLength > 0,""Para must have at least one text char""); return rslt; } /** @private */ tlf_internal static function getLeadingBasis (leadingModel:String):String { switch (leadingModel) { default: CONFIG::debug { assert(false,""Unsupported parameter to ParagraphElement.getLeadingBasis""); } // In particular, AUTO is not supported by this method. Must be mapped to one of the above case LeadingModel.ASCENT_DESCENT_UP: case LeadingModel.APPROXIMATE_TEXT_FIELD: case LeadingModel.BOX: case LeadingModel.ROMAN_UP: return flash.text.engine.TextBaseline.ROMAN; case LeadingModel.IDEOGRAPHIC_TOP_UP: case LeadingModel.IDEOGRAPHIC_TOP_DOWN: return flash.text.engine.TextBaseline.IDEOGRAPHIC_TOP; case LeadingModel.IDEOGRAPHIC_CENTER_UP: case LeadingModel.IDEOGRAPHIC_CENTER_DOWN: return flash.text.engine.TextBaseline.IDEOGRAPHIC_CENTER; } } /** @private */ tlf_internal static function useUpLeadingDirection (leadingModel:String):Boolean { switch (leadingModel) { default: CONFIG::debug { assert(false,""Unsupported parameter to ParagraphElement.useUpLeadingDirection""); } // In particular, AUTO is not supported by this method. Must be mapped to one of the above case LeadingModel.ASCENT_DESCENT_UP: case LeadingModel.APPROXIMATE_TEXT_FIELD: case LeadingModel.BOX: case LeadingModel.ROMAN_UP: case LeadingModel.IDEOGRAPHIC_TOP_UP: case LeadingModel.IDEOGRAPHIC_CENTER_UP: return true; case LeadingModel.IDEOGRAPHIC_TOP_DOWN: case LeadingModel.IDEOGRAPHIC_CENTER_DOWN: return false; } } tlf_internal function incInteractiveChildrenCount() : void { ++ _interactiveChildrenCount ; } tlf_internal function decInteractiveChildrenCount() : void { -- _interactiveChildrenCount ; } tlf_internal function hasInteractiveChildren() : Boolean { return _interactiveChildrenCount != 0 ; } tlf_internal function get terminatorSpan():SpanElement { return _terminatorSpan; } } } ",12055,False,2328.792256433331,median "package{ import flash.display.*; import flash.geom.*; import flash.events.*; import flash.net.*; import flash.media.*; import flash.text.*; import flash.ui.ContextMenu; import flash.ui.ContextMenuItem; import flash.events.ContextMenuEvent; import flash.ui.Keyboard; import flash.ui.Mouse; import bigroom.input.KeyPoll; import flash.system.fscommand; import flash.system.Capabilities; import flash.utils.getTimer; import flash.utils.Timer; //import com.mesmotronic.ane.AndroidFullScreen; //import com.sociodox.theminer.TheMiner; //Profiler //Real value //[SWF(width = ""1136"", height = ""768"", frameRate = ""30"", backgroundColor = ""#000000"")] //Set the size and color of the Flash file //Big frame for big androids! //[SWF(width = ""3000"", height = ""2000"", frameRate = ""30"", backgroundColor = ""#000000"")] //Set the size and color of the Flash file [SWF(frameRate = ""30"", backgroundColor = ""#000000"")] //Set the size and color of the Flash file //iPad test //[SWF(width = ""1024"", height = ""768"", frameRate=""60"", backgroundColor = ""#000000"")] //Set the size and color of the Flash file //iPhone test //[SWF(width = ""480"", height = ""320"", frameRate=""30"", backgroundColor = ""#000000"")] //Set the size and color of the Flash file //[SWF(width = ""960"", height = ""640"", frameRate=""30"", backgroundColor = ""#000000"")] //Set the size and color of the Flash file public class Main extends Sprite { static public var BLOCK:Number = 0; static public var TRIGGER:Number = 1; static public var DAMAGE:Number = 2; include ""includes/logic.as""; include ""includes/input.as""; include ""includes/render.as""; public var GAMEMODE:int = 0; public var TITLEMODE:int = 1; public var CLICKTOSTART:int = 2; public var FOCUSMODE:int = 3; public var MAPMODE:int = 4; public var TELEPORTERMODE:int = 5; public var GAMECOMPLETE:int = 6; public var GAMECOMPLETE2:int = 7; public var EDITORMODE:int = 8; public var CONTROLTUTORIALMODE:int = 9; public function Main():void { if (stage) gameinit(); else addEventListener(Event.ADDED_TO_STAGE, gameinit); } private function gameinit(e:Event = null):void { removeEventListener(Event.ADDED_TO_STAGE, gameinit); // entry point var tempbmp:Bitmap; this.mouseEnabled = false; this.mouseChildren = false; //Ok: quick security check to make sure it doesn't get posted about if (sitelock()) { key = new KeyPoll(stage); //ANDROID SPECIFIC CODE HERE /* if (AndroidFullScreen.isSupported) { if (!AndroidFullScreen.immersiveMode()){ stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE; device.xres = flash.system.Capabilities.screenResolutionX; device.yres = flash.system.Capabilities.screenResolutionY; immersivemode = false; }else { device.xres = stage.stageWidth; device.yres = stage.stageHeight; immersivemode = true; } }else { */ stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE; device.xres = flash.system.Capabilities.screenResolutionX; device.yres = flash.system.Capabilities.screenResolutionY; immersivemode = false; //} /* if (immersivemode) { stage.addEventListener(Event.RESIZE, androidresize); } */ /* trace(""NOTE: REMEMBER TO FIX RESOLUTION SUPPORT BEFORE BUILDING""); device.xres = 1024; device.yres = 768; device.deviceresolution = device.IPAD; */ //Testing:Let's be an ipad /* device.xres = 1024; device.yres = 768; device.deviceresolution = device.IPAD; */ /* device.xres = 480; device.yres = 320; device.deviceresolution = device.IPHONE; */ /* device.xres = 960; device.yres = 640; device.deviceresolution = device.IPHONE; */ editor.init(); //Load in all the levels if (device.xres < device.yres) { //Switch them! t = device.yres; device.yres = device.xres; device.xres = t; } if (device.yres < 768) { device.deviceresolution = device.IPHONE; }else { device.deviceresolution = device.IPAD; } //Manually enable androids here! Mostly just changed buttons sizes // device.deviceresolution = device.ANDROID; //General game variables obj.init(); help.init(); /*obj.createblock(BLOCK,20,200,128,16); obj.createblock(BLOCK,130,170,128,16); obj.createblock(BLOCK,240,150,128,16); obj.createblock(BLOCK,240,20,128,16); obj.createblock(BLOCK,130,40,128,16); obj.createblock(BLOCK,20,60,128,16);*/ //Input key.definestickrange(device.xres / 2, 0, 6); SoundMixer.soundTransform = new SoundTransform(1); music.currentsong = -1; music.musicfade = 0;//no music, no amb music.initefchannels(); music.currentefchan = 0; music.nicechange = -1; music.numplays = 0; music.musicchan.push(new music_1()); // 0: Level Complete music.musicchan.push(new vmaintheme_hq()); // 1: VVVVVV Main Theme (Pushing Forward) music.musicchan.push(new vtempo_hq()); // 2: VVVVVV Tempo Theme (Positive Force) music.musicchan.push(new vpfa_hq()); // 3: Potential for Anything music.musicchan.push(new passionforexploring()); // 4: UU Brothers Instrumental music.musicchan.push(new souleye_intermission()); // 5: Jingle: Intermission music.musicchan.push(new presentingvvvvvv()); // 6: Jingle: Menu Loop music.musicchan.push(new music_2()); // 7: Jingle: Game Complete music.musicchan.push(new configmegamix_hq()); // 8: Config Megamix music.musicchan.push(new posreverse()); // 9: Tempo Theme, Reversed music.musicchan.push(new poppot()); // 10: Extra music.musicchan.push(new pipedream_hq()); // 11: Highscore music.musicchan.push(new pressurecooker_hq()); // 12: Pressure Cooker music.musicchan.push(new pacedenergy()); // NEW 13: Paced Energy music.musicchan.push(new piercingthesky()); // NEW 14: Piercing the Sky music.musicchan.push(new predestinedfateremix()); // NEW 15: Predestined Fate Remix music.efchan.push(new ef_0()); music.efchan.push(new ef_1()); music.efchan.push(new ef_2()); music.efchan.push(new ef_3()); music.efchan.push(new ef_4()); music.efchan.push(new ef_5()); music.efchan.push(new ef_6()); music.efchan.push(new ef_7()); music.efchan.push(new ef_8()); music.efchan.push(new ef_9()); music.efchan.push(new ef_10()); music.efchan.push(new ef_11()); music.efchan.push(new ef_12()); music.efchan.push(new ef_13()); music.efchan.push(new ef_14()); music.efchan.push(new ef_15()); music.efchan.push(new ef_16()); music.efchan.push(new ef_17()); music.efchan.push(new ef_18()); music.efchan.push(new ef_19()); music.efchan.push(new ef_20()); music.efchan.push(new ef_21()); music.efchan.push(new ef_22()); music.efchan.push(new ef_23()); music.efchan.push(new ef_24()); music.efchan.push(new ef_25()); music.efchan.push(new ef_26()); music.efchan.push(new ef_27()); /* Graphics Init */ //First we init the class and add its display list to the main display list dwgfx.buttonimg.push(new BitmapData(92, 30, true, 0x00000000)); dwgfx.buttonimg.push(new BitmapData(92, 30, true, 0x00000000)); dwgfx.buttonimg.push(new BitmapData(40, 40, true, 0x00000000)); dwgfx.buttonimg.push(new BitmapData(40, 40, true, 0x00000000)); tempbmp = new im_button_0(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addbutton(); tempbmp = new im_button_1(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addbutton(); tempbmp = new im_button_2(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addbutton(); tempbmp = new im_button_3(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addbutton(); tempbmp = new im_button_4(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addbutton(); tempbmp = new im_button_5(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addbutton(); tempbmp = new im_button_6(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addbutton(); tempbmp = new im_button_7(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addbutton(); tempbmp = new im_button_8(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addbutton(); tempbmp = new im_button_9(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addbutton(); tempbmp = new im_button_10(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addbutton(); tempbmp = new im_button_11(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addbutton(); tempbmp = new im_button_12(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addbutton(); dwgfx.init(); //We load all our graphics in: tempbmp = new im_tiles(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.maketilearray(); tempbmp = new im_tiles2(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.maketile2array(); tempbmp = new im_tiles3(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.maketile3array(); tempbmp = new im_sprites(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.makespritearray(); tempbmp = new im_flipsprites(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.makeflipspritearray(); tempbmp = new im_bfont(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.makebfont(); tempbmp = new im_bfontmask(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.makebfontmask(); tempbmp = new im_teleporter(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.maketelearray(); tempbmp = new im_entcolours(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.makeentcolourarray(); //Load in the images tempbmp = new im_image0(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addimage(); // 0 tempbmp = new im_image1(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addimage(); // 1 (this is the minimap!) tempbmp = new im_image2(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addimage(); // 2 tempbmp = new im_image3(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addimage(); // 3 tempbmp = new im_image4(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addimage(); // 4 tempbmp = new im_image5(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addimage(); // 5 tempbmp = new im_image6(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addimage(); // 6 tempbmp = new im_image7(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addimage(); // 7 tempbmp = new im_image8(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addimage(); // 8 tempbmp = new im_image9(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addimage(); // 9 tempbmp = new im_image10(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addimage(); // 10 tempbmp = new im_image1(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addimage(); // Minimap tempbmp = new im_image1(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addimage(); // Minimap tempbmp = new im_mobileimage1(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addmobileimage(); tempbmp = new im_mobileimage2(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addmobileimage(); tempbmp = new im_mobileimage3(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addmobileimage(); tempbmp = new im_mobileimage4(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addmobileimage(); tempbmp = new im_mobileimage5(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addmobileimage(); tempbmp = new im_mobileimage6(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addmobileimage(); tempbmp = new im_mobileimage7(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addmobileimage(); tempbmp = new im_mobileimage8(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addmobileimage(); tempbmp = new im_mobileimage9(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addmobileimage(); tempbmp = new im_imgplayerlevel0(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addplayerlevelimage(); tempbmp = new im_imgplayerlevel1(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addplayerlevelimage(); tempbmp = new im_imgplayerlevel2(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addplayerlevelimage(); tempbmp = new im_imgplayerlevel3(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addplayerlevelimage(); tempbmp = new im_imgplayerlevel4(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addplayerlevelimage(); tempbmp = new im_imgplayerlevel5(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addplayerlevelimage(); tempbmp = new im_imgplayerlevel6(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addplayerlevelimage(); tempbmp = new im_imgplayerlevel7(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addplayerlevelimage(); tempbmp = new im_imgplayerlevel8(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addplayerlevelimage(); tempbmp = new im_imgplayerlevel9(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addplayerlevelimage(); tempbmp = new im_imgplayerlevel10(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addplayerlevelimage(); tempbmp = new im_imgplayerlevel11(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addplayerlevelimage(); tempbmp = new im_imgplayerlevel12(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addplayerlevelimage(); tempbmp = new im_imgplayerlevel13(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addplayerlevelimage(); tempbmp = new im_imgplayerlevel14(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addplayerlevelimage(); tempbmp = new im_imgplayerlevel15(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addplayerlevelimage(); tempbmp = new im_imgplayerlevel16(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.addplayerlevelimage(); //Now that the graphics are loaded, init the background buffer dwgfx.buffer=new BitmapData(320,240,false,0x000000); stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; stage.quality = StageQuality.LOW; //EXACT FIT dwgfx.screensizemultiplier = device.yres / 240; dwgfx.screen.width = 320 * dwgfx.screensizemultiplier; dwgfx.screen.height = device.yres; dwgfx.screen.x = (device.xres / 2) - (320 * dwgfx.screensizemultiplier / 2); dwgfx.screen.y = 0; dwgfx.initbuttonpositions(); //PIXEL PERFECT /* dwgfx.screensizemultiplier = int(device.yres / 240); dwgfx.screen.width = 320 * dwgfx.screensizemultiplier; dwgfx.screen.height = 240 * dwgfx.screensizemultiplier; dwgfx.screenoffx = (device.xres / 2) - (320 * dwgfx.screensizemultiplier / 2); dwgfx.screenoffy = (device.yres / 2) - (240 * dwgfx.screensizemultiplier / 2); dwgfx.screen.x = dwgfx.screenoffx; dwgfx.screen.y = dwgfx.screenoffy; */ addChild(dwgfx); //stage.addChild(new TheMiner()); //Profiler //Iphone orientation fix var startOrientation:String = stage.orientation; if (startOrientation == StageOrientation.DEFAULT || startOrientation == StageOrientation.UPSIDE_DOWN){ //stage.setOrientation(StageOrientation.ROTATED_RIGHT); stage.setAspectRatio(StageAspectRatio.LANDSCAPE); }else{ stage.setOrientation(startOrientation); } stage.addEventListener(StageOrientationEvent.ORIENTATION_CHANGING, orientationChangeListener); game = new gameclass(dwgfx, map, obj, help, music); map.ypos = (700-29) * 8; map.bypos = map.ypos / 2; map.cameramode = 0; ///Test Start: //-- Comment this for real start /* gamestate = GAMEMODE; /*map.finalmode = true; //Enable final level mode //map.finalx = 41; map.finaly = 52; //Midpoint //map.finalx = 48; map.finaly = 52; //Just before the tower map.finalx = 46; map.finaly = 54; //Current //map.finalstretch = true; map.final_colormode = true; map.final_mapcol = 0; map.final_colorframe = 0; */ /* game.starttest(obj, music); obj.createentity(game, game.savex, game.savey, 0); //In this game, constant, never destroyed map.gotoroom(game.saverx, game.savery, dwgfx, game, obj, music); music.play(1); */ //game.crewstats[1] = true; //game.crewstats[2] = true; //game.crewstats[3] = true; //game.crewstats[4] = true; //game.crewstats[5] = true; //script.load(""intro""); //crew member test //obj.createentity(game, game.savex - 10, game.savey - 10, 14); //game.companion = 6; //different rules for different members //-- //Uncomment this if testing the final level /* map.finalmode = true; //Enable final level mode map.finalx = 46; map.finaly = 54; //Current //map.finalx = 41; map.finaly = 52; //Midpoint map.final_colormode = false; map.final_mapcol = 0; map.final_colorframe = 0; */ //And this if after the midpoint: /* map.finalx = 52; map.finaly = 53; //Current map.finalstretch = true; map.final_colormode = true; map.final_mapcol = 0; map.final_colorframe = 0; //map.background = 6; */ //-- Jumping right in /* game.gamestate = GAMEMODE; game.starttest(obj, music); //game.loadquick(map, obj, music); obj.createentity(game, game.savex, game.savey, 0); //In this game, constant, never destroyed map.gotoroom(game.saverx, game.savery, dwgfx, game, obj, music); music.play(4); //fscommand(""quit""); game.crewstats[1] = true; //game.crewstats[2] = true; game.crewstats[3] = true; game.crewstats[4] = true; //game.crewstats[5] = true; map.showtargets = true; map.showteleporters = true; //map.showtrinkets = true; //obj.flags[34] = 1; //obj.flags[20] = 1; //obj.flags[67] = 1; //Game complete for (i = 0; i < 20; i++) { obj.collect[i] = true; } game.trinkets = 19; obj.collect[18] = false; game.stat_trinkets = 20; //obj.altstates = 1; //initilise map info for (j = 0; j < 20; j++) { for (i = 0; i < 20; i++) { map.explored[i + (j * 20)] = 1; } } */ //obj.entities[obj.getplayer()].size = 13; //game.gamestate = 6; //game.intimetrail = true; game.timetrialcountdown = 0; //game.nodeathmode = true; //dwgfx.flipmode = true; //game.nocutscenes = true; //map.invincibility = true; //stage.frameRate = 24; //game.colourblindmode = true; //game.noflashingmode = true; //for intermission 2 test //game.lastsaved = 3; /* game.swnmode = true; game.swngame = 2; game.swndelay = 120; game.swntimer = 60 * 30; */ //script.load(""intermission_2""); //for intermission 1 test /* game.companion = 11; game.supercrewmate = true; game.scmprogress = 0; game.scmprogress = 10; game.lastsaved = 4; music.play(8); */ //game.sfpsmode = true; //Run at 60 FPS //stage.frameRate = 60; // doesn't work, it's a bit more complex than this - will have to do a double sized window instead... //dwgfx.flipmode = true; //Testing some unlock stuff /* game.unlock[9] = true; //Space Station Intro Time Trial game.unlock[10] = true; //Lab Time Trial game.unlock[11] = true; //Tower Time Trial game.unlock[12] = true; //Space Station 2 Time Trial game.unlock[13] = true; //Warp Zone Time Trial game.unlock[14] = true; //Final Level Time Trial game.unlock[17] = true; //No death mode game.unlock[18] = true; //Flip Mode */ //-- Normal start, with no fancy stuff! /* game.gamestate = CLICKTOSTART; dwgfx.createtextbox("" Click to Start "", 96, 107, 164, 164, 255); dwgfx.textboxcenter(); */ //No click to start any more! Instead go right to the menu //INIT GRAPHIC MODE HERE game.loadstats(map, dwgfx); //updategraphicsmode(game, dwgfx); game.gamestate = TITLEMODE; game.menustart = false; game.mainmenu = 0; /*if (game.quicksummary != """") { game.mainmenu = 2; } if (game.telesummary != """") { game.mainmenu = 1; }*/ //what the hell is that for /* game.gamestate = 6; game.menustart = true; map.ypos = (700-29) * 8; map.bypos = map.ypos / 2; map.cameramode = 0; */ //--Everything after this is screen recording //ok, screenrecording here //don't record anything (comment both next parts) game.recording = 0; if(game.recording==1){ trace(""warning! recording input!""); }else if(game.recording==2){ trace(""playing back input!""); game.recordstring = ""blahblahblah""; help.toclipboard(game.recordstring); game.initplayback(); game.playbackpos = 5; game.savex = game.playback[0]; game.savey = game.playback[1]; game.saverx = game.playback[2]; game.savery = game.playback[3]; game.savegc = game.playback[4]; game.savedir = 1; } //addEventListener(Event.ENTER_FRAME, mainloop); // start the tick-timer, which updates roughly every 4 milliseconds _timer.addEventListener(TimerEvent.TIMER, mainloop); _timer.start(); }else { dwgfx.init(); addChild(dwgfx); //We load the font in: tempbmp = new im_bfont(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.makebfont(); tempbmp = new im_bfontmask(); dwgfx.buffer = tempbmp.bitmapData; dwgfx.makebfontmask(); //Now that the graphics are loaded, init the background buffer dwgfx.buffer = new BitmapData(320, 240, false, 0x000000); addEventListener(Event.ENTER_FRAME, lockedloop); } } public function visit_distractionware(e:Event):void{ var distractionware_link:URLRequest = new URLRequest( ""http://www.distractionware.com"" ); navigateToURL( distractionware_link, ""_blank"" ); } public function visit_sponsor(e:Event):void{ var sponsor_link:URLRequest = new URLRequest( ""http://www.kongregate.com/?gamereferral=dontlookback"" ); navigateToURL( sponsor_link, ""_blank"" ); } public function visit_sponsor_logo():void{ var sponsor_link:URLRequest = new URLRequest( ""http://www.kongregate.com/?gamereferral=dontlookback"" ); navigateToURL( sponsor_link, ""_blank"" ); } /* public function androidresize(e:Event):void { if (immersivemode) { device.xres = stage.stageWidth; device.yres = stage.stageHeight; }else{ device.xres = flash.system.Capabilities.screenResolutionX; device.yres = flash.system.Capabilities.screenResolutionY; } if (device.xres < device.yres) { //Switch them! t = device.yres; device.yres = device.xres; device.xres = t; } key.definestickrange(device.xres / 2, 0, 6); dwgfx.screensizemultiplier = device.yres / 240; dwgfx.screen.width = 320 * dwgfx.screensizemultiplier; dwgfx.screen.height = device.yres; dwgfx.screen.x = (device.xres / 2) - (320 * dwgfx.screensizemultiplier / 2); dwgfx.screen.y = 0; dwgfx.initbuttonpositions(); } */ public function orientationChangeListener(e:StageOrientationEvent):void{ if (e.afterOrientation == StageOrientation.DEFAULT || e.afterOrientation == StageOrientation.UPSIDE_DOWN) { e.preventDefault(); } } public function lockedloop(e:Event):void { dwgfx.backbuffer.lock(); dwgfx.bprint(5, 110, ""Sorry! This game can only be"", 196-help.glow, 196-help.glow, 255-help.glow, true); dwgfx.bprint(5, 120, ""played on thelettervsixtim.es"", 196-help.glow, 196-help.glow, 255-help.glow, true); dwgfx.render(); dwgfx.backbuffer.unlock(); help.updateglow(); } public function setstage(w:int, h:int):void { //stage.stageWidth = w; //stage.stageHeight = h; } public function sitelock():Boolean { //No preloader for Kong version var currUrl:String = stage.loaderInfo.url.toLowerCase(); //chat.kongregate.com if ((currUrl.indexOf(""ile:///"") <= 0) || (currUrl.indexOf(""http"") == 0)){ //if ((currUrl.indexOf(""distractionware.com/games"") <= 0) && (currUrl.indexOf(""thelettervsixtim.es/secretarea"") <= 0)){ return true; //return false; }else{ return true; } } public function input():void { if (!game.infocus) { }else { switch(game.gamestate){ case TITLEMODE: titleinput(key, dwgfx, map, game, obj, help, music); break; case GAMEMODE: if (map.towermode) { if(game.recording==1){ recordinput(key, dwgfx, game, map, obj, help, music); }else { gameinput(key, dwgfx, game, map, obj, help, music); } }else{ if (game.recording == 1) { recordinput(key, dwgfx, game, map, obj, help, music); }else { if (script.running) { script.run(key, dwgfx, game, map, obj, help, music); } gameinput(key, dwgfx, game, map, obj, help, music); } } break; case CONTROLTUTORIALMODE: controltutorialinput(key, dwgfx, game, map, obj, help, music); break; case MAPMODE: if (game.recording == 1) { //recordinput(key, dwgfx, game, map, obj, help, music); //will implement this later if it's actually needed }else{ mapinput(key, dwgfx, game, map, obj, help, music); } break; case TELEPORTERMODE: if (game.recording == 1) { recordinput(key, dwgfx, game, map, obj, help, music); }else { if(game.useteleporter) { teleporterinput(key, dwgfx, game, map, obj, help, music); }else { if (script.running) { script.run(key, dwgfx, game, map, obj, help, music); } gameinput(key, dwgfx, game, map, obj, help, music); } } break; case GAMECOMPLETE: gamecompleteinput(key, dwgfx, game, map, obj, help, music); break; case GAMECOMPLETE2: gamecompleteinput2(key, dwgfx, game, map, obj, help, music); break; case CLICKTOSTART: if (key.click) { dwgfx.textboxremove(); } break; } //Mute button if (key.isDown(77) && game.mutebutton<=0) { game.mutebutton = 8; if (game.muted) { game.muted = false; }else { game.muted = true;} } if(game.mutebutton>0) game.mutebutton--; } //Stupid event listeners! if (key.hasclicked) key.click = false; } public function logic():void { if (!game.infocus) { if (game.globalsound > 0) { game.globalsound = 0; SoundMixer.soundTransform = new SoundTransform(0); } music.processmusic(); help.updateglow(); }else { switch(game.gamestate){ case TITLEMODE: titlelogic(key, dwgfx, game, obj, help, music); break; case GAMEMODE: if (map.towermode) { towerlogic(key, dwgfx, game, map, obj, help, music); }else{ gamelogic(key, dwgfx, game, map, obj, help, music); } break; case MAPMODE: maplogic(key, dwgfx, game, map, obj, help, music); break; case CONTROLTUTORIALMODE: controltutoriallogic(key, dwgfx, game, map, obj, help, music); break; case TELEPORTERMODE: maplogic(key, dwgfx, game, map, obj, help, music); break; case GAMECOMPLETE: gamecompletelogic(key, dwgfx, game, map, obj, help, music); break; case GAMECOMPLETE2: gamecompletelogic2(key, dwgfx, game, map, obj, help, music); break; case CLICKTOSTART: help.updateglow(); if (dwgfx.ntextbox == 0) { //music.play(6); map.ypos = (700-29) * 8; map.bypos = map.ypos / 2; map.cameramode = 0; game.gamestate = TITLEMODE; } break; } if (game.platform.wakeupcall > 0) { game.platform.wakeupcall--; if (game.platform.wakeupcall == 0) { if(immersivemode){ //AndroidFullScreen.immersiveMode(); } } } music.processmusic(); dwgfx.processfade(); game.gameclock(); dwgfx.trinketcolset = false; //Reset this in every frame, used for a new standard random colour each frame if (game.savemystats) { game.savemystats = false; game.savestats(map, dwgfx); } if (game.muted) { if (game.globalsound == 1) { game.globalsound = 0; SoundMixer.soundTransform = new SoundTransform(0); } } if (!game.muted && game.globalsound == 0) { game.globalsound = 1; SoundMixer.soundTransform = new SoundTransform(1); } } } public function render():void { if (!game.infocus) { dwgfx.backbuffer.lock(); /* dwgfx.bprint(5, 110, ""Game paused"", 196 - help.glow, 255 - help.glow, 196 - help.glow, true); dwgfx.bprint(5, 120, ""[click to resume]"", 196 - help.glow, 255 - help.glow, 196 - help.glow, true); dwgfx.bprint(5, 230, ""Press M to mute in game"", 164 - help.glow, 196 - help.glow, 164 - help.glow, true); */ dwgfx.render(); dwgfx.backbuffer.unlock(); }else { switch(game.gamestate){ case TITLEMODE: titlerender(key, dwgfx, map, game, obj, help); break; case GAMEMODE: if (map.towermode) { towerrender(key, dwgfx, game, map, obj, help); }else{ gamerender(key, dwgfx, game, map, obj, help); } break; case CONTROLTUTORIALMODE: controltutorialrender(key, dwgfx, game, map, obj, help); break; case MAPMODE: maprender(key, dwgfx, game, map, obj, help); break; case TELEPORTERMODE: teleporterrender(key, dwgfx, game, map, obj, help); break; case GAMECOMPLETE: gamecompleterender(key, dwgfx, game, obj, help); break; case GAMECOMPLETE2: gamecompleterender2(key, dwgfx, game, obj, help); break; case CLICKTOSTART: dwgfx.backbuffer.lock(); //dwgfx.bprint(5, 115, ""[Click to start]"", 196 - help.glow, 196 - help.glow, 255 - help.glow, true); dwgfx.drawgui(help); dwgfx.render(); dwgfx.backbuffer.unlock(); break; } } } public function mainloop(e:TimerEvent):void { _current = getTimer(); if (_last < 0) _last = _current; _delta += _current - _last; _last = _current; if (_delta >= _rate){ _delta %= _skip; while (_delta >= _rate){ _delta -= _rate; input(); logic(); if (key.hasclicked) key.click = false; } render(); e.updateAfterEvent(); } } public function setzoom(t:int, dwgfx:dwgraphicsclass):void { /* switch(t) { case 1: dwgfx.screen.width = 320; dwgfx.screen.height = 240; dwgfx.screen.x = (640 - 320) / 2; dwgfx.screen.y = (480 - 240) / 2; break; case 2: dwgfx.screen.width = 640; dwgfx.screen.height = 480; dwgfx.screen.x = 0; dwgfx.screen.y = 0; break; case 3: dwgfx.screen.width = 960; dwgfx.screen.height = 720; dwgfx.screen.x = (640 - 960) / 2; dwgfx.screen.y = (480 - 720) / 2; break; case 4: dwgfx.screen.width = 1280; dwgfx.screen.height = 960; dwgfx.screen.x = (640 - 1280) / 2; dwgfx.screen.y = (480 - 960) / 2; break; } */ } public function updategraphicsmode(game:gameclass, dwgfx:dwgraphicsclass):void { /* swfStage = stage; if (game.advanced_mode) { //advanced graphics mode //Screen Smooting dwgfx.screen.smoothing = game.advanced_smoothing; //Scaling if(game.advanced_scaling==0){ swfStage.scaleMode = StageScaleMode.SHOW_ALL; setzoom(2, dwgfx); }else{ swfStage.scaleMode = StageScaleMode.NO_SCALE; //Turn Scaling off setzoom(game.advanced_scaling, dwgfx); } stage.fullScreenSourceRect = null; //Fullscreen if (game.fullscreen) { stage.displayState = StageDisplayState.FULL_SCREEN; Mouse.hide(); }else { stage.displayState = StageDisplayState.NORMAL; Mouse.show(); } }else{ swfStage.scaleMode = StageScaleMode.SHOW_ALL; if (game.fullscreen) { dwgfx.screen.smoothing = true; stage.fullScreenSourceRect = new Rectangle(0, 0, 640, 480); stage.displayState = StageDisplayState.FULL_SCREEN; Mouse.hide(); }else { dwgfx.screen.smoothing = false; stage.displayState = StageDisplayState.NORMAL; Mouse.show(); } } */ } // Timer information (a shout out to ChevyRay for the implementation) public static const TARGET_FPS:Number = 30; // the fixed-FPS we want the game to run at private var _rate:Number = 1000 / TARGET_FPS; // how long (in seconds) each frame is private var _skip:Number = _rate * 10; // this tells us to allow a maximum of 10 frame skips private var _last:Number = -1; private var _current:Number = 0; private var _delta:Number = 0; private var _timer:Timer = new Timer(4); public var dwgfx:dwgraphicsclass = new dwgraphicsclass(); public var music:musicclass = new musicclass(); public var help:helpclass = new helpclass(); public var map:mapclass = new mapclass(); public var game:gameclass; public var obj:entityclass = new entityclass(); public var key:KeyPoll; public var script:scriptclass = new scriptclass(); public var slogo:MovieClip; public var logoposition:Matrix; public var pixel:uint; public var pixel2:uint; public var pi:uint, pj:uint; public var i:int, j:int, k:int, temp:int, tempx:int, tempy:int, tempstring:String; public var tr:int, tg:int, tb:int, t:int; public var tvel:Number; public var swfStage:Stage; public var immersivemode:Boolean; //Embedded resources: //Graphics [Embed(source = '../data/graphics/tiles.png')] private var im_tiles:Class; [Embed(source = '../data/graphics/tiles2.png')] private var im_tiles2:Class; [Embed(source = '../data/graphics/tiles3.png')] private var im_tiles3:Class; [Embed(source = '../data/graphics/sprites.png')] private var im_sprites:Class; [Embed(source = '../data/graphics/flipsprites.png')] private var im_flipsprites:Class; [Embed(source = '../data/graphics/font.png')] private var im_bfont:Class; [Embed(source = '../data/graphics/fontmask.png')] private var im_bfontmask:Class; [Embed(source = '../data/graphics/teleporter.png')] private var im_teleporter:Class; [Embed(source = '../data/graphics/entcolours.png')] private var im_entcolours:Class; [Embed(source = '../data/graphics/levelcomplete.png')] private var im_image0:Class; [Embed(source = '../data/graphics/minimap.png')] private var im_image1:Class; [Embed(source = '../data/graphics/covered.png')] private var im_image2:Class; [Embed(source = '../data/graphics/elephant.png')] private var im_image3:Class; [Embed(source = '../data/graphics/gamecomplete.png')] private var im_image4:Class; [Embed(source = '../data/graphics/fliplevelcomplete.png')] private var im_image5:Class; [Embed(source = '../data/graphics/flipgamecomplete.png')] private var im_image6:Class; [Embed(source = '../data/graphics/site.png')] private var im_image7:Class; [Embed(source = '../data/graphics/site2.png')] private var im_image8:Class; [Embed(source = '../data/graphics/site3.png')] private var im_image9:Class; [Embed(source = '../data/graphics/ending.png')] private var im_image10:Class; [Embed(source = '../data/graphics/controls/touchscreen.png')] private var im_mobileimage1:Class; [Embed(source = '../data/graphics/controls/lefthand_off.png')] private var im_mobileimage2:Class; [Embed(source = '../data/graphics/controls/lefthand_near.png')] private var im_mobileimage3:Class; [Embed(source = '../data/graphics/controls/lefthand_far.png')] private var im_mobileimage4:Class; [Embed(source = '../data/graphics/controls/righthand_off.png')] private var im_mobileimage5:Class; [Embed(source = '../data/graphics/controls/righthand_near.png')] private var im_mobileimage6:Class; [Embed(source = '../data/graphics/controls/righthand_far.png')] private var im_mobileimage7:Class; [Embed(source = '../data/graphics/controls/arrowleft.png')] private var im_mobileimage8:Class; [Embed(source = '../data/graphics/controls/arrowright.png')] private var im_mobileimage9:Class; //Playerlevel images [Embed(source = '../data/graphics/playerlevels/playerlevel_0.png')] private var im_imgplayerlevel0:Class; [Embed(source = '../data/graphics/playerlevels/playerlevel_1.png')] private var im_imgplayerlevel1:Class; [Embed(source = '../data/graphics/playerlevels/playerlevel_2.png')] private var im_imgplayerlevel2:Class; [Embed(source = '../data/graphics/playerlevels/playerlevel_3.png')] private var im_imgplayerlevel3:Class; [Embed(source = '../data/graphics/playerlevels/playerlevel_4.png')] private var im_imgplayerlevel4:Class; [Embed(source = '../data/graphics/playerlevels/playerlevel_5.png')] private var im_imgplayerlevel5:Class; [Embed(source = '../data/graphics/playerlevels/playerlevel_6.png')] private var im_imgplayerlevel6:Class; [Embed(source = '../data/graphics/playerlevels/playerlevel_7.png')] private var im_imgplayerlevel7:Class; [Embed(source = '../data/graphics/playerlevels/playerlevel_8.png')] private var im_imgplayerlevel8:Class; [Embed(source = '../data/graphics/playerlevels/playerlevel_9.png')] private var im_imgplayerlevel9:Class; [Embed(source = '../data/graphics/playerlevels/playerlevel_10.png')] private var im_imgplayerlevel10:Class; [Embed(source = '../data/graphics/playerlevels/playerlevel_11.png')] private var im_imgplayerlevel11:Class; [Embed(source = '../data/graphics/playerlevels/playerlevel_12.png')] private var im_imgplayerlevel12:Class; [Embed(source = '../data/graphics/playerlevels/playerlevel_13.png')] private var im_imgplayerlevel13:Class; [Embed(source = '../data/graphics/playerlevels/playerlevel_14.png')] private var im_imgplayerlevel14:Class; [Embed(source = '../data/graphics/playerlevels/playerlevel_15.png')] private var im_imgplayerlevel15:Class; [Embed(source = '../data/graphics/playerlevels/playerlevel_16.png')] private var im_imgplayerlevel16:Class; //iOS Buttons [Embed(source = '../data/graphics/mobilebuttons/map.png')] private var im_button_0:Class; [Embed(source = '../data/graphics/mobilebuttons/back.png')] private var im_button_1:Class; [Embed(source = '../data/graphics/mobilebuttons/talk_1.png')] private var im_button_2:Class; [Embed(source = '../data/graphics/mobilebuttons/talk_2.png')] private var im_button_3:Class; [Embed(source = '../data/graphics/mobilebuttons/use_1.png')] private var im_button_4:Class; [Embed(source = '../data/graphics/mobilebuttons/use_2.png')] private var im_button_5:Class; [Embed(source = '../data/graphics/mobilebuttons/teleport_1.png')] private var im_button_6:Class; [Embed(source = '../data/graphics/mobilebuttons/teleport_2.png')] private var im_button_7:Class; [Embed(source = '../data/graphics/mobilebuttons/controls_1.png')] private var im_button_8:Class; [Embed(source = '../data/graphics/mobilebuttons/controls_2.png')] private var im_button_9:Class; [Embed(source = '../data/graphics/mobilebuttons/gamecenter.png')] private var im_button_10:Class; [Embed(source = '../data/graphics/mobilebuttons/button_left.png')] private var im_button_11:Class; [Embed(source = '../data/graphics/mobilebuttons/button_right.png')] private var im_button_12:Class; //Music [Embed(source = '../data/music/levelcomplete.mp3')] private var music_1:Class; [Embed(source = '../data/music/endgame.mp3')] private var music_2:Class; //Sound effects [Embed(source = '../data/sounds/jump.mp3')] private var ef_0:Class; [Embed(source = '../data/sounds/jump2.mp3')] private var ef_1:Class; [Embed(source = '../data/sounds/hurt.mp3')] private var ef_2:Class; [Embed(source = '../data/sounds/souleyeminijingle.mp3')] private var ef_3:Class; [Embed(source = '../data/sounds/coin.mp3')] private var ef_4:Class; [Embed(source = '../data/sounds/save.mp3')] private var ef_5:Class; [Embed(source = '../data/sounds/crumble.mp3')] private var ef_6:Class; [Embed(source = '../data/sounds/vanish.mp3')] private var ef_7:Class; [Embed(source = '../data/sounds/blip.mp3')] private var ef_8:Class; [Embed(source = '../data/sounds/preteleport.mp3')] private var ef_9:Class; [Embed(source = '../data/sounds/teleport.mp3')] private var ef_10:Class; [Embed(source = '../data/sounds/crew1.mp3')] private var ef_11:Class; [Embed(source = '../data/sounds/crew2.mp3')] private var ef_12:Class; [Embed(source = '../data/sounds/crew3.mp3')] private var ef_13:Class; [Embed(source = '../data/sounds/crew4.mp3')] private var ef_14:Class; [Embed(source = '../data/sounds/crew5.mp3')] private var ef_15:Class; [Embed(source = '../data/sounds/crew6.mp3')] private var ef_16:Class; [Embed(source = '../data/sounds/terminal.mp3')] private var ef_17:Class; [Embed(source = '../data/sounds/gamesaved.mp3')] private var ef_18:Class; [Embed(source = '../data/sounds/crashing.mp3')] private var ef_19:Class; [Embed(source = '../data/sounds/blip2.mp3')] private var ef_20:Class; [Embed(source = '../data/sounds/countdown.mp3')] private var ef_21:Class; [Embed(source = '../data/sounds/go.mp3')] private var ef_22:Class; [Embed(source = '../data/sounds/crash.mp3')] private var ef_23:Class; [Embed(source = '../data/sounds/combine.mp3')] private var ef_24:Class; [Embed(source = '../data/sounds/newrecord.mp3')] private var ef_25:Class; [Embed(source = '../data/sounds/trophy.mp3')] private var ef_26:Class; [Embed(source = '../data/sounds/rescue.mp3')] private var ef_27:Class; } }",12535,False,2082.7323298555402,median "/* Feathers Copyright 2012-2019 Bowler Hat LLC. All Rights Reserved. This program is free software. You can redistribute and/or modify it in accordance with the terms of the accompanying license agreement. */ package feathers.layout { import feathers.core.IValidating; import flash.errors.IllegalOperationError; import flash.geom.Point; import flash.ui.Keyboard; import starling.display.DisplayObject; import starling.events.Event; /** * Dispatched when a property of the layout changes, indicating that a * redraw is probably needed. * *

The properties of the event object have the following values:

* * * * * * *
PropertyValue
bubblesfalse
currentTargetThe Object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
datanull
targetThe Object that dispatched the event; * it is not always the Object listening for the event. Use the * currentTarget property to always access the Object * listening for the event.
* * @eventType starling.events.Event.CHANGE */ [Event(name=""change"",type=""starling.events.Event"")] /** * Positions items of different dimensions from left to right in multiple * rows. When the width of a row reaches the width of the container, a new * row will be started. Constrained to the suggested width, the flow layout * will change in height as the number of items increases or decreases. * * @see ../../../help/flow-layout.html How to use FlowLayout with Feathers containers * * @productversion Feathers 2.2.0 */ public class FlowLayout extends BaseVariableVirtualLayout implements IVariableVirtualLayout, IDragDropLayout { /** * Constructor. */ public function FlowLayout() { super(); this._hasVariableItemDimensions = true; } /** * @private */ protected var _rowItems:Vector. = new []; /** * Quickly sets both horizontalGap and verticalGap * to the same value. The gap getter always returns the * value of horizontalGap, but the value of * verticalGap may be different. * * @default 0 * * @see #horizontalGap * @see #verticalGap */ public function get gap():Number { return this._horizontalGap; } /** * @private */ public function set gap(value:Number):void { this.horizontalGap = value; this.verticalGap = value; } /** * @private */ protected var _horizontalGap:Number = 0; /** * The horizontal space, in pixels, between items. * * @default 0 */ public function get horizontalGap():Number { return this._horizontalGap; } /** * @private */ public function set horizontalGap(value:Number):void { if(this._horizontalGap == value) { return; } this._horizontalGap = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _verticalGap:Number = 0; /** * The vertical space, in pixels, between items. * * @default 0 */ public function get verticalGap():Number { return this._verticalGap; } /** * @private */ public function set verticalGap(value:Number):void { if(this._verticalGap == value) { return; } this._verticalGap = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _firstHorizontalGap:Number = NaN; /** * The space, in pixels, between the first and second items. If the * value of firstHorizontalGap is NaN, the * value of the horizontalGap property will be used * instead. * * @default NaN * * @see #gap */ public function get firstHorizontalGap():Number { return this._firstHorizontalGap; } /** * @private */ public function set firstHorizontalGap(value:Number):void { if(this._firstHorizontalGap == value) { return; } this._firstHorizontalGap = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _lastHorizontalGap:Number = NaN; /** * The space, in pixels, between the last and second to last items. If * the value of lastHorizontalGap is NaN, the * value of the horizontalGap property will be used instead. * * @default NaN * * @see #gap */ public function get lastHorizontalGap():Number { return this._lastHorizontalGap; } /** * @private */ public function set lastHorizontalGap(value:Number):void { if(this._lastHorizontalGap == value) { return; } this._lastHorizontalGap = value; this.dispatchEventWith(Event.CHANGE); } /** * Quickly sets all padding properties to the same value. The * padding getter always returns the value of * paddingTop, but the other padding values may be * different. * * @default 0 * * @see #paddingTop * @see #paddingRight * @see #paddingBottom * @see #paddingLeft */ public function get padding():Number { return this._paddingTop; } /** * @private */ public function set padding(value:Number):void { this.paddingTop = value; this.paddingRight = value; this.paddingBottom = value; this.paddingLeft = value; } /** * @private */ protected var _paddingTop:Number = 0; /** * The space, in pixels, above of items. * * @default 0 */ public function get paddingTop():Number { return this._paddingTop; } /** * @private */ public function set paddingTop(value:Number):void { if(this._paddingTop == value) { return; } this._paddingTop = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _paddingRight:Number = 0; /** * The space, in pixels, to the right of the items. * * @default 0 */ public function get paddingRight():Number { return this._paddingRight; } /** * @private */ public function set paddingRight(value:Number):void { if(this._paddingRight == value) { return; } this._paddingRight = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _paddingBottom:Number = 0; /** * The space, in pixels, below the items. * * @default 0 */ public function get paddingBottom():Number { return this._paddingBottom; } /** * @private */ public function set paddingBottom(value:Number):void { if(this._paddingBottom == value) { return; } this._paddingBottom = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _paddingLeft:Number = 0; /** * The space, in pixels, to the left of the items. * * @default 0 */ public function get paddingLeft():Number { return this._paddingLeft; } /** * @private */ public function set paddingLeft(value:Number):void { if(this._paddingLeft == value) { return; } this._paddingLeft = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _horizontalAlign:String = HorizontalAlign.LEFT; [Inspectable(type=""String"",enumeration=""left,center,right"")] /** * If the total row width is less than the bounds, the items in the row * can be aligned horizontally. * *

Note: The HorizontalAlign.JUSTIFY * constant is not supported.

* * @default feathers.layout.HorizontalAlign.LEFT * * @see feathers.layout.HorizontalAlign#LEFT * @see feathers.layout.HorizontalAlign#CENTER * @see feathers.layout.HorizontalAlign#RIGHT * @see #verticalAlign * @see #rowVerticalAlign */ public function get horizontalAlign():String { return this._horizontalAlign; } /** * @private */ public function set horizontalAlign(value:String):void { if(this._horizontalAlign == value) { return; } this._horizontalAlign = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _verticalAlign:String = VerticalAlign.TOP; [Inspectable(type=""String"",enumeration=""top,middle,bottom"")] /** * If the total height of the content is less than the bounds, the * content may be aligned vertically. * *

Note: The VerticalAlign.JUSTIFY * constant is not supported.

* * @default feathers.layout.VerticalAlign.TOP * * @see feathers.layout.VerticalAlign#TOP * @see feathers.layout.VerticalAlign#MIDDLE * @see feathers.layout.VerticalAlign#BOTTOM * @see #horizontalAlign * @see #rowVerticalAlign */ public function get verticalAlign():String { return this._verticalAlign; } /** * @private */ public function set verticalAlign(value:String):void { if(this._verticalAlign == value) { return; } this._verticalAlign = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _rowVerticalAlign:String = VerticalAlign.TOP; [Inspectable(type=""String"",enumeration=""top,middle,bottom"")] /** * If the height of an item is less than the height of a row, it can be * aligned vertically. * * @default feathers.layout.VerticalAlign.TOP * * @see feathers.layout.VerticalAlign#TOP * @see feathers.layout.VerticalAlign#MIDDLE * @see feathers.layout.VerticalAlign#BOTTOM * @see #horizontalAlign * @see #verticalAlign */ public function get rowVerticalAlign():String { return this._rowVerticalAlign; } /** * @private */ public function set rowVerticalAlign(value:String):void { if(this._rowVerticalAlign == value) { return; } this._rowVerticalAlign = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _widthCache:Array = []; /** * @private */ protected var _heightCache:Array = []; /** * @inheritDoc */ public function layout(items:Vector., viewPortBounds:ViewPortBounds = null, result:LayoutBoundsResult = null):LayoutBoundsResult { //this function is very long because it may be called every frame, //in some situations. testing revealed that splitting this function //into separate, smaller functions affected performance. //since the SWC compiler cannot inline functions, we can't use that //feature either. //since viewPortBounds can be null, we may need to provide some defaults var boundsX:Number = viewPortBounds ? viewPortBounds.x : 0; var boundsY:Number = viewPortBounds ? viewPortBounds.y : 0; var minWidth:Number = viewPortBounds ? viewPortBounds.minWidth : 0; var minHeight:Number = viewPortBounds ? viewPortBounds.minHeight : 0; var maxWidth:Number = viewPortBounds ? viewPortBounds.maxWidth : Number.POSITIVE_INFINITY; var maxHeight:Number = viewPortBounds ? viewPortBounds.maxHeight : Number.POSITIVE_INFINITY; var explicitWidth:Number = viewPortBounds ? viewPortBounds.explicitWidth : NaN; var explicitHeight:Number = viewPortBounds ? viewPortBounds.explicitHeight : NaN; var needsWidth:Boolean = explicitWidth !== explicitWidth; //isNaN //let's figure out if we can show multiple rows var supportsMultipleRows:Boolean = true; var availableRowWidth:Number = explicitWidth; if(needsWidth) { availableRowWidth = maxWidth; if(availableRowWidth == Number.POSITIVE_INFINITY) { supportsMultipleRows = false; } } if(this._useVirtualLayout) { //if the layout is virtualized, we'll need the dimensions of the //typical item so that we have fallback values when an item is null if(this._typicalItem is IValidating) { IValidating(this._typicalItem).validate(); } var calculatedTypicalItemWidth:Number = this._typicalItem ? this._typicalItem.width : 0; var calculatedTypicalItemHeight:Number = this._typicalItem ? this._typicalItem.height : 0; } var i:int = 0; var itemCount:int = items.length; var positionY:Number = boundsY + this._paddingTop; var maxRowWidth:Number = 0; var maxItemHeight:Number = 0; var verticalGap:Number = this._verticalGap; var hasFirstHorizontalGap:Boolean = this._firstHorizontalGap === this._firstHorizontalGap; //!isNaN var hasLastHorizontalGap:Boolean = this._lastHorizontalGap === this._lastHorizontalGap; //!isNaN var secondToLastIndex:int = itemCount - 2; do { if(i > 0) { positionY += maxItemHeight + verticalGap; } //this section prepares some variables needed for the following loop maxItemHeight = this._useVirtualLayout ? calculatedTypicalItemHeight : 0; var positionX:Number = boundsX + this._paddingLeft; //we save the items in this row to align them later. this._rowItems.length = 0; var rowItemCount:int = 0; //if there are no items in the row (such as when there are no //items in the container!), then we don't want to subtract the //gap when calculating the row width, so default to 0. var horizontalGap:Number = 0; //this first loop sets the x position of items, and it calculates //the total width of all items for(; i < itemCount; i++) { var item:DisplayObject = items[i]; horizontalGap = this._horizontalGap; if(hasFirstHorizontalGap && i == 0) { horizontalGap = this._firstHorizontalGap; } else if(hasLastHorizontalGap && i > 0 && i == secondToLastIndex) { horizontalGap = this._lastHorizontalGap; } if(this._useVirtualLayout && this._hasVariableItemDimensions) { var cachedWidth:Number = this._widthCache[i]; var cachedHeight:Number = this._heightCache[i]; } if(this._useVirtualLayout && !item) { //the item is null, and the layout is virtualized, so we //need to estimate the width of the item. if(this._hasVariableItemDimensions) { if(cachedWidth !== cachedWidth) //isNaN { var itemWidth:Number = calculatedTypicalItemWidth; } else { itemWidth = cachedWidth; } if(cachedHeight !== cachedHeight) //isNaN { var itemHeight:Number = calculatedTypicalItemHeight; } else { itemHeight = cachedHeight; } } else { itemWidth = calculatedTypicalItemWidth; itemHeight = calculatedTypicalItemHeight; } } else { //we get here if the item isn't null. it is never null if //the layout isn't virtualized. if(item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout) { continue; } if(item is IValidating) { IValidating(item).validate(); } itemWidth = item.width; itemHeight = item.height; if(this._useVirtualLayout) { if(this._hasVariableItemDimensions) { if(itemWidth != cachedWidth) { //update the cache if needed. this will notify //the container that the virtualized layout has //changed, and it the view port may need to be //re-measured. this._widthCache[i] = itemWidth; this.dispatchEventWith(Event.CHANGE); } if(itemHeight != cachedHeight) { this._heightCache[i] = itemHeight; this.dispatchEventWith(Event.CHANGE); } } else { if(calculatedTypicalItemWidth >= 0) { item.width = itemWidth = calculatedTypicalItemWidth; } if(calculatedTypicalItemHeight >= 0) { item.height = itemHeight = calculatedTypicalItemHeight; } } } } if(supportsMultipleRows && rowItemCount > 0 && (positionX + itemWidth) > (availableRowWidth - this._paddingRight)) { //we need to restore the previous gap because it will be //subtracted from the x position to get the row width. var previousIndex:int = i - 1; horizontalGap = this._horizontalGap; if(hasFirstHorizontalGap && previousIndex == 0) { horizontalGap = this._firstHorizontalGap; } else if(hasLastHorizontalGap && previousIndex > 0 && previousIndex == secondToLastIndex) { horizontalGap = this._lastHorizontalGap; } //we've reached the end of the row, so go to next break; } if(item) { this._rowItems[this._rowItems.length] = item; item.x = item.pivotX + positionX; } positionX += itemWidth + horizontalGap; //we compare with > instead of Math.max() because the rest //arguments on Math.max() cause extra garbage collection and //hurt performance if(itemHeight > maxItemHeight) { //we need to know the maximum height of the items in the //case where the height of the view port needs to be //calculated by the layout. maxItemHeight = itemHeight; } rowItemCount++; } //this is the total width of all items in the row var totalRowWidth:Number = positionX - horizontalGap + this._paddingRight - boundsX; if(totalRowWidth > maxRowWidth) { maxRowWidth = totalRowWidth; } rowItemCount = this._rowItems.length; if(supportsMultipleRows) { //in this section, we handle horizontal alignment for the //current row. however, we may need to adjust it later if //the maxRowWidth is smaller than the availableRowWidth. var horizontalAlignOffsetX:Number = 0; if(this._horizontalAlign === HorizontalAlign.RIGHT) { horizontalAlignOffsetX = availableRowWidth - totalRowWidth; } else if(this._horizontalAlign === HorizontalAlign.CENTER) { horizontalAlignOffsetX = Math.round((availableRowWidth - totalRowWidth) / 2); } if(horizontalAlignOffsetX != 0) { for(var j:int = 0; j < rowItemCount; j++) { item = this._rowItems[j]; if(item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout) { continue; } item.x += horizontalAlignOffsetX; } } } for(j = 0; j < rowItemCount; j++) { item = this._rowItems[j]; var layoutItem:ILayoutDisplayObject = item as ILayoutDisplayObject; if(layoutItem && !layoutItem.includeInLayout) { continue; } //handle all other vertical alignment values. the y position //of all items is set here. switch(this._rowVerticalAlign) { case VerticalAlign.BOTTOM: { item.y = item.pivotY + positionY + maxItemHeight - item.height; break; } case VerticalAlign.MIDDLE: { //round to the nearest pixel when dividing by 2 to //align in the middle item.y = item.pivotY + positionY + Math.round((maxItemHeight - item.height) / 2); break; } default: //top { item.y = item.pivotY + positionY; } } } } while(i < itemCount) //we don't want to keep a reference to any of the items, so clear //this cache this._rowItems.length = 0; if(supportsMultipleRows && (needsWidth || explicitWidth < maxRowWidth)) { //if the maxRowWidth has changed since any row was aligned, the //items in those rows may need to be shifted a bit var contentRowWidth:Number = maxRowWidth; if(contentRowWidth < minWidth) { contentRowWidth = minWidth; } else if(contentRowWidth > maxWidth) { contentRowWidth = maxWidth; } horizontalAlignOffsetX = 0; if(this._horizontalAlign === HorizontalAlign.RIGHT) { horizontalAlignOffsetX = availableRowWidth - contentRowWidth; } else if(this._horizontalAlign === HorizontalAlign.CENTER) { horizontalAlignOffsetX = Math.round((availableRowWidth - contentRowWidth) / 2); } if(horizontalAlignOffsetX != 0) { for(i = 0; i < itemCount; i++) { item = items[i]; if(!item || (item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout)) { continue; } //previously, we used the maxWidth for alignment, //but the max row width may be smaller, so we need //to account for the difference item.x -= horizontalAlignOffsetX; } } } else { contentRowWidth = maxRowWidth; } if(needsWidth) { availableRowWidth = contentRowWidth; } var totalHeight:Number = positionY + maxItemHeight + this._paddingBottom; //the available height is the height of the viewport. if the explicit //height is NaN, we need to calculate the viewport height ourselves //based on the total height of all items. var availableHeight:Number = explicitHeight; if(availableHeight !== availableHeight) //isNaN { availableHeight = totalHeight; if(availableHeight < minHeight) { availableHeight = minHeight; } else if(availableHeight > maxHeight) { availableHeight = maxHeight; } } if(totalHeight < availableHeight && this._verticalAlign != VerticalAlign.TOP) { var verticalAlignOffset:Number = availableHeight - totalHeight; if(this._verticalAlign === VerticalAlign.MIDDLE) { verticalAlignOffset /= 2; } for(i = 0; i < itemCount; i++) { item = items[i]; if(!item || (item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout)) { continue; } item.y += verticalAlignOffset; } } //finally, we want to calculate the result so that the container //can use it to adjust its viewport and determine the minimum and //maximum scroll positions (if needed) if(!result) { result = new LayoutBoundsResult(); } result.contentX = 0; result.contentWidth = maxRowWidth; result.contentY = 0; result.contentHeight = totalHeight; result.viewPortWidth = availableRowWidth; result.viewPortHeight = availableHeight; return result; } /** * @inheritDoc */ public function measureViewPort(itemCount:int, viewPortBounds:ViewPortBounds = null, result:Point = null):Point { if(!result) { result = new Point(); } if(!this._useVirtualLayout) { throw new IllegalOperationError(""measureViewPort() may be called only if useVirtualLayout is true."") } //this function is very long because it may be called every frame, //in some situations. testing revealed that splitting this function //into separate, smaller functions affected performance. //since the SWC compiler cannot inline functions, we can't use that //feature either. //since viewPortBounds can be null, we may need to provide some defaults var boundsX:Number = viewPortBounds ? viewPortBounds.x : 0; var boundsY:Number = viewPortBounds ? viewPortBounds.y : 0; var minWidth:Number = viewPortBounds ? viewPortBounds.minWidth : 0; var minHeight:Number = viewPortBounds ? viewPortBounds.minHeight : 0; var maxWidth:Number = viewPortBounds ? viewPortBounds.maxWidth : Number.POSITIVE_INFINITY; var maxHeight:Number = viewPortBounds ? viewPortBounds.maxHeight : Number.POSITIVE_INFINITY; var explicitWidth:Number = viewPortBounds ? viewPortBounds.explicitWidth : NaN; var explicitHeight:Number = viewPortBounds ? viewPortBounds.explicitHeight : NaN; //let's figure out if we can show multiple rows var supportsMultipleRows:Boolean = true; var availableRowWidth:Number = explicitWidth; if(availableRowWidth !== availableRowWidth) //isNaN { availableRowWidth = maxWidth; if(availableRowWidth == Number.POSITIVE_INFINITY) { supportsMultipleRows = false; } } if(this._typicalItem is IValidating) { IValidating(this._typicalItem).validate(); } var calculatedTypicalItemWidth:Number = this._typicalItem ? this._typicalItem.width : 0; var calculatedTypicalItemHeight:Number = this._typicalItem ? this._typicalItem.height : 0; var i:int = 0; var positionY:Number = boundsY + this._paddingTop; var maxRowWidth:Number = 0; var maxItemHeight:Number = 0; var verticalGap:Number = this._verticalGap; var hasFirstHorizontalGap:Boolean = this._firstHorizontalGap === this._firstHorizontalGap; //!isNaN var hasLastHorizontalGap:Boolean = this._lastHorizontalGap === this._lastHorizontalGap; //!isNaN var secondToLastIndex:int = itemCount - 2; do { if(i > 0) { positionY += maxItemHeight + verticalGap; } //this section prepares some variables needed for the following loop maxItemHeight = this._useVirtualLayout ? calculatedTypicalItemHeight : 0; var positionX:Number = boundsX + this._paddingLeft; var rowItemCount:int = 0; //if there are no items in the row (such as when there are no //items in the container!), then we don't want to subtract the //gap when calculating the row width, so default to 0. var horizontalGap:Number = 0; //this first loop sets the x position of items, and it calculates //the total width of all items for(; i < itemCount; i++) { horizontalGap = this._horizontalGap; if(hasFirstHorizontalGap && i == 0) { horizontalGap = this._firstHorizontalGap; } else if(hasLastHorizontalGap && i > 0 && i == secondToLastIndex) { horizontalGap = this._lastHorizontalGap; } if(this._hasVariableItemDimensions) { var cachedWidth:Number = this._widthCache[i]; var cachedHeight:Number = this._heightCache[i]; if(cachedWidth !== cachedWidth) //isNaN { var itemWidth:Number = calculatedTypicalItemWidth; } else { itemWidth = cachedWidth; } if(cachedHeight !== cachedHeight) //isNaN { var itemHeight:Number = calculatedTypicalItemHeight; } else { itemHeight = cachedHeight; } } else { itemWidth = calculatedTypicalItemWidth; itemHeight = calculatedTypicalItemHeight; } if(supportsMultipleRows && rowItemCount > 0 && (positionX + itemWidth) > (availableRowWidth - this._paddingRight)) { //we've reached the end of the row, so go to next break; } positionX += itemWidth + horizontalGap; //we compare with > instead of Math.max() because the rest //arguments on Math.max() cause extra garbage collection and //hurt performance if(itemHeight > maxItemHeight) { //we need to know the maximum height of the items in the //case where the height of the view port needs to be //calculated by the layout. maxItemHeight = itemHeight; } rowItemCount++; } //this is the total width of all items in the row var totalRowWidth:Number = positionX - horizontalGap + this._paddingRight - boundsX; if(totalRowWidth > maxRowWidth) { maxRowWidth = totalRowWidth; } } while(i < itemCount) if(supportsMultipleRows) { if(explicitWidth !== explicitWidth) //isNaN { availableRowWidth = maxRowWidth; if(availableRowWidth < minWidth) { availableRowWidth = minWidth; } else if(availableRowWidth > maxWidth) { availableRowWidth = maxWidth; } } } else { availableRowWidth = maxRowWidth; } var totalHeight:Number = positionY + maxItemHeight + this._paddingBottom; //the available height is the height of the viewport. if the explicit //height is NaN, we need to calculate the viewport height ourselves //based on the total height of all items. var availableHeight:Number = explicitHeight; if(availableHeight !== availableHeight) //isNaN { availableHeight = totalHeight; if(availableHeight < minHeight) { availableHeight = minHeight; } else if(availableHeight > maxHeight) { availableHeight = maxHeight; } } result.x = availableRowWidth; result.y = availableHeight; return result; } /** * @inheritDoc */ public function getNearestScrollPositionForIndex(index:int, scrollX:Number, scrollY:Number, items:Vector., x:Number, y:Number, width:Number, height:Number, result:Point = null):Point { result = this.calculateMaxScrollYAndRowHeightOfIndex(index, items, x, y, width, height, result); var maxScrollY:Number = result.x; var rowHeight:Number = result.y; result.x = 0; var bottomPosition:Number = maxScrollY - (height - rowHeight); if(scrollY >= bottomPosition && scrollY <= maxScrollY) { //keep the current scroll position because the item is already //fully visible result.y = scrollY; } else { var topDifference:Number = Math.abs(maxScrollY - scrollY); var bottomDifference:Number = Math.abs(bottomPosition - scrollY); if(bottomDifference < topDifference) { result.y = bottomPosition; } else { result.y = maxScrollY; } } return result; } /** * @inheritDoc */ public function calculateNavigationDestination(items:Vector., index:int, keyCode:uint, bounds:LayoutBoundsResult):int { var result:int = index; if(keyCode == Keyboard.HOME) { if(items.length > 0) { result = 0; } } else if(keyCode == Keyboard.END) { result = items.length - 1; } else if(keyCode == Keyboard.UP) { result--; } else if(keyCode == Keyboard.DOWN) { result++; } if(result < 0) { return 0; } if(result >= items.length) { return items.length - 1; } return result; } /** * @inheritDoc */ public function getScrollPositionForIndex(index:int, items:Vector., x:Number, y:Number, width:Number, height:Number, result:Point = null):Point { result = this.calculateMaxScrollYAndRowHeightOfIndex(index, items, x, y, width, height, result); var maxScrollY:Number = result.x; var rowHeight:Number = result.y; if(this._useVirtualLayout) { if(this._hasVariableItemDimensions) { var itemHeight:Number = this._heightCache[index]; if(itemHeight !== itemHeight) //isNaN { itemHeight = this._typicalItem.height; } } else { itemHeight = this._typicalItem.height; } } else { itemHeight = items[index].height; } if(!result) { result = new Point(); } result.x = 0; result.y = maxScrollY - Math.round((height - itemHeight) / 2); return result; } /** * @inheritDoc */ public function getDropIndex(x:Number, y:Number, items:Vector., boundsX:Number, boundsY:Number, width:Number, height:Number):int { if(this._useVirtualLayout) { //if the layout is virtualized, we'll need the dimensions of the //typical item so that we have fallback values when an item is null if(this._typicalItem is IValidating) { IValidating(this._typicalItem).validate(); } var calculatedTypicalItemWidth:Number = this._typicalItem ? this._typicalItem.width : 0; var calculatedTypicalItemHeight:Number = this._typicalItem ? this._typicalItem.height : 0; } var horizontalGap:Number = this._horizontalGap; var verticalGap:Number = this._verticalGap; var maxItemHeight:Number = 0; var positionY:Number = this._paddingTop; var i:int = 0; var itemCount:int = items.length; do { if(i > 0) { positionY += maxItemHeight + verticalGap; } //this section prepares some variables needed for the following loop maxItemHeight = this._useVirtualLayout ? calculatedTypicalItemHeight : 0; var positionX:Number = this._paddingLeft; var rowItemCount:int = 0; for(; i < itemCount; i++) { var item:DisplayObject = items[i]; if(this._useVirtualLayout && this._hasVariableItemDimensions) { var cachedWidth:Number = this._widthCache[i]; var cachedHeight:Number = this._heightCache[i]; } if(this._useVirtualLayout && !item) { //the item is null, and the layout is virtualized, so we //need to estimate the width of the item. if(this._hasVariableItemDimensions) { if(cachedWidth !== cachedWidth) //isNaN { var itemWidth:Number = calculatedTypicalItemWidth; } else { itemWidth = cachedWidth; } if(cachedHeight !== cachedHeight) //isNaN { var itemHeight:Number = calculatedTypicalItemHeight; } else { itemHeight = cachedHeight; } } else { itemWidth = calculatedTypicalItemWidth; itemHeight = calculatedTypicalItemHeight; } } else { //we get here if the item isn't null. it is never null if //the layout isn't virtualized. if(item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout) { continue; } if(item is IValidating) { IValidating(item).validate(); } itemWidth = item.width; itemHeight = item.height; if(this._useVirtualLayout && this._hasVariableItemDimensions) { if(this._hasVariableItemDimensions) { if(itemWidth != cachedWidth) { this._widthCache[i] = itemWidth; this.dispatchEventWith(Event.CHANGE); } if(itemHeight != cachedHeight) { this._heightCache[i] = itemHeight; this.dispatchEventWith(Event.CHANGE); } } else { if(calculatedTypicalItemWidth >= 0) { itemWidth = calculatedTypicalItemWidth; } if(calculatedTypicalItemHeight >= 0) { itemHeight = calculatedTypicalItemHeight; } } } } var endOfRow:Boolean = rowItemCount > 0 && (positionX + itemWidth) > (width - this._paddingRight); if((endOfRow || x < (positionX + (itemWidth / 2))) && y < (positionY + itemHeight + (gap / 2))) { return i; } if(endOfRow) { //we've reached the end of the row, so go to next break; } //we compare with > instead of Math.max() because the rest //arguments on Math.max() cause extra garbage collection and //hurt performance if(itemHeight > maxItemHeight) { //we need to know the maximum height of the items in the //case where the height of the view port needs to be //calculated by the layout. maxItemHeight = itemHeight; } positionX += itemWidth + horizontalGap; rowItemCount++; } } while(i < itemCount) return itemCount; } /** * @inheritDoc */ public function positionDropIndicator(dropIndicator:DisplayObject, index:int, x:Number, y: Number, items:Vector., width:Number, height:Number):void { if(dropIndicator is IValidating) { IValidating(dropIndicator).validate(); } var horizontalGap:Number = this._horizontalGap; var verticalGap:Number = this._verticalGap; var maxItemHeight:Number = 0; var positionY:Number = this._paddingTop; var i:int = 0; var itemCount:int = items.length; do { if(i > 0) { if(y < (positionY + itemHeight + (verticalGap / 2))) { //if the x/y position is closer to the previous row, //then display the drop indicator at the end of that row var item:DisplayObject = items[i - 1]; dropIndicator.x = item.x + item.width - dropIndicator.width / 2; dropIndicator.y = item.y; dropIndicator.height = item.height; return; } positionY += maxItemHeight + verticalGap; } //this section prepares some variables needed for the following loop maxItemHeight = 0; var positionX:Number = this._paddingLeft; var rowItemCount:int = 0; for(; i < itemCount; i++) { item = items[i]; var itemWidth:Number = item.width; var itemHeight:Number = item.height; if(rowItemCount > 0 && (positionX + itemWidth) > (width - this._paddingRight)) { //we've reached the end of the row, so go to next break; } //we compare with > instead of Math.max() because the rest //arguments on Math.max() cause extra garbage collection and //hurt performance if(itemHeight > maxItemHeight) { //we need to know the maximum height of the items in the //case where the height of the view port needs to be //calculated by the layout. maxItemHeight = itemHeight; } if(i == index) { dropIndicator.x = item.x - dropIndicator.width / 2; dropIndicator.y = item.y; dropIndicator.height = item.height; return; } positionX += itemWidth + horizontalGap; rowItemCount++; } } while(i < itemCount) var lastItem:DisplayObject = items[itemCount - 1]; dropIndicator.x = lastItem.x + lastItem.width - dropIndicator.width / 2; dropIndicator.y = lastItem.y; dropIndicator.height = lastItem.height; } /** * @inheritDoc */ override public function resetVariableVirtualCache():void { this._widthCache.length = 0; this._heightCache.length = 0; } /** * @inheritDoc */ override public function resetVariableVirtualCacheAtIndex(index:int, item:DisplayObject = null):void { delete this._widthCache[index]; delete this._heightCache[index]; if(item) { this._widthCache[index] = item.width; this._heightCache[index] = item.height; this.dispatchEventWith(Event.CHANGE); } } /** * @inheritDoc */ override public function addToVariableVirtualCacheAtIndex(index:int, item:DisplayObject = null):void { var widthValue:* = (item !== null) ? item.width : undefined; var heightValue:* = (item !== null) ? item.height : undefined; this._widthCache.insertAt(index, widthValue); this._heightCache.insertAt(index, heightValue); } /** * @inheritDoc */ override public function removeFromVariableVirtualCacheAtIndex(index:int):void { this._widthCache.removeAt(index); this._heightCache.removeAt(index); } /** * @inheritDoc */ public function getVisibleIndicesAtScrollPosition(scrollX:Number, scrollY:Number, width:Number, height:Number, itemCount:int, result:Vector. = null):Vector. { if(result) { result.length = 0; } else { result = new []; } if(!this._useVirtualLayout) { throw new IllegalOperationError(""getVisibleIndicesAtScrollPosition() may be called only if useVirtualLayout is true."") } if(this._typicalItem is IValidating) { IValidating(this._typicalItem).validate(); } var calculatedTypicalItemWidth:Number = this._typicalItem ? this._typicalItem.width : 0; var calculatedTypicalItemHeight:Number = this._typicalItem ? this._typicalItem.height : 0; var resultLastIndex:int = 0; var i:int = 0; var positionY:Number = this._paddingTop; var maxItemHeight:Number = 0; var verticalGap:Number = this._verticalGap; var maxPositionY:Number = scrollY + height; var hasFirstHorizontalGap:Boolean = this._firstHorizontalGap === this._firstHorizontalGap; //!isNaN var hasLastHorizontalGap:Boolean = this._lastHorizontalGap === this._lastHorizontalGap; //!isNaN var secondToLastIndex:int = itemCount - 2; do { if(i > 0) { positionY += maxItemHeight + verticalGap; if(positionY >= maxPositionY) { //the following rows will not be visible, so we can stop break; } } //this section prepares some variables needed for the following loop maxItemHeight = calculatedTypicalItemHeight; var positionX:Number = this._paddingLeft; var rowItemCount:int = 0; //this first loop sets the x position of items, and it calculates //the total width of all items for(; i < itemCount; i++) { var horizontalGap:Number = this._horizontalGap; if(hasFirstHorizontalGap && i == 0) { horizontalGap = this._firstHorizontalGap; } else if(hasLastHorizontalGap && i > 0 && i == secondToLastIndex) { horizontalGap = this._lastHorizontalGap; } if(this._hasVariableItemDimensions) { var cachedWidth:Number = this._widthCache[i]; var cachedHeight:Number = this._heightCache[i]; } if(this._hasVariableItemDimensions) { if(cachedWidth !== cachedWidth) //isNaN { var itemWidth:Number = calculatedTypicalItemWidth; } else { itemWidth = cachedWidth; } if(cachedHeight !== cachedHeight) //isNaN { var itemHeight:Number = calculatedTypicalItemHeight; } else { itemHeight = cachedHeight; } } else { itemWidth = calculatedTypicalItemWidth; itemHeight = calculatedTypicalItemHeight; } if(rowItemCount > 0 && (positionX + itemWidth) > (width - this._paddingRight)) { //we've reached the end of the row, so go to next break; } if((positionY + itemHeight) > scrollY) { result[resultLastIndex] = i; resultLastIndex++; } positionX += itemWidth + horizontalGap; //we compare with > instead of Math.max() because the rest //arguments on Math.max() cause extra garbage collection and //hurt performance if(itemHeight > maxItemHeight) { //we need to know the maximum height of the items in the //case where the height of the view port needs to be //calculated by the layout. maxItemHeight = itemHeight; } rowItemCount++; } } while(i < itemCount) return result; } /** * @private */ protected function calculateMaxScrollYAndRowHeightOfIndex(index:int, items:Vector., x:Number, y:Number, width:Number, height:Number, result:Point = null):Point { if(!result) { result = new Point(); } if(this._useVirtualLayout) { //if the layout is virtualized, we'll need the dimensions of the //typical item so that we have fallback values when an item is null if(this._typicalItem is IValidating) { IValidating(this._typicalItem).validate(); } var calculatedTypicalItemWidth:Number = this._typicalItem ? this._typicalItem.width : 0; var calculatedTypicalItemHeight:Number = this._typicalItem ? this._typicalItem.height : 0; } var horizontalGap:Number = this._horizontalGap; var verticalGap:Number = this._verticalGap; var maxItemHeight:Number = 0; var positionY:Number = y + this._paddingTop; var i:int = 0; var itemCount:int = items.length; var isLastRow:Boolean = false; do { if(isLastRow) { break; } if(i > 0) { positionY += maxItemHeight + verticalGap; } //this section prepares some variables needed for the following loop maxItemHeight = this._useVirtualLayout ? calculatedTypicalItemHeight : 0; var positionX:Number = x + this._paddingLeft; var rowItemCount:int = 0; for(; i < itemCount; i++) { var item:DisplayObject = items[i]; if(this._useVirtualLayout && this._hasVariableItemDimensions) { var cachedWidth:Number = this._widthCache[i]; var cachedHeight:Number = this._heightCache[i]; } if(this._useVirtualLayout && !item) { //the item is null, and the layout is virtualized, so we //need to estimate the width of the item. if(this._hasVariableItemDimensions) { if(cachedWidth !== cachedWidth) //isNaN { var itemWidth:Number = calculatedTypicalItemWidth; } else { itemWidth = cachedWidth; } if(cachedHeight !== cachedHeight) //isNaN { var itemHeight:Number = calculatedTypicalItemHeight; } else { itemHeight = cachedHeight; } } else { itemWidth = calculatedTypicalItemWidth; itemHeight = calculatedTypicalItemHeight; } } else { //we get here if the item isn't null. it is never null if //the layout isn't virtualized. if(item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout) { continue; } if(item is IValidating) { IValidating(item).validate(); } itemWidth = item.width; itemHeight = item.height; if(this._useVirtualLayout && this._hasVariableItemDimensions) { if(this._hasVariableItemDimensions) { if(itemWidth != cachedWidth) { this._widthCache[i] = itemWidth; this.dispatchEventWith(Event.CHANGE); } if(itemHeight != cachedHeight) { this._heightCache[i] = itemHeight; this.dispatchEventWith(Event.CHANGE); } } else { if(calculatedTypicalItemWidth >= 0) { itemWidth = calculatedTypicalItemWidth; } if(calculatedTypicalItemHeight >= 0) { itemHeight = calculatedTypicalItemHeight; } } } } if(rowItemCount > 0 && (positionX + itemWidth) > (width - this._paddingRight)) { //we've reached the end of the row, so go to next break; } //we don't check this at the beginning of the loop because //it may break to start a new row and then redo this item if(i == index) { isLastRow = true; } //we compare with > instead of Math.max() because the rest //arguments on Math.max() cause extra garbage collection and //hurt performance if(itemHeight > maxItemHeight) { //we need to know the maximum height of the items in the //case where the height of the view port needs to be //calculated by the layout. maxItemHeight = itemHeight; } positionX += itemWidth + horizontalGap; rowItemCount++; } } while(i < itemCount) result.setTo(positionY, maxItemHeight); return result; } } } ",12313,True,2588.7331203259787,median "package com.splunk.charting.charts { import com.jasongatt.core.ObservableProperty; import com.jasongatt.graphics.brushes.DrawingUtils; import com.jasongatt.graphics.brushes.IBrush; import com.jasongatt.graphics.brushes.SolidFillBrush; import com.jasongatt.graphics.brushes.SolidStrokeBrush; import com.jasongatt.graphics.shapes.EllipseShape; import com.jasongatt.graphics.shapes.IShape; import com.jasongatt.layout.LayoutSprite; import com.jasongatt.layout.Orientation; import com.jasongatt.layout.Size; import com.jasongatt.layout.Visibility; import com.jasongatt.utils.NumberUtil; import com.splunk.charting.legend.ILegend; import com.splunk.controls.Label; import com.splunk.data.IDataTable; import com.splunk.palettes.brush.IBrushPalette; import com.splunk.palettes.brush.SolidFillBrushPalette; import com.splunk.palettes.color.ListColorPalette; import com.splunk.utils.Style; import flash.display.DisplayObject; import flash.display.Graphics; import flash.display.Shape; import flash.display.Sprite; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; public class FillerGauge extends AbstractChart { // Private Properties private var _orientation:ObservableProperty; private var _fillerBrushPalette:ObservableProperty; private var _fillerStyle:ObservableProperty; private var _fillerPlacement1:ObservableProperty; private var _fillerPlacement2:ObservableProperty; private var _rangeValues:ObservableProperty; private var _rangePadding:ObservableProperty; private var _majorTickBrush:ObservableProperty; private var _majorTickStyle:ObservableProperty; private var _majorTickPlacement1:ObservableProperty; private var _majorTickPlacement2:ObservableProperty; private var _majorUnit:ObservableProperty; private var _minorTickBrush:ObservableProperty; private var _minorTickStyle:ObservableProperty; private var _minorTickPlacement1:ObservableProperty; private var _minorTickPlacement2:ObservableProperty; private var _minorUnit:ObservableProperty; private var _labelStyle:ObservableProperty; private var _labelPlacement:ObservableProperty; private var _labelFormat:ObservableProperty; private var _valueStyle:ObservableProperty; private var _valuePlacement:ObservableProperty; private var _valueFormat:ObservableProperty; private var _warningBrush:ObservableProperty; private var _warningShape:ObservableProperty; private var _warningStyle:ObservableProperty; private var _warningPlacement:ObservableProperty; private var _warningSize:ObservableProperty; private var _foregroundBrush:ObservableProperty; private var _foregroundStyle:ObservableProperty; private var _foregroundPlacement1:ObservableProperty; private var _foregroundPlacement2:ObservableProperty; private var _foregroundPadding:ObservableProperty; private var _backgroundBrush:ObservableProperty; private var _backgroundStyle:ObservableProperty; private var _backgroundPlacement1:ObservableProperty; private var _backgroundPlacement2:ObservableProperty; private var _backgroundPadding:ObservableProperty; private var _layers:ObservableProperty; private var _usePercentageRange:ObservableProperty; private var _usePercentageValue:ObservableProperty; private var _showMajorTicks:ObservableProperty; private var _showMinorTicks:ObservableProperty; private var _showLabels:ObservableProperty; private var _showValue:ObservableProperty; private var _fillerValue:Number; private var _fillerPosition:Number; private var _rangeFields:Array; private var _rangePositions:Array; private var _majorTickValues:Array; private var _majorTickPositions:Array; private var _minorTickPositions:Array; private var _labels:Array; private var _foreground:Shape; private var _valueLabel:Label; private var _filler:Filler; private var _warningLight:Shape; private var _labelsContainer:Sprite; private var _majorTicks:Shape; private var _minorTicks:Shape; private var _background:Shape; // Constructor public function FillerGauge() { var colorPalette:ListColorPalette = new ListColorPalette([ 0x00FF00, 0xFFFF00, 0xFF0000 ], true); this._orientation = new ObservableProperty(this, ""orientation"", String, Orientation.Y, this.invalidates(LayoutSprite.MEASURE)); this._fillerBrushPalette = new ObservableProperty(this, ""fillerBrushPalette"", IBrushPalette, new SolidFillBrushPalette(colorPalette), this.invalidates(AbstractChart.RENDER_CHART)); this._fillerStyle = new ObservableProperty(this, ""fillerStyle"", Style, null, this.invalidates(AbstractChart.RENDER_CHART)); this._fillerPlacement1 = new ObservableProperty(this, ""fillerPlacement1"", Number, -20, this.invalidates(AbstractChart.RENDER_CHART)); this._fillerPlacement2 = new ObservableProperty(this, ""fillerPlacement2"", Number, 20, this.invalidates(AbstractChart.RENDER_CHART)); this._rangeValues = new ObservableProperty(this, ""rangeValues"", Array, null, this.invalidates(AbstractChart.PROCESS_DATA)); this._rangePadding = new ObservableProperty(this, ""rangePadding"", Number, 20, this.invalidates(LayoutSprite.MEASURE)); this._majorTickBrush = new ObservableProperty(this, ""majorTickBrush"", IBrush, new SolidStrokeBrush(1, 0x000000), this.invalidates(AbstractChart.RENDER_CHART)); this._majorTickStyle = new ObservableProperty(this, ""majorTickStyle"", Style, null, this.invalidates(AbstractChart.RENDER_CHART)); this._majorTickPlacement1 = new ObservableProperty(this, ""majorTickPlacement1"", Number, 20, this.invalidates(AbstractChart.RENDER_CHART)); this._majorTickPlacement2 = new ObservableProperty(this, ""majorTickPlacement2"", Number, 40, this.invalidates(AbstractChart.RENDER_CHART)); this._majorUnit = new ObservableProperty(this, ""majorUnit"", Number, NaN, this.invalidates(AbstractChart.PROCESS_DATA)); this._minorTickBrush = new ObservableProperty(this, ""minorTickBrush"", IBrush, new SolidStrokeBrush(1, 0x000000), this.invalidates(AbstractChart.RENDER_CHART)); this._minorTickStyle = new ObservableProperty(this, ""minorTickStyle"", Style, null, this.invalidates(AbstractChart.RENDER_CHART)); this._minorTickPlacement1 = new ObservableProperty(this, ""minorTickPlacement1"", Number, 20, this.invalidates(AbstractChart.RENDER_CHART)); this._minorTickPlacement2 = new ObservableProperty(this, ""minorTickPlacement2"", Number, 30, this.invalidates(AbstractChart.RENDER_CHART)); this._minorUnit = new ObservableProperty(this, ""minorUnit"", Number, NaN, this.invalidates(AbstractChart.PROCESS_DATA)); this._labelStyle = new ObservableProperty(this, ""labelStyle"", Style, null, this.invalidates(LayoutSprite.MEASURE)); this._labelPlacement = new ObservableProperty(this, ""labelPlacement"", Number, 40, this.invalidates(LayoutSprite.MEASURE)); this._labelFormat = new ObservableProperty(this, ""labelFormat"", Function, null, this.invalidates(LayoutSprite.MEASURE)); this._valueStyle = new ObservableProperty(this, ""valueStyle"", Style, null, this.invalidates(LayoutSprite.MEASURE)); this._valuePlacement = new ObservableProperty(this, ""valuePlacement"", Number, -20, this.invalidates(LayoutSprite.MEASURE)); this._valueFormat = new ObservableProperty(this, ""valueFormat"", Function, null, this.invalidates(LayoutSprite.MEASURE)); this._warningBrush = new ObservableProperty(this, ""warningBrush"", IBrush, new SolidFillBrush(0xFF0000), this.invalidates(AbstractChart.RENDER_CHART)); this._warningShape = new ObservableProperty(this, ""warningShape"", IShape, new EllipseShape(), this.invalidates(AbstractChart.RENDER_CHART)); this._warningStyle = new ObservableProperty(this, ""warningStyle"", Style, null, this.invalidates(AbstractChart.RENDER_CHART)); this._warningPlacement = new ObservableProperty(this, ""warningPlacement"", Number, 70, this.invalidates(AbstractChart.RENDER_CHART)); this._warningSize = new ObservableProperty(this, ""warningSize"", Number, 20, this.invalidates(AbstractChart.RENDER_CHART)); this._foregroundBrush = new ObservableProperty(this, ""foregroundBrush"", IBrush, null, this.invalidates(AbstractChart.RENDER_CHART)); this._foregroundStyle = new ObservableProperty(this, ""foregroundStyle"", Style, null, this.invalidates(AbstractChart.RENDER_CHART)); this._foregroundPlacement1 = new ObservableProperty(this, ""foregroundPlacement1"", Number, -20, this.invalidates(AbstractChart.RENDER_CHART)); this._foregroundPlacement2 = new ObservableProperty(this, ""foregroundPlacement2"", Number, 20, this.invalidates(AbstractChart.RENDER_CHART)); this._foregroundPadding = new ObservableProperty(this, ""foregroundPadding"", Number, 20, this.invalidates(AbstractChart.RENDER_CHART)); this._backgroundBrush = new ObservableProperty(this, ""backgroundBrush"", IBrush, null, this.invalidates(AbstractChart.RENDER_CHART)); this._backgroundStyle = new ObservableProperty(this, ""backgroundStyle"", Style, null, this.invalidates(AbstractChart.RENDER_CHART)); this._backgroundPlacement1 = new ObservableProperty(this, ""backgroundPlacement1"", Number, -20, this.invalidates(AbstractChart.RENDER_CHART)); this._backgroundPlacement2 = new ObservableProperty(this, ""backgroundPlacement2"", Number, 20, this.invalidates(AbstractChart.RENDER_CHART)); this._backgroundPadding = new ObservableProperty(this, ""backgroundPadding"", Number, 20, this.invalidates(AbstractChart.RENDER_CHART)); this._layers = new ObservableProperty(this, ""layers"", Array, new Array(), this.invalidates(AbstractChart.RENDER_CHART)); this._usePercentageRange = new ObservableProperty(this, ""usePercentageRange"", Boolean, false, this.invalidates(AbstractChart.PROCESS_DATA)); this._usePercentageValue = new ObservableProperty(this, ""usePercentageValue"", Boolean, false, this.invalidates(AbstractChart.PROCESS_DATA)); this._showMajorTicks = new ObservableProperty(this, ""showMajorTicks"", Boolean, true, this.invalidates(AbstractChart.RENDER_CHART)); this._showMinorTicks = new ObservableProperty(this, ""showMinorTicks"", Boolean, true, this.invalidates(AbstractChart.RENDER_CHART)); this._showLabels = new ObservableProperty(this, ""showLabels"", Boolean, true, this.invalidates(LayoutSprite.MEASURE)); this._showValue = new ObservableProperty(this, ""showValue"", Boolean, true, this.invalidates(LayoutSprite.MEASURE)); this._fillerValue = 0; this._fillerPosition = 0; this._rangeFields = new Array(); this._rangePositions = new Array(); this._majorTickValues = new Array(); this._majorTickPositions = new Array(); this._minorTickPositions = new Array(); this._labels = new Array(); this._foreground = new Shape(); this._valueLabel = new Label(); this._filler = new Filler(); this._warningLight = new Shape(); this._labelsContainer = new Sprite(); this._labelsContainer.mouseEnabled = false; this._majorTicks = new Shape(); this._minorTicks = new Shape(); this._background = new Shape(); this._updateLayers(); this.invalidate(AbstractChart.PROCESS_DATA); } // Public Getters/Setters public function get orientation() : String { return this._orientation.value; } public function set orientation(value:String) : void { switch (value) { case Orientation.X: case Orientation.Y: break; default: value = Orientation.Y; break; } this._orientation.value = value; } public function get fillerBrushPalette() : IBrushPalette { return this._fillerBrushPalette.value; } public function set fillerBrushPalette(value:IBrushPalette) : void { this._fillerBrushPalette.value = value; } public function get fillerStyle() : Style { return this._fillerStyle.value; } public function set fillerStyle(value:Style) : void { this._fillerStyle.value = value; } public function get fillerPlacement1() : Number { return this._fillerPlacement1.value; } public function set fillerPlacement1(value:Number) : void { this._fillerPlacement1.value = value; } public function get fillerPlacement2() : Number { return this._fillerPlacement2.value; } public function set fillerPlacement2(value:Number) : void { this._fillerPlacement2.value = value; } public function get rangeValues() : Array { var value:Array = this._rangeValues.value; return value ? value.concat() : null; } public function set rangeValues(value:Array) : void { this._rangeValues.value = value ? value.concat() : null; } public function get rangePadding() : Number { return this._rangePadding.value; } public function set rangePadding(value:Number) : void { this._rangePadding.value = value; } public function get majorTickBrush() : IBrush { return this._majorTickBrush.value; } public function set majorTickBrush(value:IBrush) : void { this._majorTickBrush.value = value; } public function get majorTickStyle() : Style { return this._majorTickStyle.value; } public function set majorTickStyle(value:Style) : void { this._majorTickStyle.value = value; } public function get majorTickPlacement1() : Number { return this._majorTickPlacement1.value; } public function set majorTickPlacement1(value:Number) : void { this._majorTickPlacement1.value = value; } public function get majorTickPlacement2() : Number { return this._majorTickPlacement2.value; } public function set majorTickPlacement2(value:Number) : void { this._majorTickPlacement2.value = value; } public function get majorUnit() : Number { return this._majorUnit.value; } public function set majorUnit(value:Number) : void { this._majorUnit.value = value; } public function get minorTickBrush() : IBrush { return this._minorTickBrush.value; } public function set minorTickBrush(value:IBrush) : void { this._minorTickBrush.value = value; } public function get minorTickStyle() : Style { return this._minorTickStyle.value; } public function set minorTickStyle(value:Style) : void { this._minorTickStyle.value = value; } public function get minorTickPlacement1() : Number { return this._minorTickPlacement1.value; } public function set minorTickPlacement1(value:Number) : void { this._minorTickPlacement1.value = value; } public function get minorTickPlacement2() : Number { return this._minorTickPlacement2.value; } public function set minorTickPlacement2(value:Number) : void { this._minorTickPlacement2.value = value; } public function get minorUnit() : Number { return this._minorUnit.value; } public function set minorUnit(value:Number) : void { this._minorUnit.value = value; } public function get labelStyle() : Style { return this._labelStyle.value; } public function set labelStyle(value:Style) : void { this._labelStyle.value = value; } public function get labelPlacement() : Number { return this._labelPlacement.value; } public function set labelPlacement(value:Number) : void { this._labelPlacement.value = value; } public function get labelFormat() : Function { return this._labelFormat.value; } public function set labelFormat(value:Function) : void { this._labelFormat.value = value; } public function get valueStyle() : Style { return this._valueStyle.value; } public function set valueStyle(value:Style) : void { this._valueStyle.value = value; } public function get valuePlacement() : Number { return this._valuePlacement.value; } public function set valuePlacement(value:Number) : void { this._valuePlacement.value = value; } public function get valueFormat() : Function { return this._valueFormat.value; } public function set valueFormat(value:Function) : void { this._valueFormat.value = value; } public function get warningBrush() : IBrush { return this._warningBrush.value; } public function set warningBrush(value:IBrush) : void { this._warningBrush.value = value; } public function get warningShape() : IShape { return this._warningShape.value; } public function set warningShape(value:IShape) : void { this._warningShape.value = value; } public function get warningStyle() : Style { return this._warningStyle.value; } public function set warningStyle(value:Style) : void { this._warningStyle.value = value; } public function get warningPlacement() : Number { return this._warningPlacement.value; } public function set warningPlacement(value:Number) : void { this._warningPlacement.value = value; } public function get warningSize() : Number { return this._warningSize.value; } public function set warningSize(value:Number) : void { this._warningSize.value = value; } public function get foregroundBrush() : IBrush { return this._foregroundBrush.value; } public function set foregroundBrush(value:IBrush) : void { this._foregroundBrush.value = value; } public function get foregroundStyle() : Style { return this._foregroundStyle.value; } public function set foregroundStyle(value:Style) : void { this._foregroundStyle.value = value; } public function get foregroundPlacement1() : Number { return this._foregroundPlacement1.value; } public function set foregroundPlacement1(value:Number) : void { this._foregroundPlacement1.value = value; } public function get foregroundPlacement2() : Number { return this._foregroundPlacement2.value; } public function set foregroundPlacement2(value:Number) : void { this._foregroundPlacement2.value = value; } public function get foregroundPadding() : Number { return this._foregroundPadding.value; } public function set foregroundPadding(value:Number) : void { this._foregroundPadding.value = value; } public function get backgroundBrush() : IBrush { return this._backgroundBrush.value; } public function set backgroundBrush(value:IBrush) : void { this._backgroundBrush.value = value; } public function get backgroundStyle() : Style { return this._backgroundStyle.value; } public function set backgroundStyle(value:Style) : void { this._backgroundStyle.value = value; } public function get backgroundPlacement1() : Number { return this._backgroundPlacement1.value; } public function set backgroundPlacement1(value:Number) : void { this._backgroundPlacement1.value = value; } public function get backgroundPlacement2() : Number { return this._backgroundPlacement2.value; } public function set backgroundPlacement2(value:Number) : void { this._backgroundPlacement2.value = value; } public function get backgroundPadding() : Number { return this._backgroundPadding.value; } public function set backgroundPadding(value:Number) : void { this._backgroundPadding.value = value; } public function get layers() : Array { return this._layers.value.concat(); } public function set layers(value:Array) : void { this._layers.value = value ? value.concat() : new Array(); } public function get usePercentageRange() : Boolean { return this._usePercentageRange.value; } public function set usePercentageRange(value:Boolean) : void { this._usePercentageRange.value = value; } public function get usePercentageValue() : Boolean { return this._usePercentageValue.value; } public function set usePercentageValue(value:Boolean) : void { this._usePercentageValue.value = value; } public function get showMajorTicks() : Boolean { return this._showMajorTicks.value; } public function set showMajorTicks(value:Boolean) : void { this._showMajorTicks.value = value; } public function get showMinorTicks() : Boolean { return this._showMinorTicks.value; } public function set showMinorTicks(value:Boolean) : void { this._showMinorTicks.value = value; } public function get showLabels() : Boolean { return this._showLabels.value; } public function set showLabels(value:Boolean) : void { this._showLabels.value = value; } public function get showValue() : Boolean { return this._showValue.value; } public function set showValue(value:Boolean) : void { this._showValue.value = value; } // Protected Methods protected override function processDataOverride(data:IDataTable) : void { super.processDataOverride(data); this.invalidate(LayoutSprite.MEASURE); var manualRangeValues:Array = this._rangeValues.value; var majorUnit:Number = this._majorUnit.value; var minorUnit:Number = this._minorUnit.value; var usePercentageRange:Number = this._usePercentageRange.value; var usePercentageValue:Number = this._usePercentageValue.value; var fillerValue:Number = NaN; var fillerPosition:Number = 0; var rangeFields:Array = new Array(); var rangeValues:Array = new Array(); var rangePositions:Array = new Array(); var majorTickValues:Array = new Array(); var majorTickPositions:Array = new Array(); var minorTickPositions:Array = new Array(); var prevValue:Number; var value:Number; var i:int; if (manualRangeValues) { prevValue = -Infinity; for each (value in manualRangeValues) { if ((value != value) || (value <= prevValue)) continue; prevValue = value; rangeValues.push(value); rangeFields.push(""range"" + rangeFields.length); } } if (data) { var numDataRows:int = data.numRows; var numDataColumns:int = data.numColumns; if ((numDataRows > 0) && (numDataColumns > 0)) { fillerValue = NumberUtil.parseNumber(data.getValue(0, 0)); if (!manualRangeValues) { prevValue = -Infinity; for (i = 1; i < numDataColumns; i++) { value = NumberUtil.parseNumber(data.getValue(0, i)); if ((value != value) || (value <= prevValue)) continue; prevValue = value; rangeValues.push(value); rangeFields.push(data.getColumnName(i)); } } } } var numRangeValues:int = rangeValues.length; if (numRangeValues < 2) { rangeValues = [ 0, 30, 70, 100 ]; rangeFields = [ ""range0"", ""range1"", ""range2"", ""range3"" ]; numRangeValues = 4; } var minimumValue:Number = rangeValues[0]; var maximumValue:Number = rangeValues[numRangeValues - 1]; var range:Number = maximumValue - minimumValue; if (fillerValue != fillerValue) fillerValue = minimumValue; fillerPosition = (fillerValue - minimumValue) / range; for each (value in rangeValues) rangePositions.push((value - minimumValue) / range); if (usePercentageValue) fillerValue = fillerPosition * 100; if (usePercentageRange) { minimumValue = 0; maximumValue = 100; } this._computeTickPositions(minimumValue, maximumValue, majorUnit, minorUnit, majorTickValues, majorTickPositions, minorTickPositions); this._fillerValue = fillerValue; this._fillerPosition = fillerPosition; this._rangeFields = rangeFields; this._rangePositions = rangePositions; this._majorTickValues = majorTickValues; this._majorTickPositions = majorTickPositions; this._minorTickPositions = minorTickPositions; } protected override function measureOverride(availableSize:Size) : Size { var orientation:String = this._orientation.value; var rangePadding:Number = this._rangePadding.value; var labelStyle:Style = this._labelStyle.value; var labelPlacement:Number = this._labelPlacement.value; var labelFormat:Function = this._labelFormat.value; var valueStyle:Style = this._valueStyle.value; var valuePlacement:Number = this._valuePlacement.value; var valueFormat:Function = this._valueFormat.value; var usePercentageRange:Number = this._usePercentageRange.value; var usePercentageValue:Number = this._usePercentageValue.value; var showLabels:Boolean = this._showLabels.value; var showValue:Boolean = this._showValue.value; var fillerValue:Number = this._fillerValue; var majorTickValues:Array = this._majorTickValues; var majorTickPositions:Array = this._majorTickPositions; var childSize:Size = new Size(); // labels var numTickValues:int = Math.min(majorTickValues.length, majorTickPositions.length); var labelsContainer:Sprite = this._labelsContainer; var labels:Array = this._labels; var numLabels:int = labels.length; var label:Label; var i:int; if (numTickValues > 1) { var position0:Number = majorTickPositions[0]; var position1:Number = majorTickPositions[1]; var dt:Number = position1 - position0; if (orientation == Orientation.X) { rangePadding = Math.min(rangePadding, availableSize.width / 2); childSize.width = (availableSize.width - rangePadding * 2) * dt; if (labelPlacement < 0) childSize.height = Math.max(availableSize.height / 2 + labelPlacement, 0); else childSize.height = Math.max(availableSize.height / 2 - labelPlacement, 0); } else { rangePadding = Math.min(rangePadding, availableSize.height / 2); childSize.height = (availableSize.height - rangePadding * 2) * dt; if (labelPlacement < 0) childSize.width = Math.max(availableSize.width / 2 + labelPlacement, 0); else childSize.width = Math.max(availableSize.width / 2 - labelPlacement, 0); } if (labelFormat == null) labelFormat = usePercentageRange ? this._percentageFormat : this._numericFormat; for (i = 0; i < numTickValues; i++) { if (i < numLabels) { label = labels[i]; } else { label = new Label(); labels.push(label); labelsContainer.addChild(label); } label.text = labelFormat(majorTickValues[i]); Style.applyStyle(label, labelStyle); label.visibility = showLabels ? Visibility.VISIBLE : Visibility.COLLAPSED; label.measure(childSize); } } for (i = labels.length - 1; i >= numTickValues; i--) { label = labels.pop(); labelsContainer.removeChild(label); } // value var valueLabel:Label = this._valueLabel; if (orientation == Orientation.X) { childSize.width = availableSize.width / 2; if (valuePlacement < 0) childSize.height = Math.max(availableSize.height / 2 + valuePlacement, 0); else childSize.height = Math.max(availableSize.height / 2 - valuePlacement, 0); } else { childSize.height = availableSize.height / 2; if (valuePlacement < 0) childSize.width = Math.max(availableSize.width / 2 + valuePlacement, 0); else childSize.width = Math.max(availableSize.width / 2 - valuePlacement, 0); } if (valueFormat == null) valueFormat = usePercentageValue ? this._percentageFormat : this._numericFormat; valueLabel.text = valueFormat(fillerValue); Style.applyStyle(valueLabel, valueStyle); valueLabel.visibility = showValue ? Visibility.VISIBLE : Visibility.COLLAPSED; valueLabel.measure(childSize); return super.measureOverride(availableSize); } protected override function renderChartOverride(chartWidth:Number, chartHeight:Number, legend:ILegend) : void { var orientation:String = this._orientation.value; var fillerBrushPalette:IBrushPalette = this._fillerBrushPalette.value; var fillerStyle:Style = this._fillerStyle.value; var fillerPlacement1:Number = this._fillerPlacement1.value; var fillerPlacement2:Number = this._fillerPlacement2.value; var rangePadding:Number = this._rangePadding.value; var majorTickBrush:IBrush = this._majorTickBrush.value; var majorTickStyle:Style = this._majorTickStyle.value; var majorTickPlacement1:Number = this._majorTickPlacement1.value; var majorTickPlacement2:Number = this._majorTickPlacement2.value; var minorTickBrush:IBrush = this._minorTickBrush.value; var minorTickStyle:Style = this._minorTickStyle.value; var minorTickPlacement1:Number = this._minorTickPlacement1.value; var minorTickPlacement2:Number = this._minorTickPlacement2.value; var labelPlacement:Number = this._labelPlacement.value; var valuePlacement:Number = this._valuePlacement.value; var warningBrush:IBrush = this._warningBrush.value; var warningShape:IShape = this._warningShape.value; var warningStyle:Style = this._warningStyle.value; var warningPlacement:Number = this._warningPlacement.value; var warningSize:Number = this._warningSize.value; var foregroundBrush:IBrush = this._foregroundBrush.value; var foregroundStyle:Style = this._foregroundStyle.value; var foregroundPlacement1:Number = this._foregroundPlacement1.value; var foregroundPlacement2:Number = this._foregroundPlacement2.value; var foregroundPadding:Number = this._foregroundPadding.value; var backgroundBrush:IBrush = this._backgroundBrush.value; var backgroundStyle:Style = this._backgroundStyle.value; var backgroundPlacement1:Number = this._backgroundPlacement1.value; var backgroundPlacement2:Number = this._backgroundPlacement2.value; var backgroundPadding:Number = this._backgroundPadding.value; var layers:Array = this._layers.value; var showMajorTicks:Boolean = this._showMajorTicks.value; var showMinorTicks:Boolean = this._showMinorTicks.value; var fillerPosition:Number = this._fillerPosition; var rangeFields:Array = this._rangeFields; var rangePositions:Array = this._rangePositions; var majorTickPositions:Array = this._majorTickPositions; var minorTickPositions:Array = this._minorTickPositions; var graphics:Graphics; // minor ticks graphics = this._minorTicks.graphics; graphics.clear(); if (showMinorTicks) { this._drawTicks(graphics, minorTickBrush, orientation, rangePadding, chartWidth, chartHeight, minorTickPlacement1, minorTickPlacement2, minorTickPositions); if (!showMajorTicks) this._drawTicks(graphics, minorTickBrush, orientation, rangePadding, chartWidth, chartHeight, minorTickPlacement1, minorTickPlacement2, majorTickPositions); } Style.applyStyle(this._minorTicks, minorTickStyle); // major ticks graphics = this._majorTicks.graphics; graphics.clear(); if (showMajorTicks) this._drawTicks(graphics, majorTickBrush, orientation, rangePadding, chartWidth, chartHeight, majorTickPlacement1, majorTickPlacement2, majorTickPositions); Style.applyStyle(this._majorTicks, majorTickStyle); // labels this._placeLabels(this._labels, orientation, rangePadding, chartWidth, chartHeight, labelPlacement, majorTickPositions); // value this._placeLabel(this._valueLabel, orientation, rangePadding, chartWidth, chartHeight, valuePlacement, fillerPosition); // warning light graphics = this._warningLight.graphics; graphics.clear(); this._drawWarningLight(graphics, warningBrush, warningShape, orientation, rangePadding, chartWidth, chartHeight, warningPlacement, warningSize, fillerPosition); Style.applyStyle(this._warningLight, warningStyle); // filler this._updateFiller(this._filler, fillerBrushPalette, orientation, rangePadding, chartWidth, chartHeight, fillerPlacement1, fillerPlacement2, rangePositions, rangeFields, fillerPosition); Style.applyStyle(this._filler, fillerStyle); // foreground graphics = this._foreground.graphics; graphics.clear(); this._drawLayer(graphics, foregroundBrush, orientation, chartWidth, chartHeight, foregroundPlacement1, foregroundPlacement2, foregroundPadding); Style.applyStyle(this._foreground, foregroundStyle); // background graphics = this._background.graphics; graphics.clear(); this._drawLayer(graphics, backgroundBrush, orientation, chartWidth, chartHeight, backgroundPlacement1, backgroundPlacement2, backgroundPadding); Style.applyStyle(this._background, backgroundStyle); // layers this._updateLayers(layers); } // Private Methods private function _drawTicks(graphics:Graphics, brush:IBrush, orientation:String, rangePadding:Number, chartWidth:Number, chartHeight:Number, placement1:Number, placement2:Number, tickPositions:Array) : void { if (!brush) brush = new SolidStrokeBrush(1, 0x000000); var position:Number; var x1:Number; var y1:Number; var x2:Number; var y2:Number; var matrix:Matrix; var brushBounds:Array; if (orientation == Orientation.X) { rangePadding = Math.min(rangePadding, chartWidth / 2); chartWidth -= rangePadding * 2; x1 = Math.round(rangePadding); x2 = Math.round(rangePadding + chartWidth); y1 = Math.round(chartHeight / 2 + placement1); y2 = Math.round(chartHeight / 2 + placement2); matrix = new Matrix(0, 1, -1, 0); brushBounds = [ new Point(x1, y1), new Point(x2, y1), new Point(x2, y2), new Point(x1, y2) ]; for each (position in tickPositions) { x1 = x2 = Math.round(rangePadding + chartWidth * position); brush.beginBrush(graphics, matrix, brushBounds); brush.moveTo(x1, y1); brush.lineTo(x2, y2); brush.endBrush(); } } else { rangePadding = Math.min(rangePadding, chartHeight / 2); chartHeight -= rangePadding * 2; x1 = Math.round(chartWidth / 2 + placement1); x2 = Math.round(chartWidth / 2 + placement2); y1 = Math.round(rangePadding); y2 = Math.round(rangePadding + chartHeight); brushBounds = [ new Point(x1, y1), new Point(x2, y1), new Point(x2, y2), new Point(x1, y2) ]; for each (position in tickPositions) { y1 = y2 = Math.round(rangePadding + chartHeight * (1 - position)); brush.beginBrush(graphics, null, brushBounds); brush.moveTo(x1, y1); brush.lineTo(x2, y2); brush.endBrush(); } } } private function _drawWarningLight(graphics:Graphics, brush:IBrush, shape:IShape, orientation:String, rangePadding:Number, chartWidth:Number, chartHeight:Number, placement:Number, size:Number, position:Number) : void { if ((position >= 0) && (position <= 1)) return; if (!brush) brush = new SolidFillBrush(0x000000); if (!shape) shape = new EllipseShape(); size /= 2; if (placement < 0) placement -= size; else placement += size; var x:Number; var y:Number; if (orientation == Orientation.X) { rangePadding = Math.min(rangePadding, chartWidth / 2); x = (position < 0) ? Math.round(rangePadding) : Math.round(chartWidth - rangePadding); y = Math.round(chartHeight / 2 + placement); } else { rangePadding = Math.min(rangePadding, chartHeight / 2); x = Math.round(chartWidth / 2 + placement); y = (position < 0) ? Math.round(chartHeight - rangePadding) : Math.round(rangePadding); } var x1:Number = Math.round(x - size); var x2:Number = Math.round(x + size); var y1:Number = Math.round(y - size); var y2:Number = Math.round(y + size); shape.draw(graphics, x1, y1, x2 - x1, y2 - y1, brush); } private function _drawLayer(graphics:Graphics, brush:IBrush, orientation:String, chartWidth:Number, chartHeight:Number, placement1:Number, placement2:Number, padding:Number) : void { if (!brush) return; var x1:Number; var y1:Number; var x2:Number; var y2:Number; var matrix:Matrix; if (orientation == Orientation.X) { padding = Math.min(padding, chartWidth / 2); x1 = Math.round(padding); x2 = Math.round(chartWidth - padding); y1 = Math.round(chartHeight / 2 + placement1); y2 = Math.round(chartHeight / 2 + placement2); matrix = new Matrix(0, 1, -1, 0); } else { padding = Math.min(padding, chartHeight / 2); x1 = Math.round(chartWidth / 2 + placement1); x2 = Math.round(chartWidth / 2 + placement2); y1 = Math.round(padding); y2 = Math.round(chartHeight - padding); } brush.beginBrush(graphics, matrix); DrawingUtils.drawRectangle(brush, x1, y1, x2 - x1, y2 - y1); brush.endBrush(); } private function _placeLabels(labels:Array, orientation:String, rangePadding:Number, chartWidth:Number, chartHeight:Number, placement:Number, positions:Array) : void { var numLabels:int = Math.min(labels.length, positions.length); var numOverlaps:int = 0; var labelBounds:Array = new Array(numLabels); var label:Label; var bounds1:Rectangle; var bounds2:Rectangle; var position:Number; var i:int; var j:int; // place labels for (i = 0; i < numLabels; i++) { label = labels[i]; position = positions[i]; labelBounds[i] = this._placeLabel(label, orientation, rangePadding, chartWidth, chartHeight, placement, position); } // compute numOverlaps for (i = 0; i < numLabels; i++) { bounds1 = labelBounds[i]; for (j = i + 1; j < numLabels; j++) { bounds2 = labelBounds[j]; if (!bounds2.intersects(bounds1)) break; numOverlaps = Math.max(numOverlaps, j - i); } } // hide overlapping labels if (numOverlaps > 0) { numOverlaps++; for (i = 0; i < numLabels; i++) { if ((numOverlaps == numLabels) || ((i % numOverlaps) != 0)) { label = labels[numLabels - i - 1]; label.visible = false; } } } } private function _placeLabel(label:Label, orientation:String, rangePadding:Number, chartWidth:Number, chartHeight:Number, placement:Number, position:Number) : Rectangle { var labelBounds:Rectangle = new Rectangle(0, 0, label.measuredWidth, label.measuredHeight); if (orientation == Orientation.X) { rangePadding = Math.min(rangePadding, chartWidth / 2); chartWidth -= rangePadding * 2; labelBounds.x = rangePadding + chartWidth * position - labelBounds.width / 2; if (placement > 0) labelBounds.y = chartHeight / 2 + placement; else if (placement < 0) labelBounds.y = chartHeight / 2 + placement - labelBounds.height; else labelBounds.y = (chartHeight - labelBounds.height) / 2; } else { rangePadding = Math.min(rangePadding, chartHeight / 2); chartHeight -= rangePadding * 2; labelBounds.y = rangePadding + chartHeight * (1 - position) - labelBounds.height / 2; if (placement > 0) labelBounds.x = chartWidth / 2 + placement; else if (placement < 0) labelBounds.x = chartWidth / 2 + placement - labelBounds.width; else labelBounds.x = (chartWidth - labelBounds.width) / 2; } // place label at snapped position label.x = Math.round(labelBounds.x); label.y = Math.round(labelBounds.y); return labelBounds; } private function _updateFiller(filler:Filler, brushPalette:IBrushPalette, orientation:String, rangePadding:Number, chartWidth:Number, chartHeight:Number, placement1:Number, placement2:Number, rangePositions:Array, rangeFields:Array, position:Number) : void { filler.label = this._valueLabel; filler.brushPalette = brushPalette; filler.orientation = orientation; filler.rangePadding = rangePadding; filler.chartWidth = chartWidth; filler.chartHeight = chartHeight; filler.placement1 = placement1; filler.placement2 = placement2; filler.rangePositions = rangePositions; filler.rangeFields = rangeFields; filler.position = position; filler.update(); } private function _updateLayers(layers:Array = null) : void { var layerNames:Array = [ ""background"", ""minorTicks"", ""majorTicks"", ""labels"", ""warning"", ""filler"", ""value"", ""foreground"" ]; var layerSprites:Array = [ this._background, this._minorTicks, this._majorTicks, this._labelsContainer, this._warningLight, this._filler, this._valueLabel, this._foreground ]; var layerName:String; var layerSprite:DisplayObject; var index:int; for each (layerName in layers) { index = layerNames.indexOf(layerName); if (index >= 0) { layerNames.splice(index, 1); layerNames.push(layerName); layerSprite = layerSprites[index]; layerSprites.splice(index, 1); layerSprites.push(layerSprite); } } for each (layerSprite in layerSprites) this.addChild(layerSprite); } private function _computeTickPositions(minimum:Number, maximum:Number, majorUnit:Number, minorUnit:Number, majorTickValues:Array, majorTickPositions:Array, minorTickPositions:Array) : void { var maxMajorUnits:int = 50; var maxMinorUnits:int = 20; var range:Number = maximum - minimum; if ((range != range) || (range <= 0) || (range == Infinity)) return; // get majorUnit, compute auto units if necessary if (majorUnit != majorUnit) majorUnit = this._computeAutoUnits(range); // verify majorUnit is between zero and infinity if ((majorUnit <= 0) || (majorUnit == Infinity)) return; // scale majorUnit if numMajorUnits is greater than maxMajorUnits var numMajorUnits:Number = 1 + Math.floor(range / majorUnit); majorUnit *= Math.ceil(numMajorUnits / maxMajorUnits); // compute major positions var majorTick:Number = Math.round(minimum / majorUnit); var majorValue:Number; while (true) { majorValue = majorUnit * majorTick; if (NumberUtil.approxLessThanOrEqual(majorValue, maximum)) { if (NumberUtil.approxGreaterThanOrEqual(majorValue, minimum)) { majorTickValues.push(majorValue); majorTickPositions.push((majorValue - minimum) / range); } } else { break; } majorTick++; } // get minorUnit, compute auto units if necessary if (minorUnit != minorUnit) minorUnit = this._computeAutoUnits(majorUnit); // verify minorUnit is between zero and majorUnit if ((minorUnit <= 0) || (minorUnit >= majorUnit)) return; // scale minorUnit if numMinorUnits is greater than maxMinorUnits var numMinorUnits:Number = 1 + Math.floor(majorUnit / minorUnit); minorUnit *= Math.ceil(numMinorUnits / maxMinorUnits); // compute minor positions var minorTick:Number = Math.round(minimum / minorUnit); var minorValue:Number; while (true) { minorValue = minorUnit * minorTick; if (NumberUtil.approxLessThanOrEqual(minorValue, maximum)) { if (NumberUtil.approxGreaterThanOrEqual(minorValue, minimum)) { majorValue = Math.round(minorValue / majorUnit) * majorUnit; if (!NumberUtil.approxEqual(minorValue, majorValue)) minorTickPositions.push((minorValue - minimum) / range); } } else { break; } minorTick++; } } private function _computeAutoUnits(range:Number) : Number { var significand:Number = range / 10; var exponent:Number = 0; if (significand > 0) { var str:String = significand.toExponential(20); var eIndex:int = str.indexOf(""e""); if (eIndex >= 0) { significand = Number(str.substring(0, eIndex)); exponent = Number(str.substring(eIndex + 1, str.length)); } } significand = Math.ceil(significand); if (significand > 5) significand = 10; else if (significand > 2) significand = 5; return significand * Math.pow(10, exponent); } private function _numericFormat(value:Number) : String { return String(Math.round(value * 100) / 100); } private function _percentageFormat(value:Number) : String { return this._numericFormat(value) + ""%""; } } } import com.jasongatt.graphics.brushes.DrawingUtils; import com.jasongatt.graphics.brushes.IBrush; import com.jasongatt.graphics.brushes.SolidFillBrush; import com.jasongatt.layout.Orientation; import com.jasongatt.utils.NumberUtil; import com.splunk.controls.Label; import com.splunk.palettes.brush.IBrushPalette; import flash.display.Graphics; import flash.display.Shape; import flash.events.Event; import flash.geom.Matrix; import flash.geom.Point; class Filler extends Shape { // Public Properties public var label:Label; public var brushPalette:IBrushPalette; public var orientation:String; public var rangePadding:Number; public var chartWidth:Number; public var chartHeight:Number; public var placement1:Number; public var placement2:Number; public var rangePositions:Array; public var rangeFields:Array; public var position:Number; // Private Properties private var _currentPosition:Number = 0; private var _isAnimating:Boolean = false; // Constructor public function Filler() { } // Public Methods public function update() : void { var label:Label = this.label; var brushPalette:IBrushPalette = this.brushPalette; var orientation:String = this.orientation; var rangePadding:Number = this.rangePadding; var chartWidth:Number = this.chartWidth; var chartHeight:Number = this.chartHeight; var placement1:Number = this.placement1; var placement2:Number = this.placement2; var rangePositions:Array = this.rangePositions; var rangeFields:Array = this.rangeFields; var position:Number = this.position; var numRangePositions:int = (rangePositions && rangeFields) ? Math.min(rangePositions.length, rangeFields.length) - 1 : 0; var brush:IBrush; var matrix:Matrix; var brushBounds:Array; var x1:Number; var y1:Number; var x2:Number; var y2:Number; if (NumberUtil.approxEqual(this._currentPosition, position, 0.001)) { this._currentPosition = position; if (this._isAnimating) { this._isAnimating = false; this.removeEventListener(Event.ENTER_FRAME, this._self_enterFrame); } } else if (!this._isAnimating) { this._isAnimating = true; this.addEventListener(Event.ENTER_FRAME, this._self_enterFrame); } if (orientation == Orientation.X) { rangePadding = Math.min(rangePadding, chartWidth / 2); chartWidth -= rangePadding * 2; x1 = Math.round(rangePadding); x2 = Math.round(rangePadding + chartWidth * NumberUtil.minMax(this._currentPosition, 0, 1)); y1 = Math.round(chartHeight / 2 + placement1); y2 = Math.round(chartHeight / 2 + placement2); matrix = new Matrix(0, 1, -1, 0); brushBounds = [ new Point(x1, y1), new Point(Math.round(rangePadding + chartWidth), y1), new Point(Math.round(rangePadding + chartWidth), y2), new Point(x1, y2) ]; if (label) label.x = Math.round(Math.max(x2 - label.measuredWidth, rangePadding)); } else { rangePadding = Math.min(rangePadding, chartHeight / 2); chartHeight -= rangePadding * 2; x1 = Math.round(chartWidth / 2 + placement1); x2 = Math.round(chartWidth / 2 + placement2); y1 = Math.round(rangePadding + chartHeight * (1 - NumberUtil.minMax(this._currentPosition, 0, 1))); y2 = Math.round(rangePadding + chartHeight); brushBounds = [ new Point(x1, Math.round(rangePadding)), new Point(x2, Math.round(rangePadding)), new Point(x2, y2), new Point(x1, y2) ]; if (label) label.y = Math.round(Math.min(y1, rangePadding + chartHeight - label.measuredHeight)); } for (var i:int = 0; i < numRangePositions; i++) { if ((position < rangePositions[i + 1]) || (i == (numRangePositions - 1))) { brush = brushPalette ? brushPalette.getBrush(rangeFields[i], i, numRangePositions) : null; break; } } if (!brush) brush = new SolidFillBrush(0x000000); var graphics:Graphics = this.graphics; graphics.clear(); brush.beginBrush(graphics, matrix, brushBounds); DrawingUtils.drawRectangle(brush, x1, y1, x2 - x1, y2 - y1); brush.endBrush(); } // Private Methods private function _self_enterFrame(e:Event) : void { this._currentPosition += (this.position - this._currentPosition) * 0.5; this.update(); } } ",12162,False,2134.910804849599,median "[[install-config-router-default-haproxy]] = Using the Default HAProxy Router {product-author} {product-version} :data-uri: :icons: :experimental: :toc: macro :toc-title: :prewrap!: toc::[] == Overview The `oc adm router` command is provided with the administrator CLI to simplify the tasks of setting up routers in a new installation. The `oc adm router` command creates the service and deployment configuration objects. Use the `--service-account` option to specify the service account the router will use to contact the master. The xref:../../install_config/router/index.adoc#creating-the-router-service-account[router service account] can be created in advance or created by the `oc adm router --service-account` command. Every form of communication between {product-title} components is secured by TLS and uses various certificates and authentication methods. The `--default-certificate` .pem format file can be supplied or one is created by the `oc adm router` command. When xref:../../architecture/networking/routes.adoc#[routes] are created, the user can provide route certificates that the router will use when handling the route. [IMPORTANT] ==== When deleting a router, ensure the deployment configuration, service, and secret are deleted as well. ==== Routers are deployed on specific nodes. This makes it easier for the cluster administrator and external network manager to coordinate which IP address will run a router and which traffic the router will handle. The routers are deployed on specific nodes by using xref:adding-nodeselector-to-a-deployment[node selectors]. [IMPORTANT] ==== Routers use host networking by default, and they directly attach to port 80 and 443 on all interfaces on a host. Restrict routers to hosts where ports 80/443 are available and not being consumed by another service, and set this using xref:adding-nodeselector-to-a-deployment[node selectors] and the xref:../../admin_guide/scheduling/scheduler.adoc#admin-guide-scheduler[scheduler configuration]. As an example, you can achieve this by dedicating infrastructure nodes to run services such as routers. ==== [IMPORTANT] ==== It is recommended to use separate distinct *openshift-router* service account with your router. This can be provided using the `--service-account` flag to the `oc adm router` command. ifdef::openshift-enterprise[] ---- $ oc adm router --dry-run --service-account=router //<1> ---- endif::[] ifdef::openshift-origin[] ---- $ oc adm router --dry-run --service-account=router //<1> ---- endif::[] <1> `--service-account` is the name of a xref:../../admin_guide/service_accounts.adoc#admin-guide-service-accounts[service account] for the *openshift-router*. ifdef::openshift-origin[] It is recommended using an *openshift-router* specific service account with appropriate permissions. endif::[] ==== [IMPORTANT] ==== Router pods created using `oc adm router` have default resource requests that a node must satisfy for the router pod to be deployed. In an effort to increase the reliability of infrastructure components, the default resource requests are used to increase the QoS tier of the router pods above pods without resource requests. The default values represent the observed minimum resources required for a basic router to be deployed and can be edited in the routers deployment configuration and you may want to increase them based on the load of the router. ==== [[deploy-router-create-router]] == Creating a Router If the router does not exist, run the following to create a router: ifdef::openshift-enterprise[] ---- $ oc adm router --replicas= --service-account=router ---- endif::[] ifdef::openshift-origin[] ---- $ oc adm router --replicas= --service-account=router ---- endif::[] `--replicas` is usually `1` unless a xref:../../admin_guide/high_availability.adoc#[high availability] configuration is being created. To find the host IP address of the router: ---- $ oc get po --template={{.status.hostIP}} ---- You can also xref:creating-router-shards[use router shards] to ensure that the router is filtered to specific namespaces or routes, or xref:../../architecture/networking/routes.adoc#env-variables[set any environment variables] after router creation. In this case create a router for each shard. [[basic-router-commands]] == Other Basic Router Commands [[deploy-router-check-default]] Checking the Default Router:: ifdef::openshift-enterprise[] The default router service account, named *router*, is automatically created during cluster installations. To verify that this account already exists: endif::[] ifdef::openshift-origin[] First, ensure you have xref:../../install_config/router/index.adoc#creating-the-router-service-account[created the router service account] before deploying a router. To check if a default router, named *router*, already exists: endif::[] ifdef::openshift-enterprise[] ---- $ oc adm router --dry-run --service-account=router ---- endif::[] ifdef::openshift-origin[] ---- $ oc adm router --dry-run --service-account=router ---- endif::[] [[deploy-router-viewing-default]] Viewing the Default Router:: To see what the default router would look like if created: ifdef::openshift-enterprise[] ---- $ oc adm router --dry-run -o yaml --service-account=router ---- endif::[] ifdef::openshift-origin[] ---- $ oc adm router --dry-run -o yaml --service-account=router ---- endif::[] [[deploy-router-to-labeled-nodes]] Deploying the Router to a Labeled Node:: To deploy the router to any node(s) that match a specified xref:../../admin_guide/manage_nodes.adoc#updating-labels-on-nodes[node label]: ifdef::openshift-enterprise[] ---- $ oc adm router --replicas= --selector=