///////////////////////////////////////////////////////////////////////////
// Copyright (c) 2010-2011 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////////
package com.esri.viewer.utils
{

import com.esri.ags.components.IdentityManager;
import com.esri.ags.events.PortalEvent;
import com.esri.ags.portal.Portal;
import com.esri.ags.portal.supportClasses.PortalGroup;
import com.esri.ags.portal.supportClasses.PortalItem;
import com.esri.ags.portal.supportClasses.PortalQueryParameters;
import com.esri.ags.portal.supportClasses.PortalQueryResult;
import com.esri.viewer.AppEvent;
import com.esri.viewer.ConfigData;

import flash.events.Event;
import flash.events.EventDispatcher;
import flash.utils.Dictionary;

import mx.resources.ResourceManager;
import mx.rpc.AsyncResponder;
import mx.rpc.Fault;
import mx.rpc.events.FaultEvent;
import mx.utils.ObjectUtil;

public class PortalBasemapAppender extends EventDispatcher
{
    private const PORTAL_BASEMAP_APPENDER:String = "PortalBasemapAppender";

    private var configData:ConfigData;
    private var portalURL:String;

    private var portalItemOrder:Array;
    private var portalItemToLabel:Dictionary;
    private var processedArcGISBasemaps:Array;
    private var totalBasemaps:int;
    private var totalPossibleArcGISBasemaps:int;

    private var comparableDefaultBasemapObjects:Array;
    private var defaultBasemapTitle:String;

    private var cultureCode:String;

    public function PortalBasemapAppender(portalURL:String, configData:ConfigData)
    {
        this.portalURL = portalURL;
        this.configData = configData;
    }

    public function fetchAndAppendPortalBasemaps():void
    {
        const idMgrEnabled:Boolean = IdentityManager.instance.enabled;
        var portal:Portal = new Portal();
        // the Portal constructor enables the IdentityManager so restore it back to what it was
        IdentityManager.instance.enabled = idMgrEnabled;

        portal.addEventListener(PortalEvent.LOAD, portal_loadHandler);
        portal.addEventListener(FaultEvent.FAULT, portal_faultHandler);

        cultureCode = toCultureCode(ResourceManager.getInstance().localeChain[0]);
        portal.load(portalURL, cultureCode);
    }

    protected function portal_loadHandler(event:PortalEvent):void
    {
        var portal:Portal = event.target as Portal;
        portal.removeEventListener(PortalEvent.LOAD, portal_loadHandler);
        portal.removeEventListener(FaultEvent.FAULT, portal_faultHandler);

        comparableDefaultBasemapObjects = getComparableBasemapObjects(portal.info.defaultBasemap);
        var queryParams:PortalQueryParameters = PortalQueryParameters.forQuery(portal.info.basemapGalleryGroupQuery);
        portal.queryGroups(queryParams, new AsyncResponder(portal_queryGroupsResultHandler, portal_queryGroupsFaultHandler, portal));
    }

    protected function portal_queryGroupsResultHandler(queryResult:PortalQueryResult, portal:Portal):void
    {
        if (queryResult.results.length > 0)
        {
            var portalGroup:PortalGroup = queryResult.results[0];
            var queryParams:PortalQueryParameters = PortalQueryParameters.forItemsInGroup(portalGroup.id).withLimit(50).withSortField("name");
            portal.queryItems(queryParams, new AsyncResponder(portal_queryItemsResultHandler, portal_queryItemsFaultHandler));
        }
        else
        {
            dispatchComplete();
        }
    }

    private function portal_queryItemsResultHandler(queryResult:PortalQueryResult, token:Object = null):void
    {
        const resultItems:Array = queryResult.results;
        totalPossibleArcGISBasemaps = resultItems.length;
        portalItemOrder = [];
        portalItemToLabel = new Dictionary(true);
        processedArcGISBasemaps = [];
        totalBasemaps = configData.basemaps.length;
        for each (var portalItem:PortalItem in resultItems)
        {
            portalItemOrder.push(portalItem);
            portalItem.getJSONData(new AsyncResponder(portalItem_getJSONDataResultHandler,
                                                      portalItem_getJSONDataFaultHandler,
                                                      portalItem));
        }
    }

    private function portalItem_getJSONDataResultHandler(itemData:Object, item:PortalItem):void
    {
        createBasemapLayerObject(itemData, item);
        if (isDefaultBasemap(itemData.baseMap))
        {
            defaultBasemapTitle = itemData.baseMap.title;
        }
        updateTotalArcGISBasemaps();
    }

    private function createBasemapLayerObject(itemData:Object, item:PortalItem):void
    {
        if (!itemData)
        {
            return;
        }

        var basemapObject:Object = itemData.baseMap;
        var basemapLayerObjects:Array = basemapObject.baseMapLayers;
        if (!(basemapObject && basemapLayerObjects))
        {
            return;
        }

        var title:String = basemapObject.title;
        var iconURL:String = item.thumbnailURL;
        var existingBasemapLayerObject:Object = findBasemapLayerObjectById(title);
        if (existingBasemapLayerObject)
        {
            existingBasemapLayerObject.icon = iconURL;
            return;
        }

        portalItemToLabel[item] = title;
        var basemapLayerObject:Object = basemapLayerObjects[0];
        addBasemapLayerObject(baseMapLayerObjectToLayerXML(title,
                                                           basemapLayerObject,
                                                           iconURL));

        var totalBaseMapLayers:int = basemapLayerObjects.length;
        if (totalBaseMapLayers > 1)
        {
            basemapLayerObject = basemapLayerObjects[1];
            addBasemapLayerObject(baseMapLayerObjectToLayerXML(title,
                                                               basemapLayerObject,
                                                               iconURL));
        }
    }

    private function isDefaultBasemap(basemapObject:Object):Boolean
    {
        var comparableBasemapObjects:Array = getComparableBasemapObjects(basemapObject);

        return (ObjectUtil.compare(comparableBasemapObjects, comparableDefaultBasemapObjects) == 0);
    }

    private function getComparableBasemapObjects(basemapObject:Object):Array
    {
        var basemapLayerObjects:Array = basemapObject.baseMapLayers;
        var comparableBasemapObjects:Array = [];
        var comparableBasemapLayerObject:Object;

        for each (var basemapLayerObject:Object in basemapLayerObjects)
        {
            comparableBasemapLayerObject = {};

            if (basemapLayerObject.url)
            {
                comparableBasemapLayerObject.url = basemapLayerObject.url;
            }
            if (basemapLayerObject.type)
            {
                comparableBasemapLayerObject.type = basemapLayerObject.type;
            }

            comparableBasemapObjects.push(comparableBasemapLayerObject);
        }

        return comparableBasemapObjects;
    }

    private function findBasemapLayerObjectById(id:String):Object
    {
        var layerObjectResult:Object;

        var basemapLayerObjects:Array = configData.basemaps;
        for each (var layerObject:Object in basemapLayerObjects)
        {
            if (layerObject.layer && (layerObject.layer.id == id))
            {
                layerObjectResult = layerObject;
                break;
            }
        }

        return layerObjectResult;
    }

    private function updateTotalArcGISBasemaps():void
    {
        totalPossibleArcGISBasemaps--;
        if (totalPossibleArcGISBasemaps == 0)
        {
            addArcGISBasemapsToConfig();
            dispatchComplete();
        }
    }

    private function dispatchComplete():void
    {
        dispatchEvent(new Event(Event.COMPLETE));
    }

    private function addArcGISBasemapsToConfig():void
    {
        var hasBasemaps:Boolean = (configData.basemaps.length > 0);

        if (!hasBasemaps)
        {
            if (defaultBasemapTitle)
            {
                setDefaultBasemapVisible();
            }
            else
            {
                setFirstBasemapVisible();
            }
        }

        addBasemapsInOrder();
    }

    private function setDefaultBasemapVisible():void
    {
        for each (var layerObject:Object in processedArcGISBasemaps)
        {
            if (defaultBasemapTitle == layerObject.label)
            {
                layerObject.visible = true;
            }
        }
    }

    private function setFirstBasemapVisible():void
    {
        if (!portalItemOrder || portalItemOrder.length == 0)
        {
            return;
        }

        var firstBasemapLabel:String = portalItemToLabel[portalItemOrder[0]];
        for each (var layerObject:Object in processedArcGISBasemaps)
        {
            if (layerObject.label == firstBasemapLabel)
            {
                layerObject.visible = true;
            }
        }
    }

    private function addBasemapsInOrder():void
    {
        for each (var portalItem:PortalItem in portalItemOrder)
        {
            for each (var layerObject:Object in processedArcGISBasemaps)
            {
                if (layerObject.label == portalItemToLabel[portalItem])
                {
                    configData.basemaps.push(layerObject);
                }
            }
        }
    }

    private function addBasemapLayerObject(layerXML:XML):void
    {
        if (layerXML)
        {
            processedArcGISBasemaps.push(LayerObjectUtil.getLayerObject(layerXML,
                                                                        totalBasemaps++,
                                                                        false,
                                                                        configData.bingKey));
        }
    }

    private function baseMapLayerObjectToLayerXML(title:String, basemapLayerObject:Object, iconURL:String = null):XML
    {
        var layerXML:XML;
        const url:String = basemapLayerObject.url;
        const type:String = basemapLayerObject.type;

        if (url)
        {
            layerXML = createTiledLayerXML(title, iconURL, url, basemapLayerObject, false);
        }
        else if (isAllowedType(type))
        {
            layerXML = createNonEsriLayerXML(title, iconURL, basemapLayerObject, false, type);
        }

        return layerXML;
    }

    private function createTiledLayerXML(title:String, iconURL:String, url:String, basemapLayerObject:Object, visible:Boolean):XML
    {
        var layerXML:XML = <layer label={title}
                type="tiled"
                icon={iconURL}
                url={url}
                alpha={basemapLayerObject.opacity}
                visible={visible}/>;

        return layerXML;
    }

    private function isAllowedType(type:String):Boolean
    {
        return type == "OpenStreetMap" ||
            (isBingBasemap(type) && hasBingKey());
    }

    private function createNonEsriLayerXML(title:String, iconURL:String, basemapLayerObject:Object, visible:Boolean, type:String):XML
    {
        var layerXML:XML = <layer label={title}
                icon={iconURL}
                type={toViewerNonEsriLayerType(basemapLayerObject.type)}
                alpha={basemapLayerObject.opacity}
                visible={visible}/>;

        if (isBingBasemap(type))
        {
            layerXML.@style = mapBingStyleFromBasemapType(type);
            layerXML.@culture = cultureCode;
        }

        return layerXML;
    }

    private function toViewerNonEsriLayerType(type:String):String
    {
        var viewerType:String;
        if (type == "OpenStreetMap")
        {
            viewerType = "osm";
        }
        else if (isBingBasemap(type))
        {
            viewerType = "bing";
        }

        return viewerType;
    }

    private function isBingBasemap(type:String):Boolean
    {
        return type && type.indexOf('BingMaps') > -1;
    }

    private function hasBingKey():Boolean
    {
        var bingKey:String = configData.bingKey;
        return (bingKey != null && bingKey.length > 0);
    }

    private function mapBingStyleFromBasemapType(type:String):String
    {
        if (type == 'BingMapsAerial')
        {
            return 'aerial';
        }
        else if (type == 'BingMapsHybrid')
        {
            return 'aerialWithLabels';
        }
        else
        {
            //default - BingMapsRoad
            return 'road';
        }
    }

    private function portalItem_getJSONDataFaultHandler(fault:Fault, token:Object = null):void
    {
        AppEvent.dispatch(AppEvent.APP_ERROR,
                          LocalizationUtil.getDefaultString("couldNotFetchBasemapData",
                                                            fault.faultString));
        updateTotalArcGISBasemaps();
    }

    private function portal_queryGroupsFaultHandler(fault:Fault, token:Object = null):void
    {
        AppEvent.showError(LocalizationUtil.getDefaultString("couldNotQueryPortal"), PORTAL_BASEMAP_APPENDER);
        dispatchComplete();
    }

    private function portal_queryItemsFaultHandler(fault:Fault, token:Object = null):void
    {
        AppEvent.showError(LocalizationUtil.getDefaultString("couldNotQueryPortalItems"), PORTAL_BASEMAP_APPENDER);
        dispatchComplete();
    }

    private function portal_faultHandler(event:FaultEvent):void
    {
        var portal:Portal = event.target as Portal;
        portal.removeEventListener(PortalEvent.LOAD, portal_loadHandler);
        portal.removeEventListener(FaultEvent.FAULT, portal_faultHandler);

        AppEvent.showError(LocalizationUtil.getDefaultString("couldNotConnectToPortal"), PORTAL_BASEMAP_APPENDER);
        dispatchComplete();
    }

    private function toCultureCode(locale:String):String
    {
        return locale ? locale.replace('_', '-') : locale;
    }
}

}

