package control
{
	import com.adobe.serialization.json.JSON;

	import dragonBones.objects.DataParser;
	import dragonBones.utils.ConstValues;

	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.geom.Matrix;
	import flash.net.FileReference;
	import flash.utils.ByteArray;

	import message.Message;
	import message.MessageDispatcher;

	import model.ImportDataProxy;
	import model.JSFLProxy;
	import model.XMLDataProxy;

	import utils.BitmapDataUtil;
	import utils.GlobalConstValues;
	import utils.PNGEncoder;
	import utils.xmlToObject;

	import zero.zip.Zip;

	public class ExportDataCommand
	{
		public static const instance:ExportDataCommand = new ExportDataCommand();

		private var _fileREF:FileReference;
		private var _exportType:uint;
		private var _isExporting:Boolean;
		private var _exportScale:Number;

		private var _importDataProxy:ImportDataProxy;

		private var _xmlDataProxy:XMLDataProxy;
		private var _bitmapData:BitmapData;

		public function ExportDataCommand()
		{
			_fileREF = new FileReference();

			_importDataProxy = ImportDataProxy.getInstance();
		}

		public function export(exportType:uint, exportScale:Number):void
		{
			if(_isExporting)
			{
				return;
			}
			_isExporting = true;

			_exportType = exportType;
			_exportScale = exportScale;

			switch(_exportType)
			{
				case 0:
				case 2:
				case 5:
					_exportScale = 1;
					break;
			}

			exportStart();
		}

		private function exportStart():void
		{
			var dataBytes:ByteArray;
			var zip:Zip;
			var date:Date;

			_xmlDataProxy = _importDataProxy.xmlDataProxy;
			_bitmapData = _importDataProxy.textureAtlas.bitmapData;

			if(_exportScale != 1)
			{
				_xmlDataProxy = _xmlDataProxy.clone();
				var subBitmapDataDic:Object;
				var movieClip:MovieClip = _importDataProxy.textureAtlas.movieClip;
				if(movieClip && movieClip.totalFrames >= 3)
				{
					subBitmapDataDic = {};
					for each (var displayName:String in _xmlDataProxy.getSubTextureListFromDisplayList())
					{
						movieClip.gotoAndStop(movieClip.totalFrames);
						movieClip.gotoAndStop(displayName);
						subBitmapDataDic[displayName] = movieClip.getChildAt(0);
					}
				}
				else
				{
					subBitmapDataDic = BitmapDataUtil.getSubBitmapDataDic(
						_bitmapData,
						_xmlDataProxy.getSubTextureRectMap()
					);
				}

				_xmlDataProxy.scaleData(_exportScale);

				_bitmapData = BitmapDataUtil.getMergeBitmapData(
					subBitmapDataDic,
					_xmlDataProxy.getSubTextureRectMap(),
					_xmlDataProxy.textureAtlasWidth,
					_xmlDataProxy.textureAtlasHeight,
					_exportScale
				);
			}

			var isSWF:Boolean = _exportType == 0 || _exportType == 2 || _exportType == 5;
			var isXML:Boolean = _exportType == 2 || _exportType == 3 || _exportType == 4;

			switch(_exportType)
			{
				case 0:
					try
					{
						dataBytes = getSWFBytes();
						if(dataBytes)
						{
							exportSave(
								DataParser.compressData(
									xmlToObject(_xmlDataProxy.xml, GlobalConstValues.XML_LIST_NAMES),
									xmlToObject(_xmlDataProxy.textureAtlasXML, GlobalConstValues.XML_LIST_NAMES),
									dataBytes
								),
								_importDataProxy.data.name + GlobalConstValues.SWF_SUFFIX
							);
							return;
						}
						break;
					}
					catch(_e:Error)
					{
						break;
					}
				case 1:
					try
					{
						dataBytes = getPNGBytes();
						if(dataBytes)
						{
							exportSave(
								DataParser.compressData(
									xmlToObject(_xmlDataProxy.xml, GlobalConstValues.XML_LIST_NAMES),
									xmlToObject(_xmlDataProxy.textureAtlasXML, GlobalConstValues.XML_LIST_NAMES),
									dataBytes
								),
								_importDataProxy.data.name + GlobalConstValues.PNG_SUFFIX
							);
							return;
						}
						break;
					}
					catch(_e:Error)
					{
						break;
					}
				case 2:
				case 3:
				case 5:
				case 6:
					try
					{
						if(isSWF)
						{
							dataBytes = getSWFBytes();
						}
						else
						{
							dataBytes = getPNGBytes();
						}

						if(dataBytes)
						{
							date = new Date();
							zip = new Zip();
							zip.add(
								dataBytes,
								GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + (isSWF?GlobalConstValues.SWF_SUFFIX:GlobalConstValues.PNG_SUFFIX),
								date
							);
							_xmlDataProxy.setImagePath(GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.PNG_SUFFIX);

							if(isXML)
							{
								zip.add(
									_xmlDataProxy.xml.toXMLString(),
									GlobalConstValues.DRAGON_BONES_DATA_NAME + GlobalConstValues.XML_SUFFIX,
									date
								);
								zip.add(
									_xmlDataProxy.textureAtlasXML.toXMLString(),
									GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.XML_SUFFIX,
									date
								);
							}
							else
							{
								zip.add(
									com.adobe.serialization.json.JSON.encode(xmlToObject(_xmlDataProxy.xml, GlobalConstValues.XML_LIST_NAMES)),
									GlobalConstValues.DRAGON_BONES_DATA_NAME + GlobalConstValues.JSON_SUFFIX,
									date
								);
								zip.add(
									com.adobe.serialization.json.JSON.encode(xmlToObject(_xmlDataProxy.textureAtlasXML, GlobalConstValues.XML_LIST_NAMES)),
									GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.JSON_SUFFIX,
									date
								);
							}
							exportSave(
								zip.encode(),
								_importDataProxy.data.name + GlobalConstValues.ZIP_SUFFIX
							);
							zip.clear();
							return;
						}
						break;
					}
					catch(_e:Error)
					{
						break;
					}
				case 4:
				case 7:
					try
					{
						date = new Date();
						zip = new Zip();

						if(_xmlDataProxy == _importDataProxy.xmlDataProxy)
						{
							_xmlDataProxy = _xmlDataProxy.clone();
						}
						_xmlDataProxy.changePath();

						subBitmapDataDic = BitmapDataUtil.getSubBitmapDataDic(
							_bitmapData,
							_xmlDataProxy.getSubTextureRectMap()
						);
						for(var subTextureName:String in subBitmapDataDic)
						{
							var subBitmapData:BitmapData = subBitmapDataDic[subTextureName];
							zip.add(
								PNGEncoder.encode(subBitmapData),
								GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + "/" + subTextureName + GlobalConstValues.PNG_SUFFIX,
								date
							);
							subBitmapData.dispose();
						}
						if(isXML)
						{
							zip.add(
								_xmlDataProxy.xml.toXMLString(),
								GlobalConstValues.DRAGON_BONES_DATA_NAME + GlobalConstValues.XML_SUFFIX,
								date
							);
							zip.add(
								_xmlDataProxy.textureAtlasXML.toXMLString(),
								GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.XML_SUFFIX,
								date
							);
						}
						else
						{
							zip.add(
								com.adobe.serialization.json.JSON.encode(xmlToObject(_xmlDataProxy.xml, GlobalConstValues.XML_LIST_NAMES)),
								GlobalConstValues.DRAGON_BONES_DATA_NAME + GlobalConstValues.JSON_SUFFIX,
								date
							);
							zip.add(
								com.adobe.serialization.json.JSON.encode(xmlToObject(_xmlDataProxy.textureAtlasXML, GlobalConstValues.XML_LIST_NAMES)),
								GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.JSON_SUFFIX,
								date
							);
						}

						exportSave(
							zip.encode(),
							_importDataProxy.data.name + GlobalConstValues.ZIP_SUFFIX
						);
						zip.clear();
						return;
					}
					catch(_e:Error)
					{
						break;
					}
				default:
					break;
			}
			_isExporting = false;
			MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT_ERROR);
		}

		private function getSWFBytes():ByteArray
		{
			if(_importDataProxy.textureAtlas.movieClip)
			{
				return _importDataProxy.textureBytes;
			}
			return null;
		}

		private function getPNGBytes():ByteArray
		{
			if(_importDataProxy.textureAtlas.movieClip)
			{
				return PNGEncoder.encode(_bitmapData);
			}
			else
			{
				if(_bitmapData && _bitmapData != _importDataProxy.textureAtlas.bitmapData)
				{
					return PNGEncoder.encode(_bitmapData);
				}
				return _importDataProxy.textureBytes;
			}
			return null;
		}

		private function exportSave(fileData:ByteArray, fileName:String):void
		{
			MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT, fileName);
			_fileREF.addEventListener(Event.CANCEL, onFileSaveHandler);
			_fileREF.addEventListener(Event.COMPLETE, onFileSaveHandler);
			_fileREF.addEventListener(IOErrorEvent.IO_ERROR, onFileSaveHandler);
			_fileREF.save(fileData, fileName);
		}

		private function onFileSaveHandler(e:Event):void
		{
			_fileREF.removeEventListener(Event.CANCEL, onFileSaveHandler);
			_fileREF.removeEventListener(Event.COMPLETE, onFileSaveHandler);
			_fileREF.removeEventListener(IOErrorEvent.IO_ERROR, onFileSaveHandler);
			_isExporting = false;
			switch(e.type)
			{
				case Event.CANCEL:
					MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT_CANCEL);
					break;
				case IOErrorEvent.IO_ERROR:
					MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT_ERROR);
					break;
				case Event.COMPLETE:
					if(_bitmapData && _bitmapData != _importDataProxy.textureAtlas.bitmapData)
					{
						_bitmapData.dispose();
						_bitmapData = null;
					}
					MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT_COMPLETE);
					break;
			}
		}
	}
}

package control
{
	import com.adobe.serialization.json.JSON;

	import dragonBones.objects.DataParser;
	import dragonBones.utils.ConstValues;

	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.net.FileReference;
	import flash.utils.ByteArray;

	import message.Message;
	import message.MessageDispatcher;

	import model.ImportDataProxy;
	import model.JSFLProxy;
	import model.XMLDataProxy;

	import utils.BitmapDataUtil;
	import utils.GlobalConstValues;
	import utils.PNGEncoder;
	import utils.xmlToObject;

	import zero.zip.Zip;

	public class ExportDataCommand
	{
		public static const instance:ExportDataCommand = new ExportDataCommand();

		private var _fileREF:FileReference;
		private var _isExporting:Boolean;
		private var _scale:Number;
		private var _exportType:uint;
		private var _backgroundColor:uint;

		private var _importDataProxy:ImportDataProxy;

		private var _xmlDataProxy:XMLDataProxy;
		private var _bitmapData:BitmapData;

		public function ExportDataCommand()
		{
			_fileREF = new FileReference();

			_importDataProxy = ImportDataProxy.getInstance();
		}

		public function export(exportType:uint, scale:Number, backgroundColor:uint = 0):void
		{
			if(_isExporting)
			{
				return;
			}
			_isExporting = true;

			_exportType = exportType;
			_scale = scale;

			switch(_exportType)
			{
				case 0:
				case 2:
				case 5:
					_scale = 1;
					break;
			}

			_backgroundColor = backgroundColor;

			exportStart();
		}

		private function exportStart():void
		{
			var dataBytes:ByteArray;
			var zip:Zip;
			var date:Date;

			_xmlDataProxy = _importDataProxy.xmlDataProxy;
			_bitmapData = _importDataProxy.textureAtlas.bitmapData;

			if(_scale != 1)
			{
				_xmlDataProxy = _xmlDataProxy.clone();
				var subBitmapDataDic:Object;
				var movieClip:MovieClip = _importDataProxy.textureAtlas.movieClip;
				if(movieClip && movieClip.totalFrames >= 3)
				{
					subBitmapDataDic = {};
					for each (var displayName:String in _xmlDataProxy.getSubTextureListFromDisplayList())
					{
						movieClip.gotoAndStop(movieClip.totalFrames);
						movieClip.gotoAndStop(displayName);
						subBitmapDataDic[displayName] = movieClip.getChildAt(0);
					}
				}
				else
				{
					subBitmapDataDic = BitmapDataUtil.getSubBitmapDataDic(
						_bitmapData,
						_xmlDataProxy.getSubTextureRectMap()
					);
				}

				_xmlDataProxy.scaleData(_scale);

				_bitmapData = BitmapDataUtil.getMergeBitmapData(
					subBitmapDataDic,
					_xmlDataProxy.getSubTextureRectMap(),
					_xmlDataProxy.textureAtlasWidth,
					_xmlDataProxy.textureAtlasHeight,
					_scale
				);
			}

			var isSWF:Boolean = _exportType == 0 || _exportType == 2 || _exportType == 5;
			var isXML:Boolean = _exportType == 2 || _exportType == 3 || _exportType == 4;

			switch(_exportType)
			{
				case 0:
					try
					{
						dataBytes = getSWFBytes();
						if(dataBytes)
						{
							exportSave(
								DataParser.compressData(
									xmlToObject(_xmlDataProxy.xml, GlobalConstValues.XML_LIST_NAMES),
									xmlToObject(_xmlDataProxy.textureAtlasXML, GlobalConstValues.XML_LIST_NAMES),
									dataBytes
								),
								_importDataProxy.data.name + GlobalConstValues.SWF_SUFFIX
							);
							return;
						}
						break;
					}
					catch(_e:Error)
					{
						break;
					}
				case 1:
					try
					{
						dataBytes = getPNGBytes(_backgroundColor);
						if(dataBytes)
						{
							exportSave(
								DataParser.compressData(
									xmlToObject(_xmlDataProxy.xml, GlobalConstValues.XML_LIST_NAMES),
									xmlToObject(_xmlDataProxy.textureAtlasXML, GlobalConstValues.XML_LIST_NAMES),
									dataBytes
								),
								_importDataProxy.data.name + GlobalConstValues.PNG_SUFFIX
							);
							return;
						}
						break;
					}
					catch(_e:Error)
					{
						break;
					}
				case 2:
				case 3:
				case 5:
				case 6:
					try
					{
						if(isSWF)
						{
							dataBytes = getSWFBytes();
						}
						else
						{
							dataBytes = getPNGBytes(_backgroundColor);
						}

						if(dataBytes)
						{
							date = new Date();
							zip = new Zip();
							zip.add(
								dataBytes,
								GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + (isSWF?GlobalConstValues.SWF_SUFFIX:GlobalConstValues.PNG_SUFFIX),
								date
							);
							_xmlDataProxy.setImagePath(GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.PNG_SUFFIX);

							if(isXML)
							{
								zip.add(
									_xmlDataProxy.xml.toXMLString(),
									GlobalConstValues.DRAGON_BONES_DATA_NAME + GlobalConstValues.XML_SUFFIX,
									date
								);
								zip.add(
									_xmlDataProxy.textureAtlasXML.toXMLString(),
									GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.XML_SUFFIX,
									date
								);
							}
							else
							{
								zip.add(
									com.adobe.serialization.json.JSON.encode(xmlToObject(_xmlDataProxy.xml, GlobalConstValues.XML_LIST_NAMES)),
									GlobalConstValues.DRAGON_BONES_DATA_NAME + GlobalConstValues.JSON_SUFFIX,
									date
								);
								zip.add(
									com.adobe.serialization.json.JSON.encode(xmlToObject(_xmlDataProxy.textureAtlasXML, GlobalConstValues.XML_LIST_NAMES)),
									GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.JSON_SUFFIX,
									date
								);
							}
							exportSave(
								zip.encode(),
								_importDataProxy.data.name + GlobalConstValues.ZIP_SUFFIX
							);
							zip.clear();
							return;
						}
						break;
					}
					catch(_e:Error)
					{
						break;
					}
				case 4:
				case 7:
					try
					{
						date = new Date();
						zip = new Zip();

						if(_xmlDataProxy == _importDataProxy.xmlDataProxy)
						{
							_xmlDataProxy = _xmlDataProxy.clone();
						}
						_xmlDataProxy.changePath();

						subBitmapDataDic = BitmapDataUtil.getSubBitmapDataDic(
							_bitmapData,
							_xmlDataProxy.getSubTextureRectMap()
						);
						for(var subTextureName:String in subBitmapDataDic)
						{
							var subBitmapData:BitmapData = subBitmapDataDic[subTextureName];
							zip.add(
								PNGEncoder.encode(subBitmapData),
								GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + "/" + subTextureName + GlobalConstValues.PNG_SUFFIX,
								date
							);
							subBitmapData.dispose();
						}
						if(isXML)
						{
							zip.add(
								_xmlDataProxy.xml.toXMLString(),
								GlobalConstValues.DRAGON_BONES_DATA_NAME + GlobalConstValues.XML_SUFFIX,
								date
							);
							zip.add(
								_xmlDataProxy.textureAtlasXML.toXMLString(),
								GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.XML_SUFFIX,
								date
							);
						}
						else
						{
							zip.add(
								com.adobe.serialization.json.JSON.encode(xmlToObject(_xmlDataProxy.xml, GlobalConstValues.XML_LIST_NAMES)),
								GlobalConstValues.DRAGON_BONES_DATA_NAME + GlobalConstValues.JSON_SUFFIX,
								date
							);
							zip.add(
								com.adobe.serialization.json.JSON.encode(xmlToObject(_xmlDataProxy.textureAtlasXML, GlobalConstValues.XML_LIST_NAMES)),
								GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.JSON_SUFFIX,
								date
							);
						}

						exportSave(
							zip.encode(),
							_importDataProxy.data.name + GlobalConstValues.ZIP_SUFFIX
						);
						zip.clear();
						return;
					}
					catch(_e:Error)
					{
						break;
					}
				default:
					break;
			}
			_isExporting = false;
			MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT_ERROR);
		}

		private function getSWFBytes():ByteArray
		{
			if(_importDataProxy.textureAtlas.movieClip)
			{
				return _importDataProxy.textureBytes;
			}
			return null;
		}

		private function getPNGBytes(color:uint = 0):ByteArray
		{
			if(color)
			{
				var bitmapData:BitmapData = new BitmapData(_bitmapData.width, _bitmapData.height, true, color);
				bitmapData.draw(_bitmapData);

				var byteArray:ByteArray = PNGEncoder.encode(bitmapData);
				bitmapData.dispose();

				return byteArray;
			}
			else if(_importDataProxy.textureAtlas.movieClip)
			{
				return PNGEncoder.encode(_bitmapData);
			}
			else
			{
				if(_bitmapData && _bitmapData != _importDataProxy.textureAtlas.bitmapData)
				{
					return PNGEncoder.encode(_bitmapData);
				}
				return _importDataProxy.textureBytes;
			}
			return null;
		}

		private function exportSave(fileData:ByteArray, fileName:String):void
		{
			MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT, fileName);
			_fileREF.addEventListener(Event.CANCEL, onFileSaveHandler);
			_fileREF.addEventListener(Event.COMPLETE, onFileSaveHandler);
			_fileREF.addEventListener(IOErrorEvent.IO_ERROR, onFileSaveHandler);
			_fileREF.save(fileData, fileName);
		}

		private function onFileSaveHandler(e:Event):void
		{
			_fileREF.removeEventListener(Event.CANCEL, onFileSaveHandler);
			_fileREF.removeEventListener(Event.COMPLETE, onFileSaveHandler);
			_fileREF.removeEventListener(IOErrorEvent.IO_ERROR, onFileSaveHandler);
			_isExporting = false;
			switch(e.type)
			{
				case Event.CANCEL:
					MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT_CANCEL);
					break;
				case IOErrorEvent.IO_ERROR:
					MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT_ERROR);
					break;
				case Event.COMPLETE:
					if(_bitmapData && _bitmapData != _importDataProxy.textureAtlas.bitmapData)
					{
						_bitmapData.dispose();
						_bitmapData = null;
					}
					MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT_COMPLETE);
					break;
			}
		}
	}
}