///////////////////////////////////////////////////////////////////////////
// Copyright (c) 2010-2011 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////////
package com.esri.viewer.utils
{

import com.esri.ags.components.IdentityManager;
import com.esri.ags.events.PortalEvent;
import com.esri.ags.portal.Portal;
import com.esri.ags.portal.supportClasses.PortalGroup;
import com.esri.ags.portal.supportClasses.PortalItem;
import com.esri.ags.portal.supportClasses.PortalQueryParameters;
import com.esri.ags.portal.supportClasses.PortalQueryResult;
import com.esri.viewer.AppEvent;
import com.esri.viewer.ConfigData;

import flash.events.Event;
import flash.events.EventDispatcher;
import flash.utils.Dictionary;

import mx.resources.ResourceManager;
import mx.rpc.AsyncResponder;
import mx.rpc.Fault;
import mx.rpc.events.FaultEvent;
import mx.utils.ObjectUtil;

public class PortalBasemapAppender extends EventDispatcher
{
    private const PORTAL_BASEMAP_APPENDER:String = "PortalBasemapAppender";

    private var configData:ConfigData;
    private var portalURL:String;

    private var portalItemOrder:Array;
    private var portalItemToLabel:Dictionary;
    private var processedArcGISBasemaps:Array;
    private var totalBasemaps:int;
    private var totalPossibleArcGISBasemaps:int;

    private var comparableDefaultBasemapObjects:Array;
    private var defaultBasemapTitle:String;

    private var cultureCode:String;

    public function PortalBasemapAppender(portalURL:String, configData:ConfigData)
    {
        this.portalURL = portalURL;
        this.configData = configData;
    }

    public function fetchAndAppendPortalBasemaps():void
    {
        const idMgrEnabled:Boolean = IdentityManager.instance.enabled;
        var portal:Portal = new Portal();
        // the Portal constructor enables the IdentityManager so restore it back to what it was
        IdentityManager.instance.enabled = idMgrEnabled;

        portal.addEventListener(PortalEvent.LOAD, portal_loadHandler);
        portal.addEventListener(FaultEvent.FAULT, portal_faultHandler);

        cultureCode = toCultureCode(ResourceManager.getInstance().localeChain[0]);
        portal.load(portalURL, cultureCode);
    }

    protected function portal_loadHandler(event:PortalEvent):void
    {
        var portal:Portal = event.target as Portal;
        portal.removeEventListener(PortalEvent.LOAD, portal_loadHandler);
        portal.removeEventListener(FaultEvent.FAULT, portal_faultHandler);

        comparableDefaultBasemapObjects = getComparableBasemapObjects(portal.info.defaultBasemap);
        var queryParams:PortalQueryParameters = PortalQueryParameters.forQuery(portal.info.basemapGalleryGroupQuery);
        portal.queryGroups(queryParams, new AsyncResponder(portal_queryGroupsResultHandler, portal_queryGroupsFaultHandler, portal));
    }

    protected function portal_queryGroupsResultHandler(queryResult:PortalQueryResult, portal:Portal):void
    {
        if (queryResult.results.length > 0)
        {
            var portalGroup:PortalGroup = queryResult.results[0];
            var queryParams:PortalQueryParameters = PortalQueryParameters.forItemsInGroup(portalGroup.id).withLimit(50).withSortField("name");
            portal.queryItems(queryParams, new AsyncResponder(portal_queryItemsResultHandler, portal_queryItemsFaultHandler));
        }
        else
        {
            dispatchComplete();
        }
    }

    private function portal_queryItemsResultHandler(queryResult:PortalQueryResult, token:Object = null):void
    {
        const resultItems:Array = queryResult.results;
        totalPossibleArcGISBasemaps = resultItems.length;
        portalItemOrder = [];
        portalItemToLabel = new Dictionary(true);
        processedArcGISBasemaps = [];
        totalBasemaps = configData.basemaps.length;
        for each (var portalItem:PortalItem in resultItems)
        {
            portalItemOrder.push(portalItem);
            portalItem.getJSONData(new AsyncResponder(portalItem_getJSONDataResultHandler,
                                                      portalItem_getJSONDataFaultHandler,
                                                      portalItem));
        }
    }

    private function portalItem_getJSONDataResultHandler(itemData:Object, item:PortalItem):void
    {
        createBasemapLayerObjectFromWebMapItemAndData(item, itemData);
        if (isDefaultBasemap(itemData.baseMap))
        {
            defaultBasemapTitle = itemData.baseMap.title;
        }
        updateTotalArcGISBasemaps();
    }

    private function createBasemapLayerObjectFromWebMapItemAndData(item:PortalItem, itemData:Object):void
    {
        if (!itemData)
        {
            return;
        }

        var basemapObject:Object = itemData.baseMap;
        var basemapLayerObjects:Array = basemapObject.baseMapLayers;
        if (!(basemapObject && basemapLayerObjects))
        {
            return;
        }

        var title:String = basemapObject.title;
        var iconURL:String = item.thumbnailURL;
        var existingBasemapLayerObject:Object = findBasemapLayerObjectById(title);
        if (existingBasemapLayerObject)
        {
            existingBasemapLayerObject.icon = iconURL;
            return;
        }

        portalItemToLabel[item] = title;
        var basemapLayerObject:Object = basemapLayerObjects[0];
        addBasemapLayerObject(baseMapLayerObjectToLayerXML(title,
                                                           basemapLayerObject,
                                                           iconURL));

        var totalBaseMapLayers:int = basemapLayerObjects.length;
        if (totalBaseMapLayers > 1)
        {
            basemapLayerObject = basemapLayerObjects[1];
            addBasemapLayerObject(baseMapLayerObjectToLayerXML(title,
                                                               basemapLayerObject,
                                                               iconURL));
        }
    }

    private function isDefaultBasemap(basemapObject:Object):Boolean
    {
        var comparableBasemapObjects:Array = getComparableBasemapObjects(basemapObject);

        return (ObjectUtil.compare(comparableBasemapObjects, comparableDefaultBasemapObjects) == 0);
    }

    private function getComparableBasemapObjects(basemapObject:Object):Array
    {
        var basemapLayerObjects:Array = basemapObject.baseMapLayers;
        var comparableBasemapObjects:Array = [];
        var comparableBasemapLayerObject:Object;

        for each (var basemapLayerObject:Object in basemapLayerObjects)
        {
            comparableBasemapLayerObject = {};

            if (basemapLayerObject.url)
            {
                comparableBasemapLayerObject.url = basemapLayerObject.url;
            }
            if (basemapLayerObject.type)
            {
                comparableBasemapLayerObject.type = basemapLayerObject.type;
            }

            comparableBasemapObjects.push(comparableBasemapLayerObject);
        }

        return comparableBasemapObjects;
    }

    private function findBasemapLayerObjectById(id:String):Object
    {
        var layerObjectResult:Object;

        var basemapLayerObjects:Array = configData.basemaps;
        for each (var layerObject:Object in basemapLayerObjects)
        {
            if (layerObject.layer && (layerObject.layer.id == id))
            {
                layerObjectResult = layerObject;
                break;
            }
        }

        return layerObjectResult;
    }

    private function updateTotalArcGISBasemaps():void
    {
        totalPossibleArcGISBasemaps--;
        if (totalPossibleArcGISBasemaps == 0)
        {
            addArcGISBasemapsToConfig();
            dispatchComplete();
        }
    }

    private function dispatchComplete():void
    {
        dispatchEvent(new Event(Event.COMPLETE));
    }

    private function addArcGISBasemapsToConfig():void
    {
        var hasBasemaps:Boolean = (configData.basemaps.length > 0);

        if (!hasBasemaps)
        {
            if (defaultBasemapTitle)
            {
                setDefaultBasemapVisible();
            }
            else
            {
                setFirstBasemapVisible();
            }
        }

        addBasemapsInOrder();
    }

    private function setDefaultBasemapVisible():void
    {
        for each (var layerObject:Object in processedArcGISBasemaps)
        {
            if (defaultBasemapTitle == layerObject.label)
            {
                layerObject.visible = true;
            }
        }
    }

    private function setFirstBasemapVisible():void
    {
        if (!portalItemOrder || portalItemOrder.length == 0)
        {
            return;
        }

        var firstBasemapLabel:String = portalItemToLabel[portalItemOrder[0]];
        for each (var layerObject:Object in processedArcGISBasemaps)
        {
            if (layerObject.label == firstBasemapLabel)
            {
                layerObject.visible = true;
            }
        }
    }

    private function addBasemapsInOrder():void
    {
        for each (var portalItem:PortalItem in portalItemOrder)
        {
            for each (var layerObject:Object in processedArcGISBasemaps)
            {
                if (layerObject.label == portalItemToLabel[portalItem])
                {
                    configData.basemaps.push(layerObject);
                }
            }
        }
    }

    private function addBasemapLayerObject(layerXML:XML):void
    {
        if (layerXML)
        {
            processedArcGISBasemaps.push(LayerObjectUtil.getLayerObject(layerXML,
                                                                        totalBasemaps++,
                                                                        false,
                                                                        configData.bingKey));
        }
    }

    private function baseMapLayerObjectToLayerXML(title:String, basemapLayerObject:Object, iconURL:String = null):XML
    {
        var layerXML:XML;
        const url:String = basemapLayerObject.url;
        const type:String = basemapLayerObject.type;

        if (url)
        {
            layerXML = createTiledLayerXML(title, iconURL, url, basemapLayerObject, false);
        }
        else if (isNonEsriType(type))
        {
            layerXML = createNonEsriLayerXML(title, iconURL, basemapLayerObject, false, type);
        }

        return layerXML;
    }

    private function createTiledLayerXML(title:String, iconURL:String, url:String, basemapLayerObject:Object, visible:Boolean):XML
    {
        var layerXML:XML = <layer label={title}
                type="tiled"
                icon={iconURL}
                url={url}
                alpha={basemapLayerObject.opacity}
                visible={visible}/>;

        return layerXML;
    }

    private function isNonEsriType(type:String):Boolean
    {
        return type == "OpenStreetMap" ||
            (isBingBasemap(type) && hasBingKey());
    }

    private function createNonEsriLayerXML(title:String, iconURL:String, basemapLayerObject:Object, visible:Boolean, type:String):XML
    {
        var layerXML:XML = <layer label={title}
                icon={iconURL}
                type={toViewerNonEsriLayerType(basemapLayerObject.type)}
                alpha={basemapLayerObject.opacity}
                visible={visible}/>;

        if (isBingBasemap(type))
        {
            layerXML.@style = mapBingStyleFromBasemapType(type);
            layerXML.@culture = cultureCode;
        }

        return layerXML;
    }

    private function toViewerNonEsriLayerType(type:String):String
    {
        var viewerType:String;
        if (type == "OpenStreetMap")
        {
            viewerType = "osm";
        }
        else if (isBingBasemap(type))
        {
            viewerType = "bing";
        }

        return viewerType;
    }

    private function isBingBasemap(type:String):Boolean
    {
        return type && type.indexOf('BingMaps') > -1;
    }

    private function hasBingKey():Boolean
    {
        var bingKey:String = configData.bingKey;
        return (bingKey != null && bingKey.length > 0);
    }

    private function mapBingStyleFromBasemapType(type:String):String
    {
        if (type == 'BingMapsAerial')
        {
            return 'aerial';
        }
        else if (type == 'BingMapsHybrid')
        {
            return 'aerialWithLabels';
        }
        else
        {
            //default - BingMapsRoad
            return 'road';
        }
    }

    private function portalItem_getJSONDataFaultHandler(fault:Fault, token:Object = null):void
    {
        AppEvent.dispatch(AppEvent.APP_ERROR,
                          LocalizationUtil.getDefaultString("couldNotFetchBasemapData",
                                                            fault.faultString));
        updateTotalArcGISBasemaps();
    }

    private function portal_queryGroupsFaultHandler(fault:Fault, token:Object = null):void
    {
        AppEvent.showError(LocalizationUtil.getDefaultString("couldNotQueryPortal"), PORTAL_BASEMAP_APPENDER);
        dispatchComplete();
    }

    private function portal_queryItemsFaultHandler(fault:Fault, token:Object = null):void
    {
        AppEvent.showError(LocalizationUtil.getDefaultString("couldNotQueryPortalItems"), PORTAL_BASEMAP_APPENDER);
        dispatchComplete();
    }

    private function portal_faultHandler(event:FaultEvent):void
    {
        var portal:Portal = event.target as Portal;
        portal.removeEventListener(PortalEvent.LOAD, portal_loadHandler);
        portal.removeEventListener(FaultEvent.FAULT, portal_faultHandler);

        AppEvent.showError(LocalizationUtil.getDefaultString("couldNotConnectToPortal"), PORTAL_BASEMAP_APPENDER);
        dispatchComplete();
    }

    private function toCultureCode(locale:String):String
    {
        return locale ? locale.replace('_', '-') : locale;
    }
}

}