add export background color

add export background color


/*
 * Copyright 2014 Mozilla Foundation
 *
 * 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 flash.text {
import flash.display.DisplayObject;
import flash.display.InteractiveObject;
import flash.geom.Rectangle;

[native(cls='TextFieldClass')]
public class TextField extends InteractiveObject {
  public static native function isFontCompatible(fontName: String, fontStyle: String): Boolean;
  public function TextField() {}
  public native function get alwaysShowSelection(): Boolean;
  public native function set alwaysShowSelection(value: Boolean): void;
  public native function get antiAliasType(): String;
  public native function set antiAliasType(antiAliasType: String): void;
  public native function get autoSize(): String;
  public native function set autoSize(value: String): void;
  public native function get background(): Boolean;
  public native function set background(value: Boolean): void;
  public native function get backgroundColor(): uint;
  public native function set backgroundColor(value: uint): void;
  public native function get border(): Boolean;
  public native function set border(value: Boolean): void;
  public native function get borderColor(): uint;
  public native function set borderColor(value: uint): void;
  public native function get bottomScrollV(): int;
  public native function get caretIndex(): int;
  public native function get condenseWhite(): Boolean;
  public native function set condenseWhite(value: Boolean): void;
  public native function get defaultTextFormat(): TextFormat;
  public native function set defaultTextFormat(format: TextFormat): void;
  public native function get embedFonts(): Boolean;
  public native function set embedFonts(value: Boolean): void;
  public native function get gridFitType(): String;
  public native function set gridFitType(gridFitType: String): void;
  public native function get htmlText(): String;
  public native function set htmlText(value: String): void;
  public native function get length(): int;
  public native function get textInteractionMode(): String;
  public native function get maxChars(): int;
  public native function set maxChars(value: int): void;
  public native function get maxScrollH(): int;
  public native function get maxScrollV(): int;
  public native function get mouseWheelEnabled(): Boolean;
  public native function set mouseWheelEnabled(value: Boolean): void;
  public native function get multiline(): Boolean;
  public native function set multiline(value: Boolean): void;
  public native function get numLines(): int;
  public native function get displayAsPassword(): Boolean;
  public native function set displayAsPassword(value: Boolean): void;
  public native function get restrict(): String;
  public native function set restrict(value: String): void;
  public native function get scrollH(): int;
  public native function set scrollH(value: int): void;
  public native function get scrollV(): int;
  public native function set scrollV(value: int): void;
  public native function get selectable(): Boolean;
  public native function set selectable(value: Boolean): void;
  public function get selectedText(): String {
    return text.substring(selectionBeginIndex, selectionEndIndex);
  }
  public native function get selectionBeginIndex(): int;
  public native function get selectionEndIndex(): int;
  public native function get sharpness(): Number;
  public native function set sharpness(value: Number): void;
  public native function get styleSheet(): StyleSheet;
  public native function set styleSheet(value: StyleSheet): void;
  public native function get text(): String;
  public native function set text(value: String): void;
  public native function get textColor(): uint;
  public native function set textColor(value: uint): void;
  public native function get textHeight(): Number;
  public native function get textWidth(): Number;
  public native function get thickness(): Number;
  public native function set thickness(value: Number): void;
  public native function get type(): String;
  public native function set type(value: String): void;
  public native function get wordWrap(): Boolean;
  public native function set wordWrap(value: Boolean): void;
  public native function get useRichTextClipboard(): Boolean;
  public native function set useRichTextClipboard(value: Boolean): void;
  public function appendText(newText: String): void {
    var beginIndex: uint = text.length;
    replaceText(beginIndex, beginIndex, newText);
  }
  public native function getCharBoundaries(charIndex: int): Rectangle;
  public native function getCharIndexAtPoint(x: Number, y: Number): int;
  public native function getFirstCharInParagraph(charIndex: int): int;
  public native function getLineIndexAtPoint(x: Number, y: Number): int;
  public native function getLineIndexOfChar(charIndex: int): int;
  public native function getLineLength(lineIndex: int): int;
  public native function getLineMetrics(lineIndex: int): TextLineMetrics;
  public native function getLineOffset(lineIndex: int): int;
  public native function getLineText(lineIndex: int): String;
  public native function getParagraphLength(charIndex: int): int;
  public native function getTextFormat(beginIndex: int = -1, endIndex: int = -1): TextFormat;
  public native function getTextRuns(beginIndex: int = 0, endIndex: int = 2147483647): Array;
  public native function getRawText(): String;
  public function getXMLText(beginIndex: int = 0, endIndex: int = 2147483647): String {
    notImplemented("getXMLText");
    return "";
  }
  public function insertXMLText(beginIndex: int, endIndex: int, richText: String,
                                pasting: Boolean = false): void
  {
    notImplemented("insertXMLText");
  }
  public native function replaceSelectedText(value: String): void;
  public native function replaceText(beginIndex: int, endIndex: int, newText: String): void;
  public native function setSelection(beginIndex: int, endIndex: int): void;
  public native function setTextFormat(format: TextFormat, beginIndex: int = -1,
                                       endIndex: int = -1): void;
  public native function getImageReference(id: String): DisplayObject;
  internal function copyRichText(): String {
    notImplemented("copyRichText");
    return "";
  }
  internal function pasteRichText(richText: String): Boolean {
    notImplemented("pasteRichText");
    return false;
  }
}
}

Add license header to flash/text/TextField


/**
 * Copyright (c) 2009 Lance Carlson
 * See LICENSE for full license information.
 */

package flails.resource {

  import flash.events.EventDispatcher;

  dynamic public class Record extends EventDispatcher {
    public function Record(attributes:Object=null) {
      trace("initializing Record with attributes " + attributes)

      if (attributes != null) {
        setAttributes(attributes);
      }
    }

    public function setAttributes(attributes:Object):void {
      trace("setting the record's attributes");

      for (var key:String in attributes) {
        trace("setting " + key + " with " + attributes[key]);
        this[key] = attributes[key];
      }
    }

    /*    public function resource():Resource {
      return new Resource(type, this.constructor);
      }

    public function save():Request {
      return resource().update(this.id, sanitized());
    }

    private function sanitized():Record {
      var sanitizedRecord:Record = this;
      delete sanitizedRecord["id"];
      deleteBelongsToAssociations(sanitizedRecord);
      return sanitizedRecord;
    }

    private function belongsToKeys():Array {
      var belongsToKeys:Array = new Array;
      for (var key:String in this) {
        var matches:Array = key.match(/^(.*)_id$/);
        if (matches != null) {
          belongsToKeys.push(String(matches[1]));
        }
      }
      return belongsToKeys;
    }

    private function setBelongsToAssociations():void {
      belongsToKeys().forEach(function(belongsToKey:String, index:int, array:Array):void {
        this[belongsToKey] = function():Request {
          return Resource.forName(belongsToKey).findByID(this[belongsToKey + "_id"]);
        }
      });
    }

    private function deleteBelongsToAssociations(record:Record):Record {
      belongsToKeys().forEach(function(belongsToKey:String, index:int, array:Array):void {
        delete record[belongsToKey];
      });

      return record;
    }
    */

/*    public static function create(json:Object):Object {
      var type:String = findType(json);
      var record:Object = json[type];

      record = assignRequiredAttributes(record, type);
      record = assignFunctions(record);
      record = assignBelongsToAssociations(record);

      return record;
    }*/

/*    private static function sanitizeObject(unsanitized:Object):Object {
      delete unsanitized._type;
      delete unsanitized._model;
      delete unsanitized.save;

      unsanitized = deleteBelongsToAssociations(unsanitized);

      return unsanitized;
    }
    */
/*    private static function camelize(lowerCaseAndUnderscoredWord:String):String {
      var firstLetterLowerCase:String = lowerCaseAndUnderscoredWord.charAt(0).toLowerCase() + lowerCaseAndUnderscoredWord.slice(1);

      return firstLetterLowerCase.replace(/_(.)/g, function():String {
        return arguments[1].toUpperCase();
      });
    }*/

/*    public function updateAttributes(attributes:Object):Request {
      return this["model"].update(this["id"], attributes);
        return new Request("post");
    }*/

  }
}

/**
 * Copyright (c) 2009 Lance Carlson
 * See LICENSE for full license information.
 */

package flails.resource {

  import flash.events.EventDispatcher;

  dynamic public class Record extends EventDispatcher {
    public function Record(attributes:Object=null) {
      trace("initializing Record with attributes " + attributes)

      if (attributes != null) {
        setAttributes(attributes);
      }
    }

    public function setAttributes(attributes:Object):Record {
      trace("setting the record's attributes");

      for (var key:String in attributes) {
        trace("setting " + key + " with " + attributes[key]);
        this[key] = attributes[key];
      }

      return this;
    }

    /*    public function resource():Resource {
      return new Resource(type, this.constructor);
      }

    public function save():Request {
      return resource().update(this.id, sanitized());
    }

    private function sanitized():Record {
      var sanitizedRecord:Record = this;
      delete sanitizedRecord["id"];
      deleteBelongsToAssociations(sanitizedRecord);
      return sanitizedRecord;
    }

    private function belongsToKeys():Array {
      var belongsToKeys:Array = new Array;
      for (var key:String in this) {
        var matches:Array = key.match(/^(.*)_id$/);
        if (matches != null) {
          belongsToKeys.push(String(matches[1]));
        }
      }
      return belongsToKeys;
    }

    private function setBelongsToAssociations():void {
      belongsToKeys().forEach(function(belongsToKey:String, index:int, array:Array):void {
        this[belongsToKey] = function():Request {
          return Resource.forName(belongsToKey).findByID(this[belongsToKey + "_id"]);
        }
      });
    }

    private function deleteBelongsToAssociations(record:Record):Record {
      belongsToKeys().forEach(function(belongsToKey:String, index:int, array:Array):void {
        delete record[belongsToKey];
      });

      return record;
    }
    */

/*    public static function create(json:Object):Object {
      var type:String = findType(json);
      var record:Object = json[type];

      record = assignRequiredAttributes(record, type);
      record = assignFunctions(record);
      record = assignBelongsToAssociations(record);

      return record;
    }*/

/*    private static function sanitizeObject(unsanitized:Object):Object {
      delete unsanitized._type;
      delete unsanitized._model;
      delete unsanitized.save;

      unsanitized = deleteBelongsToAssociations(unsanitized);

      return unsanitized;
    }
    */
/*    private static function camelize(lowerCaseAndUnderscoredWord:String):String {
      var firstLetterLowerCase:String = lowerCaseAndUnderscoredWord.charAt(0).toLowerCase() + lowerCaseAndUnderscoredWord.slice(1);

      return firstLetterLowerCase.replace(/_(.)/g, function():String {
        return arguments[1].toUpperCase();
      });
    }*/

/*    public function updateAttributes(attributes:Object):Request {
      return this["model"].update(this["id"], attributes);
        return new Request("post");
    }*/

  }
}

Return the Record upon calling setAttributes().


// This ActionScript file defines a list of values that are considered
// important for checking various ActionScript operations.
// It defines 2 variables:
// - "values": The array of values to be checked
// - "names": The array of corresponding string representations for values.
//            It's suggested to use these instead of using values directly to
//            avoid spurious toString and valueOf calls.

printall = new Object ();
printall.valueOf = function () {
  trace ("valueOf called");
  return this;
};
printall.toString = function () {
  trace ("toString called");
  return this;
};

printtostring = new Object ();
printtostring.toString = function () {
  trace ("toString called with " + arguments);
  return this;
};

printvalueof = new Object ();
printvalueof.valueOf = function () {
  trace ("valueOf called with " + arguments);
  return this;
};

nothing = new Object ();
nothing.__proto__ = undefined;
values = [
  undefined,
  null,
  true, false,
  0, 1, 0.5, -1, -0.5, Infinity, -Infinity, NaN,
  "", "0", "-0", "0.0", "1", "Hello World!", "true", "_level0", "äöü",
  this, new Object (), new Date (), new String (),
  Function, printall, printtostring, printvalueof, nothing ];

var l = values.length;
var v = function () {
  trace (this.nr + ": valueOf!");
  return this.v;
};
var s = function () {
  trace (this.nr + ": toString!");
  return this.v;
};
for (i = 0; i < l; i++) {
  var o = new Object ();
  o.nr = i;
  o.valueOf = v;
  o.toString = s;
  o.v = values[i];
  values.push (o);
};

names = [];
for (i = 0; i < values.length; i++) {
  names[i] = "(" + i + ") " + values[i] + " (" + typeof (values[i]) + ")";
};