Clean up.

Clean up.


/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 package org.mangui.osmf.plugins.traits {
    import org.mangui.hls.HLS;
	import org.mangui.hls.constant.HLSPlayStates;
    import org.mangui.hls.event.HLSEvent;
    import org.osmf.traits.PlayState;
    import org.osmf.traits.PlayTrait;

    CONFIG::LOGGING {
    import org.mangui.hls.utils.Log;
    }

    public class HLSPlayTrait extends PlayTrait
    {
        private var _hls : HLS;

        private var streamStarted : Boolean = false;

        public function HLSPlayTrait(hls : HLS)
        {
            CONFIG::LOGGING {
            Log.debug("HLSPlayTrait()");
            }
            super();
            _hls = hls;
			_hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateChangedHandler);
            _hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _playbackComplete);
        }

        override public function dispose() : void
        {
            CONFIG::LOGGING {
            Log.debug("HLSPlayTrait:dispose");
            }
			_hls.removeEventListener(HLSEvent.PLAYBACK_STATE, _stateChangedHandler);
            _hls.removeEventListener(HLSEvent.PLAYBACK_COMPLETE, _playbackComplete);
            super.dispose();
        }

        override protected function playStateChangeStart(newPlayState:String):void
        {
            CONFIG::LOGGING
            {
                Log.info("HLSPlayTrait:playStateChangeStart:" + newPlayState);
            }
            switch (newPlayState)
            {
                case PlayState.PLAYING:
                    if (!streamStarted)
                    {
                        _hls.stream.play();
                        streamStarted = true;
                    }
                    else
                    {
                        _hls.stream.resume();

                    }
                    break;
                case PlayState.PAUSED:
                    _hls.stream.pause();
                    break;
                case PlayState.STOPPED:
                    streamStarted = false;
                    _hls.stream.close();
                    break;
            }
        }

        /** state changed handler **/
        private function _stateChangedHandler(event:HLSEvent):void
        {
            switch (event.state)
            {
                case HLSPlayStates.PLAYING:
                CONFIG::LOGGING
                {
                    Log.debug("HLSPlayTrait:_stateChangedHandler:setBuffering(true)");
                }
                    if (!streamStarted)
                    {
                        streamStarted = true;
                        play();
                    }
                default:
            }
        }

        /** playback complete handler **/
        private function _playbackComplete(event : HLSEvent) : void {
            stop();
        }
    }
}

fix indents and spaces

fix indents and spaces


package aerys.minko.scene.node
{
	import aerys.minko.render.Viewport;
	import aerys.minko.scene.controller.camera.CameraController;
	import aerys.minko.type.Signal;
	import aerys.minko.type.data.IDataProvider;
	import aerys.minko.type.math.Frustum;
	import aerys.minko.type.math.Matrix4x4;
	import aerys.minko.type.math.Vector4;

	/**
	 * Camera objects describe the position and the look-at point of a 3D camera.
	 *
	 * @author Jean-Marc Le Roux
	 *
	 */
	public final class Camera extends AbstractSceneNode implements IDataProvider
	{
		public static const DEFAULT_FOV			: Number	= Math.PI * .25;
		public static const DEFAULT_ZNEAR		: Number	= .1;
		public static const DEFAULT_ZFAR		: Number	= 1000.;

		private static const DATA_DESCRIPTOR	: Object	= {
			"camera position"		: "position",
			"camera look at"		: "lookAt",
			"camera up"				: "up",
			"camera world position"	: "worldPosition",
			"camera world look at"	: "worldLookAt",
			"camera world up"		: "worldUp",
			"camera fov"			: "fieldOfView",
			"camera z near"			: "zNear",
			"camera z far"			: "zFar",
			"world to view"			: "worldToView",
			"projection"			: "projection",
			"world to screen"		: "worldToScreen"
		};

		private var _viewport		: Viewport	= null;

		private var _position		: Vector4	= new Vector4(0, 0, 0);
		private var _lookAt			: Vector4	= new Vector4(0, 0, 1);
		private var _up				: Vector4	= new Vector4(0, 1, 0);

		private var _worldToView	: Matrix4x4	= new Matrix4x4();
		private var _worldPosition	: Vector4	= new Vector4();
		private var _worldLookAt	: Vector4	= new Vector4();
		private var _worldUp		: Vector4	= new Vector4();

		private var _fov			: Number	= 0;
		private var _zNear			: Number	= 0;
		private var _zFar			: Number	= 0;
		private var _frustum		: Frustum	= new Frustum();
		private var _projection		: Matrix4x4	= new Matrix4x4();

		private var _worldToScreen	: Matrix4x4	= new Matrix4x4();

		private var _locked			: Boolean	= false;
		private var _changed		: Signal	= new Signal();

		public function get viewport() : Viewport
		{
			return _viewport;
		}

		/**
		 * The position of the camera in local space.
		 * @return
		 *
		 */
		public function get position() : Vector4
		{
			return _position;
		}

		/**
		 * The look-at point of the camera in local space.
		 * @return
		 *
		 */
		public function get lookAt() : Vector4
		{
			return _lookAt;
		}

		/**
		 * The up axis of the camera in local space. Default value
		 * is the +Y axis.
		 * @return
		 *
		 */
		public function get up() : Vector4
		{
			return _up;
		}

		/**
		 * The position of the camera in world space. This value is
		 * updated everytime:
		 *

		 *
The parent 3D transformation changes.

		 *
The "position" property changes.

		 *

		 * @return
		 *
		 */
		public function get worldPosition() : Vector4
		{
			return _worldPosition;
		}

		/**
		 * The look-at point of the camera in world space. This value is
		 * updated everytime:
		 *

		 *
The parent 3D transformation changes.

		 *
The "lookAt" property changes.

		 *

		 * @return
		 *
		 */
		public function get worldLookAt() : Vector4
		{
			return _worldLookAt;
		}

		/**
		 * The up axis of the camera in world space. This value is
		 * updated everytime:
		 *

		 *
The parent 3D transformation changes.

		 *
The "up" property changes.

		 *

		 * @return
		 *
		 */
		public function get worldUp() : Vector4
		{
			return _worldUp;
		}

		/**
		 * The matrix that transforms world space coordinates
		 * into view (or camera) space coordinates.
		 * @return
		 *
		 */
		public function get worldToView() : Matrix4x4
		{
			return _worldToView;
		}

		/**
		 * The matrix that transforms view space coordinates
		 * into clip space (or normalized screen space) coordinates.
		 * @return
		 *
		 */
		public function get projection() : Matrix4x4
		{
			return _projection;
		}

		/**
		 * The matrix that transforms world space coordinates
		 * into clip space (or normalized space) coordinates.
		 * @return
		 *
		 */
		public function get worldToScreen() : Matrix4x4
		{
			return _worldToScreen;
		}

		/**
		 * The field of view of the camera. Setting this property
		 * will update the projection matrix and trigger the "changed"
		 * signal.
		 * @return
		 *
		 */
		public function get fieldOfView() : Number
		{
			return _fov;
		}
		public function set fieldOfView(value : Number) : void
		{
			_fov = value;

			if (!_locked)
				_changed.execute(this, "fieldOfView");
		}

		/**
		 * The z-near clipping plane of the camera. Setting this
		 * property will update the projection matrix and trigger the "changed"
		 * signal.
		 * @return
		 *
		 */
		public function get zNear() : Number
		{
			return _zNear;
		}
		public function set zNear(value : Number) : void
		{
			_zNear = value;

			if (!_locked)
				_changed.execute(this, "zNear");
		}

		/**
		 * The z-far clipping plane of the camera. Setting this property
		 * will update the projection matrix and trigger the "changed"
		 * signal.
		 * @return
		 *
		 */
		public function get zFar() : Number
		{
			return _zFar;
		}
		public function set zFar(value : Number) : void
		{
			_zFar = value;

			if (!_locked)
				_changed.execute(this, "zFar");
		}

		public function get frustum() : Frustum
		{
			return _frustum;
		}

		public function get locked() : Boolean
		{
			return _locked;
		}

		public function get changed() : Signal
		{
			return _changed;
		}

		public function get dataDescriptor() : Object
		{
			return DATA_DESCRIPTOR;
		}

		public function Camera(viewport		: Viewport,
							   fieldOfView	: Number	= DEFAULT_FOV,
							   zNear		: Number	= DEFAULT_ZNEAR,
							   zFar			: Number	= DEFAULT_ZFAR)
		{
			super();

			_viewport = viewport;
			_fov = fieldOfView;
			_zNear = zNear;
			_zFar = zFar;

			addController(new CameraController(viewport));
		}

		public function lock() : void
		{
			_locked = true;
		}

		public function unlock() : void
		{
			var locked : Boolean = _locked;

			_locked = false;
			if (locked)
				_changed.execute(this, null);
		}
	}
}

package aerys.minko.scene.node
{
	import aerys.minko.render.Viewport;
	import aerys.minko.scene.controller.camera.CameraController;
	import aerys.minko.type.Signal;
	import aerys.minko.type.data.IDataProvider;
	import aerys.minko.type.math.Frustum;
	import aerys.minko.type.math.Matrix4x4;
	import aerys.minko.type.math.Vector4;

	/**
	 * Camera objects describe the position and the look-at point of a 3D camera.
	 *
	 * @author Jean-Marc Le Roux
	 *
	 */
	public class Camera extends AbstractSceneNode implements IDataProvider
	{
		public static const DEFAULT_FOV			: Number	= Math.PI * .25;
		public static const DEFAULT_ZNEAR		: Number	= .1;
		public static const DEFAULT_ZFAR		: Number	= 1000.;

		private static const DATA_DESCRIPTOR	: Object	= {
			"camera position"		: "position",
			"camera look at"		: "lookAt",
			"camera up"				: "up",
			"camera world position"	: "worldPosition",
			"camera world look at"	: "worldLookAt",
			"camera world up"		: "worldUp",
			"camera fov"			: "fieldOfView",
			"camera z near"			: "zNear",
			"camera z far"			: "zFar",
			"world to view"			: "worldToView",
			"projection"			: "projection",
			"world to screen"		: "worldToScreen"
		};

		private var _viewport		: Viewport	= null;

		private var _position		: Vector4	= new Vector4(0, 0, 0);
		private var _lookAt			: Vector4	= new Vector4(0, 0, 1);
		private var _up				: Vector4	= new Vector4(0, 1, 0);

		private var _worldToView	: Matrix4x4	= new Matrix4x4();
		private var _worldPosition	: Vector4	= new Vector4();
		private var _worldLookAt	: Vector4	= new Vector4();
		private var _worldUp		: Vector4	= new Vector4();

		private var _fov			: Number	= 0;
		private var _zNear			: Number	= 0;
		private var _zFar			: Number	= 0;
		private var _frustum		: Frustum	= new Frustum();
		private var _projection		: Matrix4x4	= new Matrix4x4();

		private var _worldToScreen	: Matrix4x4	= new Matrix4x4();

		private var _locked			: Boolean	= false;
		private var _changed		: Signal	= new Signal();

		public function get viewport() : Viewport
		{
			return _viewport;
		}

		/**
		 * The position of the camera in local space.
		 * @return
		 *
		 */
		public function get position() : Vector4
		{
			return _position;
		}

		/**
		 * The look-at point of the camera in local space.
		 * @return
		 *
		 */
		public function get lookAt() : Vector4
		{
			return _lookAt;
		}

		/**
		 * The up axis of the camera in local space. Default value
		 * is the +Y axis.
		 * @return
		 *
		 */
		public function get up() : Vector4
		{
			return _up;
		}

		/**
		 * The position of the camera in world space. This value is
		 * updated everytime:
		 *

		 *
The parent 3D transformation changes.

		 *
The "position" property changes.

		 *

		 * @return
		 *
		 */
		public function get worldPosition() : Vector4
		{
			return _worldPosition;
		}

		/**
		 * The look-at point of the camera in world space. This value is
		 * updated everytime:
		 *

		 *
The parent 3D transformation changes.

		 *
The "lookAt" property changes.

		 *

		 * @return
		 *
		 */
		public function get worldLookAt() : Vector4
		{
			return _worldLookAt;
		}

		/**
		 * The up axis of the camera in world space. This value is
		 * updated everytime:
		 *

		 *
The parent 3D transformation changes.

		 *
The "up" property changes.

		 *

		 * @return
		 *
		 */
		public function get worldUp() : Vector4
		{
			return _worldUp;
		}

		/**
		 * The matrix that transforms world space coordinates
		 * into view (or camera) space coordinates.
		 * @return
		 *
		 */
		public function get worldToView() : Matrix4x4
		{
			return _worldToView;
		}

		/**
		 * The matrix that transforms view space coordinates
		 * into clip space (or normalized screen space) coordinates.
		 * @return
		 *
		 */
		public function get projection() : Matrix4x4
		{
			return _projection;
		}

		/**
		 * The matrix that transforms world space coordinates
		 * into clip space (or normalized space) coordinates.
		 * @return
		 *
		 */
		public function get worldToScreen() : Matrix4x4
		{
			return _worldToScreen;
		}

		/**
		 * The field of view of the camera. Setting this property
		 * will update the projection matrix and trigger the "changed"
		 * signal.
		 * @return
		 *
		 */
		public function get fieldOfView() : Number
		{
			return _fov;
		}
		public function set fieldOfView(value : Number) : void
		{
			_fov = value;

			if (!_locked)
				_changed.execute(this, "fieldOfView");
		}

		/**
		 * The z-near clipping plane of the camera. Setting this
		 * property will update the projection matrix and trigger the "changed"
		 * signal.
		 * @return
		 *
		 */
		public function get zNear() : Number
		{
			return _zNear;
		}
		public function set zNear(value : Number) : void
		{
			_zNear = value;

			if (!_locked)
				_changed.execute(this, "zNear");
		}

		/**
		 * The z-far clipping plane of the camera. Setting this property
		 * will update the projection matrix and trigger the "changed"
		 * signal.
		 * @return
		 *
		 */
		public function get zFar() : Number
		{
			return _zFar;
		}
		public function set zFar(value : Number) : void
		{
			_zFar = value;

			if (!_locked)
				_changed.execute(this, "zFar");
		}

		public function get frustum() : Frustum
		{
			return _frustum;
		}

		public function get locked() : Boolean
		{
			return _locked;
		}

		public function get changed() : Signal
		{
			return _changed;
		}

		public function get dataDescriptor() : Object
		{
			return DATA_DESCRIPTOR;
		}

		public function Camera(viewport		: Viewport,
							   fieldOfView	: Number	= DEFAULT_FOV,
							   zNear		: Number	= DEFAULT_ZNEAR,
							   zFar			: Number	= DEFAULT_ZFAR)
		{
			super();

			_viewport = viewport;
			_fov = fieldOfView;
			_zNear = zNear;
			_zFar = zFar;

			addController(new CameraController(viewport));
		}

		public function lock() : void
		{
			_locked = true;
		}

		public function unlock() : void
		{
			var locked : Boolean = _locked;

			_locked = false;
			if (locked)
				_changed.execute(this, null);
		}
	}
}

Remove final from Camera.

Remove final from Camera.


package org.shypl.common.util {
	import org.shypl.common.lang.IllegalStateException;

	public class SimplePath implements Path {
		private var _value:String;

		public function SimplePath(value:String = null) {
			if (value === "") {
				value = null;
			}
			else if (value !== null) {
				while (StringUtils.endsWith(value, "/")) {
					value = value.substr(0, -1);
				}
			}
			_value = value;
		}

		public function get empty():Boolean {
			return _value === null;
		}

		public function get parent():Path {
			if (_value === null) {
				throw new IllegalStateException();
			}

			var i:int = _value.lastIndexOf("/");
			if (i === -1) {
				throw new IllegalStateException();
			}

			return factoryPath(_value.substring(0, i));
		}

		public function get value():String {
			return _value;
		}

		public function resolve(path:String):Path {
			var i:int;
			var p:Path = this;
			while ((i = path.indexOf("../")) >= 0) {
				p = p.parent;
				path = path.substr(3);
			}
			return factoryPath(p.empty ? path : (p.value + "/" + path));
		}

		public function resolveSibling(path:String):Path {
			return parent.resolve(path);
		}

		public function toString():String {
			return _value;
		}

		protected function factoryPath(value:String):Path {
			return new SimplePath(value);
		}
	}
}

package org.shypl.common.util {
	import org.shypl.common.lang.IllegalStateException;

	public class SimplePath implements Path {
		private var _value:String;

		public function SimplePath(value:String = null) {
			if (value === "") {
				value = null;
			}
			else if (value !== null) {
				while (StringUtils.endsWith(value, "/")) {
					value = value.substr(0, -1);
				}
			}
			_value = value;
		}

		public function get empty():Boolean {
			return _value === null;
		}

		public function get parent():Path {
			if (_value === null) {
				throw new IllegalStateException();
			}

			var i:int = _value.lastIndexOf("/");
			if (i === -1) {
				throw new IllegalStateException();
			}

			return factoryPath(_value.substring(0, i));
		}

		public function get value():String {
			return _value;
		}

		public function resolve(path:String):Path {
			var i:int;
			var p:Path = this;
			while ((i = path.indexOf("..")) == 0) {
				p = p.parent;
				if (path.indexOf("../") == 0) {
					path = path.substr(3);
				}
				else {
					path = path.substr(2);
				}
			}
			return factoryPath(p.empty ? path : (p.value + "/" + path));
		}

		public function resolveSibling(path:String):Path {
			return parent.resolve(path);
		}

		public function toString():String {
			return _value;
		}

		protected function factoryPath(value:String):Path {
			return new SimplePath(value);
		}
	}
}

Refactor Path

Refactor Path