// This ActionScript file defines a list of values that are considered
// important for checking various ActionScript operations.
// It defines 2 variables:
// - "values": The array of values to be checked
// - "names": The array of corresponding string representations for values.
//            It's suggested to use these instead of using values directly to
//            avoid spurious toString and valueOf calls.

printall = new Object ();
printall.valueOf = function () {
  trace ("valueOf called");
  return this;
};
printall.toString = function () {
  trace ("toString called");
  return this;
};

printtostring = new Object ();
printtostring.toString = function () {
  trace ("toString called with " + arguments);
  return this;
};

printvalueof = new Object ();
printvalueof.valueOf = function () {
  trace ("valueOf called with " + arguments);
  return this;
};

nothing = new Object ();
nothing.__proto__ = undefined;
values = [
  undefined,
  null,
  true, false,
  0, 1, 0.5, -1, -0.5, Infinity, -Infinity, NaN,
  "", "0", "-0", "0.0", "1", "Hello World!", "true", "_level0", "äöü",
  this, new Object (), new Date (1239752134235.94), new String (),
  Function, printall, printtostring, printvalueof, nothing ];

var l = values.length;
var v = function () {
  trace (this.nr + ": valueOf!");
  return this.v;
};
var s = function () {
  trace (this.nr + ": toString!");
  return this.v;
};
for (i = 0; i < l; i++) {
  var o = new Object ();
  o.nr = i;
  o.valueOf = v;
  o.toString = s;
  o.v = values[i];
  values.push (o);
};

names = [];
for (i = 0; i < values.length; i++) {
  names[i] = "(" + i + ") " + values[i] + " (" + typeof (values[i]) + ")";
};

Change values.as to use a specific date

Change values.as to use a specific date


//
// $Id$
//
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/nenya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

package com.threerings.flex {

import flash.display.DisplayObject;

import mx.core.UIComponent;

/**
 * Wraps a non-Flex component for use in Flex.
 */
public class FlexWrapper extends UIComponent
{
    public function FlexWrapper (object :DisplayObject)
    {
        // don't capture mouse events in this wrapper
        mouseEnabled = false;
        addChild(object);
        width = object.width;
        height = object.height;
    }
}
}

//
// $Id$
//
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/nenya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

package com.threerings.flex {

import flash.display.DisplayObject;

import mx.core.UIComponent;

/**
 * Wraps a non-Flex component for use in Flex.
 */
public class FlexWrapper extends UIComponent
{
    public function FlexWrapper (object :DisplayObject, inheritSize :Boolean = false)
    {
        // don't capture mouse events in this wrapper
        mouseEnabled = false;
        addChild(object);
        if (inheritSize) {
            width = object.width;
            height = object.height;
        }
    }
}
}

Make this optional, and not the default.
Turns out a bunch of shit makes the wrapper size a little bigger,
and some things seem to freak out when the wrapper has a size,
even when includeInLayout=false.
Flex you very much.

git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@616 ed5b42cb-e716-0410-a449-f6a68f950b19


package {
    import flash.display.Sprite;
    import flash.display.StageScaleMode;
    import flash.display.StageAlign;
    import flash.geom.Point;

    import flash.external.ExternalInterface;

    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.media.Camera;
    import flash.media.Video;
    import flash.utils.ByteArray;
    import mx.graphics.codec.JPEGEncoder;

    import flash.events.Event;
    import flash.events.HTTPStatusEvent;
    import flash.events.IOErrorEvent;
    import flash.events.SecurityErrorEvent;
    import flash.net.URLLoader;
    import flash.net.URLRequest;

    public class CameraMan extends Sprite {

        private var videoface:Video;
        private var cam:Camera;
        private var photo:BitmapData;
        private var sendto:String;
        private var movieSize:Point;

        public function CameraMan() {
            stage.align = StageAlign.TOP_LEFT;

            trace("START ME UP");
            this.loaderInfo.addEventListener("init", init);

            if (ExternalInterface.available) {
                ExternalInterface.addCallback("takePhoto", takePhoto);
                ExternalInterface.addCallback("sendPhoto", sendPhoto);
            }
        }

        public function init(event:Event) : void {
            trace("initizing");

            sendto = this.loaderInfo.parameters.sendto;
            trace("Sending to " + sendto);
            movieSize = new Point(this.loaderInfo.width, this.loaderInfo.height);
            trace("Movie size is " + this.loaderInfo.width + ", " + this.loaderInfo.height);

            this.initCamera();
        }

        public function initCamera() : void {
            videoface = new Video(movieSize.x, movieSize.y);
            this.addChild(videoface);
            trace("Video is " + videoface.videoWidth + ", " + videoface.videoHeight);
            cam = Camera.getCamera();
            cam.setMode(movieSize.x, movieSize.y, 15);
            videoface.attachCamera(cam);
            trace("Video w/ camera is " + videoface.videoWidth + ", " + videoface.videoHeight);
        }

        public function takePhoto() : void {
            // freeze image
            try {
                photo = new BitmapData(videoface.videoWidth, videoface.videoHeight, false);
                photo.draw(videoface);

                // Swap the video for the captured bitmap.
                var bitty:Bitmap = new Bitmap(photo);
                this.addChild(bitty);
                this.removeChild(videoface);
            } catch(err:Error) {
                trace(err.name + " " + err.message);
            }

            if (ExternalInterface.available) {
                ExternalInterface.call('cameraman._tookPhoto');
            }
        }

        public function sendPhoto() : void {
            try {
                // produce image file
                var peggy:JPEGEncoder = new JPEGEncoder(75.0);
                var image:ByteArray = peggy.encode(photo);

                // send image file to server
                var req:URLRequest = new URLRequest();
                req.url = this.sendto;
                req.method = "POST";
                req.contentType = peggy.contentType;
                req.data = image;

                var http:URLLoader = new URLLoader();
                http.addEventListener("complete", sentPhoto);
                http.addEventListener("ioError", sendingIOError);
                http.addEventListener("securityError", sendingSecurityError);
                http.addEventListener("httpStatus", sendingHttpStatus);
                http.load(req);
            } catch(err:Error) {
                trace(err.name + " " + err.message);
            }
        }

        public function sendingHttpStatus(event:HTTPStatusEvent) : void {
            trace("HTTPStatus: " + event.status + " " + event.target);
        }

        public function sendingIOError(event:IOErrorEvent) : void {
            trace("IOError: " + event.type + " " + event.text + " " + event.target + " " + event.target.bytesLoaded);
        }

        public function sendingSecurityError(event:SecurityErrorEvent) : void {
            trace("SecurityError: " + event.text + " " + event.target);
        }

        public function sentPhoto(event:Event) : void {
            var url:String = event.target.data;
            if (ExternalInterface.available)
                ExternalInterface.call('cameraman._sentPhoto', url);
        }

    }
}

package {
    import flash.display.Sprite;
    import flash.display.StageScaleMode;
    import flash.display.StageAlign;
    import flash.geom.Point;

    import flash.external.ExternalInterface;

    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.media.Camera;
    import flash.media.Video;
    import flash.utils.ByteArray;
    import mx.graphics.codec.JPEGEncoder;

    import flash.events.Event;
    import flash.events.HTTPStatusEvent;
    import flash.events.IOErrorEvent;
    import flash.events.SecurityErrorEvent;
    import flash.net.URLLoader;
    import flash.net.URLRequest;

    public class CameraMan extends Sprite {

        private var videoface:Video;
        private var cam:Camera;
        private var photo:BitmapData;
        private var sendto:String;
        private var movieSize:Point;

        public function CameraMan() {
            stage.scaleMode = StageScaleMode.NO_SCALE;
            stage.align = StageAlign.TOP_LEFT;

            trace("START ME UP");
            this.loaderInfo.addEventListener("init", init);

            if (ExternalInterface.available) {
                ExternalInterface.addCallback("takePhoto", takePhoto);
                ExternalInterface.addCallback("sendPhoto", sendPhoto);
            }
        }

        public function init(event:Event) : void {
            trace("initizing");
            sendto = this.loaderInfo.parameters.sendto;

            movieSize = new Point(this.loaderInfo.width, this.loaderInfo.height);
            trace("Movie size is " + this.loaderInfo.width + ", " + this.loaderInfo.height);

            cam = Camera.getCamera();
            cam.setMode(movieSize.x, movieSize.y, 15);
            trace("Camera size is " + cam.width + ", " + cam.height);

            videoface = new Video(cam.width, cam.height);
            videoface.attachCamera(cam);

            this.addChild(videoface);
        }

        public function takePhoto() : void {
            // freeze image
            try {
                photo = new BitmapData(videoface.videoWidth, videoface.videoHeight, false);
                photo.draw(videoface);

                // Swap the video for the captured bitmap.
                var bitty:Bitmap = new Bitmap(photo);
                this.addChild(bitty);
                this.removeChild(videoface);
            } catch(err:Error) {
                trace(err.name + " " + err.message);
            }

            if (ExternalInterface.available) {
                ExternalInterface.call('cameraman._tookPhoto');
            }
        }

        public function sendPhoto() : void {
            try {
                // produce image file
                var peggy:JPEGEncoder = new JPEGEncoder(75.0);
                var image:ByteArray = peggy.encode(photo);

                // send image file to server
                var req:URLRequest = new URLRequest();
                req.url = this.sendto;
                req.method = "POST";
                req.contentType = peggy.contentType;
                req.data = image;

                var http:URLLoader = new URLLoader();
                http.addEventListener("complete", sentPhoto);
                http.addEventListener("ioError", sendingIOError);
                http.addEventListener("securityError", sendingSecurityError);
                http.addEventListener("httpStatus", sendingHttpStatus);
                http.load(req);
            } catch(err:Error) {
                trace(err.name + " " + err.message);
            }
        }

        public function sendingHttpStatus(event:HTTPStatusEvent) : void {
            trace("HTTPStatus: " + event.status + " " + event.target);
        }

        public function sendingIOError(event:IOErrorEvent) : void {
            trace("IOError: " + event.type + " " + event.text + " " + event.target + " " + event.target.bytesLoaded);
        }

        public function sendingSecurityError(event:SecurityErrorEvent) : void {
            trace("SecurityError: " + event.text + " " + event.target);
        }

        public function sentPhoto(event:Event) : void {
            var url:String = event.target.data;
            if (ExternalInterface.available)
                ExternalInterface.call('cameraman._sentPhoto', url);
        }

    }
}

Adjust how the video and camera are created to reality


/*
 * Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contributor(s):
 *   Zwetan Kjukov <zwetan@gmail.com>.
 */

package com.google.analytics.core
{
    import com.google.analytics.external.AdSenseGlobals;
    import com.google.analytics.utils.Environment;
    import com.google.analytics.utils.Variables;
    import com.google.analytics.v4.Configuration;

    /**
     * The DocumentInfo class.
     */
    public class DocumentInfo
    {
        private var _config:Configuration;
        private var _info:Environment;
        private var _adSense:AdSenseGlobals;

        private var _pageURL:String;
        private var _utmr:String;

        /**
         * Creates a new DocumentInfo instance.
         */
        public function DocumentInfo( config:Configuration, info:Environment, formatedReferrer:String,
                                      pageURL:String = null, adSense:AdSenseGlobals = null )
        {
            _config  = config;
            _info    = info;
            _utmr    = formatedReferrer;
            _pageURL = pageURL;
            _adSense = adSense;
        }

        /**
         * Generates hit id for revenue per page tracking for AdSense.
         *
This method first examines the DOM for existing hid.

         *
If there is already a hid in DOM, then this method will return the existing hid.

         *
If there isn't any hid in DOM, then this method will generate a new hid, and both stores it in DOM, and returns it to the caller.

         * @return hid used by AdSense for revenue per page tracking
         */
        private function _generateHitId():Number
        {
            var hid:Number;

            //have hid in DOM
            if( _adSense.hid && (_adSense.hid != "") )
            {
                hid = Number( _adSense.hid );
            }
            //doesn't have hid in DOM
            else
            {
                hid = Math.round( Math.random() * 0x7fffffff );
                _adSense.hid = String( hid );
            }

            return hid;
        }

        /**
         * This method will collect and return the page URL information based on
         * the page URL specified by the user if present. If there is no parameter,
         * the URL of the HTML page embedding the SWF will be sent. If
         * ExternalInterface.avaliable=false, a default of "/" will be used.
         *
         * @private
         * @param {String} opt_pageURL (Optional) User-specified Page URL to assign
         *     metrics to at the back-end.
         *
         * @return {String} Final page URL to assign metrics to at the back-end.
         */
        private function _renderPageURL( pageURL:String = "" ):String
        {
            var pathname:String = _info.locationPath;
            var search:String   = _info.locationSearch;

            if( !pageURL || (pageURL == "") )
            {
                pageURL = pathname + unescape( search );
            	if ( pageURL == "" )
            	{
            		pageURL = "/";
            	}
            }

            return pageURL;
        }

        /**
         * Page title, which is a URL-encoded string.
         *
Example :

         *
utmdt=analytics%20page%20test

         */
        public function get utmdt():String
        {
            return _info.documentTitle;
        }

        /**
         * Hit id for revenue per page tracking for AdSense.
         *
Example :utmhid=2059107202

         */
        public function get utmhid():String
        {
            return String( _generateHitId() );
        }

        /**
         * Referral, complete URL.
         *
Example :utmr=http://www.example.com/aboutUs/index.php?var=selected

         */
        public function get utmr():String
        {
            if( !_utmr )
            {
                return "-";
            }

            return _utmr;
        }

        /**
         * Page request of the current page.
         *
Example :utmp=/testDirectory/myPage.html

         */
        public function get utmp():String
        {
            return _renderPageURL( _pageURL );
        }

        /**
         * Returns a Variables object representation.
         * @return a Variables object representation.
         */
        public function toVariables():Variables
        {
            var variables:Variables = new Variables();
                variables.URIencode = true;

                if( _config.detectTitle && ( utmdt != "") )
                {
                    variables.utmdt = utmdt;
                }

                variables.utmhid = utmhid;
                variables.utmr   = utmr;
                variables.utmp   = utmp;

            return variables;
        }

        /**
         * Returns the url String representation of the object.
         * @return the url String representation of the object.
         */
        public function toURLString():String
        {
            var v:Variables = toVariables();
            return v.toString();
        }
    }
}

fix comment for asdoc

fix comment for asdoc


/*
 * Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contributor(s):
 *   Zwetan Kjukov <zwetan@gmail.com>.
 *   Marc Alcaraz <ekameleon@gmail.com>.
 */