package battlecode.client.viewer.render {
    import battlecode.common.MapLocation;
    import battlecode.common.ResearchType;
    import battlecode.common.RobotType;
    import battlecode.common.Team;
    import battlecode.serial.RoundDelta;
    import battlecode.serial.RoundStats;
    import battlecode.world.GameMap;
    import battlecode.world.signals.*;

    public class DrawState extends DefaultSignalHandler {
        // state
        private var mines:Array; // Team[][]
        private var neutralEncampments:Object;
        private var encampments:Object;
        private var groundRobots:Object;
        private var hqA:DrawRobot;
        private var hqB:DrawRobot;

        // stats
        private var aPoints:Number;
        private var bPoints:Number;
        private var aFlux:Number;
        private var bFlux:Number;
        private var aGatheredPoints:Number;
        private var bGatheredPoints:Number;
        private var roundNum:uint;
        private var progressA:Array;
        private var progressB:Array;
        private var unitCounts:Object;

        // immutables
        private var map:GameMap;
        private var origin:MapLocation;

        public function DrawState(map:GameMap) {
            neutralEncampments = new Object();
            encampments = new Object();
            groundRobots = new Object();

            mines = new Array();
            for (var i:int = 0; i < map.getWidth(); i++) {
                mines[i] = new Array();
                for (var j:int = 0; j < map.getHeight(); j++) {
                    mines[i][j] = null;
                }
            }

            aPoints = 0;
            bPoints = 0;
            aFlux = 0;
            bFlux = 0;
            aGatheredPoints = 0;
            bGatheredPoints = 0;
            roundNum = 1;

            progressA = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
            progressB = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];

            unitCounts = new Object();
            unitCounts[Team.A] = new Object();
            unitCounts[Team.B] = new Object();
            for each (var type:String in RobotType.values()) {
                unitCounts[Team.A][type] = 0;
                unitCounts[Team.B][type] = 0;
            }

            this.map = map;
            this.origin = map.getOrigin();
        }

        ///////////////////////////////////////////////////////
        ///////////////// PROPERTY GETTERS ////////////////////
        ///////////////////////////////////////////////////////

        public function getMines():Array {
            return mines;
        }

        public function getNeutralEncampments():Object {
            return neutralEncampments;
        }

        public function getEncampments():Object {
            return encampments
        }

        public function getGroundRobots():Object {
            return groundRobots;
        }

        public function getHQ(team:String):DrawRobot {
            return team == Team.A ? hqA : hqB;
        }

        public function getPoints(team:String):uint {
            return (team == Team.A) ? aPoints : bPoints;
        }

        public function getFlux(team:String):uint {
            return (team == Team.A) ? aFlux : bFlux;
        }

        public function getResearchProgress(team:String):Array {
            return team == Team.A ? progressA : progressB;
        }

        public function getUnitCount(type:String, team:String):int {
            return unitCounts[team][type];
        }

        ///////////////////////////////////////////////////////
        /////////////////// CORE FUNCTIONS ////////////////////
        ///////////////////////////////////////////////////////

        private function copyStateFrom(state:DrawState):void {
            var a:*;

            mines = new Array();
            for (var i:int = 0; i < map.getWidth(); i++) {
                mines[i] = new Array();
                for (var j:int = 0; j < map.getHeight(); j++) {
                    mines[i][j] = state.mines[i][j];
                }
            }

            neutralEncampments = new Object();
            for (a in state.neutralEncampments) {
                neutralEncampments[a] = state.neutralEncampments[a].clone();
            }

            encampments = new Object();
            for (a in state.encampments) {
                encampments[a] = state.encampments[a].clone();
            }

            groundRobots = new Object();
            for (a in state.groundRobots) {
                groundRobots[a] = state.groundRobots[a].clone();
            }

            hqA = state.hqA ? state.hqA.clone() as DrawRobot : null;
            hqB = state.hqB ? state.hqB.clone() as DrawRobot : null;

            progressA = state.progressA.concat();
            progressB = state.progressB.concat();

            unitCounts = new Object();
            unitCounts[Team.A] = new Object();
            unitCounts[Team.B] = new Object();
            for (a in state.unitCounts[Team.A]) {
                unitCounts[Team.A][a] = state.unitCounts[Team.A][a];
                unitCounts[Team.B][a] = state.unitCounts[Team.B][a];
            }

            roundNum = state.roundNum;
        }

        public function clone():DrawState {
            var state:DrawState = new DrawState(map);
            state.copyStateFrom(this);
            return state;
        }

        public function applyDelta(delta:RoundDelta):void {
            updateRound();
            for each (var signal:Signal in delta.getSignals()) {
                applySignal(signal);
            }
            processEndOfRound();
        }

        public function applySignal(signal:Signal):void {
            if (signal != null) signal.accept(this);
        }

        public function applyStats(stats:RoundStats):void {
            aPoints = stats.getPoints(Team.A);
            bPoints = stats.getPoints(Team.B);
            aGatheredPoints = stats.getGatheredPoints(Team.A);
            bGatheredPoints = stats.getGatheredPoints(Team.B);
        }

        public function updateRound():void {
            var a:*, i:uint, j:uint;
            var o:DrawRobot;

            for (a in groundRobots) {
                o = groundRobots[a] as DrawRobot;
                o.updateRound();
                if (!o.isAlive()) {
                    if (o.parent) {
                        o.parent.removeChild(o);
                    }
                    delete groundRobots[a];
                }
            }

            for (a in encampments) {
                o = encampments[a] as DrawRobot;
                o.updateRound();
                if (!o.isAlive()) {
                    if (o.parent) {
                        o.parent.removeChild(o);
                    }
                    delete encampments[a];
                }
            }

            if (hqA) {
                hqA.updateRound();
                if (!hqA.isAlive()) {
                    if (hqA.parent) {
                        hqA.parent.removeChild(hqA);
                    }
                    hqA = null;
                }
            }

            if (hqB) {
                hqB.updateRound();
                if (!hqB.isAlive()) {
                    if (hqB.parent) {
                        hqB.parent.removeChild(hqB);
                    }
                    hqB = null;
                }
            }
        }

        private function processEndOfRound():void {
            roundNum++;
        }

        ///////////////////////////////////////////////////////
        ////////////// PRIVATE HELPER FUNCTIONS ///////////////
        ///////////////////////////////////////////////////////

        private function getRobot(id:uint):DrawRobot {
            if (groundRobots[id]) return groundRobots[id] as DrawRobot;
            if (encampments[id]) return encampments[id] as DrawRobot;
            return null;
        }

        private function removeRobot(id:uint):void {
            if (groundRobots[id]) delete groundRobots[id];
            if (encampments[id]) delete encampments[id];
        }

        private function translateCoordinates(loc:MapLocation):MapLocation {
            return new MapLocation(loc.getX() - origin.getX(), loc.getY() - origin.getY());
        }

        ///////////////////////////////////////////////////////
        /////////////////// SIGNAL HANDLERS ///////////////////
        ///////////////////////////////////////////////////////

        override public function visitAttackSignal(s:AttackSignal):* {
            getRobot(s.getRobotID()).attack(s.getTargetLoc());
        }

        override public function visitBroadcastSignal(s:BroadcastSignal):* {
            getRobot(s.getRobotID()).broadcast();
        }

        override public function visitCaptureSignal(s:CaptureSignal):* {
            var robot:DrawRobot = getRobot(s.getParentID());
            robot.capture();
        }

        override public function visitDeathSignal(s:DeathSignal):* {
            var robot:DrawRobot = getRobot(s.getRobotID());
            robot.destroyUnit();

            if (robot.getType() == RobotType.HQ) {
                var hq:DrawRobot = robot.getTeam() == Team.A ? hqA : hqB;
                hq.destroyUnit();
            }

            if (RobotType.isEncampment(robot.getType())) {
                var encampment:DrawRobot = new DrawRobot(0, RobotType.ENCAMPMENT, Team.NEUTRAL);
                encampment.setLocation(robot.getLocation());
                neutralEncampments[robot.getLocation()] = encampment;
            }

            unitCounts[robot.getTeam()][robot.getType()]--;
        }

        override public function visitEnergonChangeSignal(s:EnergonChangeSignal):* {
            var robotIDs:Array = s.getRobotIDs();
            var energon:Array = s.getEnergon();

            for (var i:uint; i < robotIDs.length; i++) {
                var robot:DrawRobot = getRobot(robotIDs[i]);
                robot.setEnergon(energon[i]);

                if (robot.getType() == RobotType.HQ) {
                    var hq:DrawRobot = robot.getTeam() == Team.A ? hqA : hqB;
                    hq.setEnergon(energon[i]);
                }
            }
        }

        override public function visitFluxChangeSignal(s:FluxChangeSignal):* {
            aFlux = s.getFlux(Team.A);
            bFlux = s.getFlux(Team.B);
        }

        override public function visitIndicatorStringSignal(s:IndicatorStringSignal):* {
            getRobot(s.getRobotID()).setIndicatorString(s.getIndicatorString(), s.getIndex());
        }

        override public function visitMineSignal(s:MineSignal):* {
            var loc:MapLocation = translateCoordinates(s.getLocation());
            if (map.isOnMap(loc)) {
                if (s.isBirth()) {
                    if (!mines[loc.getX()][loc.getY()]) {
                        mines[loc.getX()][loc.getY()] = s.getTeam();
                    }
                } else {
                    mines[loc.getX()][loc.getY()] = null;
                }
            }
        }

        override public function visitMineLayerSignal(s:MineLayerSignal):* {
            var robot:DrawRobot = getRobot(s.getRobotID());
            if (s.isLaying()) {
                robot.layMine();
            } else {
                var researchProgress:Array = robot.getTeam() == Team.A ? progressA : progressB;
                var hasUpgrade:Boolean = researchProgress[ResearchType.getField(ResearchType.DEFUSION)] == 1.0;
                robot.diffuseMine(hasUpgrade);
            }
        }

        override public function visitMovementSignal(s:MovementSignal):* {
            getRobot(s.getRobotID()).moveToLocation(s.getTargetLoc());
        }

        override public function visitNodeBirthSignal(s:NodeBirthSignal):* {
            var encampment:DrawRobot = new DrawRobot(0, RobotType.ENCAMPMENT, Team.NEUTRAL);
            encampment.setLocation(s.getLocation());
            neutralEncampments[s.getLocation()] = encampment;
        }

        override public function visitResearchChangeSignal(s:ResearchChangeSignal):* {
            progressA = s.getProgress(Team.A);
            progressB = s.getProgress(Team.B);
        }

        override public function visitSpawnSignal(s:SpawnSignal):* {
            var robot:DrawRobot = new DrawRobot(s.getRobotID(), s.getRobotType(), s.getTeam());
            robot.setLocation(s.getLocation());

            if (s.getRobotType() == RobotType.HQ) {
                if (s.getTeam() == Team.A) hqA = robot.clone() as DrawRobot;
                if (s.getTeam() == Team.B) hqB = robot.clone() as DrawRobot;
            }

            if (RobotType.isEncampment(s.getRobotType())) {
                var o:DrawRobot = neutralEncampments[s.getLocation()];
                if (o) {
                    if (o.parent) {
                        o.parent.removeChild(o);
                    }
                    delete neutralEncampments[s.getLocation()];
                }
                encampments[s.getRobotID()] = robot;
            } else {
                groundRobots[s.getRobotID()] = robot;
            }

            if (RobotType.isEncampment(s.getRobotType())) {
                trace(s.getRobotType())
            }
            unitCounts[s.getTeam()][s.getRobotType()]++;
        }

    }

}