package com.google.analytics.utils
{
    import com.google.analytics.core.ga_internal;
    import com.google.analytics.debug.DebugConfiguration;
    import com.google.analytics.external.HTMLDOM;

    import core.strings.userAgent;
    import core.uri;

    import flash.system.Capabilities;
    import flash.system.Security;
    import flash.system.System;

    /**
     * Environment provides informations for the local environment.
     */
    public class Environment
    {
        private var _debug:DebugConfiguration;
        private var _dom:HTMLDOM;

        private var _protocol:String;
        private var _appName:String;
        private var _appVersion:Version;
        private var _userAgent:String;
        private var _url:String;

        /**
         * Creates a new Environment instance.
         * @param url The URL of the SWF.
         * @param app The application name
         * @param version The application version
         * @param dom the HTMLDOM reference.
         */
        public function Environment( url:String = "", app:String = "", version:String = "",
                                     debug:DebugConfiguration = null, dom:HTMLDOM = null )
        {
            var v:Version;

            if( app == "" )
            {
                if( isAIR() )
                {
                    app = "AIR";
                }
                else
                {
                    app = "Flash";
                }
            }

            if( version == "" )
            {
                v = flashVersion;
            }
            else
            {
                v = Version.fromString( version );
            }

            _url        = url;
            _appName    = app;
            _appVersion = v;

            _debug      = debug;
            _dom        = dom;
        }

        /**
         * @private
         */
        private function _findProtocol():void
        {
            _protocol = "";

            if( _url != "" )
            {
                var url:uri = new uri( _url );
                _protocol = url.scheme;
            }
        }

        /**
         * Indicates the name of the application.
         */
        public function get appName():String
        {
            return _appName;
        }

        /**
         * @private
         */
        public function set appName( value:String ):void
        {
            _appName = value;
            _defineUserAgent();
        }

        /**
         * Indicates the version of the application.
         */
        public function get appVersion():Version
        {
            return _appVersion;
        }

        /**
         * @private
         */
        public function set appVersion( value:Version ):void
        {
            _appVersion = value;
            _defineUserAgent();

        }

        /**
         * Sets the stage reference value of the application.
         */
        ga_internal function set url( value:String ):void
        {
            _url = value;
        }

        /**
         * Indicates the location of swf.
         */
        public function get locationSWFPath():String
        {
            return _url;
        }

        /**
         * Indicates the referrer value.
         */
        public function get referrer():String
        {
            var _referrer:String = _dom.referrer;

            if( _referrer )
            {
                return _referrer;
            }

            if( protocol == "file" )
            {
                return "localhost";
            }

            return "";
        }

        /**
         * Indicates the title of the document.
         */
        public function get documentTitle():String
        {
            var _title:String = _dom.title;

            if( _title )
            {
                return _title;
            }

            return "";
        }

        /**
         * Indicates the local domain name value.
         */
        public function get domainName():String
        {
            if( (protocol == "http") ||
                (protocol == "https") )
            {
                var url:uri = new uri( _url.toLowerCase() );
                return url.host;
            }

            if( protocol == "file" )
            {
                return "localhost";
            }

            return "";
        }

        /**
         * Indicates if the application is running in AIR.
         */
        public function isAIR():Boolean
        {
            return Security.sandboxType == "application";
        }

        /**
         * Indicates if the SWF is embeded in an HTML page.
         * @return true if the SWF is embeded in an HTML page.
         */
        public function isInHTML():Boolean
        {
            return Capabilities.playerType == "PlugIn" ;
        }

        /**
         * Indicates the locationPath value.
         */
        public function get locationPath():String
        {
            var _pathname:String = _dom.pathname;

            if( _pathname )
            {
                return _pathname;
            }

            return "";
        }

        /**
         * Indicates the locationSearch value.
         */
        public function get locationSearch():String
        {
            var _search:String = _dom.search;

            if( _search )
            {
                return _search;
            }

            return "";
        }

        /**
         * Returns the flash version object representation of the application.
         *
This object contains the attributes major, minor, build and revision :

         *
Example :

         *

         * import com.google.analytics.utils.Environment ;
         *
         * var info:Environment = new Environment( "http://www.domain.com" ) ;
         * var version:Object = info.flashVersion ;
         *
         * trace( version.major    ) ; // 9
         * trace( version.minor    ) ; // 0
         * trace( version.build    ) ; // 124
         * trace( version.revision ) ; // 0
         *

         * @return the flash version object representation of the application.
         */
        public function get flashVersion():Version
        {
            var v:Version = Version.fromString( Capabilities.version.split( " " )[1], "," ) ;
            return v ;
        }

        /**
         * Returns the language string as a lowercase two-letter language code from ISO 639-1.
         * @see Capabilities.language
         */
        public function get language():String
        {
            var _lang:String = _dom.language;
            var lang:String  = Capabilities.language;

            if( _lang )
            {
                if( (_lang.length > lang.length) &&
                    (_lang.substr(0,lang.length) == lang) )
                {
                    lang = _lang;
                }
            }

            return lang;
        }

        /**
         * Returns the internal character set used by the flash player
         *
Logic : by default flash player use unicode internally so we return UTF-8.

         *
If the player use the system code page then we try to return the char set of the browser.

         * @return the internal character set used by the flash player
         */
        public function get languageEncoding():String
        {
            if( System.useCodePage )
            {
                var _charset:String = _dom.characterSet;
                if( _charset )
                {
                    return _charset;
                }
                return "-"; //not found
            }
            //default
            return "UTF-8" ;
        }

        /**
         * Returns the operating system string.
         *
Note: The flash documentation indicate those strings

         *
"Windows XP"

         *
"Windows 2000"

         *
"Windows NT"

         *
"Windows 98/ME"

         *
"Windows 95"

         *
"Windows CE" (available only in Flash Player SDK, not in the desktop version)

         *
"Linux"

         *
"MacOS"

         *
Other strings we can obtain ( not documented : "Mac OS 10.5.4" , "Windows Vista")

         * @return the operating system string.
         * @see Capabilities.os
         */
        public function get operatingSystem():String
        {
            return Capabilities.os ;
        }

        /**
         * Returns the player type.
         *
Note : The flash documentation indicate those strings.

         *
"ActiveX"    : for the Flash Player ActiveX control used by Microsoft Internet Explorer.

         *
"Desktop"    : for the Adobe AIR runtime (except for SWF content loaded by an HTML page, which has Capabilities.playerType set to "PlugIn").

         *
"External"   : for the external Flash Player "PlugIn" for the Flash Player browser plug-in (and for SWF content loaded by an HTML page in an AIR application).

         *
"StandAlone" : for the stand-alone Flash Player.

         * @return the player type.
         * @see Capabilities.playerType
         */
        public function get playerType():String
        {
            return Capabilities.playerType;
        }

        /**
         * Returns the platform, can be "Windows", "Macintosh" or "Linux"
         * @see Capabilities.manufacturer
         */
        public function get platform():String
        {
            var p:String = Capabilities.manufacturer;
            return p.split( "Adobe " )[1];
        }

        /**
         * Indicates the Protocols object of this local info.
         */
        public function get protocol():String
        {
            if(!_protocol)
            {
                _findProtocol();
            }

            return _protocol;
        }

        /**
         * Indicates the height of the screen.
         * @see Capabilities.screenResolutionY
         */
        public function get screenHeight():Number
        {
            return Capabilities.screenResolutionY;
        }

        /**
         * Indicates the width of the screen.
         * @see Capabilities.screenResolutionX
         */
        public function get screenWidth():Number
        {
            return Capabilities.screenResolutionX;
        }

        /**
         * In AIR we can use flash.display.Screen to directly get the colorDepth property
         * in flash player we can only access screenColor in flash.system.Capabilities.
         *
Some ref : http://en.wikipedia.org/wiki/Color_depth

         *
"color" -> 16-bit or 24-bit or 32-bit

         *
"gray"  -> 2-bit

         *
"bw"    -> 1-bit

         */
        public function get screenColorDepth():String
        {
            var color:String;
            switch( Capabilities.screenColor )
            {
                case "bw":
                {
                    color = "1";
                    break;
                }
                case "gray":
                {
                    color = "2";
                    break;
                }
                /* note:
                   as we have no way to know if
                   we are in 16-bit, 24-bit or 32-bit
                   we gives 24-bit by default
                */
                case "color" :
                default      :
                {
                    color = "24" ;
                }
            }

            var _colorDepth:String = _dom.colorDepth;

            if( _colorDepth )
            {
                color = _colorDepth;
            }

            return color;
        }

        private function _defineUserAgent():void
        {
            _userAgent = core.strings.userAgent( appName + "/" + appVersion.toString(4) );
        }

        /**
         * Defines a custom user agent.
         *
For case where the user would want to define its own application name and version
         * it is possible to change appName and appVersion which are in sync with
         * applicationProduct and applicationVersion properties.

         */
        public function get userAgent():String
        {
            if( !_userAgent )
            {
                 _defineUserAgent();
            }

            return _userAgent;
        }

        /**
         * @private
         */
        public function set userAgent( custom:String ):void
        {
            _userAgent = custom;
        }

    }
}

/*
 * Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contributor(s):
 *   Zwetan Kjukov <zwetan@gmail.com>.
 *   Marc Alcaraz <ekameleon@gmail.com>.
 */