package battlecode.client.viewer.render {
    import battlecode.common.MapLocation;
    import battlecode.common.ResearchType;
    import battlecode.common.RobotType;
    import battlecode.common.Team;
    import battlecode.serial.RoundDelta;
    import battlecode.serial.RoundStats;
    import battlecode.world.GameMap;
    import battlecode.world.signals.*;

    public class DrawState extends DefaultSignalHandler {
        // state
        private var mines:Array; // Team[][]
        private var neutralEncampments:Object;
        private var encampments:Object;
        private var groundRobots:Object;
        private var hqA:DrawRobot;
        private var hqB:DrawRobot;

        // stats
        private var aPoints:Number;
        private var bPoints:Number;
        private var aFlux:Number;
        private var bFlux:Number;
        private var aGatheredPoints:Number;
        private var bGatheredPoints:Number;
        private var roundNum:uint;
        private var progressA:Array;
        private var progressB:Array;
        private var unitCounts:Object;

        // immutables
        private var map:GameMap;
        private var origin:MapLocation;

        public function DrawState(map:GameMap) {
            neutralEncampments = new Object();
            encampments = new Object();
            groundRobots = new Object();

            mines = new Array();
            for (var i:int = 0; i < map.getWidth(); i++) {
                mines[i] = new Array();
                for (var j:int = 0; j < map.getHeight(); j++) {
                    mines[i][j] = null;
                }
            }

            aPoints = 0;
            bPoints = 0;
            aFlux = 0;
            bFlux = 0;
            aGatheredPoints = 0;
            bGatheredPoints = 0;
            roundNum = 1;

            progressA = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
            progressB = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];

            unitCounts = new Object();
            unitCounts[Team.A] = new Object();
            unitCounts[Team.B] = new Object();
            for each (var type:String in RobotType.values()) {
                unitCounts[Team.A][type] = 0;
                unitCounts[Team.B][type] = 0;
            }

            this.map = map;
            this.origin = map.getOrigin();
        }

        ///////////////////////////////////////////////////////
        ///////////////// PROPERTY GETTERS ////////////////////
        ///////////////////////////////////////////////////////

        public function getMines():Array {
            return mines;
        }

        public function getNeutralEncampments():Object {
            return neutralEncampments;
        }

        public function getEncampments():Object {
            return encampments
        }

        public function getGroundRobots():Object {
            return groundRobots;
        }

        public function getHQ(team:String):DrawRobot {
            return team == Team.A ? hqA : hqB;
        }

        public function getPoints(team:String):uint {
            return (team == Team.A) ? aPoints : bPoints;
        }

        public function getFlux(team:String):uint {
            return (team == Team.A) ? aFlux : bFlux;
        }

        public function getResearchProgress(team:String):Array {
            return team == Team.A ? progressA : progressB;
        }

        public function getUnitCount(type:String, team:String):int {
            return unitCounts[team][type];
        }

        ///////////////////////////////////////////////////////
        /////////////////// CORE FUNCTIONS ////////////////////
        ///////////////////////////////////////////////////////

        private function copyStateFrom(state:DrawState):void {
            var a:*;

            mines = new Array();
            for (var i:int = 0; i < map.getWidth(); i++) {
                mines[i] = new Array();
                for (var j:int = 0; j < map.getHeight(); j++) {
                    mines[i][j] = state.mines[i][j];
                }
            }

            neutralEncampments = new Object();
            for (a in state.neutralEncampments) {
                neutralEncampments[a] = state.neutralEncampments[a].clone();
            }

            encampments = new Object();
            for (a in state.encampments) {
                encampments[a] = state.encampments[a].clone();
            }

            groundRobots = new Object();
            for (a in state.groundRobots) {
                groundRobots[a] = state.groundRobots[a].clone();
            }

            hqA = state.hqA ? state.hqA.clone() as DrawRobot : null;
            hqB = state.hqB ? state.hqB.clone() as DrawRobot : null;

            progressA = state.progressA.concat();
            progressB = state.progressB.concat();

            unitCounts = new Object();
            unitCounts[Team.A] = new Object();
            unitCounts[Team.B] = new Object();
            for (a in state.unitCounts[Team.A]) {
                unitCounts[Team.A][a] = state.unitCounts[Team.A][a];
                unitCounts[Team.B][a] = state.unitCounts[Team.B][a];
            }

            roundNum = state.roundNum;
        }

        public function clone():DrawState {
            var state:DrawState = new DrawState(map);
            state.copyStateFrom(this);
            return state;
        }

        public function applyDelta(delta:RoundDelta):void {
            updateRound();
            for each (var signal:Signal in delta.getSignals()) {
                applySignal(signal);
            }
            processEndOfRound();
        }

        public function applySignal(signal:Signal):void {
            if (signal != null) signal.accept(this);
        }

        public function applyStats(stats:RoundStats):void {
            aPoints = stats.getPoints(Team.A);
            bPoints = stats.getPoints(Team.B);
            aGatheredPoints = stats.getGatheredPoints(Team.A);
            bGatheredPoints = stats.getGatheredPoints(Team.B);
        }

        public function updateRound():void {
            var a:*, i:uint, j:uint;
            var o:DrawRobot;

            for (a in groundRobots) {
                o = groundRobots[a] as DrawRobot;
                o.updateRound();
                if (!o.isAlive()) {
                    if (o.parent) {
                        o.parent.removeChild(o);
                    }
                    delete groundRobots[a];
                }
            }

            for (a in encampments) {
                o = encampments[a] as DrawRobot;
                o.updateRound();
                if (!o.isAlive()) {
                    if (o.parent) {
                        o.parent.removeChild(o);
                    }
                    delete encampments[a];
                }
            }

            if (hqA) {
                hqA.updateRound();
                if (!hqA.isAlive()) {
                    if (hqA.parent) {
                        hqA.parent.removeChild(hqA);
                    }
                    hqA = null;
                }
            }

            if (hqB) {
                hqB.updateRound();
                if (!hqB.isAlive()) {
                    if (hqB.parent) {
                        hqB.parent.removeChild(hqB);
                    }
                    hqB = null;
                }
            }
        }

        private function processEndOfRound():void {
            roundNum++;
        }

        ///////////////////////////////////////////////////////
        ////////////// PRIVATE HELPER FUNCTIONS ///////////////
        ///////////////////////////////////////////////////////

        private function getRobot(id:uint):DrawRobot {
            if (groundRobots[id]) return groundRobots[id] as DrawRobot;
            if (encampments[id]) return encampments[id] as DrawRobot;
            return null;
        }

        private function removeRobot(id:uint):void {
            if (groundRobots[id]) delete groundRobots[id];
            if (encampments[id]) delete encampments[id];
        }

        private function translateCoordinates(loc:MapLocation):MapLocation {
            return new MapLocation(loc.getX() - origin.getX(), loc.getY() - origin.getY());
        }

        ///////////////////////////////////////////////////////
        /////////////////// SIGNAL HANDLERS ///////////////////
        ///////////////////////////////////////////////////////

        override public function visitAttackSignal(s:AttackSignal):* {
            getRobot(s.getRobotID()).attack(s.getTargetLoc());
        }

        override public function visitBroadcastSignal(s:BroadcastSignal):* {
            getRobot(s.getRobotID()).broadcast();
        }

        override public function visitCaptureSignal(s:CaptureSignal):* {
            var robot:DrawRobot = getRobot(s.getParentID());
            robot.capture();
        }

        override public function visitDeathSignal(s:DeathSignal):* {
            var robot:DrawRobot = getRobot(s.getRobotID());
            robot.destroyUnit();

            if (robot.getType() == RobotType.HQ) {
                var hq:DrawRobot = robot.getTeam() == Team.A ? hqA : hqB;
                hq.destroyUnit();
            }

            if (RobotType.isEncampment(robot.getType())) {
                var encampment:DrawRobot = new DrawRobot(0, RobotType.ENCAMPMENT, Team.NEUTRAL);
                encampment.setLocation(robot.getLocation());
                neutralEncampments[robot.getLocation()] = encampment;
            }

            unitCounts[robot.getTeam()][robot.getType()]--;
        }

        override public function visitEnergonChangeSignal(s:EnergonChangeSignal):* {
            var robotIDs:Array = s.getRobotIDs();
            var energon:Array = s.getEnergon();

            for (var i:uint; i < robotIDs.length; i++) {
                var robot:DrawRobot = getRobot(robotIDs[i]);
                robot.setEnergon(energon[i]);

                if (robot.getType() == RobotType.HQ) {
                    var hq:DrawRobot = robot.getTeam() == Team.A ? hqA : hqB;
                    hq.setEnergon(energon[i]);
                }
            }
        }

        override public function visitFluxChangeSignal(s:FluxChangeSignal):* {
            aFlux = s.getFlux(Team.A);
            bFlux = s.getFlux(Team.B);
        }

        override public function visitIndicatorStringSignal(s:IndicatorStringSignal):* {
            getRobot(s.getRobotID()).setIndicatorString(s.getIndicatorString(), s.getIndex());
        }

        override public function visitMineSignal(s:MineSignal):* {
            var loc:MapLocation = translateCoordinates(s.getLocation());
            if (map.isOnMap(loc)) {
                if (s.isBirth()) {
                    if (!mines[loc.getX()][loc.getY()]) {
                        mines[loc.getX()][loc.getY()] = s.getTeam();
                    }
                } else {
                    mines[loc.getX()][loc.getY()] = null;
                }
            }
        }

        override public function visitMineLayerSignal(s:MineLayerSignal):* {
            var robot:DrawRobot = getRobot(s.getRobotID());
            if (s.isLaying()) {
                robot.layMine();
            } else {
                var researchProgress:Array = robot.getTeam() == Team.A ? progressA : progressB;
                var hasUpgrade:Boolean = researchProgress[ResearchType.getField(ResearchType.DEFUSION)] == 1.0;
                robot.diffuseMine(hasUpgrade);
            }
        }

        override public function visitMovementSignal(s:MovementSignal):* {
            getRobot(s.getRobotID()).moveToLocation(s.getTargetLoc());
        }

        override public function visitNodeBirthSignal(s:NodeBirthSignal):* {
            var encampment:DrawRobot = new DrawRobot(0, RobotType.ENCAMPMENT, Team.NEUTRAL);
            encampment.setLocation(s.getLocation());
            neutralEncampments[s.getLocation()] = encampment;
        }

        override public function visitResearchChangeSignal(s:ResearchChangeSignal):* {
            progressA = s.getProgress(Team.A);
            progressB = s.getProgress(Team.B);
        }

        override public function visitSpawnSignal(s:SpawnSignal):* {
            var robot:DrawRobot = new DrawRobot(s.getRobotID(), s.getRobotType(), s.getTeam());
            robot.setLocation(s.getLocation());

            if (s.getRobotType() == RobotType.HQ) {
                if (s.getTeam() == Team.A) hqA = robot.clone() as DrawRobot;
                if (s.getTeam() == Team.B) hqB = robot.clone() as DrawRobot;
            }

            if (RobotType.isEncampment(s.getRobotType())) {
                var o:DrawRobot = neutralEncampments[s.getLocation()];
                if (o) {
                    if (o.parent) {
                        o.parent.removeChild(o);
                    }
                    delete neutralEncampments[s.getLocation()];
                }
                encampments[s.getRobotID()] = robot;
            } else {
                groundRobots[s.getRobotID()] = robot;
            }

            unitCounts[s.getTeam()][s.getRobotType()]++;
        }

    }

}

remove trace statement

remove trace statement


/*
 *  Copyright: (c) 2015. Turtsevich Alexander
 *
 *  Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.html
 */