package com.google.analytics.utils
{
    import com.google.analytics.core.ga_internal;
    import com.google.analytics.debug.DebugConfiguration;
    import com.google.analytics.external.HTMLDOM;

    import core.strings.userAgent;
    import core.uri;
    import core.version;

    import flash.system.Capabilities;
    import flash.system.Security;
    import flash.system.System;

    /**
     * Environment provides informations for the local environment.
     */
    public class Environment
    {
        private var _debug:DebugConfiguration;
        private var _dom:HTMLDOM;

        private var _protocol:String;
        private var _appName:String;
        private var _appVersion:version;
        private var _userAgent:String;
        private var _url:String;

        /**
         * Creates a new Environment instance.
         * @param url The URL of the SWF.
         * @param app The application name
         * @param version The application version
         * @param dom the HTMLDOM reference.
         */
        public function Environment( url:String = "", app:String = "", version:String = "",
                                     debug:DebugConfiguration = null, dom:HTMLDOM = null )
        {
            var v:core.version;

            if( app == "" )
            {
                if( isAIR() )
                {
                    app = "AIR";
                }
                else
                {
                    app = "Flash";
                }
            }

            if( version == "" )
            {
                v = flashVersion;
            }
            else
            {
                v = getVersionFromString( version );
            }

            _url        = url;
            _appName    = app;
            _appVersion = v;

            _debug      = debug;
            _dom        = dom;
        }

        /**
         * @private
         */
        private function _findProtocol():void
        {
            _protocol = "";

            if( _url != "" )
            {
                var url:uri = new uri( _url );
                _protocol = url.scheme;
            }
        }

        /**
         * Indicates the name of the application.
         */
        public function get appName():String
        {
            return _appName;
        }

        /**
         * @private
         */
        public function set appName( value:String ):void
        {
            _appName = value;
            _defineUserAgent();
        }

        /**
         * Indicates the version of the application.
         */
        public function get appVersion():version
        {
            return _appVersion;
        }

        /**
         * @private
         */
        public function set appVersion( value:version ):void
        {
            _appVersion = value;
            _defineUserAgent();

        }

        /**
         * Sets the stage reference value of the application.
         */
        ga_internal function set url( value:String ):void
        {
            _url = value;
        }

        /**
         * Indicates the location of swf.
         */
        public function get locationSWFPath():String
        {
            return _url;
        }

        /**
         * Indicates the referrer value.
         */
        public function get referrer():String
        {
            var _referrer:String = _dom.referrer;

            if( _referrer )
            {
                return _referrer;
            }

            if( protocol == "file" )
            {
                return "localhost";
            }

            return "";
        }

        /**
         * Indicates the title of the document.
         */
        public function get documentTitle():String
        {
            var _title:String = _dom.title;

            if( _title )
            {
                return _title;
            }

            return "";
        }

        /**
         * Indicates the local domain name value.
         */
        public function get domainName():String
        {
            if( (protocol == "http") ||
                (protocol == "https") )
            {
                var url:uri = new uri( _url.toLowerCase() );
                return url.host;
            }

            if( protocol == "file" )
            {
                return "localhost";
            }

            return "";
        }

        /**
         * Indicates if the application is running in AIR.
         */
        public function isAIR():Boolean
        {
            return Security.sandboxType == "application";
        }

        /**
         * Indicates if the SWF is embeded in an HTML page.
         * @return true if the SWF is embeded in an HTML page.
         */
        public function isInHTML():Boolean
        {
            return Capabilities.playerType == "PlugIn" ;
        }

        /**
         * Indicates the locationPath value.
         */
        public function get locationPath():String
        {
            var _pathname:String = _dom.pathname;

            if( _pathname )
            {
                return _pathname;
            }

            return "";
        }

        /**
         * Indicates the locationSearch value.
         */
        public function get locationSearch():String
        {
            var _search:String = _dom.search;

            if( _search )
            {
                return _search;
            }

            return "";
        }

        /**
         * Returns the flash version object representation of the application.
         *
This object contains the attributes major, minor, build and revision :

         *
Example :

         *

         * import com.google.analytics.utils.Environment ;
         *
         * var info:Environment = new Environment( "http://www.domain.com" ) ;
         * var version:Object = info.flashVersion ;
         *
         * trace( version.major    ) ; // 9
         * trace( version.minor    ) ; // 0
         * trace( version.build    ) ; // 124
         * trace( version.revision ) ; // 0
         *

         * @return the flash version object representation of the application.
         */
        public function get flashVersion():version
        {
            var v:version = getVersionFromString( Capabilities.version.split( " " )[1], "," ) ;
            return v ;
        }

        /**
         * Returns the language string as a lowercase two-letter language code from ISO 639-1.
         * @see Capabilities.language
         */
        public function get language():String
        {
            var _lang:String = _dom.language;
            var lang:String  = Capabilities.language;

            if( _lang )
            {
                if( (_lang.length > lang.length) &&
                    (_lang.substr(0,lang.length) == lang) )
                {
                    lang = _lang;
                }
            }

            return lang;
        }

        /**
         * Returns the internal character set used by the flash player
         *
Logic : by default flash player use unicode internally so we return UTF-8.

         *
If the player use the system code page then we try to return the char set of the browser.

         * @return the internal character set used by the flash player
         */
        public function get languageEncoding():String
        {
            if( System.useCodePage )
            {
                var _charset:String = _dom.characterSet;
                if( _charset )
                {
                    return _charset;
                }
                return "-"; //not found
            }
            //default
            return "UTF-8" ;
        }

        /**
         * Returns the operating system string.
         *
Note: The flash documentation indicate those strings

         *
"Windows XP"

         *
"Windows 2000"

         *
"Windows NT"

         *
"Windows 98/ME"

         *
"Windows 95"

         *
"Windows CE" (available only in Flash Player SDK, not in the desktop version)

         *
"Linux"

         *
"MacOS"

         *
Other strings we can obtain ( not documented : "Mac OS 10.5.4" , "Windows Vista")

         * @return the operating system string.
         * @see Capabilities.os
         */
        public function get operatingSystem():String
        {
            return Capabilities.os ;
        }

        /**
         * Returns the player type.
         *
Note : The flash documentation indicate those strings.

         *
"ActiveX"    : for the Flash Player ActiveX control used by Microsoft Internet Explorer.

         *
"Desktop"    : for the Adobe AIR runtime (except for SWF content loaded by an HTML page, which has Capabilities.playerType set to "PlugIn").

         *
"External"   : for the external Flash Player "PlugIn" for the Flash Player browser plug-in (and for SWF content loaded by an HTML page in an AIR application).

         *
"StandAlone" : for the stand-alone Flash Player.

         * @return the player type.
         * @see Capabilities.playerType
         */
        public function get playerType():String
        {
            return Capabilities.playerType;
        }

        /**
         * Returns the platform, can be "Windows", "Macintosh" or "Linux"
         * @see Capabilities.manufacturer
         */
        public function get platform():String
        {
            var p:String = Capabilities.manufacturer;
            return p.split( "Adobe " )[1];
        }

        /**
         * Indicates the Protocols object of this local info.
         */
        public function get protocol():String
        {
            if(!_protocol)
            {
                _findProtocol();
            }

            return _protocol;
        }

        /**
         * Indicates the height of the screen.
         * @see Capabilities.screenResolutionY
         */
        public function get screenHeight():Number
        {
            return Capabilities.screenResolutionY;
        }

        /**
         * Indicates the width of the screen.
         * @see Capabilities.screenResolutionX
         */
        public function get screenWidth():Number
        {
            return Capabilities.screenResolutionX;
        }

        /**
         * In AIR we can use flash.display.Screen to directly get the colorDepth property
         * in flash player we can only access screenColor in flash.system.Capabilities.
         *
Some ref : http://en.wikipedia.org/wiki/Color_depth

         *
"color" -> 16-bit or 24-bit or 32-bit

         *
"gray"  -> 2-bit

         *
"bw"    -> 1-bit

         */
        public function get screenColorDepth():String
        {
            var color:String;
            switch( Capabilities.screenColor )
            {
                case "bw":
                {
                    color = "1";
                    break;
                }
                case "gray":
                {
                    color = "2";
                    break;
                }
                /* note:
                   as we have no way to know if
                   we are in 16-bit, 24-bit or 32-bit
                   we gives 24-bit by default
                */
                case "color" :
                default      :
                {
                    color = "24" ;
                }
            }

            var _colorDepth:String = _dom.colorDepth;

            if( _colorDepth )
            {
                color = _colorDepth;
            }

            return color;
        }

        private function _defineUserAgent():void
        {
            _userAgent = core.strings.userAgent( appName + "/" + appVersion.toString(4) );
        }

        /**
         * Defines a custom user agent.
         *
For case where the user would want to define its own application name and version
         * it is possible to change appName and appVersion which are in sync with
         * applicationProduct and applicationVersion properties.

         */
        public function get userAgent():String
        {
            if( !_userAgent )
            {
                 _defineUserAgent();
            }

            return _userAgent;
        }

        /**
         * @private
         */
        public function set userAgent( custom:String ):void
        {
            _userAgent = custom;
        }

    }
}

replace class Version by core.version

replace class Version by core.version