package com.kemsky.support
{
    import com.kemsky.Iterator;
    import com.kemsky.Stream;

    import flash.utils.Proxy;
    import flash.utils.flash_proxy;

    use namespace flash_proxy;

    /**
     * @private
     */
    public class ValueIterator extends Proxy implements Iterator
    {
        protected var stream:Stream;

        protected var _next:int;

        protected var _current:int = -1;

        public function ValueIterator(array:Stream, index:uint = 0)
        {
            stream = array;

            _next = index >= stream.length ? -1 : index;
        }

        /**
         * @private
         */
        private function get nextIndex():int
        {
            return _next;
        }

        /**
         * @inheritDoc
         */
        public function get index():int
        {
            return _current;
        }

        /**
         * @inheritDoc
         */
        public function get item():*
        {
            return stream.getItem(_current);
        }

        /**
         * @inheritDoc
         */
        public function reset():void
        {
            _next = stream.length ? 0 : -1;
            _current = -1;
        }

        /**
         * @inheritDoc
         */
        public function end():void
        {
            _next = _current = -1;
        }

        /**
         * @inheritDoc
         */
        public function remove():void
        {
            if (_current == -1)
            {
                throw new StreamError("Current item is not available");
            }

            if (_next > 0)
            {
                _next--;
            }

            stream.removeItem(_current);
            _current = -1;
        }

        /**
         * @inheritDoc
         */
        public function get hasNext():Boolean
        {
            return _next > -1;
        }

        /**
         * @inheritDoc
         */
        public function next():*
        {
            if (_next == -1)
            {
                throw new StreamError("Next item is not available");
            }

            _current = _next;
            _next = _next >= stream.length - 1 ? -1 : _next + 1;

            return stream.getItem(_current);
        }

        /**
         * @inheritDoc
         */
        public function set item(value:*):void
        {
            if (_current == -1 || _current == stream.length)
            {
                throw new StreamError("Current item is not available");
            }
            stream.setItem(_current, value);
        }

        /**
         * @private
         */
        override flash_proxy function nextNameIndex(index:int):int
        {
            return hasNext ? nextIndex + 1 : 0;
        }

        /**
         * @private
         */
        override flash_proxy function nextValue(index:int):*
        {
            return next();
        }
    }
}

/*
 *  Copyright: (c) 2015. Turtsevich Alexander
 *
 *  Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.html
 */

package com.kemsky.support
{
    import com.kemsky.Iterator;
    import com.kemsky.Stream;

    import flash.utils.Proxy;
    import flash.utils.flash_proxy;

    use namespace flash_proxy;

    /**
     * @private
     */
    public class ValueIterator extends Proxy implements Iterator
    {
        protected var stream:Stream;

        protected var _next:int;

        protected var _current:int = -1;

        /**
         * Constructor.
         * @param stream underlying stream.
         */
        public function ValueIterator(stream:Stream)
        {
            this.stream = stream;
            _next = this.stream.length == 0 ? -1 : 0;
        }

        /**
         * @private
         */
        private function get nextIndex():int
        {
            return _next;
        }

        /**
         * @inheritDoc
         */
        public function get index():int
        {
            return _current;
        }

        /**
         * @inheritDoc
         */
        public function get item():*
        {
            return stream.getItem(_current);
        }

        /**
         * @inheritDoc
         */
        public function reset():void
        {
            _next = stream.length ? 0 : -1;
            _current = -1;
        }

        /**
         * @inheritDoc
         */
        public function end():void
        {
            _next = _current = -1;
        }

        /**
         * @inheritDoc
         */
        public function remove():void
        {
            if (_current == -1)
            {
                throw new StreamError("Current item is not available");
            }

            if (_next > 0)
            {
                _next--;
            }

            stream.removeItem(_current);
            _current = -1;
        }

        /**
         * @inheritDoc
         */
        public function get hasNext():Boolean
        {
            return _next > -1;
        }

        /**
         * @inheritDoc
         */
        public function next():*
        {
            if (_next == -1)
            {
                throw new StreamError("Next item is not available");
            }

            _current = _next;
            _next = _next >= stream.length - 1 ? -1 : _next + 1;

            return stream.getItem(_current);
        }

        /**
         * @inheritDoc
         */
        public function set item(value:*):void
        {
            if (_current == -1 || _current == stream.length)
            {
                throw new StreamError("Current item is not available");
            }
            stream.setItem(_current, value);
        }

        /**
         * @private
         */
        override flash_proxy function nextNameIndex(index:int):int
        {
            return hasNext ? nextIndex + 1 : 0;
        }

        /**
         * @private
         */
        override flash_proxy function nextValue(index:int):*
        {
            return next();
        }
    }
}

clean up

clean up


/*
 *  SteamConstants.as
 *  This file is part of FRESteamWorks.
 *
 *  Created by David ´Oldes´ Oliva on 3/29/12.
 *  Contributors: Ventero <http://github.com/Ventero>
 *  Copyright (c) 2012 Amanita Design. All rights reserved.
 *  Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved.
 */

package com.amanitadesign.steam
{
	public class SteamConstants
	{
		/* response values */
		public static const RESPONSE_OK:int = 0;
		public static const RESPONSE_FAILED:int = 1;

		/* response types */
		public static const RESPONSE_OnUserStatsReceived:int = 0;
		public static const RESPONSE_OnUserStatsStored:int = 1;
		public static const RESPONSE_OnAchievementStored:int = 2;
		public static const RESPONSE_OnGameOverlayActivated:int = 3;
		public static const RESPONSE_OnFileShared:int = 4;
		public static const RESPONSE_OnUGCDownload:int = 5;
		public static const RESPONSE_OnPublishWorkshopFile:int = 6;
		public static const RESPONSE_OnDeletePublishedFile:int = 7;
		public static const RESPONSE_OnGetPublishedFileDetails:int = 8;
		public static const RESPONSE_OnEnumerateUserPublishedFiles:int = 9;
		public static const RESPONSE_OnEnumeratePublishedWorkshopFiles:int = 10;
		public static const RESPONSE_OnEnumerateUserSubscribedFiles:int = 11;
		public static const RESPONSE_OnEnumerateUserSharedWorkshopFiles:int = 12;
		public static const RESPONSE_OnEnumeratePublishedFilesByUserAction:int = 13;
		public static const RESPONSE_OnCommitPublishedFileUpdate:int = 14;
		public static const RESPONSE_OnSubscribePublishedFile:int = 15;
		public static const RESPONSE_OnUnsubscribePublishedFile:int = 16;
		public static const RESPONSE_OnGetPublishedItemVoteDetails:int = 17;
		public static const RESPONSE_OnUpdateUserPublishedItemVote:int = 18;
		public static const RESPONSE_OnSetUserPublishedFileAction:int = 19;
		public static const RESPONSE_OnDLCInstalled:int = 20;
	}

}

/*
 *  SteamConstants.as
 *  This file is part of FRESteamWorks.
 *
 *  Created by David ´Oldes´ Oliva on 3/29/12.
 *  Contributors: Ventero <http://github.com/Ventero>
 *  Copyright (c) 2012 Amanita Design. All rights reserved.
 *  Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved.
 */

package com.amanitadesign.steam
{
	public class SteamConstants
	{
		/* response types */
		public static const RESPONSE_OnUserStatsReceived:int = 0;
		public static const RESPONSE_OnUserStatsStored:int = 1;
		public static const RESPONSE_OnAchievementStored:int = 2;
		public static const RESPONSE_OnGameOverlayActivated:int = 3;
		public static const RESPONSE_OnFileShared:int = 4;
		public static const RESPONSE_OnUGCDownload:int = 5;
		public static const RESPONSE_OnPublishWorkshopFile:int = 6;
		public static const RESPONSE_OnDeletePublishedFile:int = 7;
		public static const RESPONSE_OnGetPublishedFileDetails:int = 8;
		public static const RESPONSE_OnEnumerateUserPublishedFiles:int = 9;
		public static const RESPONSE_OnEnumeratePublishedWorkshopFiles:int = 10;
		public static const RESPONSE_OnEnumerateUserSubscribedFiles:int = 11;
		public static const RESPONSE_OnEnumerateUserSharedWorkshopFiles:int = 12;
		public static const RESPONSE_OnEnumeratePublishedFilesByUserAction:int = 13;
		public static const RESPONSE_OnCommitPublishedFileUpdate:int = 14;
		public static const RESPONSE_OnSubscribePublishedFile:int = 15;
		public static const RESPONSE_OnUnsubscribePublishedFile:int = 16;
		public static const RESPONSE_OnGetPublishedItemVoteDetails:int = 17;
		public static const RESPONSE_OnUpdateUserPublishedItemVote:int = 18;
		public static const RESPONSE_OnSetUserPublishedFileAction:int = 19;
		public static const RESPONSE_OnDLCInstalled:int = 20;
	}

}

Remove obsolete values

Remove obsolete values


/* -*- mode: JavaScript; c-basic-offset: 2; -*- */

/*
 * Platform-specific DebugService
  *
  * @copyright Copyright 2001-2008 Laszlo Systems, Inc.  All Rights Reserved.
  *            Use is subject to license terms.

 */

// The last three debugger eval values
var _;
var __;
var ___;

class LzAS3DebugService extends LzDebugService {
    #passthrough (toplevel:true) {
    import flash.net.*;
    import flash.events.*;
    import flash.external.*;
    import flash.display.*;
    import flash.utils.*;
    import flash.system.*;
    import mx.core.Application;
    }#

  /**
   * @access private
   */
  function LzAS3DebugService (base:LzBootstrapDebugService) {
    super(null);
  }

  /**
   ** Platform-specific implementation of debug I/O
   **/

  /**
   * Instantiates an instance of the user Debugger window
   * Called last thing by the compiler when the app is completely loaded.
   * @access private
   */
  function makeDebugWindow () {
    // Make the real console.  This is only called if the user code
    // did not actually instantiate a <debug /> tag
    var params:Object = LFCApplication.stage.loaderInfo.parameters;
    var remote =( params[ "lzconsoledebug" ] );
    trace('makeDebugWindow lzconsoledebug=',  'remote=', remote);
    if (remote == 'true') {
      // Open the remote debugger socket
      this.attachDebugConsole(new LzFlashRemoteDebugConsole());
    } else {
      // This will attach itself, once it is fully initialized.
      new lz.LzDebugWindow();
    }
  }

  // Map of object=>id
  var swf9_object_table:Dictionary = new Dictionary();
  // Map of id=>object
  var swf9_id_table:Array = [];

  override function IDForObject (obj:*, force:Boolean=false):Number {
    var id:Number;
    // TODO [hqm 2008-09-11] in swf9 we can use the flash.utils.Dictionary object
    // to do hash table lookups using === object equality, so we don't need to
    // iterate over the id_to_object_table to see if an object has been interned.
    var ot = this.swf9_object_table;
    if (ot[obj]  != null) {
      return ot[obj];
    }
    if (!force) {
      // ID anything that has identity
      if (! this.isObjectLike(obj)) {
        return null;
      }
    }
    id = this.objseq++;
    this.swf9_object_table[obj] = id;
    this.swf9_id_table[id] = obj;
    return id;
  };

  override function ObjectForID (id) {
    return this.swf9_id_table[id];
  };

   /**
    * @access private
   * @devnote The only reason this is here is because the SWF eval
   * compiler does not (yet) wrap `with (Debug.environment)` around the
   * compiled expression, so we have to put the "previous value's" in
  * _level0
   */
  override function displayResult (result=(void 0)) {
    if (typeof(result) != 'undefined') {
      // Advance saved results if you have a new one
      if (result !== global._) {
        if (typeof(global.__) != 'undefined') {
          global.___ = global.__;
        }
        if (typeof(global._) != 'undefined') {
          global.__ = global._;
        }
        global._ = result;
      }
    }
    this.freshLine();
    // Output any result from the evalloader
    if (typeof(result) != 'undefined') {
      this.format("%#w", result);
    }
    this.freshPrompt();
  };

  /**
   * @access private
   */
  override function functionName (fn, mustBeUnique:Boolean=false) {
    if ((fn is Class) && fn['tagname']) {
      // Handle tag classes
      if ((! mustBeUnique) || (fn === lz[fn.tagname])) {
        return '<' + fn.tagname + '>';
      }
    }
    return super.functionName(fn, mustBeUnique);
  }

  /**
   * @access private
   */
  /**
   * Adds unenumerable object properties for DHMTL runtime
   *
   * @access private
   */
  override function objectOwnProperties (obj:*, names:Array=null, indices:Array=null, limit:Number=Infinity, nonEnumerable:Boolean=false) {
    // TODO [2008-09-11 hqm] not sure what to do here, maybe we can use the introspection API
    // flash.utils.describeType() to at least enumerate public properties...
    return super.objectOwnProperties(obj, names, indices, limit,nonEnumerable);

  }
}

var Debug = new LzAS3DebugService(null);
var __LzDebug = Debug;

/* -*- mode: JavaScript; c-basic-offset: 2; -*- */

/*
 * Platform-specific DebugService
  *
  * @copyright Copyright 2001-2008 Laszlo Systems, Inc.  All Rights Reserved.
  *            Use is subject to license terms.

 */

// The last three debugger eval values
var _;
var __;
var ___;

class LzAS3DebugService extends LzDebugService {
    #passthrough (toplevel:true) {
    import flash.net.*;
    import flash.events.*;
    import flash.external.*;
    import flash.display.*;
    import flash.utils.*;
    import flash.system.*;
    import mx.core.Application;
    }#

  /**
   * @access private
   */
  function LzAS3DebugService (base:LzBootstrapDebugService) {
    super(null);
  }

  /**
   ** Platform-specific implementation of debug I/O
   **/

  /**
   * Instantiates an instance of the user Debugger window
   * Called last thing by the compiler when the app is completely loaded.
   * @access private
   */
  function makeDebugWindow () {
    // Make the real console.  This is only called if the user code
    // did not actually instantiate a <debug /> tag
    var params:Object = LFCApplication.stage.loaderInfo.parameters;
    var remote =( params[ "lzconsoledebug" ] );
    trace('makeDebugWindow lzconsoledebug=',  'remote=', remote);
    if (remote == 'true') {
      // Open the remote debugger socket
      this.attachDebugConsole(new LzFlashRemoteDebugConsole());
    } else {
      // This will attach itself, once it is fully initialized.
      new lz.LzDebugWindow();
    }
  }

  // Map of object=>id
  var swf9_object_table:Dictionary = new Dictionary();
  // Map of id=>object
  var swf9_id_table:Array = [];

  override function IDForObject (obj:*, force:Boolean=false):Number {
    var id:Number;
    // TODO [hqm 2008-09-11] in swf9 we can use the flash.utils.Dictionary object
    // to do hash table lookups using === object equality, so we don't need to
    // iterate over the id_to_object_table to see if an object has been interned.
    var ot = this.swf9_object_table;
    if (ot[obj]  != null) {
      return ot[obj];
    }
    if (!force) {
      // ID anything that has identity
      if (! this.isObjectLike(obj)) {
        return null;
      }
    }
    id = this.objseq++;
    this.swf9_object_table[obj] = id;
    this.swf9_id_table[id] = obj;
    return id;
  };

  override function ObjectForID (id) {
    return this.swf9_id_table[id];
  };

   /**
    * @access private
   * @devnote The only reason this is here is because the SWF eval
   * compiler does not (yet) wrap `with (Debug.environment)` around the
   * compiled expression, so we have to put the "previous value's" in
  * _level0
   */
  override function displayResult (result=(void 0)) {
    if (typeof(result) != 'undefined') {
      // Advance saved results if you have a new one
      if (result !== global._) {
        if (typeof(global.__) != 'undefined') {
          global.___ = global.__;
        }
        if (typeof(global._) != 'undefined') {
          global.__ = global._;
        }
        global._ = result;
      }
    }
    this.freshLine();
    // Output any result from the evalloader
    if (typeof(result) != 'undefined') {
      this.format("%#w", result);
    }
    this.freshPrompt();
  };

  /**
   * @access private
   */
  override function functionName (fn, mustBeUnique:Boolean=false) {
    if ((fn is Class) && fn['tagname']) {
      // Handle tag classes
      if ((! mustBeUnique) || (fn === lz[fn.tagname])) {
        return '<' + fn.tagname + '>';
      }
    }
    return super.functionName(fn, mustBeUnique);
  }

  /**
   * @access private
   */
  /**
   * Adds unenumerable object properties for DHMTL runtime
   *
   * @access private
   */
  #passthrough {
  override function objectOwnProperties (obj:*, names:Array=null, indices:Array=null, limit:Number=Infinity, nonEnumerable:Boolean=false) {
    // TODO [2008-09-11 hqm] not sure what to do here, maybe we can use the introspection API
    // flash.utils.describeType() to at least enumerate public properties...
    var description:XML = describeType(obj);
    trace('objectOwnProperties', description);
    for each(var a:XML in description.variable) {
        if (names != null) {
          names.push(a.@name);
        }
      }
    return super.objectOwnProperties(obj, names, indices, limit,nonEnumerable);
  }
  }#
}

var Debug = new LzAS3DebugService(null);
var __LzDebug = Debug;

Change 20080918-hqm-z by hqm@badtzmaru.home on 2008-09-18 16:07:26 EDT
    in /Users/hqm/openlaszlo/trunk
    for http://svn.openlaszlo.org/openlaszlo/trunk

Summary: use swf9 introspection in debugger inspector

New Features:

Bugs Fixed:

Technical Reviewer: ptr (pending)
QA Reviewer: (pending)
Doc Reviewer: (pending)

Documentation:

Release Notes:

Details:

Tests:

git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@11083 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c


package {
  import stdio.Sprite

  [SWF(width=0, height=0)]
  public class flash_test extends Sprite {
    public function main(): void {
      test_body()
    }
  }
}

package {
  import stdio.Sprite

  [SWF(width=100, height=100)]
  public class flash_test extends Sprite {
    public function flash_test(): void {
      graphics.beginFill(0xff0000)
      graphics.drawRect(10, 10, 80, 80)
      graphics.endFill()
    }

    public function main(): void {
      graphics.beginFill(0x0000ff)
      graphics.drawRect(30, 30, 40, 40)
      graphics.endFill()

      test_body()
    }
  }
}

Add colors to Flash test to ease debugging.


//
// Flump - Copyright 2013 Flump Authors

package flump.export {

import aspire.util.Log;

import flash.filesystem.File;

import flump.xfl.XflLibrary;

public class Publisher
{
    public function Publisher (exportDir :File, project :ProjectConf, projectName :String) {
        _exportDir = exportDir;
        _projectName = projectName;
        for each (var export :ExportConf in project.exports) _confs.push(export);
    }

    public function modified (libs :Vector.<XflLibrary>, idx :int = -1) :Boolean {
        // Instantiate all formats and check for modified. For a ProjectConf that contains combined
        // exports, all individual libs will check as modified if any single lib is modified
        return instantiate(libs, idx).some(function (export :PublishFormat, ..._) :Boolean {
            return export.modified;
        });
    }

    public function publishSingle (lib :XflLibrary) :int {
        var libs :Vector.<XflLibrary> = new <XflLibrary>[lib];
        var formats :Vector.<PublishFormat> = instantiate(libs, 0, false);
        for each (var format :PublishFormat in formats) format.publish();
        return formats.length;
    }

    public function publishCombined (libs :Vector.<XflLibrary>) :int {
        // no index passed to instantiate() acts as a <do not include non-combined> flag
        var formats :Vector.<PublishFormat> = instantiate(libs);
        for each (var format :PublishFormat in formats) format.publish();
        return formats.length;
    }

    protected function instantiate (libs :Vector.<XflLibrary>,
            idx :int = -1, includeCombined :Boolean = true) :Vector.<PublishFormat> {
        const formats :Vector.<PublishFormat> = new <PublishFormat>[];
        for each (var conf :ExportConf in _confs) {
            if (conf.combine && includeCombined) {
                formats.push(conf.createPublishFormat(_exportDir, libs, _projectName));
            } else if (!conf.combine && idx >= 0) {
                formats.push(conf.createPublishFormat(_exportDir, new <XflLibrary>[libs[idx]],
                    _projectName))
            }
        }
        return formats;
    }

    private var _exportDir :File;
    private var _projectName :String;
    private const _confs :Vector.<ExportConf> = new <ExportConf>[];
    private static const log :Log = Log.getLog(Publisher);
}
}

//
// Flump - Copyright 2013 Flump Authors

package flump.export {

import flash.filesystem.File;

import flump.xfl.XflLibrary;

public class Publisher
{
    public function Publisher (exportDir :File, project :ProjectConf, projectName :String) {
        _exportDir = exportDir;
        _projectName = projectName;
        for each (var conf :ExportConf in project.exports) _confs.push(conf);
    }

    public function modified (libs :Vector.<XflLibrary>, idx :int = -1) :Boolean {
        // Instantiate all formats and check for modified. For a ProjectConf that contains combined
        // exports, all individual libs will check as modified if any single lib is modified
        return instantiate(libs, idx).some(function (conf :PublishFormat, ..._) :Boolean {
            return conf.modified;
        });
    }

    public function publishSingle (lib :XflLibrary) :int {
        var libs :Vector.<XflLibrary> = new <XflLibrary>[lib];
        var formats :Vector.<PublishFormat> = instantiate(libs, 0, false);
        for each (var format :PublishFormat in formats) format.publish();
        return formats.length;
    }

    public function publishCombined (libs :Vector.<XflLibrary>) :int {
        // no index passed to instantiate() acts as a <do not include non-combined> flag
        var formats :Vector.<PublishFormat> = instantiate(libs);
        for each (var format :PublishFormat in formats) format.publish();
        return formats.length;
    }

    protected function instantiate (libs :Vector.<XflLibrary>,
            idx :int = -1, includeCombined :Boolean = true) :Vector.<PublishFormat> {
        const formats :Vector.<PublishFormat> = new <PublishFormat>[];
        for each (var conf :ExportConf in _confs) {
            if (conf.combine && includeCombined) {
                formats.push(conf.createPublishFormat(_exportDir, libs, _projectName));
            } else if (!conf.combine && idx >= 0) {
                formats.push(conf.createPublishFormat(_exportDir, new <XflLibrary>[libs[idx]],
                    _projectName))
            }
        }
        return formats;
    }

    private var _exportDir :File;
    private var _projectName :String;
    private const _confs :Vector.<ExportConf> = new <ExportConf>[];
}
}

Remove unused log; fix IntelliJ warnings

("export" is a reserved keyword)